Unix C C++ Lab MCA Sem 1 and 2
Unix C C++ Lab MCA Sem 1 and 2
‘C’
Lab Manual
Page 1
Unix, C & C++
1. Write a function to input a character and display the character input twice.
Solution
#include<stdio.h>
main()
{
char c;
c=getc(stdin);
fflush(stdin);
putc(c, stdout);
putc(c,stdout);
}
Output:
*
**
Solution
#include<stdio.h>
main()
{
char in_str[21];
puts("Enter a string to a maximum of 20 characters");
gets(in_str);
fflush(stdin);
puts(in_str);
}
Output:
Enter a string to a maximum of 20 characters
Welcome
Welcome
3. Write a function to accept and store two characters in different memory locations, and
display them one after the other using the functions getchar() and putchar().
Solution
#include<stdio.h>
main()
{
Page 2
Unix, C & C++
char a,b;
a=getchar();
fflush(stdin);
b=getchar();
fflush(stdin);
putchar(a);
putchar(b);
}
Output:
1
a
1a
4. Write a function that prompts the user to input a name upto a maximum of 25
characters, and display the following message:
Hello. How do you do?
(name)
Solution
#include<stdio.h>
main()
{
char instr[26];
puts("Enter Your Name to a maximum of 25 characters");
gets(instr);
fflush(stdin);
puts("Hello. How do you do?");
puts(instr);
}
Output:
Enter Your Name to a maximum of 25 characters
CharlesBabbage
Hello. How do you do?
CharlesBabbage
5. Write a function that prompts for a name (upto 20 characters) and address (upto 30
characters) and accepts them one at a time. Finally the name and address are
displayed in the following way:
Page 3
Unix, C & C++
Solution
#include<stdio.h>
main()
{
char name[21], addrs[31];
puts("Enter your Name to a maximum of 20 characters");
gets(name);
fflush(stdin);
puts("Enter your Address to a maximum of 30 characters");
gets(addrs);
fflush(stdin);
puts(“Your Name is:");
puts(name);
puts(“Your Address is:");
puts(addrs);
}
Output:
6. Write a function using the if…else condition, if the input character is A then display a
message "Character is A" otherwise display a message "Character is not A"
Solution
#include<stdio.h>
main()
{
char chr;
puts("Enter a character");
chr=getchar();
fflush(stdin);
if(chr=='A')
puts("Character is A");
else
puts("Character is not A");
}
Page 4
Unix, C & C++
Solution 7
#include<stdio.h>
main()
{
char inp;
puts("Enter a character");
inp=getchar();
fflush(stdin);
if(inp>='A')
if(inp<='Z')
puts("Upper case”);
else if(inp>='a')
if(inp<='z')
puts("Lower case”);
}
Output 1:
Enter a character
a
Lower case
Output 2:
Enter a character
G
Upper case
Page 5
Unix, C & C++
Solution
#include<stdio.h>
#include <ctype.h>
main()
{
char s;
s=getchar();
if (isdigit(s))
puts(“The character is a number”);
else
puts(“The character is not a number”);
}
Output:
5
The character is a number
9. Write a function to check if the input character is a vowel, else print an appropriate
message.
Solution
#include<stdio.h>
main()
{
char in_chr;
puts("Enter a character in lower case:");
in_chr=getchar();
fflush(stdin);
if(in_chr=='a')
puts("Vowel a");
else if(in_chr=='e')
puts(“vowel e");
else if(in_chr=='i')
puts(“vowel i”);
else if(in_chr=='o')
puts(“vowel o”);
else if(in_chr=='u')
puts(“vowel u");
else
puts("The character is not a vowel");
}
Page 6
Unix, C & C++
Output:
10. Write a function that accepts a single-character grade code, and depending on what
grade is input, displays the DA percentage according to the table given below:
Grade DA%
1 95%
2 80%
3 70%
4 65%
Solution
#include<stdio.h>
main()
{
char inp;
puts("Enter Grade Code:");
inp=getchar();
fflush(stdin);
if(inp=='1')
puts("DA percentage is 95%");
else if(inp =='2')
puts("DA percentage is 80%");
else if(inp =='3')
puts("DA percentage is 70%");
else if(inp =='4')
puts("DA percentage is 65%");
else
puts("Invalid Grade Code");
Output:
Page 7
Unix, C & C++
11. Write a function to display the following menu and accept a choice number. If an
invalid choice is entered an appropriate error message must be displayed, else the
choice number entered must be displayed. Menu
1. Master
2. Transaction
3. Reports
4. Exit
Your Choice :
Solution
#include<stdio.h>
main()
{
char chc;
puts("Menu");
puts("1. Masters");
puts("2. Transaction");
puts("3. Reports");
puts("4. Exit");
puts(" ");
puts("your choice :");
chc=getchar();
fflush(stdin);
switch(chc)
{
case'1' : puts(“choice is 1");
break;
case'2' : puts(“choice is 2");
break;
case'3' : puts(“choice is 3");
break;
case'4' : puts(“choice is 4");
break;
default : puts("Invalid choice");
}
}
Output:
Menu
1. Masters
2. Transaction
3. Reports
4. Exit
your choice :
1
choice is 1
Page 8
Unix, C & C++
12. Write a function to accept characters from the keyboard until the character '!' is input,
and to display the total number of vowel characters entered.
Solution
#include <stdio.h>
main()
{
int v;
char inp;
v=0;
while(inp!='!')
{
puts("Enter a character");
inp=getchar();
fflush(stdin);
switch(inp)
{
case'A' :
case'a' :
case'E' :
case'e' :
case'I' :
case'i' :
case'O' :
case'o' :
case'U' :
case'u' :
v++;
break;
}
}
puts("No. of vowels are : ");
printf("%d", v);
}
Output:
Enter a character
q
Enter a character
a
Enter a character
p
Enter a character
e
Enter a character
Page 9
Unix, C & C++
!
No. of Vowels are :
2
Solution
#include<stdio.h>
main()
{
char chr;
int i=0;
puts("Enter a character”);
chr=getchar();
fflush(stdin);
while(i<40)
{
putchar(chr);
i=i+1;
}
}
Output:
Enter a character
#
########################################
14. Write a function that accepts a number from 0 to 9. A string should then be displayed
the number of times specified.
Solution
#include<stdio.h>
main()
{
char str[50],i;
int rep,j=0;
puts("Enter a string”);
gets(str);
fflush(stdin);
puts("Enter the number of times”);
i=getchar();
fflush(stdin);
switch(i)
Page 10
Unix, C & C++
{
case '0' : rep=0;
break;
case '1' : rep=1;
break;
case '2' : rep=2;
break;
case '3' : rep=3;
break;
case '4' : rep=4;
break;
case '5' : rep=5;
break;
case '6' : rep=6;
break;
case '7' : rep=7;
break;
case '8' : rep=8;
break;
case '9' : rep=9;
break;
default : puts("Invalid choice");
}
while(j<rep)
{
puts(str);
j=j+1;
}
}
Output:
Enter a string
Where there is a will there is a way
Enter the number of times
5
Where there is a will there is a way
Where there is a will there is a way
Where there is a will there is a way
Where there is a will there is a way
Where there is a will there is a way
Page 11
Unix, C & C++
15. Write a function that accepts either 'y' or 'n' only as input. For any other character
input, an appropriate error message should be displayed and the input accepted again.
Solution
#include<stdio.h>
main()
{
char yn;
do
{
puts("Enter y/n (Yes/No)”);
yn=getchar();
fflush(stdin);
if(yn!='y' &&yn!='n')
puts("Invalid input”);
}while(yn!='y'&&yn!='n');
}
Output:
16. Write a function to accept ten characters from the character set, and to display
whether the number of lower-case characters is greater than, less than or equal to
number of upper-case characters. Display an error message if the input is not an
alphabet.
Solution
#include<stdio.h>
main()
{
char chr;
int I, low, upp;
low=upp=0;
for (I=0;I<10;I=I+1)
{
puts("Enter a character");
Page 12
Unix, C & C++
chr=getchar();
fflush(stdin);
if(chr<'A'||(chr>'Z'&&chr<'a')||chr>'z')
{
puts("the input is not an alphabet");
}
else if(chr>='a'&&chr<='z')
{
low=low+1;
}
else upp=upp+1;
}
if(low>upp)
puts("count of lower-case characters is more");
else if(upp>low)
puts("count of upper-case characters is more");
else
puts("count of lower-case and upper-case characters is equal");
}
Output:
Enter a character
a
Enter a character
A
Enter a character
S
Enter a character
B
Enter a character
M
Enter a character
y
Enter a character
@
the input is not an alphabet
Enter a character
2
the input is not an alphabet
Enter a character
+
the input is not an alphabet
Enter a character
z
count of upper-case characters is more
Page 13
Unix, C & C++
17. Write a function to find the sum of numbers entered until the input value 999 is
entered or until 10 numbers have been entered.
Solution
#include<stdio.h>
main()
{
int num,sum,cnt;
cnt=sum=0;
while(cnt<10)
{
printf("Enter a number(999 to quit)\n");
scanf("%d",&num);
fflush(stdin);
if(num==999)
break;
sum=sum+num;
cnt=cnt+1;
}
printf("The sum of %d numbers is :%d\n",cnt, sum);
}
Output:
18. Write a function to accept 8 numbers and print the sum of all positive numbers
entered.
Solution
#include<stdio.h>
main()
{
int I,sum,num;
Page 14
Unix, C & C++
sum=num=0;
for(I=0;I<8;I=I+1)
{
puts("Enter a number");
scanf("%d",&num);
fflush(stdin);
if(num<=0)
continue;
sum=sum+num;
}
printf("The sum of positive numbers entered is %d\n",sum);
}
Output:
Enter a number
5
Enter a number
-2
Enter a number
3
Enter a number
4
Enter a number
-1
Enter a number
7
Enter a number
2
Enter a number
1
The sum of positive numbers entered is 22
19. Write a function that stores the alphabets A to Z in an array by making use of their
ASCII codes, given that the ASCII code of character A is 65. The function should
also display the string.
Solution
#include<stdio.h>
main()
{
int I, asc=65;
char alpha[27];
for(I=0;I<26;I=I+1)
{
alpha[I]=asc;
Page 15
Unix, C & C++
asc=asc+1;
}
alpha[26]='\0';
printf("The alphabets are :%s\n",alpha);
}
Output:
The alphabets are :ABCDEFGHIJKLMNOPQRSTUVWXYZ
20. In a file delete utility program for 5 files the user response to whether a file is to be
deleted or not is to be stored in an array as 'Y' for yes and 'N' for no for all files. By
default the user response should be N for all files. Write a function that sets up an
array and accepts users response.
Solution
#include<stdio.h>
main()
{
char ans, file_yn[5];
int I;
for(I=0;I<5;I=I+1)
file_yn[I]='N';
printf("The string has been initialized \n");
for(I=0;I<5;I=I+1)
{
printf("Enter Y/N for deleting a file no# %d\n",I+1);
ans =getchar();
fflush(stdin);
if(ans=='y'||ans=='Y')
file_yn[I]=ans;
}
printf("\n The status Report: \n");
for(I=0;I<5;I=I+1)
printf("Delete file no# %d : %c\n",I+1,file_yn[I]);
}
Output:
Page 16
Unix, C & C++
n
Enter Y/N for deleting a file no# 5
y
Solution
#include<stdio.h>
main()
{
char in_str[101];
int I=0;
printf("Enter a string (upto 100 characters)\n");
gets(in_str);
fflush(stdin);
while(in_str[I]!='\0')
{
if(in_str[I]>='A'&&in_str[I]<='Z')
in_str[I]=in_str[I]+32;
I=I+1;
}
printf("The converted string is %s\n",in_str);
}
Output:
22. Write a function to compare two strings and to print the larger one. The strings may
be compared in terms of ASCII code of each character in the string.
Solution
#include<stdio.h>
main()
{
Page 17
Unix, C & C++
char str1[101],str2[101];
int diff, I=0;
printf("Enter string#1(upto 100 chrs)\n");
gets(str1);
fflush(stdin);
printf("Entering string#2(upto 100 chrs)\n");
gets(str2);
fflush(stdin);
do
{
diff=str1[I]-str2[I];
if(str1[I]=='\0'||str2[I]=='\0')
break;
I=I+1;
}while(diff==0);
if(diff>0)
printf("Larger string :%s \n",str1);
else if(diff<0)
printf("Larger string :%s\n",str2);
else
printf("strings are equal\n");
}
Output:
23. Write a function to accept a maximum of 25 numbers and to display the highest and
lowest numbers along with all the numbers.
Solution
#include<stdio.h>
main()
{
int arry[25], low, high, I=-1;
do
{
I=I+1;
printf("Enter no.%d,(0 to terminate)\n",I+1);
scanf("%d",&arry[I]);
fflush(stdin);
Page 18
Unix, C & C++
}while(arry[I]!=0);
I=0;
low=high=arry[0];
while(arry[I]!=0)
{
if(low>arry[I])
low=arry[I];
else if (high<arry[I])
high = arry[I];
I=I+1;
}
for(I=0;arry[I]!=0;I=I+1)
printf("Number %dis %d\n",I+1,arry[I]);
printf("Lowest number is %d\nHighest number is %d\n",low, high);
Output:
Page 19
Unix, C & C++
24. Write a program, which reads in a year and reports on whether it is a leap year or not.
Solution
#include<stdio.h>
main()
{
int year;
printf("\n please input the year:");
scanf("%d",&year);
fflush(stdin);
if((((year%4)==0)&&((year%100)!=0))||((year%400)==0))
{
printf("\n\n Given year %d is a leap year", year);
}
else
{
printf("\n\n Given year %d is not a leap year",year);
}
}
Output:
please input the year:1940
Given year 1940 is a leap year
Solution
#include<stdio.h>
main()
{
int count;
char mesg[25];
char*ptr;
printf(“Enter a String :”);
gets(mesg);
for(ptr=mesg,count=0;*ptr!='\0';ptr++)
{
count++;
}
printf("Length of the string is :%d\n",count);
}
Output:
Enter a String :Welcome
Length of the string is :7
Page 20
Unix, C & C++
26. Write a program to compare two strings and determine if they are the same.
Solution
#include<stdio.h>
main()
{
char *ptr1,*ptr2;
char m1[20], m2[20];
int c=0;
printf("Enter the first String" );
gets(m1);
printf("Enter the second String" );
gets(m2);
for(ptr1=m1,ptr2=m2;(*ptr1!='\0')&&(*ptr2!='\0'); ptr1++,ptr2++)
{
if(*ptr1==*ptr2)
{
c=1;
continue;
}
else
{
c=0;
break;
}
}
if( c==0)
printf("The two strings are not the same");
else
printf("The two strings are the same");
}
Output1:
Output2:
Page 21
Unix, C & C++
Solution
#include<stdio.h>
main()
{
int a, b;
char cmd[25];
puts("Enter 2 numbers \n");
scanf("%d%d”, &a,&b);
fflush(stdin);
sprintf(cmd, "The sum of %d and %d is %d",a,b, (a+b));
puts(cmd);
}
Output:
Enter 2 numbers
2
3
The sum of 2 and 3 is 5
Solution
#include<stdio.h>
#include<string.h>
char str[51]="";
search(char* s, char c);
main()
{
char chr;
puts("Enter a string:");
scanf(“%s”,str);
fflush(stdin);
puts(“Enter a character to search for :”);
scanf("%s",&chr);
fflush(stdin);
search(str,chr);
}
search(string,c)
char*string;
char c;
Page 22
Unix, C & C++
{
int I, len;
char rev_str[100];
len=strlen(string);
for(I=0;len!=0;len--,I++)
rev_str[I]=string[I];
I=0;
while (rev_str[I]!=’\0’)
{
if(rev_str[I]==c)
printf(“character :%c found at %d position \n”,c,I+1);
I++;
}
}
Output:
Enter a string:
Welcome
Enter a character to search for :
e
character :e found at 2 position
character :e found at 7 position
29. Write a function sum() to add two values and to return the value to the main function
and print the value.
Solution
#include<stdio.h>
sum(int a,int b);
main()
{
int x,y,value;
scanf(“%d%d”,&x,&y);
fflush(stdin);
value=sum(x,y);
printf(“Total is %d \n”,value);
}
sum(int a,int b)
{
return a+b;
}
Output:
3
7
Total is 10
Page 23
Unix, C & C++
30. Write a program to call a function power(m,n) to display the nth power of the
integer m.
Solution
#include<stdio.h>
power(int *m,int *n);
main()
{
int x,y;
printf(“Enter number :”);
scanf(“%d”,&x);
fflush(stdin);
printf(“Enter power to raise to :”);
scanf(“%d”,&y);
fflush(stdin);
power(&x,&y);
}
power(int *m,int *n)
{
int I=1,val=1;
while(I++<=*n)
val=val**m;
printf(“%dth power of %d is %d \n”,*n,*m,val);
}
Output:
Enter number :2
Enter power to raise to :5
5th power of 2 is 32
31. Write a program to display the error messages shown in the table along with the error
number.
Error Number Error Message
Solution
#include<stdio.h>
#define Errors 4
char err_msg[][29]={
Page 24
Unix, C & C++
Output:
32. Give appropriate statements to accept values into the members of the structure date
and then print out the date as mm/dd/yyyy. Assume that the members of the structure
are : day, month and year.
Solution
scanf (“%d%d%d”,&date.day,&date.month,&date.year);
printf(“%d/%d/%d”,date.month,date.day,date.year);
Solution
#include<stdio.h>
struct
{
char eno [6];
char efname [21];
Page 25
Unix, C & C++
main()
{
int I;
for(I=0;I<3;I++)
{
sprintf(empstruct[I].eno, "EMP#%d",I+1);
printf("Employee Number:%s\n", empstruct[I].eno);
printf("Enter the employee name (firstName Initial lastName):");
scanf("%s %c %s", &empstruct[I].efname, &empstruct[I].einitial,
&empstruct[I].elname);
}
for(I=0;I<3;I++)
{
printf("\n%s : %s %c %s\n",empstruct[I].eno,
empstruct[I].efname,empstruct[I].einitial,empstruct[I].elname);
}
}
Output:
Employee Number:EMP#1
Enter the employee name (firstName Initial lastName):abc d efg
Employee Number:EMP#2
Enter the employee name (firstName Initial lastName):hij k lmn
Employee Number:EMP#3
Enter the employee name (firstName Initial lastName):opq r stu
Solution
Page 26
Unix, C & C++
Solution
#include<stdio.h>
sum_bal(sal)
float sal;
{
if(sal <6000)
return (sal+1000);
else if(sal>=6000 && sal<10000)
return(sal+2000);
else
return (sal+3000);
}
main()
{ float sl, s;
printf("Enter Salary : ");
scanf("%f", & sl);
s = sum_bal(sl);
printf("%f", s);
}
Output :
35. Write a program to accept a number as a string and return the sign and absolute value.
Solution
#include<stdio.h>
main()
{
char str[6];
printf(“Enter a Number”);
gets(str);
char sgn = ‘+’;
int n=0;
if(str[n]== ‘-’)
{
sgn = ‘-’ ;
}
printf(“Sign : %c\n”,sgn);
printf(“Abs. Value: “);
Page 27
Unix, C & C++
while(str[++n] != ‘\0’)
putchar(str[n]);
}
Output 1:
Enter a Number-125
Sign : -
Abs. Value: 125
Output 2:
Enter a Number456
Sign : +
Abs. Value: 56
36. Find the error in following code.
cal(x,y)
int x,y;
{
return x+y;
return x-y;
return x*y;
}
Solution
Solution
#include<stdio.h>
main()
{
char inp;
FILE *pointer1;
pointer1=fopen(“hi1.txt”,”w”);
while((inp=fgetc(pointer1))!=eof)
{
printf(“%c”,inp);
}
}
The file hi1.txt should be opened in the read mode (“r”) for input. The variable
eof cannot be written in lower case.
Page 28
Unix, C & C++
38. Write a program to append the contents of the first file to the second file. The
program should also terminate in the following cases
a. If 2 arguments are not specified on the command line. Then display
Usage : append file1file2
b. If the file to be read cannot be opened then display
Cannot open input file.
Solution
#include<stdio.h>
#include<process.h>
main(argc,argv)
int argc;
char *argv[];
{
FILE *ptr1,*ptr2;
char inp;
if(argc!=3)
{
printf("Usage : append file1file2\n");
exit(1);
}
else
{
if((ptr1=fopen(argv[1],"r"))==NULL)
{
printf("cannot open input file \n");
exit(1);
}
}
ptr2=fopen(argv[2],"a");
while((inp=fgetc(ptr1))!=EOF)
{
fputc(inp,ptr2);
}
fclose(ptr1);
fclose(ptr2);
}
Page 29
Unix, C & C++
File2.txt contains
How are you?
I am fine.
Exercise: -
2. Write a program to accept the details(name, salary) of 5 persons and give a grade
according to the salary range and finally display the name, salary and grade using
a. switch-case
b. if-else
3. Write a program to find the sum and product of numbers from 50 to 100 using a
while loop.
6. Write a program that will read in numerical values for x and n , evaluate the
formula y=x^n using function.
7. Write a program that displays the numbers that are cubes of numbers from 1 to
10.
11. Write a program to arrange the names in alphabetical order with swapping done in
a separate function.
12. Write a program to find the out the average in 5 subjects of 10 STUDENTS.
Page 30
Unix, C & C++
C++
Lab Manual
Page 31
Unix, C & C++
C++
Lab Manual
1. Write a simple program that prints a string on the screen.
Solution
#include<iostream.h>
#include<conio.h>
main ()
{
cout << "Welcome to C++ lab Exercise";
getch();
}
Solution
#include<iostream.h>
#include<conio.h>
main ()
{
float num1, num2, sum, avg;
cout << "Enter two numbers :";
cin >> num1;
cin >> num2;
sum = num1+num2;
avg=sum/2;
cout << "Sum = " << sum << "\n";
cout << "Average = " << avg << "\n";
getch();
}
3. Write a program to get the Name, Age, address, phone number from the user and
display them by using the class function.
Solution
#include<iostream.h>
#include<conio.h>
Page 32
Unix, C & C++
class sample
{
char name[30];
int age;
char add[30];
int phone;
public :
void getdata(void);
void display(void);
};
void main()
{
sample s;
s.getdata();
s.display();
getch();
}
Solution
#include<iostream.h>
#include<conio.h>
Page 33
Unix, C & C++
int a=10;
void main()
{
int a=15;
cout<<a<<::a<<endl;
::a=20;
cout<<a<<::a;
getch();
}
5. Write a program to get the input from the user and display the out what he\she has
entered.
Solution
#include<iostream.h>
#include<conio.h>
void main(void)
{
char a[999];
cout << "Type something :" << endl;
cin >> a;
cout << "You have typed :" << a << endl;
getch();
}
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a=5,x;
int b=6;
x=++a+b++;
cout<<x<<a<<b;
getch();
}
7. Write a program to convert the alphabet from lower case to uppercase.
Page 34
Unix, C & C++
Solution
#include<iostream.h>
#include<ctype.h>
#include<conio.h>
void main(void)
{
Page 35
Unix, C & C++
Solution
#include<iostream.h>
#include<conio.h>
class c
{
volatile x;
public:
void show()
{
x=9.899;
cout<<x;
}
};
void main()
{
c c1;
c1.show();
getch();
}
9. Write a program to input a text string and count the length of it using get() and
put().
Solution
#include<iostream.h>
#include<conio.h>
main()
{
int count = 0;
char c;
cout<< "Input text\n";
cin.get(c);
while(c != '\n')
{
cout.put(c);
Page 36
Unix, C & C++
count ++;
cin.get(c);
}
cout <<"\nNumber of characters = "<< count << "\n";
getch( );
}
10. Write a program to multiply numbers by taking assigned default values (First
assign default values 3 and 10 and then substitute 3 with 4 and 10 and then substitute
4&10 with 4 and 5).
Solution
#include<iostream.h>
#include<conio.h>
int multiply ( int x=3, int y=10);
void main(void)
{
int iresult;
iresult = multiply();
cout << "\n When using multiply ( ) : iresult="<< iresult << endl;
iresult = multiply( 4 );
cout << "\n When using multiply (4 ) : iresult="<< iresult << endl;
iresult = multiply( 4, 5 );
cout << "\n When using multiply (4 5 ) : iresult="<< iresult << endl;
getch( );
}
int multiply ( int x, int y)
{
return x*y;
}
Page 37
Unix, C & C++
When you execute the program you get an error j is not declared. But you have declared
j. The problem is that you have declared the variable j with in the for( ) loop. Thus the
scope is only in between the braces({}) of the for () loop. Declare the j variable outside
the for() loop as you have declared the i variable.
12. Write a program to display two variables by declaring them as local and global
variables and show the result has follows.
Solution
#include<iostream.h>
#include<conio.h>
int a=200;
void main (void)
{
cout<<"\n Results :";
cout<<"\n ----------";
int a =100;
cout<<"\n Local variable is :"<<a;
cout<<"\n global variable is :"<< a<<endl;
}
13. Find if any error exists and correct the parameter list.
Solution
Since there cannot be two identical list of Parameters even if the returned values
is different. So we can change the parameter list as follows.
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
float a;
Page 38
Unix, C & C++
char b;
do
{
cout<<"Enter a number:";
cin>>a;
if(a= =0)
break;
cout<<"Inverse of the number is :"<<1/a;
cin>>b;
}while(b!='n');
getch( );
}
15. Write a program to find the square of the numbers less than 100.
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
char b='y';
do
{
cout<<"Enter a number :";
cin>>a;
if(a>100)
{
cout<<"The number is greater than 100, enter another number :"<<endl;
continue;
}
cout<<"The square of the numbers is :"<<a*a<<endl;
cout<<"Do you want to enter another (y/n)";
cin>>b;
}while(b!='n');
getch( );
}
Solution
#include<iostream.h>
#include<conio.h>
void main()
Page 39
Unix, C & C++
{
int i;
for(i=0;i<10;i++);
cout<<i;
getch();
}
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a=12,b;
b=++a;
cout<<"a ="<<a<<"b="<<b<<endl;
getch( );
}
18. Write a program to get the input from the user and check if the input value is "y"
or "n", if it is other than these values return a message " Invalid option". If it is right
choice return a message "Right choice".
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
char a;
cout<<"Enter y or n";
cin>>a;
if(a = = 'y' | | a = = 'n' )
{
cout<<"Right choice";
}
else
{
cout<<"Invalid choice";
}
getch();
}
Page 40
Unix, C & C++
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
float a;
cout<<"Enter the temperature in Farenheir:";
cin >>a;
float b=(a-32)*5/9;
cout<<"The equivalent temperature in Celsius is:"<<b<<endl;
getch( );
}
20. Write a program to input two numbers and find the largest of them using nesting
member function.
Solution
#include<iostream.h>
#include<conio.h>
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
int set :: largest(void)
{
if(m>=n)
return (m);
else
return(n);
}
void set :: input(void)
{
cout<<"Input values of m and n" << "\n";
cin >> m >>n;
}
void set :: display(void)
{
Page 41
Unix, C & C++
21. Write a program to calculate the square of the first ten natural numbers.
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
for(a=1;a<=10;a++)
{
cout<<a*a<<" ";
}
getch( );
}
Page 42
Unix, C & C++
23. Write a program to accept two numbers and find the greatest number among
them.
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
cout<<"Input the first number:";
cin>>a;
cout<<"Input the second number:";
cin >>b;
if(a>b)
{
cout<<"a is greater than b" <<endl;
}
else
{
cout<<"b is greater than a" <<endl;
}
getch();
}
24. Write a program to find whether the input number is an even or odd number.
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
cout<<"Enter a number:";
cin>>a;
if((a!=0)&&((a%2) = = 0))
{
cout<<"Even number";
}
else
{
cout<<"Odd number or the number is Zero";
}
getch();
}
Page 43
Unix, C & C++
25. Write a program to accept strings into a two-dimensional array and display them
(User can enter five strings).
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
char name[5][21];
int i;
for(i=0; i<5; i++)
{
cout<<"Enter Name "<<(i+1)<<" : ";
cin>>name[i];
}
for (i=0; i<5; i++)
{
cout<<"Name"<<(i+1)<<" is : "<<name[i]<<endl;
}
getch();
}
26. Write a program that calculates the sum of two or three numbers.
(The first two numbers are 25 35 and the second set of numbers 12 13 45)
Solution
#include<iostream.h>
#include<conio.h>
int add(int, int);
int add(int, int, int);
void main()
{
cout<<"Sum of two Numbers is : " << add(25,35)<<endl;
cout<<"Sum of three Numbers is : " << add(12,13,45)<<endl;
getch();
}
int add(int a, int b)
{
return a+b;
}
int add( int a, int b, int c)
{
return a+b+c;
}
Page 44
Unix, C & C++
27. Write a program to print hi followed by the name of the user entered at the
command line.
Solution
#include<iostream.h>
#include<conio.h>
void main ( int argc, char *argv[])
{
if (argc!=2)
{
cout<<" You have not typed your name"<<endl;
}
else
{
cout<<" Hi "<<argv[1]<<endl;
}
getch();
}
28. Write a program to input three students Name and Age and display them.
Solution
#include<iostream.h>
#include<conio.h>
class student
{
char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
void student :: getdata(void)
{
cout << "Enter Name :";
cin >> name;
cout << "Enter Age:";
cin >> age;
}
void student :: putdata(void)
{
cout << "Name :" << name << "\n";
cout << "Age :" << age << "\n";
}
Page 45
Unix, C & C++
29. Write a program to find the mean of two numbers (25,40) using the friend
function.
Solution
#include<iostream.h>
#include<conio.h>
class sample
{
int a;
int b;
public:
void setvalue ( ) { a = 25; b =40; }
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/2.0;
}
main()
{
sample x;
x.setvalue();
cout << "Mean value = " << mean(x) << "\n";
getch();
}
Page 46
Unix, C & C++
30. Write a program to display Roll number and marks of Tamil and English subjects
and the total marks scored, using multilevel inheritance.
Solution
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int roll_number;
public:
void get_number(int);
void put_number(void);
};
void student :: get_number(int a)
{
roll_number =a;
}
void student :: put_number()
{
cout << "Roll Number :" << roll_number << "\n";
}
class test : public student
{
protected:
float tamil;
float english;
public:
void get_marks(float, float);
void put_marks(void);
};
void test :: get_marks(float x, float y)
{
tamil = x; english=y;
}
void test :: put_marks()
{
cout<<"Marks scored in Tamil = " <<tamil << "\n";
cout<<"Marks scored in English = " <<english << "\n";
}
class result : public test
{
float total;
public:
Page 47
Unix, C & C++
void display(void);
};
void result :: display(void)
{
total = tamil+english;
put_number();
put_marks();
cout<<"Total = " << total << "\n";
}
main()
{
result student1;
student1.get_number(222);
student1.get_marks(90.0, 90.0);
student1.display();
getch();
}
Do it yourself: -
1. Write a program to input city names and ask a question from the user whether he
wants to add more cities.
2. Write a program to find the volume of a cube, cylinder, and rectangle. For the given
values (cube length = 10, cylinder radius =2.5 and height = 8, rectangle length = 100,
breath = 75 and height = 15).
3. Write a program to perform the following, a vendor wants to place an order with a
dealer to purchase provision items, by providing the following details such as the
code number and price of each item. The user has to perform adding an item to the
list deleting an item from the list and printing the total value of the order.
The output of the screen should be as follows (ask the option from the user)
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
Page 48
Unix, C & C++
6. Write a program to accept the invoice number and rate of an item from the user and
display “ The amount for the Invoice no (Invoice no) is amount.
7. Write a program to find who is the elder person from the given data and display their
name and age as given in the out put format.
Name Age
1. vijay 27
2. sundar 28
3. saro 32
Elder person is
Name :
Age:
Page 49
Unix, C & C++
Solved Examples: -
Solution
Solution
The pwd command is used to display the full path of the current working
directory.
3. Create a new directory called sample in the current working directory and under
the sample directory create a new directory called test.
Solution
mkdir sample
cd sample
mkdir test
4. What is the command used to change from the current working directory to the
parent directory.
Solution
5. What is the command to list all the files and directories under current working
directory?
Solution
ls
Output
$ pwd
/usr/student/sample
Page 50
Unix, C & C++
$ ls
test
6. Give the command to display the name of your terminal file.
Solution
who am I command displays the name of your terminal file. The command
displays:
a) login name
b) user’s terminal file name
c) day and the time user logged in
Output
$ who am I
student ttyp0 Jun 27 11:06
7. Give the command to display the message “Error Message.. keep the cursor on
the same line” along with a beep sound.
Solution
Output
8. Write a shell script called Sample that asks the user to enter their name, and then
display the message
HI (User name)….! Solve the problem!
Solution
Output
$ sh s8
Hi student......!
Solve the problem...!
Page 51
Unix, C & C++
9. Give the command to provide execute permission for the owner of the file. The
name of the file is sample_test.
Solution
$ ls -l sample_test
-rw-r--r-- 1 student group 39 Jun 27 11:44 sample_test
$ chmod u+x sample_test
$ ls -l sample_test
-rwxr--r-- 1 student group 39 Jun 27 11:44 sample_test
10. How can a user set the Unix prompt to – Type here:
Solution
PS1=“Type here :”
Output
11. How can the user reset the prompt to the $symbol?
Solution
PS1=“$”
Output
12. Write a script that checks if an argument is passed and prints the number of
arguments passed. The script exits without printing anything if the argument string is
empty.
Solution
if test $# = 0
then
exit
else
Page 52
Unix, C & C++
Output
$sh s12
$sh s12 God
No of arguments entered: 1
$sh s12 God Great
No of arguments entered: 2
13. What does the following shell script do?
if test $# != 1
then echo “Invalid number of arguments”
exit
else
echo “continuing execution”
fi
Solution
Output
$sh s13
Invalid number of arguments
$sh s13 abc
continuing execution
$sh s13 a b
Invalid number of arguments
14. Write a shell script which will accept two strings and compare the two to see if
the two strings are same. If they are same, the message “Strings are equal” should be
displayed. If the 2 strings are different, the message “Strings are not equal” should
be displayed.
Solution
Page 53
Unix, C & C++
Output
$sh s14
Enter first string:God
Enter second string:Good
Strings are not equal
$sh s14
Enter first string:Great
Enter second string:Great
Strings are equal
15. State what the following shell script called test1 does.
Solution
The shell script test1 takes 2 filenames as arguments. The contents of the first file
is displayed after specifying the message “Display contents of the file” followed by the
name of the first file. The script copies the contents of the first file to the second file and
displays the message “File copied successfully”.
Output
$cat s
I am fine
$cat m
cat: cannot open m: No such file or directory (error 2)
$sh test1 s m
Display contents of file: s
I am fine
File copied successfully
$cat m
I am fine
Page 54
Unix, C & C++
16. Create a file called sample_file with the content “This is a sample file” and close
the file.
Solution
17. Write a command to redirect the contents of the file sample_file to test_file.
Solution
18. Create two files sample1 and sample2. In sample1 enter the following content
“This is a sample file for test”
In the sample2 file enter the following content
“This is a Sample file for test”
Compare the two files and find where they differ
Solution
Output
Solution
Page 55
Unix, C & C++
20. Two files are identical from lines 1 to 50. However, one of the files contain a
black line at the end of the file. Will the cmp command indicate that the two files are
different?
Solution
21. Give the command to check if a file called test is present in the current directory
or any of its subdirectories.
Solution
22. Give the command to delete all the files in a subdirectory called sub that were
accessed within a day.
Solution
Output
$ls sub
a
b
$find ./sub -atime -1 -exec rm {} \;
rm: ./sub directory
$ls sub
$
23. What is the command used to find all the subdirectories in the current directory?
Solution
Output
Page 56
Unix, C & C++
Solution
The {}are missing after rm, the characters \;are also missing.
25. Give the command to sort a file called phone_numbers and redirect the sorted list
to a new file called phone_list.
Solution
$cat phone_numbers
Amar 4568998
John 2344545
Bala 2345667
Mala 4567578
$sort phone_numbers > phone_list
$cat phone_list
Amar 4568998
Bala 2345667
John 2344545
Mala 4567578
26. Write a script to get an input from the user to run unix commands and use the case
structure to display the commands. If the user wants to exit without entering any
option in the case provide an exit to exit from the program.
Solution
while true
do
echo “Enter the number of the program you wish to run”
echo “(press ‘q’ to exit)”
echo “1 date 2 who”
echo “3 ls 4 pwd”
read choice
case $choice in
1) date;;
2) who;;
3) ls;;
Page 57
Unix, C & C++
4) pwd;;
q)break;;
*)echo” Choice is not in the list”
esac
done
Output
$sh choose
Enter the number of the program you wish to run
(press 'q' to exit)
1 date 2 who
3 ls 4 pwd
1
Thu Jun 27 14:01:26 IST 2002
Enter the number of the program you wish to run
(press 'q' to exit)
1 date 2 who
3 ls 4 pwd
2
student ttyp0 Jun 27 11:32
Enter the number of the program you wish to run
(press 'q' to exit)
1 date 2 who
3 ls 4 pwd
3
test
choose
Enter the number of the program you wish to run
(press 'q' to exit)
1 date 2 who
3 ls 4 pwd
4
/usr/student/Ex/sub
Enter the number of the program you wish to run
(press 'q' to exit)
1 date 2 who
3 ls 4 pwd
q
$
Page 58
Unix, C & C++
Solution
Output
28. Write a shell script to check if the name of a person is present in 2 files
Solution
Output
$cat L1
Vijai
Ajai
Haresh
$cat L2
Rajesh
Vijai
Satish
$sh s28
Enter the file names
L1
L2
The list of names present in both the files
Vijai
Solution
Page 59
Unix, C & C++
Output
$cat demo
How are you?
I am fine.
$sh s29
Enter the name of the file to be edited
demo
Enter the character to be searched
a
Enter the character to be substituted
#
File after Modification
How #re you?
I #m fine.
30. Write a shell script to accept a set of names and display them in alphabetical order
Solution
Output
$sh s30
Page 60
Unix, C & C++
Solution
Output
Solution
Output
$sh s32
Enter a String
Welcome
emocleW
Page 61
Unix, C & C++
Solution
Output
$sh s33
Enter a number
5
Factorial of 5 is 120
Solution
Output
$sh s34
Enter a number
3
The number is positive
$sh s34
Enter a number
Page 62
Unix, C & C++
-1
The number is negative
$sh s34
Enter a number
0
The entered number is zero
Solution
Output
$sh s35
Enter the name of the directory to be deleted
sub
$cd sub
sub: does not exist
36. Write a shell script to list the files in a directory
Solution
Output
$sh s36
Enter the name of the directory
lab
m45
m46
m48
m49
s
Page 63
Unix, C & C++
37. Write a shell script to check if the string entered is name of a directory
Solution
Output
$sh s37
Enter the name of the directory
first
It is not a name of the directory
$sh s37
Enter the name of the directory
lab
It is the name of the directory
38. Write a shell script to check if the character entered is a vowel or not
Solution
Output
$sh s38
Enter a character
a
It is a vowel
$sh s38
Page 64
Unix, C & C++
Enter a character
q
Not a vowel
39. Write a shell script to check if arguments are given to a script or not
Solution
if test -z "$*"
then
echo "No argument"
else
echo "Arguments are : $*"
fi
Output
$sh s39
No argument
$sh s39 1 2 3
Arguments are : 1 2 3
40. Write a script program to accept two numbers and find the sum.
Solution
$sh s40
Enter 2 numbers
5
3
Sum is 8
Page 65
Unix, C & C++
Solution
for i in 1 2 3 4 5
do
j=1
while [ $j -le $i ]
do
echo -n $i
j=`expr $j + 1`
done
echo
done
Solution
$ls -l a
-rwxr--r-- 1 student group 0 Jun 26 15:58 a
$sh s42
Enter a file name
a
You can edit the file
$chmod u-w a
$ls -l a
-r-xr--r-- 1 student group 0 Jun 26 15:58 a
$sh s42
Enter a file name
a
### You cannot edit ###
Solution
Page 66
Unix, C & C++
read s
echo "Destination file :\c"
read d
cp $s $d
Output
$cat a
God is Great
$cat s
$sh s43
Source file :a
Destination file :s
$cat s
God is Great
44. Write a shell script to accept a number from 0 to 9 and display the same number
in words.
Solution
$ sh s44
Enter a number from 0 to 9
5
five
$sh s44
Enter a number from 0 to 9
w
invalid character
Page 67
Unix, C & C++
45. Write a shell script to execute date and then display good morning, good
afternoon or good evening as appropriate.
Solution
echo `date`
hour=`date|cut -c12-13`
echo $hour
if [ $hour -gt 0 -a $hour -lt 12 ]
then
echo "Good Morning"
elif [ $hour -gt 12 -a $hour -lt 14 ]
then
echo "Good Afternoon"
else
echo "Good Evening"
fi
Output
$sh s45
Thu Jun 27 15:59:14 IST 2002
15
Good Evening
46. Write a shell script to look for a person’s phone number in the phone book.
Solution
if [ $# -ne 1 ]
then
echo "usage : Enter name "
else
output=` grep $1 /usr/student/test/phone_book `
l=` echo $output | wc -c`
if [ l != 0 ]
then
echo "$output"
fi
fi
Output
$cat ./test/phone_book
abc 12 asdsafsdfsdf
Page 68
Unix, C & C++
def 13 sdsdhsdfhshdfdfjhkjf
hij 14 dfsdfsfsdfsdfdfdf
$sh s46
usage : Enter name
$sh s46 abc
abc 12 asdsafsdfsdf
$sh s46 xyz
47. Write a shell script that displays two lines of stars with an interval of 60 seconds
between each display.
Solution
a=1
while [ $a -lt 80 ]
do
echo -n “*”
a=`expr $a + 1`
done
sleep 60
a=1
while [ $a -lt 80 ]
do
echo -n “*”
a=`expr $a + 1`
done
Output
$sh s47
*********************************************************************
*********************************************************************
48. Write a shell script that converts all the lower case alphabets in the file s into
upper case alphabets and display the result.
Solution
$cat s
God is Great
$tr a-z A-Z < s
GOD IS GREAT
Page 69
Unix, C & C++
49. Write a shell script to remove a file called sam from the current directory and
move it to a subdirectory called sub.
Solution
mv sam ./sub
Output
$ls sa*
sam
sample_file
sat
$ls ./sub
s
$mv sam ./sub
$ls sa*
sample_file
sat
$ls ./sub
s
sam
Solution
$sh s50
Enter User Name
student
### student already exists ###
### abort ###
$sh s50
Enter User Name
Stud
$
Page 70
Unix, C & C++
Exercise: -
Page 71