Download - Unix C C++ Lab MCA Sem 1 and 2
Unix, C & C++
‘C’Lab Manual
Page 1
Unix, C & C++
'C' Lab ManualExamples: -
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 charactersWelcomeWelcome
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:
1a1a
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 charactersCharlesBabbageHello. 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 charactersMacmillanEnter your Address to a maximum of 30 characters5, Dale Street, New YorkYour Name is:MacmillanYour 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");elseputs("Character is not A");}
Page 4
Unix, C & C++
Output:(When a wrong character is entered)
Enter a characteraCharacter is not A
Output:(When a right character is entered)
Enter a characterACharacter 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 characteraLower case
Output 2:
Enter a characterGUpper 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:5The 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");elseputs("The character is not a vowel");}
Page 6
Unix, C & C++
Output:
Enter a character in lower case:evowel 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:2DA 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.
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:
Menu1. Masters2. Transaction3. Reports4. Exit
your choice :1choice is 1
Page 8
Menu1. Master2. Transaction3. Reports4. Exit
Your Choice :
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 characterqEnter a characteraEnter a characterpEnter a charactereEnter 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 stringWhere there is a will there is a wayEnter the number of times5Where there is a will there is a wayWhere there is a will there is a wayWhere there is a will there is a wayWhere there is a will there is a wayWhere 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)mInvalid inputEnter y/n (Yes/No)3Invalid inputEnter 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");elseputs("count of lower-case and upper-case characters is equal"); }
Output:
Enter a characteraEnter a characterAEnter a characterSEnter a characterBEnter a characterMEnter a characteryEnter a character@the input is not an alphabetEnter a character2the input is not an alphabetEnter a character+the input is not an alphabetEnter a characterzcount 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)11Enter a number(999 to quit)14Enter a number(999 to quit)78Enter a number(999 to quit)19Enter a number(999 to quit)999The 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 number5Enter a number-2Enter a number3Enter a number4Enter a number-1Enter a number7Enter a number2Enter a number1The 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 initializedEnter Y/N for deleting a file no# 1yEnter Y/N for deleting a file no# 2nEnter Y/N for deleting a file no# 3Enter Y/N for deleting a file no# 4
Page 16
Unix, C & C++
nEnter Y/N for deleting a file no# 5y
The status Report:Delete file no# 1 : yDelete file no# 2 : NDelete file no# 3 : NDelete file no# 4 : NDelete 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 pussyThe 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);elseprintf("strings are equal\n");}
Output:
Enter string#1(upto 100 chrs)HelloEntering string#2(upto 100 chrs)HellLarger 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)5Enter no.2,(0 to terminate)9Enter no.3,(0 to terminate)14Enter no.4,(0 to terminate)23Enter no.5,(0 to terminate)78Enter no.6,(0 to terminate)19Enter no.7,(0 to terminate)0Number 1is 5Number 2is 9Number 3is 14Number 4is 23Number 5is 78Number 6is 19Lowest number is 5Highest 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 :WelcomeLength 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");elseprintf("The two strings are the same");}
Output1:
Enter the first StringGodEnter the second StringGodThe two strings are the same
Output2:
Enter the first StringGoodEnter the second StringFoodThe 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
23The 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:WelcomeEnter a character to search for :echaracter :e found at 2 positioncharacter :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:
37Total 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 :2Enter power to raise to :55th power of 2 is 32
31. Write a program to display the error messages shown in the table along with the error number.
Solution
#include<stdio.h>#define Errors 4char err_msg[][29]={
Page 24
Error Number Error Message
Directory not foundFunction not foundMissing errorData type error
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 foundError message 2 is : Function not foundError message 3 is : Missing errorError 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 followsEmployee 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#1Enter the employee name (firstName Initial lastName):abc d efgEmployee Number:EMP#2Enter the employee name (firstName Initial lastName):hij k lmnEmployee Number:EMP#3Enter 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 1000between 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);elsereturn (sal+3000);}main(){ float sl, s; printf("Enter Salary : "); scanf("%f", & sl); s = sum_bal(sl); printf("%f", s);}
Output :
Enter Salary : 1200015000.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-125Sign : -Abs. Value: 125
Output 2:
Enter a Number456Sign : +Abs. Value: 5636. 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 displayUsage : append file1file2
b. If the file to be read cannot be opened then displayCannot 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-caseb. 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 272. sundar 283. saro 32
Out put format
Elder person isName :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++
$ lstest
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 nameb) user’s terminal file name c) day and the time user logged in
Output
$ who am Istudent 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 s8Hi 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_testOutput
$ 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 $# = 0thenexitelse
Page 52
Unix, C & C++
echo “No of arguments entered: $#” fi
Output
$sh s12$sh s12 GodNo of arguments entered: 1$sh s12 God GreatNo of arguments entered: 2
13. What does the following shell script do?
if test $# != 1then echo “Invalid number of arguments”exitelseecho “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 s13Invalid number of arguments$sh s13 abccontinuing execution$sh s13 a bInvalid 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 str1echo “Enter second string:\c”read str2if test $str1 = $str2
Page 53
Unix, C & C++
then echo “Strings are equal”else echo “Strings are not equal”fi
Output
$sh s14Enter first string:GodEnter second string:GoodStrings are not equal$sh s14Enter first string:GreatEnter second string:GreatStrings are equal
15. State what the following shell script called test1 does.
echo “Display contents of file: $1”cat $1cp $1 $2echo “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 sI am fine$cat mcat: cannot open m: No such file or directory (error 2)$sh test1 s mDisplay contents of file: sI am fineFile copied successfully$cat mI 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_fileOutput
$cat sample_file > test_file$cat test_fileThis 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 > sample1This is a sample file for test$cat > sample2This is a Sample file for test$cmp sample1 sample2sample1 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 –printOutput
$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 subab$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_numbersAmar 4568998John 2344545Bala 2345667Mala 4567578$sort phone_numbers > phone_list$cat phone_listAmar 4568998Bala 2345667John 2344545Mala 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 doecho “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 choicecase $choice in1) date;;2) who;;3) ls;;
Page 57
Unix, C & C++
4) pwd;;q)break;;*)echo” Choice is not in the list”esacdone
Output
$sh chooseEnter the number of the program you wish to run(press 'q' to exit)1 date 2 who3 ls 4 pwd1Thu Jun 27 14:01:26 IST 2002Enter the number of the program you wish to run(press 'q' to exit)1 date 2 who3 ls 4 pwd2student ttyp0 Jun 27 11:32Enter the number of the program you wish to run(press 'q' to exit)1 date 2 who3 ls 4 pwd3testchooseEnter the number of the program you wish to run(press 'q' to exit)1 date 2 who3 ls 4 pwd 4/usr/student/Ex/subEnter the number of the program you wish to run(press 'q' to exit)1 date 2 who3 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 aread becho " The list of names present in both the files"sort $a $b | uniq -d#uniq -d $a $b
Output
$cat L1VijaiAjaiHaresh$cat L2RajeshVijaiSatish$sh s28Enter the file namesL1L2The list of names present in both the filesVijai
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 secho " Enter the character to be substituted"read wecho " File after Modification"cat $f | tr $s $w
Output
$cat demoHow are you?I am fine.$sh s29 Enter the name of the file to be editeddemo Enter the character to be searcheda Enter the character to be substituted# File after ModificationHow #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 necho " Enter the names"if test -f "xymn345man23"thenrm xymn345man23fiwhile test $n -gt 0doread secho $s | cat >> xymn345man23n=`expr $n - 1`doneechoecho " The Alphabetical order for the names enter is "sort xymn345man23
Output
$sh s30
Page 60
Unix, C & C++
enter the number of names3 Enter the namesUshaVidyaPraveena
The Alphabetical order for the names enter isPraveenaUshaVidya
31. Write a shell script to find the home directory of the user.
Solution
echo "Enter the user name"read uecho "Home directory of $u is :"echo `grep $u /etc/passwd | cut -d: -f6`
Output
Enter the user namestudentHome directory of student is :/usr/student
32. Write a shell script to reverse a string
Solution
echo " Enter a String"read sz=`echo $s | wc -m`while test $z -gt 0doz=`expr $z - 1`echo -n `echo $s | cut -c$z`doneecho
Output
$sh s32 Enter a StringWelcomeemocleW
Page 61
Unix, C & C++
33. Write a shell script to find the factorial of a number
Solution
echo "Enter a number"read nf=1i=1while test $i -le $ndof=`expr $f \* $i`i=`expr $i + 1`doneecho " Factorial of $n is $f"
Output
$sh s33Enter a number5Factorial 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 nif test $n -eq 0thenecho "The entered number is zero"elif test $n -lt 0then echo "The number is negative"elseecho " The number is positive"
fi
Output
$sh s34 Enter a number3 The number is positive$sh s34 Enter a number
Page 62
Unix, C & C++
-1The number is negative$sh s34 Enter a number0The 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 sc=`ls $s | wc -l`if test $c = 0thenrmdir $selserm -r $sfi
Output
$sh s35 Enter the name of the directory to be deletedsub$cd subsub: does not exist
36. Write a shell script to list the files in a directory
Solution
echo "Enter the name of the directory"read dls $d
Output
$sh s36Enter the name of the directorylabm45m46m48m49s
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 sif [ -d $s ]thenecho " It is the name of the directory "elseecho " It is not a name of the directory "fi
Output
$sh s37Enter the name of the directoryfirstIt is not a name of the directory$sh s37Enter the name of the directorylabIt 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 acase $a ina) 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 s38Enter a characteraIt is a vowel$sh s38
Page 64
Unix, C & C++
Enter a characterqNot a vowel
39. Write a shell script to check if arguments are given to a script or not
Solution
if test -z "$*"thenecho "No argument"elseecho "Arguments are : $*"fi
Output
$sh s39No argument$sh s39 1 2 3Arguments are : 1 2 3
40. Write a script program to accept two numbers and find the sum.
Solution
echo "Enter 2 numbers "read aread bc=`expr $a + $b`echo "Sum is $c"
Output
$sh s40Enter 2 numbers53Sum is 8
41. Write a shell script to display the following output122333444455555
Page 65
Unix, C & C++
Solutionfor i in 1 2 3 4 5doj=1while [ $j -le $i ]doecho -n $ij=`expr $j + 1`doneechodone
42. Write a script to check if a file is writeable
Solution
echo "Enter a file name"read hif [ ! -w $h ]thenecho "### You cannot edit \007###"elseecho "You can edit the file"fi
Output
$ls -l a-rwxr--r-- 1 student group 0 Jun 26 15:58 a$sh s42Enter a file nameaYou can edit the file$chmod u-w a$ls -l a-r-xr--r-- 1 student group 0 Jun 26 15:58 a$sh s42Enter a file namea### You cannot edit ###
43. Write a shell script to copy files
Solution
echo "Source file :\c"
Page 66
Unix, C & C++
read secho "Destination file :\c"read d
cp $s $d
Output$cat aGod is Great$cat s$sh s43Source file :aDestination file :s$cat sGod 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 rcase $rin0) 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 s44Enter a number from 0 to 95five$sh s44Enter a number from 0 to 9winvalid 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 $hourif [ $hour -gt 0 -a $hour -lt 12 ]thenecho "Good Morning"elif [ $hour -gt 12 -a $hour -lt 14 ]thenecho "Good Afternoon"elseecho "Good Evening"fi
Output
$sh s45Thu Jun 27 15:59:14 IST 200215Good Evening
46. Write a shell script to look for a person’s phone number in the phone book.
Solution
if [ $# -ne 1 ]thenecho "usage : Enter name "elseoutput=` grep $1 /usr/student/test/phone_book `l=` echo $output | wc -c`if [ l != 0 ]thenecho "$output"fifi
Output
$cat ./test/phone_bookabc 12 asdsafsdfsdf
Page 68
Unix, C & C++
def 13 sdsdhsdfhshdfdfjhkjfhij 14 dfsdfsfsdfsdfdfdf$sh s46usage : Enter name$sh s46 abcabc 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=1while [ $a -lt 80 ]doecho -n “*”a=`expr $a + 1`donesleep 60a=1while [ $a -lt 80 ]doecho -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 < sOutput
$cat sGod is Great$tr a-z A-Z < sGOD 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*samsample_filesat$ls ./subs$mv sam ./sub$ls sa*sample_filesat$ls ./subssam
50. Write a shell script to see if a user already exists.
Solution
echo "Enter User Name"read useridif grep "^$userid:" /etc/passwd > /dev/nullthenecho "### $userid already exists ###"echo "### abort ###"exitfi
Output
$sh s50Enter User Namestudent### student already exists ###### abort ###$sh s50Enter User NameStud$
Page 70
Unix, C & C++
Exercise: -
1. Write a shell script to swap two numbers2. Write a shell script to move a file in one directory to another directory3. Write a shell script to display the following output
112123123412345
4. Write a shell script to find the sum of numbers from 1 to 105. 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 series8. Write a shell script that counts the number of words in a file9. Write a shell script to find the greatest of 3 numbers10. Write a shell script that asks for the capital of India and repeats the question until
the user gives the correct answer.
Page 71