Tuesday, 4 December 2018

C Programs for class 12


'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()
{
            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: (name)
                                                ii.      Your address is: (address)


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



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


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%

11. 

                Menu
  1. Master
  2. Transaction
  3. Reports
  4. Exit

Your Choice :
 
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:

Menu
1. Masters
2. Transaction
3. Reports
4. Exit

your choice :
1
choice is 1
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
!
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)
{
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







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



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

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;
{
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
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.
 









Solution

#include<stdio.h>
#define Errors 4
char err_msg[][29]={
“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];
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
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: “);
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.

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?
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.


No comments:

Post a Comment