Sunteți pe pagina 1din 71

Unix, C & C++

‘C’
Lab Manual

Page 1
Unix, C & C++

'C' Lab Manual


Examples: -

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:
*
**

2. Write a function to accept and display a string.

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:

i. Your name is:


ii. (name)
iii. Your address is:
iv. (address)

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:

Enter your Name to a maximum of 20 characters


Macmillan
Enter your Address to a maximum of 30 characters
5, Dale Street, New York
Your Name is:
Macmillan
Your Address is:
5, Dale Street, New York

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++

Output:(When a wrong character is entered)


Enter a character
a
Character is not A
Output:(When a right character is entered)
Enter a character
A
Character is A

7. Write a nested if..else construct to check if an input character is in upper-case or


lower-case.

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++

8. Write a program that checks whether an input character is a digit or not.

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:

Enter a character in lower case:


e
vowel e

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:

Enter Grade Code:


2
DA percentage is 80%

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

13. Write a function to accept a character and display it 40 times.

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:

Enter y/n (Yes/No)


m
Invalid input
Enter y/n (Yes/No)
3
Invalid input
Enter y/n (Yes/No)
y

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:

Enter a number(999 to quit)


11
Enter a number(999 to quit)
14
Enter a number(999 to quit)
78
Enter a number(999 to quit)
19
Enter a number(999 to quit)
999
The sum of 4 numbers is :122

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:

The string has been initialized


Enter Y/N for deleting a file no# 1
y
Enter Y/N for deleting a file no# 2
n
Enter Y/N for deleting a file no# 3
Enter Y/N for deleting a file no# 4

Page 16
Unix, C & C++

n
Enter Y/N for deleting a file no# 5
y

The status Report:


Delete file no# 1 : y
Delete file no# 2 : N
Delete file no# 3 : N
Delete file no# 4 : N
Delete file no# 5 : y

21. Write a function to convert a character string into lower case

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:

Enter a string (upto 100 characters)


The Little Brown Fox Jumped Over a pussy
The converted string is the little brown fox jumped over a pussy

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:

Enter string#1(upto 100 chrs)


Hello
Entering string#2(upto 100 chrs)
Hell
Larger string :Hello

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:

Enter no.1,(0 to terminate)


5
Enter no.2,(0 to terminate)
9
Enter no.3,(0 to terminate)
14
Enter no.4,(0 to terminate)
23
Enter no.5,(0 to terminate)
78
Enter no.6,(0 to terminate)
19
Enter no.7,(0 to terminate)
0
Number 1is 5
Number 2is 9
Number 3is 14
Number 4is 23
Number 5is 78
Number 6is 19
Lowest number is 5
Highest number is 78

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

25. Write a program to determine the length of a string.

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:

Enter the first StringGod


Enter the second StringGod
The two strings are the same

Output2:

Enter the first StringGood


Enter the second StringFood
The two strings are not the same

Page 21
Unix, C & C++

27. Write a program to copy a formatted string into a character array.

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

28. Write a program to search for a character in the input string.

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

Directory not found


Function not found
Missing error
Data type error

Solution
#include<stdio.h>
#define Errors 4
char err_msg[][29]={

Page 24
Unix, C & C++

“Directory not found”,


“Function not found”,
“Missing error”,
“Data type error “
};
main()
{
int err_no;
for(err_no=0;err_no<Errors;err_no=err_no+1)
{
printf(“\nError message %d is :%s”,err_no+1,err_msg[err_no]);
}
}

Output:

Error message 1 is : Directory not found


Error message 2 is : Function not found
Error message 3 is : Missing error
Error message 4 is : Data type error

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);

33. Declare a structure as follows


Employee Number (3 character)
Employee First Name (20 characters)
Employee Last Name (20 characters)
Employee Initial (1 character)
Write a code to input the names of 3 employees and print out their initials along
with their employee number. The employee number should be assigned
automatically in a serial order.

Solution
#include<stdio.h>
struct
{
char eno [6];
char efname [21];

Page 25
Unix, C & C++

char elname [21];


char einitial;
} empstruct[3];

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

EMP#1 : abc d efg

EMP#2 : hij k lmn

EMP#3 : opq r stu

34. Write a function to update salary with the following data

Solution

If salary is Increment salary by

< Rs6000 Rs 1000


between Rs 6000 and Rs10000 Rs 2000
>= Rs10000 Rs 3000

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 :

Enter Salary : 12000


15000.000000

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

The program gives an unreachable code warning.

37. Find the error in the following code.

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);
}

Save the file as cla.c


Output:

Consider file1.txt contains:


I am fine.
Consider file2.txt contains:
How are you?

Page 29
Unix, C & C++

In the command prompt type as follows:

C:> Cla file1.txt file2.txt

Now the file1.txt contains


I am fine

File2.txt contains
How are you?
I am fine.

Exercise: -

1. Write a program to find out the product of digits of a three-digit number.

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.

4. Write a program to find the factorial of a number.

5. Write a program to display all even numbers from 1 to 100.

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.

8. Write a program to find out the number of occurrences of a particular character in


a string.

9. Write a program to accept a string and check if it is a palindrome or not.

10. Write a program to find out if a number is Armstrong number or not.

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();
}

2. Write a program to find the average of two numbers.

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 sample :: getdata(void)


{
cout << " Enter your Name : " ;
cin >> name;
cout << " Enter your Age :";
cin >> age;
cout << " Enter your Address :";
cin >> add;
cout << " Enter your Phone Number :";
cin >> phone;
}

void sample :: display(void)


{
cout << "\n Name : " << name;
cout << "\n Age : " << age;
cout << "\n Address : " << add;
cout << "\n Phone Number : " << phone;
}

void main()
{
sample s;
s.getdata();
s.display();
getch();
}

4. What is the output of the following code?

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();
}

6. What is the output of the following code?

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++

char mydata = 'a';


char s= toupper(mydata);
cout <<" My data in ASCII is : " << s << "." << endl;
getch();
}

8. What is the output of the following code?

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;
}

11. Find the error in the program and explain it.


Solution
#include <iostream.h>
void main()
{
for (int i=1; i<3; i++)
{
int j=3;
cout << i;
}
cout<<i;
cout<<j;
}

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

Int showit ( int s);


Float showit ( int s);

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.

Int showit ( int s, int t);


Int showit ( int s);

14. Write a program to find the inverse of a number.

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( );
}

16. Find the output of the following statements.

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();
}

17. Find the output of the following program

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++

19. Write a program to convert temperature from farenheit to Celsius.

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++

cout<<"Largest value ="<< largest( ) << "\n";


}
main( )
{
set A;
A.input( );
A.display( );
getch( );
}

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( );
}

22. Write a program using function to add two numbers.


Solution
#include<iostream.h>
#include<conio.h>
int add(int,int);
void main()
{
int a,b,c;
cout<<"Enter two numbers:"<<endl;
cin>>b;
cin>>c;
a=add(b,c);
cout<<"The sum of the two numbers is :" <<a<<endl;
getch();
}
int add(int x, int y)
{
return x+y;
}

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++

const int size = 3;


main()
{
student info[3];
for(int i=0; i<size; i++)
{
cout<<"\nDetails of Students" << (i+1) << "\n";
info[i].getdata();
}
cout << "\n";
for (int i=0; i< size; i++)
{
cout <<"\nStudent"<< (i+1) << "\n";
info[i].putdata();
}
getch();
}

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)

You can do the following : Enter appropriate number

1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit

4. Write a program to construct a matrix of size m x n.

5. Write a program to swap the input numbers.

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

Out put format

Elder person is
Name :
Age:

Page 49
Unix, C & C++

Unix Lab Manual

Solved Examples: -

1. Give the command to create a password for a new user.

Solution

The passwd command is used to create password for new user.

2. What is the command used to display the current working directory.

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

cd .. is used to change to parent directory.

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

echo "Error Message... Keep the cursor on the same line\C\007"

Output

$ echo "Error Message... Keep the cursor on the same line\C\007"


Error Message... Keep the cursor on the same line\C

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

echo “Hi ${LOGNAME}……!”


echo “Solve the problem…!”

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

chmod u+x sample_test


Output

$ 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

$ PS1="Type here :"


Type here :

11. How can the user reset the prompt to the $symbol?

Solution

PS1=“$”

Output

Type here :PS1="$"


$

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++

echo “No of arguments entered: $#”


fi

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

Checks the number of arguments entered. If the number of arguments entered is


not 1, then the script displays “ Invalid number of arguments” and exits. Otherwise it
prints “Continuing Execution”

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

echo “Enter first string:\c”


read str1
echo “Enter second string:\c”
read str2
if test $str1 = $str2

Page 53
Unix, C & C++

then echo “Strings are equal”


else echo “Strings are not equal”
fi

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.

echo “Display contents of file: $1”


cat $1
cp $1 $2
echo “File copied successfully”

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

$cat > sample_file <enter>


This is a sample file <enter><ctrl +d>

17. Write a command to redirect the contents of the file sample_file to test_file.

Solution

cat sample_file > test_file


Output

$cat sample_file > test_file


$cat test_file
This is a sample file

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

cmp sample1 sample2

Output

$cat > sample1


This is a sample file for test
$cat > sample2
This is a Sample file for test
$cmp sample1 sample2
sample1 sample2 differ: char 11, line 1

19. State whether the following statement is true


If 2 files differ in five lines, then the cmp command will display all the
differences?

Solution

No, only the first difference is displayed.

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

Yes, because a blank space is also a character.

21. Give the command to check if a file called test is present in the current directory
or any of its subdirectories.

Solution

find . –name test –print


Output

$find . -name test -print


./test

22. Give the command to delete all the files in a subdirectory called sub that were
accessed within a day.
Solution

find ./sub -atime -1 -exec rm {} \;

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

find . –type d –print

Output

$find . -type d -print


.
./sub

Page 56
Unix, C & C++

24. Find the errors in the following commands

find . –name “ram*” –exec rm

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

sort phone_numbers > phone_list


Output

$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
$

27. Give the command to display the following.

i. The day is : (dd)


ii. The weekday is :( name of weekday)

Page 58
Unix, C & C++

Solution

a) date "+ The day is :%d"


b) date "+ The weekday is : %a"

Output

$date "+ The day is :%d"


The day is :27
$date "+ The weekday is :%a"
The weekday is :Thu

28. Write a shell script to check if the name of a person is present in 2 files

Solution

echo "Enter the file names"


read a
read b
echo " The list of names present in both the files"
sort $a $b | uniq -d
#uniq -d $a $b

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

29. Write a shell script to replace a particular character of the file.

Solution

echo " Enter the name of the file to be edited"


read f

Page 59
Unix, C & C++

echo " Enter the character to be searched"


read s
echo " Enter the character to be substituted"
read w
echo " File after Modification"
cat $f | tr $s $w

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

echo " enter the number of names"


read n
echo " Enter the names"
if test -f "xymn345man23"
then
rm xymn345man23
fi
while test $n -gt 0
do
read s
echo $s | cat >> xymn345man23
n=`expr $n - 1`
done
echo
echo " The Alphabetical order for the names enter is "
sort xymn345man23

Output

$sh s30

Page 60
Unix, C & C++

enter the number of names


3
Enter the names
Usha
Vidya
Praveena

The Alphabetical order for the names enter is


Praveena
Usha
Vidya
31. Write a shell script to find the home directory of the user.

Solution

echo "Enter the user name"


read u
echo "Home directory of $u is :"
echo `grep $u /etc/passwd | cut -d: -f6`

Output

Enter the user name


student
Home directory of student is :
/usr/student
32. Write a shell script to reverse a string

Solution

echo " Enter a String"


read s
z=`echo $s | wc -m`
while test $z -gt 0
do
z=`expr $z - 1`
echo -n `echo $s | cut -c$z`
done
echo

Output

$sh s32
Enter a String
Welcome
emocleW

Page 61
Unix, C & C++

33. Write a shell script to find the factorial of a number

Solution

echo "Enter a number"


read n
f=1
i=1
while test $i -le $n
do
f=`expr $f \* $i`
i=`expr $i + 1`
done
echo " Factorial of $n is $f"

Output

$sh s33
Enter a number
5
Factorial of 5 is 120

34. Write a shell script to check if a number is positive negative or zero

Solution

echo " Enter a number"


read n
if test $n -eq 0
then
echo "The entered number is zero"
elif test $n -lt 0
then echo "The number is negative"
else
echo " The number is positive"
fi

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

35. Write a shell script to delete a directory

Solution

echo " Enter the name of the directory to be deleted"


read s
c=`ls $s | wc -l`
if test $c = 0
then
rmdir $s
else
rm -r $s
fi

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

echo "Enter the name of the directory"


read d
ls $d

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

echo " Enter the name of the directory"


read s
if [ -d $s ]
then
echo " It is the name of the directory "
else
echo " It is not a name of the directory "
fi

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

echo "Enter a character"


read a
case $a in
a) echo "It is a vowel";;
e) echo "It is a vowel";;
i) echo "It is a vowel";;
o) echo "It is a vowel";;
u) echo "It is a vowel";;
*) echo "Not a vowel";;
esac

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

echo "Enter 2 numbers "


read a
read b
c=`expr $a + $b`
echo "Sum is $c"
Output

$sh s40
Enter 2 numbers
5
3
Sum is 8

41. Write a shell script to display the following output


1
22
333
4444
55555

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

42. Write a script to check if a file is writeable

Solution

echo "Enter a file name"


read h
if [ ! -w $h ]
then
echo "### You cannot edit \007###"
else
echo "You can edit the file"
fi
Output

$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 ###

43. Write a shell script to copy files

Solution

echo "Source file :\c"

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

echo "Enter a number from 0 to 9 "


read r
case $r
in
0) echo zero;;
1) echo one;;
2) echo two;;
3) echo three;;
4) echo four;;
5) echo five;;
6) echo six;;
7) echo seven;;
8) echo eight;;
9) echo nine;;
*) echo invalid character;;
esac
Output

$ 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

tr a-z A-Z < s


Output

$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

50. Write a shell script to see if a user already exists.

Solution

echo "Enter User Name"


read userid
if grep "^$userid:" /etc/passwd > /dev/null
then
echo "### $userid already exists ###"
echo "### abort ###"
exit
fi
Output

$sh s50
Enter User Name
student
### student already exists ###
### abort ###
$sh s50
Enter User Name
Stud
$

Page 70
Unix, C & C++

Exercise: -

1. Write a shell script to swap two numbers


2. Write a shell script to move a file in one directory to another directory
3. Write a shell script to display the following output
1
12
123
1234
12345

4. Write a shell script to find the sum of numbers from 1 to 10


5. Write a shell script to display all the names of the files starting with the letter s the
current directory.
6. Write a shell script to accept a number from 1 to 12 and display the corresponding
month (1  January, 2  February, … , 12  December)
7. Write a shell script to generate a Fibonacci series
8. Write a shell script that counts the number of words in a file
9. Write a shell script to find the greatest of 3 numbers
10. Write a shell script that asks for the capital of India and repeats the question until
the user gives the correct answer.

Page 71

S-ar putea să vă placă și