SlideShare a Scribd company logo
1 of 115
Table of Contents
Table of Contents...................................................................................................................................1
Types, Operators and Expressions.........................................................................................................1
Control Flow........................................................................................................................................13
Functions and Program structure........................................................................................................26
Pointers and Arrays.............................................................................................................................46
Structures ...........................................................................................................................................59
Input and Output...............................................................................................................................102
Types, Operators and Expressions
1. Write a program to convert a given number of days into months and days.
#include<stdio.h>
int main()
{
int days,months;
printf("Enter the number of days:");
scanf("%d",&days);
months=(days/30);
days=days-months*30; // days=days%30;
printf("The entered number of days are equal to %d months%d days",months,days);
}
Output:
[pmanne@oradb ~]$ gcc dy_to_mn_conv.c
[pmanne@oradb ~]$ ./a.out
Enter the number of days:45
The entered number of days are equal to 1 months15 days
2. Write a program to read length and width from the input and compute perimeter and area of the
rectangle.
#include<stdio.h>
int main()
{
float length,width;
float area,perimeter;
printf("Enter the length and width of a reactangle:");
scanf("%f %f",&length,&width);
area=length*width; //calculates area
perimeter=2*(length+width);//calculates perimeter
printf("Area is %f and perimeter is%f",area,perimeter);
}
Output:
[pmanne@oradb ~]$ gcc area_peri.c
[pmanne@oradb ~]$ ./a.out
Enter the length and width of a reactangle:2.5 3
Area is 7.500000 and perimeter is11.000000[
3. Write a program to read the diameter of the circle and compute the perimeter and area of the
circle.
#include<stdio.h>
int main()
{
int diameter;
float perimeter,area;
printf("Enter the diameter of the circle");
scanf("%d",&diameter);
perimeter=diameter*3.14; //calculates perimeter
area=(3.14*diameter*diameter)/4;//calculates area
printf("Area of circle is %f and perimeter of circle is %f",area,perimeter);
}
Output:
[pmanne@oradb ~]$ gcc areaofcircle.c
[pmanne@oradb ~]$ ./a.out
Enter the diameter of the circle26
Area of circle is 530.659973 and perimeter of circle is 81.639999
4. Write a program to read a floating point number from the standard input and print right most digit
of the integral part and left most digit of real part.
#include<stdio.h>
#define EXIT_SUCCESS 0
int main()
{
float num,real_part;
int int_part,r_num,i_num;
printf("Enter floating type number:");
scanf("%f",&num);
int_part=num;
real_part=num-int_part;
printf("integral part is %dn real part is %f",int_part,real_part);
i_num=int_part%10;//gives the leftmostdigit of realpart
real_part=real_part*10;//gives the rightmost digit of intger part
r_num=(int)real_part;
printf("n leftmost digit of realpart is %dn right most digit of integral part is %d",r_num,i_num);
return EXIT_SUCCESS;
}
Output:
[pmanne@oradb ~]$ gcc floatir.c
[pmanne@oradb ~]$ ./a.out
Enter floating type number:1234.56
integral part is 1234
real part is 0.560059
leftmost digit of realpart is 5
right most digit of integral part is 4
5. Write a program to read values of “x” and “y” from the input and evaluate the following
expression and print the result
Expr: 7x5 + 3x3 + 12 x2 + 5x + 10
#include<stdio.h>
#include<math.h>
#define exit 0
int main()
{
int x,res;
printf("Enter the values of X:");
scanf("%d",&x);
res=(7*pow(x,5))+(3*pow(x,3))+(12*pow(x,2))+(5*x)+10;
printf("nResult of the expresison is%d",res);
return exit;
}
Output:
[pmanne@oradb ~]$ gcc -lm eval_expr.c -o eval
[pmanne@oradb ~]$ ./eval
Enter the values of X:12
Result of the expresison is1748806
6. Write a program to determine the ranges of char, short, int, float and long variables both signed
and unsigned.
Output:- Range of signed char is -128 to 127.
Range of unsigned char is from 0 to 255.
#include<stdio.h>
#include<limits.h>//contains the functions to check the range of char,so on
#define exit 0
int main()
{
printf("Max value of type char is %dn",CHAR_MAX);
printf("Min value of type char is %dn",CHAR_MIN);
printf("Max value of type SIGNED char is %dn",SCHAR_MAX);
printf("Min value of type SIGNED char is %dn",SCHAR_MIN);
printf("Max value of type UNSIGNED char is %un",UCHAR_MAX);
printf("Max value of short is %dn",SHRT_MAX);
printf("Min value of short is %dn",SHRT_MIN);
printf("Max value of UNSIGNED short is%un",USHRT_MAX);
printf("Max&MIN value of type int is%d%dn",INT_MAX,INT_MIN);
printf("Max value of type UNSIGNED int is %dn",UINT_MAX);
printf("Max value of type long is %ldn",LONG_MAX);
printf("Min value of type long is %ldn",LONG_MIN);
printf("Max value of UNSIGNED long is%ldn",ULONG_MAX);
}
Output:
[pmanne@oradb ~]$ gcc range.c -o range
[pmanne@oradb ~]$ ./range
Max value of type char is 127
Min value of type char is -128
Max value of type SIGNED char is 127
Min value of type SIGNED char is -128
Max value of type UNSIGNED char is 255
Max value of short is 32767
Min value of short is -32768
Max value of UNSIGNED short is65535
Max&MIN value of type int is2147483647-2147483648
Max value of type UNSIGNED int is -1
Max value of type long is 2147483647
Min value of type long is -2147483648
Max value of UNSIGNED long is-1
7. Write a loop equivalent to below for loop without using ’&&’ or ‘||’
#include<stdio.h>
#define exit 0
int main()
{
/* int i; //given loop in the assignment
char c;
char s[100];
int limit=100;
for(i=0;i<limit-1&&(c=getchar())!='n' && c!=EOF;++i)
s[i]=c;
printf("%s",s);*/
int i=0,limit=100;
char c,s[100];
while(i<limit-1)//untill this condition fails
{
c=getchar(); //read into c
if(c==EOF) // && c!=EOF-->if c=end of file stop rading char and come out
break;
else if (c=='n')//&&(c=getchar())!='n'-->equal to newline comeout
break;
s[i++]=c; //if both the above conditions are satisfied,copy it into s
}
s[i]='0'; //terminate the string
printf("%s",s);
return exit;
}
Output:
[pmanne@oradb ~]$ gcc equivfor.c -o for
[pmanne@oradb ~]$ ./for
this is a program to write the loop without using && or ||
this is a program to write the loop without using && or ||
8. Write a program to give the count of No of 1s in binary format of a number given.
Eg: count = NoOf1sCount(155) = 5 (as Binary form of 155 is 10011011)
#include<stdio.h>
#define exit 0
int main()
{
long base=1,number,snum,count=0,rem,bin=0;
printf("Enter an decimal number");
scanf("%d",&number);
//----converting into binary----//
snum=number;
while(number>0)
{
rem=number%2;
if(rem==1)//if it finds a 1 then increment the count
{
count++;
}
bin=bin+rem*base;
number=number/2;
base=base*10;
}
printf("Input number is:%d n",snum);
printf("Binary equivalent is: %dn",bin);
printf("NO.of 1's are: %d n",count);
return exit;
}
Output:
[pmanne@oradb ~]$ gcc count_binary.c -o count
[pmanne@oradb ~]$ ./count
Enter an decimal number155
Input number is:155
Binary equivalent is: 10011011
NO.of 1's are: 5
9. Write a program to get product of 2 pow n and a given number without using “*’ operation
Eg: res = myProduct(32, 2) = 32 * 4 = 128
myProduct(25, 4) = 25 * 16 = 400
#include<stdio.h>
#define exit 0
int main()
{
int x,y,prod;
printf("Enter a number and the value of n in 2 pow n:");
scanf("%d%d",&x,&y);
prod=x<<y;
printf("Product is %dn",prod);
return exit;
}
Output:
[pmanne@oradb ~]$ gcc myProduct.c -o product
[pmanne@oradb ~]$ ./product
Enter a number and the value of n in 2 pow n:32
2
Product is 128
10. Write a program to get 1’s compliment of a given number without using “~” operator.
Eg: res= compliment1s(170) = 85
#include<string.h>
#define EXIT 0
int main()
{
int num,i=0,j,s=0,k=0,l;
char bin[50];
printf("Enter an integer:");
scanf("%d",&num);
//converting an integer to binary
while(num>0)
{
bin[i]=('1'-1)+(num%2);
i++;
num=num/2;
}
printf("Equivalent binary is :");
for(j=i-1;j>=0;j--)
printf("%c",bin[j]);
//fliiping 1's and 0's to get 1s complement
for(j=i;j>=0;j--)
{
if(j==i)
{
if(bin[j]=='0')
bin[j]='1';
else if(bin[j]=='1')
bin[j]='0';
}
}
printf("n 1's Complement is %s",bin);
//converting again into integer
l=strlen(bin);
l--;
for(i=l;bin[i]>=0;i--)
{
if(bin[i]=='1')
{
s=pow(2,k)+s;
k++;
}
else
k++;
}
printf("nEquivalent integer is %d",s);
}
Output:
[pmanne@oradb ~]$ gcc -lm withoutild.c -o wtild
[pmanne@oradb ~]$ ./wtild
Enter an integer:170
Equivalent binary is :10101010
1's Complement is 01010101
Equivalent integer is 85
11. Write a program to get hexadecimal representation of given number using bit wise operations.
#include <stdio.h>
void hexconv(int a);
main()
{
int a;
printf("Enter a no. in decimal system:- ");
scanf("%d",&a);
hexconv(a);
}
void hexconv(int a)//converts an integer into hex
{
int b,c=0,hex[5],i=0;
b=a;
while (b>15)
{
hex[i]=b%16;
b=b>>4;
i++;
c++;
}
hex[i]=b;
printf("Its hexadecimal equivalent is ");
for (i=c;i>=0;--i)
{
if (hex[i]==10)
printf("A");
else if (hex[i]==11)
printf("B");
else if (hex[i]==12)
printf("C");
else if (hex[i]==13)
printf("D");
else if (hex[i]==14)
printf("E");
else if (hex[i]==15)
printf("F");
else
printf("%d",hex[i]);
}
return;
}
Output:
[pmanne@oradb ~]$ vi Hex_conv.c
[pmanne@oradb ~]$ gcc Hex_conv.c -o hex
[pmanne@oradb ~]$ ./hex
Enter a no. in decimal system:- 123
Its hexadecimal equivalent is 7B
12. Write a function setbits(x, p,n,y) that returns x with the n bits that begin at position p set to the
rightmost n bits of y, leaving the other bits unchanged.
Eg: res = setbits(0xB26A, 9,4,0xA)= 0xB2FA
Control Flow
13. Write a function htoi(s), which converts a string of hexa-decimal digits (including an optional 0x
or 0X) into its equivalent integer value.
(The allowed digits are 0 through 9, a through f, and A through F)
Input: - oxAA
Output: - 170
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define EXIT_SUCCESS 0
long htoi(char *);
void strrev(char *);
int main()
{
long number=0;
char inputstr[30];
printf("Enter a hexadecimal string ");
scanf("%s",inputstr);
printf("string is %sn",inputstr);
number=htoi(inputstr);
printf("Integer is %ldn",number);
return EXIT_SUCCESS;
}
long htoi(char * inputstr)//converts the hexrepresentation to integer
{
int length=0, base=1,i=0,k;
long hnumber=0;
char str[30];
strrev(inputstr);
length=strlen(inputstr);
//to include optional ox
if((inputstr[length-1]=='O' || inputstr[length-1]=='o')&&(inputstr[length-2]=='X' ||
inputstr[length-2]=='x'))
{
length=length-2;
}
while(i<=length-1)
{if(inputstr[i]=='a'||inputstr[i]=='A')
hnumber=hnumber+base*10;
else if(inputstr[i]=='b'||inputstr[i]=='B')
hnumber=hnumber+base*11;
else if(inputstr[i]=='c'||inputstr[i]=='C')
hnumber=hnumber+base*12;
else if(inputstr[i]=='d'||inputstr[i]=='D')
hnumber=hnumber+base*13;
else if(inputstr[i]=='e'||inputstr[i]=='E')
hnumber=hnumber+base*14;
else if(inputstr[i]=='f'||inputstr[i]=='F')
hnumber=hnumber+base*15;
else
{
str[0]=inputstr[i];
str[1]='0';
hnumber=hnumber+(base*atoi(str));
}
base=base*16;
i++;
}
printf("%ldn",hnumber);
return hnumber;
}
void strrev(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
Output:
[pmanne@oradb ~]$ gcc hextoint.c -o htoi
[pmanne@oradb ~]$ ./htoi
Enter a hexadecimal string oxAA
Integer is 170
14. Write a function squeeze(s1,s2) that deletes each character in s1 that matches any character in the
string s2.
Input: -
S1 = “character”
S2 = “at”
Output: -
S1=”chrcer”
S2
:q=”at”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void squeeze(char*,char*);
int main()
{
char s1[15],s2[15]="";
printf("Enter first string:");
scanf("%s",s1);
printf("Enter the second string:");
scanf("%s",s2);
squeeze(s1,s2);
printf("Final result after squeezing is %sn",s1);
return 0;
}
void squeeze(char *s1,char *s2)
{
int i,j,k=0;
for(i=0;i<strlen(s1);i++)
for(j=0;j<strlen(s2);j++)
{
if(s1[i]==s2[j])
{
for(k=i;k<(strlen(s1))-1;k++)
{
s1[k]=s1[k+1];
}
s1[k]='0';
}
}
}
Output:
[pmanne@oradb ~]$ gcc squeeze.c
[pmanne@oradb ~]$ ./a.out
Enter first string:character
Enter the second string:at
Final result after squeezing is chrcer
15. Write a function any(s1,s2) which returns
the first location in the string s1 where any character from the string s2 occurs, or
-1 if s1 contains no characters from s2.
i) Input: - S1 = “character” S2 = “abc”
Output: - Function should return “3”
ii)Input: - S1 = “character” S2 = “xyz”
Output: - Function should return “-1”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int any(char *,char *);
int main()
{
char s1[15],s2[15];
int pos;
printf("Enter first string:");
scanf("%s",s1);
printf("Enter the second string:");
scanf("%s",s2);
pos=any(s1,s2);
printf("position at which it occurs is %dn",pos);
return 0;
}
int any(char *s1,char *s2)
{
int i,j=0;
int pos=-1;
for(i=0;i<(strlen(s2));i++)
for(j=0;j<(strlen(s1));j++)
if(s1[i]==s2[j])
{
pos=i+1;
break; }
return pos;
}
Output:
[pmanne@oradb ~]$ gcc any.c -o any
[pmanne@oradb ~]$ ./any
Enter first string:character
Enter the second string:abc
pos at which it occurs is 3
[pmanne@oradb ~]$ ./any
Enter first string:character
Enter the second string:xyz
pos at which it occurs is -1
16. Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted(i.e., 1
changed to 0 and vice versa), leaving the others unchanged.
Input: - Invert(45,3,2)
Output:- 53
17. Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit
positions.
Input: - rightrot(48,3)
Output: - x=9
18. In a two’s complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain.
Input: - X= 45
Output: - X=44
19. .
(Use conditional expression instead of if-else)
Input: - S1=”APPLE”
Output:= S1=”apple”
#include<stdio.h>
#include<string.h>
int lowerfunc(int);
int main()
{
char bound[30];
char *p;
printf("enter the string ");
scanf("%s",bound);
p=bound;
int result=0;
while('0'!=*p)/*while the string is not null*/
{
result=lowerfunc(*p);
printf("%c",result);
++p;
}
return 0;
}
int lowerfunc(int val)
{
{
if(val>=65 && val<=90)/*ASCII value of A-65,Z-90,if the input is in between these ascii
values*/
return val+97-65;/*difference will be the same value to get lower case letter*/
else
return val;
}
Output:
[pmanne@oradb ~]$ gcc tolow_func.c -o tolow
[pmanne@oradb ~]$ ./tolow
enter the string APPLE
apple
20.
I. Write a function escape(s,t) that converts characters like newline and tab into visible escape
sequences like n and t as it copies the string t to s. Use a switch.
a. Input : - S1=” Encapsulation
Inheritance polymorphism”
b. Output: - S1=”EncapsulationnInheritancetpolymorphism”;
#include<stdio.h>
#define exit 0
void escape(char *s,char *t);
int main()
{
char s1[100]="Encapsulation n Inheritance t t Polymorphism";
char s2[100];
printf("entered string is:%s :n",s1);
escape(s2,s1);
printf("Escaped string is:n %s n",s2);
return exit;
}
void escape(char *s,char *t)
{
int i=0,j=0;
while(t[i])
{
switch(t[i])
{
case 'n':
s[j++]='';
s[j]='n';
break;
case 't':
s[j++]='';
s[j]='t';
break;
default:
s[j]=t[i];
break;
}
++i;
++j;
}
s[j]=t[i];
}
Output:
[pmanne@oradb ~]$ gcc escape.c
[pmanne@oradb ~]$ ./a.out
entered string is:Encapsulation
Inheritance Polymorphism :
Escaped string is:
Encapsulation n Inheritance t t Polymorphism
II. Write a function which converts escape sequences into the real characters.
a. Input: - S1=”EncapsulationnInheritancetpolymorphism”;
b. output : - S1=” Encapsulation
c. Inheritance polymorphism”
#include<stdio.h>
#define exit 0
void escapetoreal(char *s,char *t);
int main()
{
char s1[100]="nEncapsulationnInheritancettPolymorphism";
char s2[100]="";
printf("Entered string is %sn:",s1);
escapetoreal(s1,s2);
printf("after converting the escape sequences to real:%s",s1);
return exit;
}
void escapetoreal(char *s,char *t)
{
int i=0,j=0;
while(t[i])
{
switch(t[i])
{
case '':
switch(t[++i])
{
case 'n':
s[j]='n';
break;
case 't':
s[j]='t';
break;
/*
case '"':
s[j]='"';
break; */
default:
s[j++]='';
s[j]=t[i];
}
break;
default:
s[j]=t[i];
}
i++;
j++;
}
}
Output:
[pmanne@oradb ~]$ gcc Escape_to_real.c -o escape
[pmanne@oradb ~]$ ./escape
Entered string is
Encapsulation
Inheritance Polymorphism
:after converting the escape sequences to real:
Encapsulation
Inheritance Polymorphism
Functions and Program structure
21. Write the function itob(n,s,b) that converts the integer n into a base b character representation in
the string s.(In particular, itob(n,s,16) formats n as a hexadecimal integer in s).
Input :- itob(15,s,16)
Output:- s= “E”
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define EXIT 0
void itob(int, char * ,int);
char * equi(int, char *);
void reverse(char *);
int main()
{
int number=0, base=0;
char result[50];
printf("Enter integer number: ");
scanf("%d",&number);
printf("Enter base ");
scanf("%d",&base);
itob(number,result,base);
return EXIT;
}
void itob(int number, char * result,int base)
{
long remainder=0,num=0, snum=number, b=base;
char c[5];
while(number>0)
{
if(b<10)
{
remainder=number%b;
number=number/b;
base=base*b;
strcat(result,equi(remainder,c));
}
else
{
remainder=number%b;
if(remainder>9)
{
if(remainder==10) strcat(result,"A");
else if(remainder==11) strcat(result,"B");
else if(remainder==12) strcat(result,"C");
else if(remainder==13) strcat(result,"D");
else if(remainder==14) strcat(result,"E");
else if(remainder==15) strcat(result,"F");
else {}
}
else
{
strcat(result,equi(remainder,c));
}
number=number/b;
base=base*b;
}
}
reverse(result);
printf("Input number is:%d n",snum);
printf("Equivalent of %d in %d base is %sn",snum,b,result);
}
char * equi(int number, char * c)
{
c[0]=('1'-1)+number;
c[1]='0';
return c;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
22. Write a function itoa that accepts three arguments instead of two. The third argument is a
minimum field width; the converted number must be padded with blanks on the left if necessary
to make it wide enough.
Input: - itoa(40,buffer,5)
Output :- “ 40” (i.e 3 spaces before 40)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define EXIT_SUCCESS 0
void itoa(int, char *, int);
char * chareq(int, char *);
void reverse(char *);
int main()
{
int numtoconvert=0, width=0;
char result[50]="";
printf("Enter integer number to convert to string: ");
scanf("%d",&numtoconvert);
printf("Enter width ");
scanf("%d",&width);
itoa(numtoconvert,result,width);
return EXIT_SUCCESS;
}
char * chareq(int number, char * c)
{
switch(number)
{
case 0: c[0]='0';break;
case 1: c[0]='1';break;
case 2: c[0]='2';break;
case 3: c[0]='3';break;
case 4: c[0]='4';break;
case 5: c[0]='5';break;
case 6: c[0]='6';break;
case 7: c[0]='7';break;
case 8: c[0]='8';break;
case 9: c[0]='9';break;
}
c[1]='0';
return c;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
void itoa(int number, char *result, int width)
{
int rem=0, length=0,i=0,base=1;
char c[5];
while(number>0)
{
rem=number%10;
number=number/10;
base=base*10;
strcat(result,chareq(rem,c));
}
length=strlen(result);
for(i=length;i<width;i++)
result[i]=' ';
result[width]='0';
reverse(result);
printf("The converted string is '%s'n",result);
}
23. Write a function that returns the right most position of char t in the given string S or -1 if there is
none.
Eg: string S1 = “Testing”
int Pos = myPos(S1, ‘t’) then Pos =4.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define EXIT_SUCCESS 0
int rightmostpos(char *, char);
int main()
{
int position;
char string[50];char c;
printf("Enter character to get its right most occurance ");
scanf("%c",&c);
printf("Enter a string ");
scanf("%s",string);
position=rightmostpos(string,c);
printf("nPosition of rightmost occurance of %c in string '%s' is %dn",c,string,position);
return EXIT_SUCCESS;
}
int rightmostpos(char *string, char c)
{
int i=0, j=0, k=0, length=0, position=-1;
length=strlen(string);
for(i=0;i<length;i++)
if(string[i]==c)
position=i+1;
return position;
}
24. Write a function to get the floating point number from the given input.
Eg: Buffer = “123.54”
myFloat = myfloat(Buffer) then myFloat = 123.54
if Buffer = “123.453e-6”
then myFloat = myfloat(Buffer) = 0.00012345
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define EXIT_SUCCESS 0
void myfloat(char *,float *);
float number;
int pr;
int main()
{
float *f;
number=0;int p=0;
char inputstr[50]="";
printf("Enter input float in string: ");
scanf("%s",inputstr);
myfloat(inputstr,f);
// number=*f;p=*(f++);
printf("the float number is %.*fn",pr,number);
return EXIT_SUCCESS;
}
void myfloat(char *result,float *f)
{
int length=0,i=0,intlen=0,decilen=0,exp=0,d=0,il=0;
float base=1,k;
length=strlen(result);
for(i=0;i<length;i++)
{
if(result[i]=='.')
break;
intlen++;
}
il=intlen;
while((result[i]!='e' || result[i]!='E') && i<length)
{
i++;
decilen++;
if(result[i]=='e' || result[i]=='E') break;
}
decilen--;
d=decilen;
if(result[i]=='e' || result[i]=='E')
{
i++;
if(result[i]=='+') exp=(result[i+1]-('1'-1));
if(result[i]=='-') exp=(result[i+1]-('1'-1));
}
printf("intlen is %d, decilen is %d, exp is %dn",intlen, decilen, exp);
while(decilen!=0)
{
k=result[decilen+intlen]-('1'-1);
number=number+k*base;
base=base*10;
decilen--;
}
while(intlen!=0)
{
k=result[intlen-1]-('1'-1);
number=number+k*base;
base=base*10;
intlen--;
}
i=d+exp;
number=number/pow(10,i);
pr=d+exp;
}
25. Write a program which implements getch() and ungetch().
Getch – gets a character from keyboard
Ungetch - push a character onto the input queue
26. Write functions to print the first element of the stack (without popping), to duplicate it and swap
the first two elements of the stack.
Eg: Stack = { 4,6,9,12}
printFirst(Stack) should print 4 and now
Stack = {6,4,9,12}
#include<stdio.h>
#define max 5
int top=-1,stack[max];
void push();
void display();
void display2();
void displayall();
void swap();
main()
{
int ch,x;
do
{
printf("n 1.Push an element using a stack");
printf("n 2.Display the first element of the stack");
printf("n 3.Display the first&second element of the stack");
printf("n 4.Dispaly all the elements in stack");
printf("n 5.After swaping the first two elements");
printf("n 6.Exit");
printf("nselect your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter an element to push:");
scanf("%d",&x);
push(x);
break;
case 2:
display();
break;
case 3:
display2();
break;
case 4:
displayall();
break;
case 5:
swap();
break;
default:printf("Exit");
return 0;
}
}while(ch!=6);
}
void push(int x)
{
if(top==max-1)
{
display();
printf("stack overflow");
}
else
{
stack[++top]=x;
displayall();
}
}
void display()
{
if(top==-1)
printf("empty stack");
/*for(i=top;i>=0;i--)*/
printf("%4dn",stack[0]);
}
void display2()
{
int i=0;
if(top==-1)
printf("empty stack");
for(i=0;i<2;i++)
printf("%4dn",stack[i]);
}
void swap()
{
int temp[0],j;
if(top==-1)
printf("empty stack");
// int temp[0]=0,j=0;
temp[0]=stack[0];
stack[0]=stack[1];
stack[1]=temp[0];
for(j=0;j<=top;j++)
printf("%4dn",stack[j]);
}
void displayall()
{
int i=0;
if(top==-1)
printf("empty stack");
for(i=0;i<=top;i++)
printf("%4dn",stack[i]);
}
27. Write a function to clear the stack. (program to delete the elements.)
#include<stdio.h>
#define max 6
int top=-1,stack[max];
void push();
void clear();
void display();
main()
{
int ch,x;
do
{
printf("nn1.Push a element using a stackn");
printf("n2.clear all elements using stackn");
printf("n3.Display all the elementsn");
printf("n4.Exit Programn");
printf("nSelect any one of the above==>");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("nEnter the element to be pushed into the stack==>");
scanf("%d",&x);
push(x);
break;
case 2: clear();
break;
case 3: display();
break;
default:printf("n EXIT");
}
}while(ch!=4);
}
void push(int x)
{
if(top==max-1)
{
display();
printf("Stack overflow....n");
}
else
{
stack[++top]=x;
display();
}
if(top==max-1)
{
display();
printf("The stack is full....n");
}
}
void clear()
{
if(top==-1)
printf("nStack underflow....n");
else
{
int i=0;
for(i=top;i<=max;i++)
stack[top--];
if(top<=0)
printf("nThe stack is empty....n");
}
}
void display()
{
int i;
if(top==-1)
printf("nEmpty stack....n");
for(i=top;i>=0;i--)
printf("n%4d",stack[i]);
}
28. Write a function to get a string from the number given.
Eg: input: str1 = myItoa(1234)
Output: str1= “1234”
#include<stdio.h>
#include<string.h>
#define EXIT 0
#define MAX 50
void myitoa(int,char *);
void reverse(char *);
char * chareq(int, char *);
int main()
{
int number;
char str[MAX]="";
printf("Enter an integer to be converted into string:");
scanf("%d",&number);
myitoa(number,str);
printf("After conversion the string is %sn",str);
return EXIT;
}
void myitoa(int number, char * str)
{
int i=0,j=0,rem=0;char c[2];
while(number!=0)
{
rem=number%10;
strcat(str,chareq(rem,c));
number=number/10;
i++;
}
reverse(str);
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
char * chareq(int number, char * c)
{
c[0]=48+number;
c[1]='0';
return c;
}
29. Write the recursive version for the above function
30. Write a recursive function reverse (char* s).
Char* s = “Testing”
Output: s = “gnitseT”
#include<stdio.h>
#define EXIT 0
#define max 50
void reverse(char *);
int main()
{
char a[max];
printf("Enter the string to be reversed:");
scanf("%s",a);
reverse(a);
}
void reverse(char * str)
{
if(*str)
{
reverse(str+1);
printf("%c",*str);
}
}
31. Define a macro swap(t,x,y) that interchanges two arguments of type t.
32. Write a function to get an integer from the given input buffer. If there are ‘+’ or ‘-‘ symbols not
followed by a digit then push those symbols back to the buffer.
Eg: Buffer = “*12+-0(5*#3”
Call Mynum1 = getint(Buffer) should return 12 to Mynum1
Call mynum2 = getint(Buffer) should return 0 to mynum2
33. Write a function to get a float from the given input buffer. If there are ‘+’ or ‘-‘ symbols not
followed by a digit then push those symbols back to the buffer.
Eg: Buffer = “*12.5+-0(5.3*#3”
Call myfloat1 = getint(Buffer) should return 12.5 to myfloat1
Call myfloat2 = getint(Buffer) should return 5.3 to myfloat1
34. Write a function to concatenate two strings using pointers
Eg: str1 = “CMC”, str2= “LTD”
Str1 = mystrcat(str1, str2)
Then str1 = “CMCLTD”
Pointers and Arrays
35. Use pointers to write function mystrend(s, t) which takes two strings “s”, and “t” as input and
returns 1 if string “t” is present at the end in the string “s” otherwise 0.
a. Eg: str1 = “CMCLTD”, str2=”LTD”
i. Res = mystrend(str1, str2) then Res = 1.
#include<stdio.h>
#define EXIT 0
#define max 50
int mystrend(char *,char *);
void reverse(char *);
int main()
{
char s[max],t[max];int temp1;
printf("Enter string1:");
scanf("%s",s);
printf("Enter string2:");
scanf("%s",t);
temp1= mystrend(s,t);
if(temp1==1)
printf("Both are same");
else if(temp1==0)
printf("NOt same");
}
int mystrend(char *s,char *t)
{
int len1,len2,i,temp;
char ls[max]="";
len1=strlen(s);
len2=strlen(t);
reverse(s);
reverse(t);
for(i=0;i<len2;i++){
ls[i]=s[i];}
for(i=0;i<len2;i++)
{
if(ls[i]==t[i]){
temp=1;}
else{
temp=0;}}
return temp;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = strlen(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
36. Write a function “mystrncpy” which copies at most “n” charactors from string1 to string2. Use
pointers instead of array indexing.
ii. Eg: Str1 = “”, str2= “Hyderabad”
iii. Str1= mystrncpy(Str1, str2, 3) then Str1 = “Hyd”
#include<stdio.h>
#include<string.h>
#define EXIT 0
char * mystrncpy(char *,char *,int);
int main()
{
char str1[50];
char str2[50];
int n;
printf("Enter String1:");
scanf("%s",str1);
printf("Enter string2 which is to be coopied into string1:");
scanf("%s",str2);
printf("Enter the vale of n to copy atmost n characters:");
scanf("%d",&n);
mystrncpy(str1,str2,n);
return EXIT;
}
char * mystrncpy(char *str1,char *str2,int n)
{
int i,len1;
char *str;
str=str1;
for(i=0;i<n;i++)
*str++=*str2++;
printf("The copied value into string1 from string2 is %s",str1);
}
37. Write a function “strncmp” which compares at most “n” charactors of string1 and string2 and
returns 0 if they are equal and -1 or 1 if they have difference respectively. Use pointers instead
of array indexing.
a. Eg: Str1 = “CMCLtd”, str2= “Hyderabad”
Res = mystrncmp(Str1, str2, 3) should Res = -1
#include<stdio.h>
#include<string.h>
#define EXIT 0
#define DIFF -1
#define max 50
int trncmp(char *,char *,int);
int main()
{
char str1[max];
char str2[max];
int n,temp;
printf("Enter string1:");
scanf("%s",str1);
printf("Enter string2:");
scanf("%s",str2);
printf("Enter the vale of n to compare atmost n characters:");
scanf("%d",&n);
temp=trncmp(str1,str2,n);
printf("%d",temp);
return EXIT;
}
int trncmp(char *str1,char *str2,int n)
{
int i;
char *str;
str=str1;
for(i=0;i<n;i++)
if(*str++==*str2++)
// printf("same");
return EXIT;
else
// printf("different");
return DIFF;
}
38. Write a function month_day(int year, int yearday, int *pMonth, int *pDay) where year and
yearday are inputs and the functions writes the month and date into pMonth and pDay.
i. Eg : the function call month_day(1988,60, &m, &d) should fill m with 2
and d with 29.
39. Write a function to get an integer from the given input buffer. If there are ‘+’ or ‘-‘ symbols not
followed by a digit then push those symbols back to the buffer.
40. Write a function to get a float from the given input buffer. If there are ‘+’ or ‘-‘ symbols not
followed by a digit then push those symbols back to the buffer.
41. Write a function to concatenate two strings using pointers
42. Use pointers to write function strend(s, t) which takes two strings “s”, and “t” as input and
returns 1 if string “t” is present at the end in the string “s” otherwise 0.
43. Write a function “strncpy” which copies at most “n” charactors from string1 to string2. Use
pointers instead of array indexing.
44. Write a function “strncmp” which compares at most “n” charactors of string1 and string2 and
returns 0 if they are equal and -1 or 1 if they have difference respectively. Use pointers instead
of array indexing.
45. Write a function month_day(int year, int yearday, int *pMonth, int *pDay) where year and
yearday are inputs and the functions writes the month and date into pMonth and pDay.
b. Eg : the function call month_day(1988,60, &m, &d) should fill m with 2 and d with
29
46. Write the quick sorting program to sort given strings in decreasing order.
#include <stdio.h>
#include <string.h>
47. In the declaration int *daytab[13] , describe daytab.
48. Give the C-declaration for : function returing pointer to array[] of pointer to function returning
char.
49. Write a function to insert a node into a single linked list exactly in the middle.
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define max 6
#define EXIT_SUCCESS 0
struct node
{
int num;
struct node * next;
};
void insertinmiddle(int);
void add(int);
void display();
void delete(int);
struct node * head=NULL;
struct node * end=NULL;
int main()
{
int ch,x,y;
do
{
printf("nn1.Add elementn");
printf("n2.Add element in the middlen");
printf("n3.Remove elementn");
printf("n4.Display all the elementsn");
printf("n5.Exit Programn");
printf("nSelect any one of the above : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("nEnter the element to add:");
scanf("%d",&x);
add(x);
break;
case 2: printf("nEnter the element to insert in the middle:");
scanf("%d",&y);printf("y is %dn",y);
insertinmiddle(y);
break;
case 3: printf("nEnter the element to remove:");
scanf("%d",&x);
delete(x);
break;
case 4: display();
break;
default: printf("n EXITn");
}
}while(ch!=5);
return EXIT_SUCCESS;
}
void add(int x)
{
struct node * temp,*newnode;
if(head==NULL)
{
head=(struct node*) malloc(sizeof(struct node));
head->num=x;
head->next=NULL;
end=head;
}
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
newnode=(struct node*) malloc(sizeof(struct node));
temp->next=newnode;
newnode->num=x;
newnode->next=NULL;
end=newnode;
}
}
void insertinmiddle(int x)
{
fflush(stdout);
struct node * temp;
struct node * temp1;
struct node * newnode;
int length=0,i=0;
temp=head;
if(head==NULL)
printf("List is empty");
else
{
while(temp!=NULL)
{
//length++;
temp=temp->next;
length++;
}
printf("length is %d",length);
temp=head;
for(i=0;i<length/2-1;i++)
temp=temp->next;
temp1=temp->next;
newnode=(struct node*) malloc(sizeof(struct node));
temp->next=newnode;
newnode->num=x;
newnode->next=temp1;
}
}
void delete(int x)
{
if(head==NULL)
printf("nList is emptyn");
else
{
struct node * temp=head,* temp1;
if(head->num==x)
{
temp1=temp->next;
head=temp1;
free(temp);
}
else
while(temp->next!=NULL)
{
if(temp->next->num==x)
{
temp1=temp->next;
temp->next=temp1->next;
free(temp1);
}
temp=temp->next;
}
}
}
void display()
{
struct node * temp=head;
if(head==NULL)
printf("List is empty");
else
{
do
{
printf("%d ",temp->num);
temp=temp->next;
}while(temp!=NULL);
}
}
50. Write C functions Push(), Pop() to insert and delete item from a stack using arrays.
Structures
51. Write C functions Push(), Pop() to insert and delete item from a stack using single linked lists.
#include<stdio.h>
#include<stdlib.h>
void push();
void pop();
void display();
struct node
{
int data;
struct node *next;
}*top=NULL,*p,*newp,*temp;
typedef struct node N;
int main()
{
int ch,x;
do
{
printf("nn1.Pushn");
printf("n2.Popn");
printf("n3.Displayn");
printf("n4.Exitn");
printf("nSelect any one of the above:");
scanf("%d",&ch);
switch(ch)
{
case 1: /*printf("nEnter the element to be pushed into the stack:");
scanf("%d",&x);*/
push();
break;
case 2: pop();
break;
case 3: display();
break;
default:printf("n EXIT");
}
}while(ch!=4);
}
void push()
{
newp=(N*)(malloc(sizeof(N)));
printf("Enter the element:");
scanf("%d",&newp->data);
newp->next=NULL;
if(top==NULL)
top=newp;
else
{
p=top;
while(p->next!=NULL)
p=p->next;
p->next=newp;
}
}
void pop()
{
if(top==NULL)
printf("n stack empty");
else if(top->next==NULL)
{
printf("The deleted item is:%d",top->data);
free(top);
top=NULL;
}
else
{
p=top;
while(p->next!=NULL)
{
temp=p;
p=p->next;
}
printf("Deleted item is:%d",p->data);
temp->next=NULL;
free(p);
}
}
void display()
{
if(top==NULL)
printf("nStack is empty");
else
{
printf("nThe elements are :n ");
p=top;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
printf("n");
}
printf("n");
}
}
52. Write a function to insert the given item into a Binary Search Tree (BST).
#include<stdio.h>
#include<stdlib.h>
struct bst //bst-->binary search tree
{
int element;
struct bst *left,*right;
}*root;
typedef struct bst *node;
node insert(int,node);
void display(node,int);
int main()
{
int ch;
int a;
// node temp;
while(1)
{
printf("n1.Insert n2.Displayn3.ExitnEnter ur choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter an integer element to insert");
scanf("%d",&a);
root=insert(a,root);
break;
case 2:
if(root==NULL)
printf("nEmpty tree");
else
display(root, 1);
break;
case 3:
exit(0);
break;
default:
printf("Exit");
}
}
}
//Insert an element into BST
node insert(int x,node t)
{
if(t==NULL)//if root is null
{
t=(node)malloc(sizeof(node));
t->element=x;
return t;
t->left=NULL;
t->right=NULL;
}
else
{
if(x<t->element) {
t->left=insert(x,t->left);
return t;}
else if(x>t->element){
t->right=insert(x,t->right); return t;}
}
return t;
}
void display(node t,int level)
{
int i;
if(t)
{
display(t->right,level+1);
printf("n");
for(i=0;i<level;i++)
printf(" ");
printf("%d",t->element);
display(t->left,level+1);
}
}
53. Write a function to delete a given item from the Binary Search Tree (BST).
#include<stdio.h>
#include<stdlib.h>
struct bst //bst-->binary search tree
{
int element;
struct bst *left,*right;
}*root;
typedef struct bst *node;
node insert(int,node);
node del(int,node);
//void display(node,int);
void display(node);//to print inorder and postorder traversal
node minValue(node);
int main()
{
int ch;node temp;
int a;
while(1)
{
printf("n1.Insert n2.Displayn3.Deleten4.ExitnEnter ur choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter an integer element to insert");
scanf("%d",&a);
root=insert(a,root);
break;
case 2:
if(root==NULL)
printf("nEmpty tree");
else
// display(root,1);
display(root);
break;
case 3:printf("Enter an element to delete");
scanf("%d",&a);
if(root==NULL)
printf("Empty tree");
else
root=del(a,root);
// printf("Deleted item is %d",root);
break;
case 4:
exit(0);
break;
default:
printf("Exit");
}
}
}
//Insert an element into BST
node insert(int x,node t)
{
if(t==NULL)//if root is null
{
t=(node)malloc(sizeof(node));
t->element=x;
return t;
t->left=NULL;
t->right=NULL;
}
else
{
if(x<t->element) {
t->left=insert(x,t->left);
return t;}
else if(x>t->element){
t->right=insert(x,t->right); return t;}
}
return t;
}
//delete an element from the BST
node del(int x,node t)
{
node temp;
if(t==NULL)
printf("Empty tree");
else
{ //if the entered element does not have any children
if(x<t->element)
t->left=del(x,t->left);
else if(x>t->element)
t->right=del(x,t->right);
else
{ //if the enetered element has two children
if(t->left&&t->right)
{ //replace the deleted node with minvalue of the children
temp=minValue(t->right);
t->element=temp->element;
t->right=del(t->element,t->right);
}
else if(t->left==NULL)
t=t->right;
else
t=t->left;
}
}return t;
}
/*void display(node t,int level)*/
void display(node t) //for inorder and postorder display
{
int i;
if(t)
{/*
display(t->right,level+1);
printf("n");
for(i=0;i<level;i++)
printf(" ");
printf("%d",t->element);
display(t->left,level+1);*/
/* //inorder traversal
display(t->left);
printf("%d",t->element);
display(t->right);*/
//postorder traversal
display(t->left);
display(t->right);
printf("%d",t->element);
}
}
/* find the minimum value..In a BST minimum value will be always present on the left side*/
node minValue(node temp)
{
if(temp==NULL||temp->left==NULL)
return temp;
return minValue(temp->left);
}
/*Inorder traversal
void inorder(node */
54. Write a function to find if the given list has duplicate item, if so delete them and sort the list.
(Should not create another list)
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define MAX 10
struct list
{
int num;
struct list * next;
}*head,*end;
typedef struct list * node;
void add(int);
void display();
void sort();
void removeDuplicates(node);
int main()
{
int ch,x,y;
do
{
printf("nn1.Add elementn");
printf("n2.Display all the elementsn");
printf("n3.Sort the listn");
printf("n4.Find and remove duplicatesn");
printf("n5.EXIT n");
printf("nSelect any one of the above : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("nEnter the element to add:");
scanf("%d",&x);
add(x);
break;
case 2: display();
break;
case 3: sort();
display();
break;
case 4: sort();
removeDuplicates(head);
display();
break;
default: printf("n EXITn");
}
}while(ch!=5);
return EXIT_SUCCESS;
}
//insert an element into list
void add(int x)
{
node temp,newnode;
if(head==NULL)
{
head=malloc(sizeof *head);
head->num=x;
head->next=NULL;
end=head;
}
else
{
/* temp=head;
while(temp->next!=NULL)
temp=temp->next;*/
for(temp=head;temp->next!=NULL;temp=temp->next);
newnode=(node) malloc(sizeof(node));
temp->next=newnode;
newnode->num=x;
newnode->next=NULL;
end=newnode;
}
}
//sort the element in list
void sort()
{
node a = NULL,b=NULL,c=NULL,e=NULL,tmp=NULL;
// the `c' node precedes the `a' and `e' node
while(e != head->next) {
c = a = head;
b = a->next;
while(a != e) {
if(a->num > b->num) {
if(a == head) {
tmp = b -> next;
b->next = a;
a->next = tmp;
head = b;
c = b;
} else {
tmp = b->next;
b->next = a;
a->next = tmp;
c->next = b;
c = b;
}
} else {
c = a;
a = a->next;
}
b = a->next;
if(b == e)
e = a;
}
}
}
//display the list
void display()
{
node temp=head;
if(head==NULL)
printf("List is empty");
else
{
do
{
printf("%d-> ",temp->num);
temp=temp->next;
}while(temp!=NULL);
}
}
//remove duplicates in the sorted list
void removeDuplicates(node head)
{
struct list *current=head;
node temp1=current->next;
if(current==NULL)
return;
while(temp1!=NULL)
{
if(current->num==temp1->num)//if the element and the next element are equal
{
// printf("dup is %d",current->num);
current->next=temp1->next;//point that element to the next one and free
free(temp1);
}
else
{
current=temp1;
temp1=temp1->next;
}
}
}
55. Use double linked lists and write functions to insert and delete items into a circular queue.
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define EXIT 0
struct node
{
int num;
struct node * next;
struct node * prev;
}*head=NULL,*end=NULL;
typedef struct node * node;
void add(int);
void display();
void delete();
int i=2;
int main()
{
int ch,x,y;
do
{
printf("n1.Add");
printf("n2.Remove");
printf("n3.Display");
printf("n4.Exit");
printf("nSelect any one of the above : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("nEnter the element to add:");
scanf("%d",&x);
add(x);
break;
case 2: delete();
break;
case 3: display();
break;
default: printf("n EXITn");
}
}while(ch!=4);
return EXIT;
}
void add(int x)
{
node temp=head,newnode;
newnode=(node) malloc(sizeof(node));
if(head==NULL)
{
head=(node) malloc(sizeof(node));
head->num=x;
head->next=NULL;
head->prev=NULL;
end=head;
}
else if(head==end)
{
temp->next=newnode;
temp->prev=newnode;
newnode->prev=temp;
newnode->next=temp;
newnode->num=x;
end=newnode;
}
else
{ i++;
while(temp->next!=head)
{
temp=temp->next;
}
temp->next=newnode;
newnode->prev=temp;
newnode->num=x;
newnode->next=head;
head->prev=newnode;
end=newnode;
}
}
void delete()
{
if(head==NULL)
printf("nList is empty, No elements to deleten");
else
{
node temp=head;
head=head->next;
head->prev=end;
end->next=head;
free(temp);
printf("Element deleted");
}
}
void display()
{
node temp=head;
if(head==NULL)
printf("List is empty");
else
{
do
{ printf("%d-> ",temp->num);
temp=temp->next;
}while(temp->next!=head->next && head->next!=NULL);
}
}
Output:
[pmanne@oradb ~]$ gcc circ_queue.c
[pmanne@oradb ~]$ ./a.out
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 1
Enter the element to add:1
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 1
Enter the element to add:2
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 1
Enter the element to add:3
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 3
1-> 2-> 3->
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 4
EXIT
56. Write a function to merge two sorted single linked list. ( should not create another new list)
57. Write a C program to multiply two different order polynomials.
58. Use pointers and function pointers to add, subtract and multiply two matrices/real numbers.
#include<stdio.h>
int *a,*b,*c;
int i=0,j=0,k=0;
int r1,c1,r2,c2;
int *add(int*,int*,int,int,int,int);
int *sub(int*,int*,int,int,int,int);
int *mul(int*,int*,int,int,int,int);
int main()
{
printf("nMatrix An"); /*Enter the size for matrix A */
printf("nEnter Number Of Rows : ");
scanf("%d",&r1);
printf("nEnter Number Of Columns : ");
scanf("%d",&c1);
printf("n Matrix Bn"); /*Enter the size for matrix B */
printf("nEnter Number Of Rows : ");
scanf("%d",&r2);
printf("nEnter Number Of Columns : ");
scanf("%d",&c2);
printf("nn MATRIX A : n");/* Enter elements for Matrix A*/
a=(int*) malloc(sizeof(int)*r1*c1); /*allocate memory for a */
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("Enter Element:");
scanf("%d",(a+i*c1+j)); /*For ex: *(a+i)-->a[i] */
}
}
printf("nn MATRIX B : n"); /* Enter elements for Matrix B*/
b=(int*) malloc(sizeof(int)*r2*c2);/*allocate memory for b */
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("Enter Element:");
scanf("%d",(b+i*c2+j));
}
}
add(a,b,r1,c1,r2,c2);
sub(a,b,r1,c1,r2,c2);
mul(a,b,r1,c1,r2,c2);
}
int *add(int *a,int *b,int r1,int c1,int r2,int c2)//ADDITION
{
if ((r1 != r2) || (c1 != c2))
{
printf("size mismatch");
return 0;
}
int *c=(int *)malloc(r1*c1*sizeof(int));
for (i=0; i<r1; i++)
{
for (j=0;j<c1; j++)
{
*(c+(i*c1)+j)=*(a+(i*c1)+j)+*(b+(i*c1)+j); //Adding two matrices and
store the result in c
}
}
printf("Addition of two matrices using pointers is:nn");
for(i=0;i<r1;i++)
{
printf("tt");
for(j=0;j<c1;j++)
{
printf("%d ",*(c+i*c1+j));
}
printf("n");
}
}
int *sub(int *a,int *b,int r1,int c1,int r2,int c2)//SUBTRACTION
{
if ((r1 != r2) || (c1 != c2))
{
printf("size mismatch");
return 0;
}
int *c=(int *)malloc(r1*c1*sizeof(int));
for (i=0; i<r1; i++)
{
for (j=0;j<c1; j++)
{
*(c+(i*c1)+j)=*(a+(i*c1)+j)-*(b+(i*c1)+j); //Subtracting two matrices and store
the result in c
}
}
printf("Subtraction of two matrices using pointers is:nn");
for(i=0;i<r1;i++)
{
printf("tt");
for(j=0;j<c1;j++)
{
printf("%d ",*(c+i*c1+j));
}
printf("n");
}
}
int *mul(int *a,int *b,int r1,int c1,int r2,int c2)//MULTIPLICATION
{
if ((r1 != r2) || (c1 != c2)||(r2!=c1))
{
printf("size mismatch..cant multiply");
return 0;
}
int *c=(int *)malloc(r1*c1*sizeof(int));
for (i=0; i<r1; i++)
{
for (j=0;j<c2; j++)
{
*(c+i*c2+j)=0;
for(k=0;k<r2;k++)
{
*(c+(i*c2)+j)+=*(a+(i*c2)+k)*(*(b+(k*c2)+j)); //Multiplicating two matrices
and store the result in c
}
}
}
printf("Multiplication of two matrices using pointers is:nn");
for(i=0;i<r1;i++)
{
printf("tt");
for(j=0;j<c1;j++)
{
printf("%d ",*(c+i*c1+j));
}
printf("n");
}
}
Output:
[pmanne@oradb ~]$ gcc matrixp.c
[pmanne@oradb ~]$ ./a.out
Matrix A
Enter Number Of Rows : 2
Enter Number Of Columns : 2
Matrix B
Enter Number Of Rows : 2
Enter Number Of Columns : 2
MATRIX A :
Enter Element:12
Enter Element:23
Enter Element:45
Enter Element:56
MATRIX B :
Enter Element:56
Enter Element:45
Enter Element:23
Enter Element:12
Addition of two matrices using pointers is:
68 68
68 68
Subtraction of two matrices using pointers is:
-44 -22
22 44
Multiplication of two matrices using pointers is:
1201 816
3808 2697
59. Implement the Qsort (quick sort) method using callback functions (function pointers)
Input and Output
60. Write a C program , which will search for a given string with no special symbols in a given file and
print all such No Of occurrences in the file along with line no only.
Eg : myGrep CMC CMCLtd.txt
Should give the output
Word LineNo Occurences
CMC 5 2
CMC 8 1
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define EXIT 0
#define MAX 40
int main(int argc, char **argv)
{ FILE *fp;
char filename[MAX],*word;
int linenumber=0, wordcount=0;
int c,i=0;
if(argc==1)
{
printf("No input filesn");
exit(1);
}
strcpy(filename, argv[2]);
fp=fopen(filename,"r");
if(fp == NULL)
{ printf("Cannot open the file");
exit(1);
}
c=fgetc(fp);
printf("WORDtLNE NUMBERtOCCURANCESn");
fflush(stdout);
do
{ i=0,strcpy(word,"");
fflush(stdout);
if(c!=' ')
{ while(c!=' ')
{ word[i]=c;i++;
c=fgetc(fp);
if(c=='n') break;
}
word[i]='0';
if(strcmp(word,argv[1])==0)
wordcount++;
}
if(c=='n')
{ linenumber++;
printf("%stt%dtt%dn",argv[1],linenumber,wordcount);
fflush(stdout);
wordcount=0;
}
c=fgetc(fp);
}while(c!=EOF);
printf("n");
fclose(fp);
return EXIT;
}
Output: [pmanne@oradb ~]$ ./a.out hello e5
WORD LNE NUMBER OCCURANCES
hello 1 1
hello 2 2
hello 3 1
hello 4 1
hello 5 1
hello 6 3
hello 7 0
hello 8 0
hello 9 0
61. Write a C program to print the total word count for given file. The program should have an
option argument of “-l” to print total line numbers
Eg: WC filename output: words:150 Char: 675
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define EXIT 0
#define MAX 20
int main()
{ FILE *fp;
char filename[MAX];
int linecount=0, wordcount=0, charcount=0;
int c;
printf("Enter the file name :");
scanf("%s",filename);
fp=fopen(filename,"r");
if(fp == NULL)
{
printf("Cannot open the file");
return EXIT;
}
c=fgetc(fp);
while(c!=EOF)
{ charcount++;
if(c==' ')
wordcount++;
if(c=='n') {
linecount++;
wordcount++;
charcount--;
}
c=fgetc(fp);
}
printf("No of characters is : %dn",charcount);
printf("No of words is : %dn",wordcount);
printf("No of lines is : %dn",linecount);
fclose(fp);
return EXIT;
}
Output:
[pmanne@oradb ~]$ gcc totalcount61.c -o total
[pmanne@oradb ~]$ ./total
Enter the file name :e5
No of characters is : 145
No of words is : 30
No of lines is : 9
62. Write a C program to print only last “n” number of lines from the file passed.(“ n” is passed as
argument)
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define EXIT_SUCCESS 0
int main(int argc, char **argv)
{ FILE *fp,*fopen();
char filename[40];
int linecount=0, length=0;
int c=0,n=0,k, base=1;
if(argc==1)
{ fprintf(stderr,"No input filesn");
exit(1);
}
if( argv[1][0]=='-')
strcpy(filename, argv[2]);
length=strlen(argv[1])-1;//finding length of the argument
while(length!=0)
{ k=argv[1][length]-'0';
n=n+k*base;
base=base*10;
length--;
}
fp=fopen(filename,"r");
if(fp == NULL)
{ printf("Cannot open the file ex:./a.out -n filenamen");
exit(1);
}
c=fgetc(fp);//get the first character
while(c!=EOF)
{ if(c=='n')
linecount++;//count no. of lines i the file
c=fgetc(fp);
}
k=fseek(fp,0,SEEK_SET);//set the position of pointer to the start of file
c=fgetc(fp);
if(linecount<n)
printf("Only %d lines exist in the given filen",linecount);
else
{ while(linecount!=n)//got to the nth line
{ c=fgetc(fp);
if(c=='n') linecount--;
}
while(c!=EOF)//print the last n lines
{ printf("%c",c);
c=fgetc(fp);
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Output:
[pmanne@oradb ~]$ gcc lastn62.c -o last
[pmanne@oradb ~]$ ./last 5 e5
Cannot open the file ex:./a.out -n filename
[pmanne@oradb ~]$ ./last -5 e5
Hello hello
hello hi hello hello
abcd efgh
hijk lmnop
ghjghgh vamsi
63. Write a C program that will compare two text files and prints the differences line wise.
Eg: myDiff file1 file2
Output: LineNo difference
#include<stdio.h>
#include<string.h>
#define MAX 1000
int main(int argc,char *argv[])
{
FILE *fp,*fp1;
char buff1[MAX],buff2[MAX],c1,c2;
int n=0,count=0;
if(argc!=3)
{
printf("NOT VALID");
exit(0);
}
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("Unable to open");
exit(0);
}
fp1=fopen(argv[2],"r");
if(fp1==NULL)
{
printf("Unable to open");
exit(0);
}
while(fgets(buff1,MAX,fp)!=NULL && fgets(buff2,MAX,fp1)!=NULL)
{
count++;
n=strcmp(buff1,buff2);
if(n!=0)
{
printf("nLine number is:%dn",count);
printf("nLine where First file doesnot match secnd is:%sn",buff1);
printf("n line in second file is:%sn",buff2);
fseek(fp,0,SEEK_CUR);
fseek(fp1,0,SEEK_CUR);
}
else
{
printf("SAME");
fclose(fp);
fclose(fp1);
}
}
}
Output:
[pmanne@oradb ~]$ ./a.out
NOT VALID[pmanne@oradb ~]$ ./a.out e1 e2
Line number is:1
Line where First file doesnot match secnd is:L|ine|1 abcd
line in second file is:line1
Line number is:2
Line where First file doesnot match secnd is:Li|ne|2
line in second file is:line2
Line number is:3
Line where First file doesnot match secnd is:l|i|n|e|3
line in second file is:line3
[pmanne@oradb ~]$ ./a.out e2 e3
SAME
64. Write a C program to print only 2nd column words of a given file.
65. Write a program to open a binary file and replace all the contents from middle on wards with
reversing words in each line.
66. Write a function in C to find the size of a raw file passed to it. ( Should not use standard library
function or system call to get the size)
Eg: size = fsize(filename) should print the size of the file.
#include <stdio.h>
#include <stdlib.h>
#define EXIT 0
int main(int argc,char **argv)
{
FILE *fp;
fp=fopen(argv[1],"rb");
long size;
if(argc!=2)
{
printf("Invalid arguments,ENTER FILE NAME ALSO:");
return EXIT;
}
if(fp==NULL)
{
printf("Can't open file");
return EXIT;
}
else
{
fseek(fp,0,SEEK_END);//seek to the end of the file
size=ftell(fp); //get current file pointer
//ftell is used for binary files returns the value for the file position pointer
printf("Size of the file is:%ldn",size);
fclose(fp);
return EXIT;
}
}
Output:
[pmanne@oradb ~]$ vi f_size.c
[pmanne@oradb ~]$ gcc f_size.c -o f
[pmanne@oradb ~]$ ./f
Invalid arguments,ENTER FILE NAME ALSO:[pmanne@oradb ~]$ ./f e1
Size of the file is:34

More Related Content

What's hot

54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101premrings
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTsKevlin Henney
 
Computer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsComputer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsVishvjeet Yadav
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd marchRajeev Sharan
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Aman Deep
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++Dendi Riadi
 
Introduction to AspectJ
Introduction to AspectJIntroduction to AspectJ
Introduction to AspectJmukhtarhudaya
 
[KOSSA] C++ Programming - 17th Study - STL #3
[KOSSA] C++ Programming - 17th Study - STL #3[KOSSA] C++ Programming - 17th Study - STL #3
[KOSSA] C++ Programming - 17th Study - STL #3Seok-joon Yun
 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5Rumman Ansari
 

What's hot (18)

Implementing string
Implementing stringImplementing string
Implementing string
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
C questions
C questionsC questions
C questions
 
C++ TUTORIAL 2
C++ TUTORIAL 2C++ TUTORIAL 2
C++ TUTORIAL 2
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
 
Arrays
ArraysArrays
Arrays
 
Computer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsComputer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commands
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Vcs5
Vcs5Vcs5
Vcs5
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd march
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
C programs
C programsC programs
C programs
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++
 
Introduction to AspectJ
Introduction to AspectJIntroduction to AspectJ
Introduction to AspectJ
 
[KOSSA] C++ Programming - 17th Study - STL #3
[KOSSA] C++ Programming - 17th Study - STL #3[KOSSA] C++ Programming - 17th Study - STL #3
[KOSSA] C++ Programming - 17th Study - STL #3
 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5
 

Similar to Useful c programs (20)

So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]
 
Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
 
Functions
FunctionsFunctions
Functions
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
First c program
First c programFirst c program
First c program
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
Best C Programming Solution
Best C Programming SolutionBest C Programming Solution
Best C Programming Solution
 
Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 Foc
 
pointers 1
pointers 1pointers 1
pointers 1
 
Array Cont
Array ContArray Cont
Array Cont
 
C tutorial
C tutorialC tutorial
C tutorial
 
SaraPIC
SaraPICSaraPIC
SaraPIC
 
Hargun
HargunHargun
Hargun
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
 
C Programming
C ProgrammingC Programming
C Programming
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 

Recently uploaded (20)

9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 

Useful c programs

  • 1. Table of Contents Table of Contents...................................................................................................................................1 Types, Operators and Expressions.........................................................................................................1 Control Flow........................................................................................................................................13 Functions and Program structure........................................................................................................26 Pointers and Arrays.............................................................................................................................46 Structures ...........................................................................................................................................59 Input and Output...............................................................................................................................102 Types, Operators and Expressions 1. Write a program to convert a given number of days into months and days. #include<stdio.h> int main() { int days,months; printf("Enter the number of days:"); scanf("%d",&days); months=(days/30); days=days-months*30; // days=days%30; printf("The entered number of days are equal to %d months%d days",months,days); } Output: [pmanne@oradb ~]$ gcc dy_to_mn_conv.c [pmanne@oradb ~]$ ./a.out
  • 2. Enter the number of days:45 The entered number of days are equal to 1 months15 days 2. Write a program to read length and width from the input and compute perimeter and area of the rectangle. #include<stdio.h> int main() { float length,width; float area,perimeter; printf("Enter the length and width of a reactangle:"); scanf("%f %f",&length,&width); area=length*width; //calculates area perimeter=2*(length+width);//calculates perimeter printf("Area is %f and perimeter is%f",area,perimeter); } Output: [pmanne@oradb ~]$ gcc area_peri.c [pmanne@oradb ~]$ ./a.out Enter the length and width of a reactangle:2.5 3 Area is 7.500000 and perimeter is11.000000[ 3. Write a program to read the diameter of the circle and compute the perimeter and area of the circle. #include<stdio.h> int main() { int diameter;
  • 3. float perimeter,area; printf("Enter the diameter of the circle"); scanf("%d",&diameter); perimeter=diameter*3.14; //calculates perimeter area=(3.14*diameter*diameter)/4;//calculates area printf("Area of circle is %f and perimeter of circle is %f",area,perimeter); } Output: [pmanne@oradb ~]$ gcc areaofcircle.c [pmanne@oradb ~]$ ./a.out Enter the diameter of the circle26 Area of circle is 530.659973 and perimeter of circle is 81.639999 4. Write a program to read a floating point number from the standard input and print right most digit of the integral part and left most digit of real part. #include<stdio.h> #define EXIT_SUCCESS 0 int main() { float num,real_part; int int_part,r_num,i_num; printf("Enter floating type number:"); scanf("%f",&num); int_part=num; real_part=num-int_part;
  • 4. printf("integral part is %dn real part is %f",int_part,real_part); i_num=int_part%10;//gives the leftmostdigit of realpart real_part=real_part*10;//gives the rightmost digit of intger part r_num=(int)real_part; printf("n leftmost digit of realpart is %dn right most digit of integral part is %d",r_num,i_num); return EXIT_SUCCESS; } Output: [pmanne@oradb ~]$ gcc floatir.c [pmanne@oradb ~]$ ./a.out Enter floating type number:1234.56 integral part is 1234 real part is 0.560059 leftmost digit of realpart is 5 right most digit of integral part is 4 5. Write a program to read values of “x” and “y” from the input and evaluate the following expression and print the result Expr: 7x5 + 3x3 + 12 x2 + 5x + 10 #include<stdio.h> #include<math.h> #define exit 0 int main() { int x,res; printf("Enter the values of X:"); scanf("%d",&x);
  • 5. res=(7*pow(x,5))+(3*pow(x,3))+(12*pow(x,2))+(5*x)+10; printf("nResult of the expresison is%d",res); return exit; } Output: [pmanne@oradb ~]$ gcc -lm eval_expr.c -o eval [pmanne@oradb ~]$ ./eval Enter the values of X:12 Result of the expresison is1748806 6. Write a program to determine the ranges of char, short, int, float and long variables both signed and unsigned. Output:- Range of signed char is -128 to 127. Range of unsigned char is from 0 to 255. #include<stdio.h> #include<limits.h>//contains the functions to check the range of char,so on #define exit 0 int main() { printf("Max value of type char is %dn",CHAR_MAX); printf("Min value of type char is %dn",CHAR_MIN); printf("Max value of type SIGNED char is %dn",SCHAR_MAX); printf("Min value of type SIGNED char is %dn",SCHAR_MIN); printf("Max value of type UNSIGNED char is %un",UCHAR_MAX); printf("Max value of short is %dn",SHRT_MAX); printf("Min value of short is %dn",SHRT_MIN); printf("Max value of UNSIGNED short is%un",USHRT_MAX); printf("Max&MIN value of type int is%d%dn",INT_MAX,INT_MIN); printf("Max value of type UNSIGNED int is %dn",UINT_MAX);
  • 6. printf("Max value of type long is %ldn",LONG_MAX); printf("Min value of type long is %ldn",LONG_MIN); printf("Max value of UNSIGNED long is%ldn",ULONG_MAX); } Output: [pmanne@oradb ~]$ gcc range.c -o range [pmanne@oradb ~]$ ./range Max value of type char is 127 Min value of type char is -128 Max value of type SIGNED char is 127 Min value of type SIGNED char is -128 Max value of type UNSIGNED char is 255 Max value of short is 32767 Min value of short is -32768 Max value of UNSIGNED short is65535 Max&MIN value of type int is2147483647-2147483648 Max value of type UNSIGNED int is -1 Max value of type long is 2147483647 Min value of type long is -2147483648 Max value of UNSIGNED long is-1 7. Write a loop equivalent to below for loop without using ’&&’ or ‘||’ #include<stdio.h> #define exit 0 int main() {
  • 7. /* int i; //given loop in the assignment char c; char s[100]; int limit=100; for(i=0;i<limit-1&&(c=getchar())!='n' && c!=EOF;++i) s[i]=c; printf("%s",s);*/ int i=0,limit=100; char c,s[100]; while(i<limit-1)//untill this condition fails { c=getchar(); //read into c if(c==EOF) // && c!=EOF-->if c=end of file stop rading char and come out break; else if (c=='n')//&&(c=getchar())!='n'-->equal to newline comeout break; s[i++]=c; //if both the above conditions are satisfied,copy it into s } s[i]='0'; //terminate the string printf("%s",s); return exit; } Output: [pmanne@oradb ~]$ gcc equivfor.c -o for [pmanne@oradb ~]$ ./for this is a program to write the loop without using && or || this is a program to write the loop without using && or ||
  • 8. 8. Write a program to give the count of No of 1s in binary format of a number given. Eg: count = NoOf1sCount(155) = 5 (as Binary form of 155 is 10011011) #include<stdio.h> #define exit 0 int main() { long base=1,number,snum,count=0,rem,bin=0; printf("Enter an decimal number"); scanf("%d",&number); //----converting into binary----// snum=number; while(number>0) { rem=number%2; if(rem==1)//if it finds a 1 then increment the count { count++; } bin=bin+rem*base; number=number/2; base=base*10; } printf("Input number is:%d n",snum); printf("Binary equivalent is: %dn",bin); printf("NO.of 1's are: %d n",count); return exit; }
  • 9. Output: [pmanne@oradb ~]$ gcc count_binary.c -o count [pmanne@oradb ~]$ ./count Enter an decimal number155 Input number is:155 Binary equivalent is: 10011011 NO.of 1's are: 5 9. Write a program to get product of 2 pow n and a given number without using “*’ operation Eg: res = myProduct(32, 2) = 32 * 4 = 128 myProduct(25, 4) = 25 * 16 = 400 #include<stdio.h> #define exit 0 int main() { int x,y,prod; printf("Enter a number and the value of n in 2 pow n:"); scanf("%d%d",&x,&y); prod=x<<y; printf("Product is %dn",prod); return exit; } Output: [pmanne@oradb ~]$ gcc myProduct.c -o product [pmanne@oradb ~]$ ./product Enter a number and the value of n in 2 pow n:32 2 Product is 128
  • 10. 10. Write a program to get 1’s compliment of a given number without using “~” operator. Eg: res= compliment1s(170) = 85 #include<string.h> #define EXIT 0 int main() { int num,i=0,j,s=0,k=0,l; char bin[50]; printf("Enter an integer:"); scanf("%d",&num); //converting an integer to binary while(num>0) { bin[i]=('1'-1)+(num%2); i++; num=num/2; } printf("Equivalent binary is :"); for(j=i-1;j>=0;j--) printf("%c",bin[j]); //fliiping 1's and 0's to get 1s complement for(j=i;j>=0;j--) { if(j==i) {
  • 11. if(bin[j]=='0') bin[j]='1'; else if(bin[j]=='1') bin[j]='0'; } } printf("n 1's Complement is %s",bin); //converting again into integer l=strlen(bin); l--; for(i=l;bin[i]>=0;i--) { if(bin[i]=='1') { s=pow(2,k)+s; k++; } else k++; } printf("nEquivalent integer is %d",s); } Output: [pmanne@oradb ~]$ gcc -lm withoutild.c -o wtild [pmanne@oradb ~]$ ./wtild Enter an integer:170 Equivalent binary is :10101010
  • 12. 1's Complement is 01010101 Equivalent integer is 85 11. Write a program to get hexadecimal representation of given number using bit wise operations. #include <stdio.h> void hexconv(int a); main() { int a; printf("Enter a no. in decimal system:- "); scanf("%d",&a); hexconv(a); } void hexconv(int a)//converts an integer into hex { int b,c=0,hex[5],i=0; b=a; while (b>15) { hex[i]=b%16; b=b>>4; i++; c++; } hex[i]=b; printf("Its hexadecimal equivalent is "); for (i=c;i>=0;--i) {
  • 13. if (hex[i]==10) printf("A"); else if (hex[i]==11) printf("B"); else if (hex[i]==12) printf("C"); else if (hex[i]==13) printf("D"); else if (hex[i]==14) printf("E"); else if (hex[i]==15) printf("F"); else printf("%d",hex[i]); } return; } Output: [pmanne@oradb ~]$ vi Hex_conv.c [pmanne@oradb ~]$ gcc Hex_conv.c -o hex [pmanne@oradb ~]$ ./hex Enter a no. in decimal system:- 123 Its hexadecimal equivalent is 7B 12. Write a function setbits(x, p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. Eg: res = setbits(0xB26A, 9,4,0xA)= 0xB2FA Control Flow
  • 14. 13. Write a function htoi(s), which converts a string of hexa-decimal digits (including an optional 0x or 0X) into its equivalent integer value. (The allowed digits are 0 through 9, a through f, and A through F) Input: - oxAA Output: - 170 #include<stdio.h> #include<string.h> #include<stdlib.h> #define EXIT_SUCCESS 0 long htoi(char *); void strrev(char *); int main() { long number=0; char inputstr[30]; printf("Enter a hexadecimal string "); scanf("%s",inputstr); printf("string is %sn",inputstr); number=htoi(inputstr); printf("Integer is %ldn",number); return EXIT_SUCCESS; } long htoi(char * inputstr)//converts the hexrepresentation to integer {
  • 15. int length=0, base=1,i=0,k; long hnumber=0; char str[30]; strrev(inputstr); length=strlen(inputstr); //to include optional ox if((inputstr[length-1]=='O' || inputstr[length-1]=='o')&&(inputstr[length-2]=='X' || inputstr[length-2]=='x')) { length=length-2; } while(i<=length-1) {if(inputstr[i]=='a'||inputstr[i]=='A') hnumber=hnumber+base*10; else if(inputstr[i]=='b'||inputstr[i]=='B') hnumber=hnumber+base*11; else if(inputstr[i]=='c'||inputstr[i]=='C') hnumber=hnumber+base*12; else if(inputstr[i]=='d'||inputstr[i]=='D') hnumber=hnumber+base*13; else if(inputstr[i]=='e'||inputstr[i]=='E') hnumber=hnumber+base*14; else if(inputstr[i]=='f'||inputstr[i]=='F') hnumber=hnumber+base*15; else { str[0]=inputstr[i]; str[1]='0'; hnumber=hnumber+(base*atoi(str));
  • 16. } base=base*16; i++; } printf("%ldn",hnumber); return hnumber; } void strrev(char *string) { int length, c; char *begin, *end, temp; length = strlen(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) {temp = *end; *end = *begin; *begin = temp; begin++;
  • 17. end--; } } Output: [pmanne@oradb ~]$ gcc hextoint.c -o htoi [pmanne@oradb ~]$ ./htoi Enter a hexadecimal string oxAA Integer is 170 14. Write a function squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2. Input: - S1 = “character” S2 = “at” Output: - S1=”chrcer” S2 :q=”at” #include<stdio.h> #include<stdlib.h> #include<string.h> void squeeze(char*,char*); int main() { char s1[15],s2[15]=""; printf("Enter first string:"); scanf("%s",s1);
  • 18. printf("Enter the second string:"); scanf("%s",s2); squeeze(s1,s2); printf("Final result after squeezing is %sn",s1); return 0; } void squeeze(char *s1,char *s2) { int i,j,k=0; for(i=0;i<strlen(s1);i++) for(j=0;j<strlen(s2);j++) { if(s1[i]==s2[j]) { for(k=i;k<(strlen(s1))-1;k++) { s1[k]=s1[k+1]; } s1[k]='0'; } } } Output: [pmanne@oradb ~]$ gcc squeeze.c [pmanne@oradb ~]$ ./a.out Enter first string:character Enter the second string:at
  • 19. Final result after squeezing is chrcer 15. Write a function any(s1,s2) which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. i) Input: - S1 = “character” S2 = “abc” Output: - Function should return “3” ii)Input: - S1 = “character” S2 = “xyz” Output: - Function should return “-1” #include<stdio.h> #include<stdlib.h> #include<string.h> int any(char *,char *); int main() { char s1[15],s2[15]; int pos; printf("Enter first string:"); scanf("%s",s1); printf("Enter the second string:"); scanf("%s",s2); pos=any(s1,s2); printf("position at which it occurs is %dn",pos); return 0; } int any(char *s1,char *s2) { int i,j=0;
  • 20. int pos=-1; for(i=0;i<(strlen(s2));i++) for(j=0;j<(strlen(s1));j++) if(s1[i]==s2[j]) { pos=i+1; break; } return pos; } Output: [pmanne@oradb ~]$ gcc any.c -o any [pmanne@oradb ~]$ ./any Enter first string:character Enter the second string:abc pos at which it occurs is 3 [pmanne@oradb ~]$ ./any Enter first string:character Enter the second string:xyz pos at which it occurs is -1 16. Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted(i.e., 1 changed to 0 and vice versa), leaving the others unchanged. Input: - Invert(45,3,2) Output:- 53
  • 21. 17. Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. Input: - rightrot(48,3) Output: - x=9 18. In a two’s complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain. Input: - X= 45 Output: - X=44 19. . (Use conditional expression instead of if-else) Input: - S1=”APPLE” Output:= S1=”apple” #include<stdio.h> #include<string.h> int lowerfunc(int); int main() { char bound[30]; char *p; printf("enter the string "); scanf("%s",bound); p=bound; int result=0; while('0'!=*p)/*while the string is not null*/
  • 22. { result=lowerfunc(*p); printf("%c",result); ++p; } return 0; } int lowerfunc(int val) { { if(val>=65 && val<=90)/*ASCII value of A-65,Z-90,if the input is in between these ascii values*/ return val+97-65;/*difference will be the same value to get lower case letter*/ else return val; } Output: [pmanne@oradb ~]$ gcc tolow_func.c -o tolow [pmanne@oradb ~]$ ./tolow enter the string APPLE apple 20. I. Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like n and t as it copies the string t to s. Use a switch. a. Input : - S1=” Encapsulation
  • 23. Inheritance polymorphism” b. Output: - S1=”EncapsulationnInheritancetpolymorphism”; #include<stdio.h> #define exit 0 void escape(char *s,char *t); int main() { char s1[100]="Encapsulation n Inheritance t t Polymorphism"; char s2[100]; printf("entered string is:%s :n",s1); escape(s2,s1); printf("Escaped string is:n %s n",s2); return exit; } void escape(char *s,char *t) { int i=0,j=0; while(t[i]) { switch(t[i]) { case 'n': s[j++]=''; s[j]='n'; break; case 't': s[j++]='';
  • 24. s[j]='t'; break; default: s[j]=t[i]; break; } ++i; ++j; } s[j]=t[i]; } Output: [pmanne@oradb ~]$ gcc escape.c [pmanne@oradb ~]$ ./a.out entered string is:Encapsulation Inheritance Polymorphism : Escaped string is: Encapsulation n Inheritance t t Polymorphism II. Write a function which converts escape sequences into the real characters. a. Input: - S1=”EncapsulationnInheritancetpolymorphism”; b. output : - S1=” Encapsulation c. Inheritance polymorphism” #include<stdio.h> #define exit 0 void escapetoreal(char *s,char *t); int main()
  • 25. { char s1[100]="nEncapsulationnInheritancettPolymorphism"; char s2[100]=""; printf("Entered string is %sn:",s1); escapetoreal(s1,s2); printf("after converting the escape sequences to real:%s",s1); return exit; } void escapetoreal(char *s,char *t) { int i=0,j=0; while(t[i]) { switch(t[i]) { case '': switch(t[++i]) { case 'n': s[j]='n'; break; case 't': s[j]='t'; break; /* case '"': s[j]='"';
  • 26. break; */ default: s[j++]=''; s[j]=t[i]; } break; default: s[j]=t[i]; } i++; j++; } } Output: [pmanne@oradb ~]$ gcc Escape_to_real.c -o escape [pmanne@oradb ~]$ ./escape Entered string is Encapsulation Inheritance Polymorphism :after converting the escape sequences to real: Encapsulation Inheritance Polymorphism Functions and Program structure 21. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s.(In particular, itob(n,s,16) formats n as a hexadecimal integer in s). Input :- itob(15,s,16)
  • 27. Output:- s= “E” #include<stdio.h> #include<string.h> #include<stdlib.h> #define EXIT 0 void itob(int, char * ,int); char * equi(int, char *); void reverse(char *); int main() { int number=0, base=0; char result[50]; printf("Enter integer number: "); scanf("%d",&number); printf("Enter base "); scanf("%d",&base); itob(number,result,base); return EXIT; } void itob(int number, char * result,int base) { long remainder=0,num=0, snum=number, b=base; char c[5]; while(number>0) { if(b<10)
  • 28. { remainder=number%b; number=number/b; base=base*b; strcat(result,equi(remainder,c)); } else { remainder=number%b; if(remainder>9) { if(remainder==10) strcat(result,"A"); else if(remainder==11) strcat(result,"B"); else if(remainder==12) strcat(result,"C"); else if(remainder==13) strcat(result,"D"); else if(remainder==14) strcat(result,"E"); else if(remainder==15) strcat(result,"F"); else {} } else { strcat(result,equi(remainder,c)); } number=number/b; base=base*b; } }
  • 29. reverse(result); printf("Input number is:%d n",snum); printf("Equivalent of %d in %d base is %sn",snum,b,result); } char * equi(int number, char * c) { c[0]=('1'-1)+number; c[1]='0'; return c; } void reverse(char *string) { int length, c; char *begin, *end, temp; length = strlen(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin;
  • 30. *begin = temp; begin++; end--; } } 22. Write a function itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough. Input: - itoa(40,buffer,5) Output :- “ 40” (i.e 3 spaces before 40) #include<stdio.h> #include<string.h> #include<stdlib.h> #define EXIT_SUCCESS 0 void itoa(int, char *, int); char * chareq(int, char *); void reverse(char *); int main() { int numtoconvert=0, width=0; char result[50]=""; printf("Enter integer number to convert to string: "); scanf("%d",&numtoconvert); printf("Enter width "); scanf("%d",&width); itoa(numtoconvert,result,width);
  • 31. return EXIT_SUCCESS; } char * chareq(int number, char * c) { switch(number) { case 0: c[0]='0';break; case 1: c[0]='1';break; case 2: c[0]='2';break; case 3: c[0]='3';break; case 4: c[0]='4';break; case 5: c[0]='5';break; case 6: c[0]='6';break; case 7: c[0]='7';break; case 8: c[0]='8';break; case 9: c[0]='9';break; } c[1]='0'; return c; } void reverse(char *string) { int length, c; char *begin, *end, temp; length = strlen(string);
  • 32. begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } void itoa(int number, char *result, int width) { int rem=0, length=0,i=0,base=1; char c[5]; while(number>0) { rem=number%10; number=number/10; base=base*10; strcat(result,chareq(rem,c)); }
  • 33. length=strlen(result); for(i=length;i<width;i++) result[i]=' '; result[width]='0'; reverse(result); printf("The converted string is '%s'n",result); } 23. Write a function that returns the right most position of char t in the given string S or -1 if there is none. Eg: string S1 = “Testing” int Pos = myPos(S1, ‘t’) then Pos =4. #include<stdio.h> #include<string.h> #include<stdlib.h> #define EXIT_SUCCESS 0 int rightmostpos(char *, char); int main() { int position; char string[50];char c; printf("Enter character to get its right most occurance "); scanf("%c",&c); printf("Enter a string "); scanf("%s",string); position=rightmostpos(string,c);
  • 34. printf("nPosition of rightmost occurance of %c in string '%s' is %dn",c,string,position); return EXIT_SUCCESS; } int rightmostpos(char *string, char c) { int i=0, j=0, k=0, length=0, position=-1; length=strlen(string); for(i=0;i<length;i++) if(string[i]==c) position=i+1; return position; } 24. Write a function to get the floating point number from the given input. Eg: Buffer = “123.54” myFloat = myfloat(Buffer) then myFloat = 123.54 if Buffer = “123.453e-6” then myFloat = myfloat(Buffer) = 0.00012345 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define EXIT_SUCCESS 0 void myfloat(char *,float *); float number;
  • 35. int pr; int main() { float *f; number=0;int p=0; char inputstr[50]=""; printf("Enter input float in string: "); scanf("%s",inputstr); myfloat(inputstr,f); // number=*f;p=*(f++); printf("the float number is %.*fn",pr,number); return EXIT_SUCCESS; } void myfloat(char *result,float *f) { int length=0,i=0,intlen=0,decilen=0,exp=0,d=0,il=0; float base=1,k; length=strlen(result); for(i=0;i<length;i++) { if(result[i]=='.') break; intlen++; }
  • 36. il=intlen; while((result[i]!='e' || result[i]!='E') && i<length) { i++; decilen++; if(result[i]=='e' || result[i]=='E') break; } decilen--; d=decilen; if(result[i]=='e' || result[i]=='E') { i++; if(result[i]=='+') exp=(result[i+1]-('1'-1)); if(result[i]=='-') exp=(result[i+1]-('1'-1)); } printf("intlen is %d, decilen is %d, exp is %dn",intlen, decilen, exp); while(decilen!=0) { k=result[decilen+intlen]-('1'-1); number=number+k*base; base=base*10; decilen--; } while(intlen!=0) { k=result[intlen-1]-('1'-1); number=number+k*base;
  • 37. base=base*10; intlen--; } i=d+exp; number=number/pow(10,i); pr=d+exp; } 25. Write a program which implements getch() and ungetch(). Getch – gets a character from keyboard Ungetch - push a character onto the input queue 26. Write functions to print the first element of the stack (without popping), to duplicate it and swap the first two elements of the stack. Eg: Stack = { 4,6,9,12} printFirst(Stack) should print 4 and now Stack = {6,4,9,12} #include<stdio.h> #define max 5 int top=-1,stack[max]; void push(); void display(); void display2(); void displayall(); void swap(); main() { int ch,x; do { printf("n 1.Push an element using a stack"); printf("n 2.Display the first element of the stack"); printf("n 3.Display the first&second element of the stack"); printf("n 4.Dispaly all the elements in stack"); printf("n 5.After swaping the first two elements"); printf("n 6.Exit"); printf("nselect your choice:"); scanf("%d",&ch);
  • 38. switch(ch) { case 1: printf("enter an element to push:"); scanf("%d",&x); push(x); break; case 2: display(); break; case 3: display2(); break; case 4: displayall(); break; case 5: swap(); break; default:printf("Exit"); return 0; } }while(ch!=6); } void push(int x) { if(top==max-1) { display(); printf("stack overflow"); } else { stack[++top]=x; displayall(); } } void display() { if(top==-1) printf("empty stack"); /*for(i=top;i>=0;i--)*/ printf("%4dn",stack[0]); } void display2() { int i=0; if(top==-1) printf("empty stack"); for(i=0;i<2;i++) printf("%4dn",stack[i]); } void swap() { int temp[0],j; if(top==-1) printf("empty stack"); // int temp[0]=0,j=0; temp[0]=stack[0]; stack[0]=stack[1]; stack[1]=temp[0];
  • 39. for(j=0;j<=top;j++) printf("%4dn",stack[j]); } void displayall() { int i=0; if(top==-1) printf("empty stack"); for(i=0;i<=top;i++) printf("%4dn",stack[i]); } 27. Write a function to clear the stack. (program to delete the elements.) #include<stdio.h> #define max 6 int top=-1,stack[max]; void push(); void clear(); void display(); main() { int ch,x; do { printf("nn1.Push a element using a stackn"); printf("n2.clear all elements using stackn"); printf("n3.Display all the elementsn"); printf("n4.Exit Programn"); printf("nSelect any one of the above==>"); scanf("%d",&ch); switch(ch)
  • 40. { case 1: printf("nEnter the element to be pushed into the stack==>"); scanf("%d",&x); push(x); break; case 2: clear(); break; case 3: display(); break; default:printf("n EXIT"); } }while(ch!=4); } void push(int x) { if(top==max-1) { display(); printf("Stack overflow....n"); } else { stack[++top]=x; display(); } if(top==max-1) {
  • 41. display(); printf("The stack is full....n"); } } void clear() { if(top==-1) printf("nStack underflow....n"); else { int i=0; for(i=top;i<=max;i++) stack[top--]; if(top<=0) printf("nThe stack is empty....n"); } } void display() { int i; if(top==-1) printf("nEmpty stack....n"); for(i=top;i>=0;i--) printf("n%4d",stack[i]); }
  • 42. 28. Write a function to get a string from the number given. Eg: input: str1 = myItoa(1234) Output: str1= “1234” #include<stdio.h> #include<string.h> #define EXIT 0 #define MAX 50 void myitoa(int,char *); void reverse(char *); char * chareq(int, char *); int main() { int number; char str[MAX]=""; printf("Enter an integer to be converted into string:"); scanf("%d",&number); myitoa(number,str); printf("After conversion the string is %sn",str); return EXIT; } void myitoa(int number, char * str) { int i=0,j=0,rem=0;char c[2];
  • 43. while(number!=0) { rem=number%10; strcat(str,chareq(rem,c)); number=number/10; i++; } reverse(str); } void reverse(char *string) { int length, c; char *begin, *end, temp; length = strlen(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp;
  • 44. begin++; end--; } } char * chareq(int number, char * c) { c[0]=48+number; c[1]='0'; return c; } 29. Write the recursive version for the above function 30. Write a recursive function reverse (char* s). Char* s = “Testing” Output: s = “gnitseT” #include<stdio.h> #define EXIT 0 #define max 50 void reverse(char *); int main() { char a[max]; printf("Enter the string to be reversed:"); scanf("%s",a);
  • 45. reverse(a); } void reverse(char * str) { if(*str) { reverse(str+1); printf("%c",*str); } } 31. Define a macro swap(t,x,y) that interchanges two arguments of type t. 32. Write a function to get an integer from the given input buffer. If there are ‘+’ or ‘-‘ symbols not followed by a digit then push those symbols back to the buffer. Eg: Buffer = “*12+-0(5*#3” Call Mynum1 = getint(Buffer) should return 12 to Mynum1 Call mynum2 = getint(Buffer) should return 0 to mynum2 33. Write a function to get a float from the given input buffer. If there are ‘+’ or ‘-‘ symbols not followed by a digit then push those symbols back to the buffer. Eg: Buffer = “*12.5+-0(5.3*#3” Call myfloat1 = getint(Buffer) should return 12.5 to myfloat1 Call myfloat2 = getint(Buffer) should return 5.3 to myfloat1 34. Write a function to concatenate two strings using pointers Eg: str1 = “CMC”, str2= “LTD”
  • 46. Str1 = mystrcat(str1, str2) Then str1 = “CMCLTD” Pointers and Arrays 35. Use pointers to write function mystrend(s, t) which takes two strings “s”, and “t” as input and returns 1 if string “t” is present at the end in the string “s” otherwise 0. a. Eg: str1 = “CMCLTD”, str2=”LTD” i. Res = mystrend(str1, str2) then Res = 1. #include<stdio.h> #define EXIT 0 #define max 50 int mystrend(char *,char *); void reverse(char *); int main() { char s[max],t[max];int temp1; printf("Enter string1:"); scanf("%s",s); printf("Enter string2:"); scanf("%s",t); temp1= mystrend(s,t); if(temp1==1) printf("Both are same"); else if(temp1==0) printf("NOt same"); } int mystrend(char *s,char *t)
  • 48. end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } 36. Write a function “mystrncpy” which copies at most “n” charactors from string1 to string2. Use pointers instead of array indexing. ii. Eg: Str1 = “”, str2= “Hyderabad” iii. Str1= mystrncpy(Str1, str2, 3) then Str1 = “Hyd” #include<stdio.h> #include<string.h> #define EXIT 0 char * mystrncpy(char *,char *,int); int main() {
  • 49. char str1[50]; char str2[50]; int n; printf("Enter String1:"); scanf("%s",str1); printf("Enter string2 which is to be coopied into string1:"); scanf("%s",str2); printf("Enter the vale of n to copy atmost n characters:"); scanf("%d",&n); mystrncpy(str1,str2,n); return EXIT; } char * mystrncpy(char *str1,char *str2,int n) { int i,len1; char *str; str=str1; for(i=0;i<n;i++) *str++=*str2++; printf("The copied value into string1 from string2 is %s",str1); } 37. Write a function “strncmp” which compares at most “n” charactors of string1 and string2 and returns 0 if they are equal and -1 or 1 if they have difference respectively. Use pointers instead of array indexing. a. Eg: Str1 = “CMCLtd”, str2= “Hyderabad” Res = mystrncmp(Str1, str2, 3) should Res = -1
  • 50. #include<stdio.h> #include<string.h> #define EXIT 0 #define DIFF -1 #define max 50 int trncmp(char *,char *,int); int main() { char str1[max]; char str2[max]; int n,temp; printf("Enter string1:"); scanf("%s",str1); printf("Enter string2:"); scanf("%s",str2); printf("Enter the vale of n to compare atmost n characters:"); scanf("%d",&n); temp=trncmp(str1,str2,n); printf("%d",temp); return EXIT; } int trncmp(char *str1,char *str2,int n) { int i; char *str;
  • 51. str=str1; for(i=0;i<n;i++) if(*str++==*str2++) // printf("same"); return EXIT; else // printf("different"); return DIFF; } 38. Write a function month_day(int year, int yearday, int *pMonth, int *pDay) where year and yearday are inputs and the functions writes the month and date into pMonth and pDay. i. Eg : the function call month_day(1988,60, &m, &d) should fill m with 2 and d with 29. 39. Write a function to get an integer from the given input buffer. If there are ‘+’ or ‘-‘ symbols not followed by a digit then push those symbols back to the buffer. 40. Write a function to get a float from the given input buffer. If there are ‘+’ or ‘-‘ symbols not followed by a digit then push those symbols back to the buffer. 41. Write a function to concatenate two strings using pointers 42. Use pointers to write function strend(s, t) which takes two strings “s”, and “t” as input and returns 1 if string “t” is present at the end in the string “s” otherwise 0. 43. Write a function “strncpy” which copies at most “n” charactors from string1 to string2. Use pointers instead of array indexing.
  • 52. 44. Write a function “strncmp” which compares at most “n” charactors of string1 and string2 and returns 0 if they are equal and -1 or 1 if they have difference respectively. Use pointers instead of array indexing. 45. Write a function month_day(int year, int yearday, int *pMonth, int *pDay) where year and yearday are inputs and the functions writes the month and date into pMonth and pDay. b. Eg : the function call month_day(1988,60, &m, &d) should fill m with 2 and d with 29 46. Write the quick sorting program to sort given strings in decreasing order. #include <stdio.h> #include <string.h> 47. In the declaration int *daytab[13] , describe daytab. 48. Give the C-declaration for : function returing pointer to array[] of pointer to function returning char. 49. Write a function to insert a node into a single linked list exactly in the middle. #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define max 6 #define EXIT_SUCCESS 0 struct node
  • 53. { int num; struct node * next; }; void insertinmiddle(int); void add(int); void display(); void delete(int); struct node * head=NULL; struct node * end=NULL; int main() { int ch,x,y; do { printf("nn1.Add elementn"); printf("n2.Add element in the middlen"); printf("n3.Remove elementn"); printf("n4.Display all the elementsn"); printf("n5.Exit Programn");
  • 54. printf("nSelect any one of the above : "); scanf("%d",&ch); switch(ch) { case 1: printf("nEnter the element to add:"); scanf("%d",&x); add(x); break; case 2: printf("nEnter the element to insert in the middle:"); scanf("%d",&y);printf("y is %dn",y); insertinmiddle(y); break; case 3: printf("nEnter the element to remove:"); scanf("%d",&x); delete(x); break; case 4: display(); break; default: printf("n EXITn"); }
  • 55. }while(ch!=5); return EXIT_SUCCESS; } void add(int x) { struct node * temp,*newnode; if(head==NULL) { head=(struct node*) malloc(sizeof(struct node)); head->num=x; head->next=NULL; end=head; } else { temp=head; while(temp->next!=NULL) temp=temp->next; newnode=(struct node*) malloc(sizeof(struct node)); temp->next=newnode; newnode->num=x;
  • 56. newnode->next=NULL; end=newnode; } } void insertinmiddle(int x) { fflush(stdout); struct node * temp; struct node * temp1; struct node * newnode; int length=0,i=0; temp=head; if(head==NULL) printf("List is empty"); else { while(temp!=NULL) { //length++; temp=temp->next; length++; }
  • 57. printf("length is %d",length); temp=head; for(i=0;i<length/2-1;i++) temp=temp->next; temp1=temp->next; newnode=(struct node*) malloc(sizeof(struct node)); temp->next=newnode; newnode->num=x; newnode->next=temp1; } } void delete(int x) { if(head==NULL) printf("nList is emptyn"); else { struct node * temp=head,* temp1; if(head->num==x) { temp1=temp->next; head=temp1; free(temp);
  • 59. { printf("%d ",temp->num); temp=temp->next; }while(temp!=NULL); } } 50. Write C functions Push(), Pop() to insert and delete item from a stack using arrays. Structures 51. Write C functions Push(), Pop() to insert and delete item from a stack using single linked lists. #include<stdio.h> #include<stdlib.h> void push(); void pop(); void display(); struct node { int data; struct node *next; }*top=NULL,*p,*newp,*temp;
  • 60. typedef struct node N; int main() { int ch,x; do { printf("nn1.Pushn"); printf("n2.Popn"); printf("n3.Displayn"); printf("n4.Exitn"); printf("nSelect any one of the above:"); scanf("%d",&ch); switch(ch) { case 1: /*printf("nEnter the element to be pushed into the stack:"); scanf("%d",&x);*/ push(); break; case 2: pop();
  • 61. break; case 3: display(); break; default:printf("n EXIT"); } }while(ch!=4); } void push() { newp=(N*)(malloc(sizeof(N))); printf("Enter the element:"); scanf("%d",&newp->data); newp->next=NULL; if(top==NULL) top=newp; else { p=top;
  • 62. while(p->next!=NULL) p=p->next; p->next=newp; } } void pop() { if(top==NULL) printf("n stack empty"); else if(top->next==NULL) { printf("The deleted item is:%d",top->data); free(top); top=NULL; } else {
  • 63. p=top; while(p->next!=NULL) { temp=p; p=p->next; } printf("Deleted item is:%d",p->data); temp->next=NULL; free(p); } } void display() { if(top==NULL) printf("nStack is empty"); else { printf("nThe elements are :n ");
  • 64. p=top; while(p!=NULL) { printf("%d",p->data); p=p->next; printf("n"); } printf("n"); } } 52. Write a function to insert the given item into a Binary Search Tree (BST). #include<stdio.h> #include<stdlib.h> struct bst //bst-->binary search tree { int element;
  • 65. struct bst *left,*right; }*root; typedef struct bst *node; node insert(int,node); void display(node,int); int main() { int ch; int a; // node temp; while(1) { printf("n1.Insert n2.Displayn3.ExitnEnter ur choice:"); scanf("%d",&ch); switch(ch) {
  • 66. case 1: printf("Enter an integer element to insert"); scanf("%d",&a); root=insert(a,root); break; case 2: if(root==NULL) printf("nEmpty tree"); else display(root, 1); break; case 3: exit(0); break; default: printf("Exit"); } } }
  • 67. //Insert an element into BST node insert(int x,node t) { if(t==NULL)//if root is null { t=(node)malloc(sizeof(node)); t->element=x; return t; t->left=NULL; t->right=NULL; } else { if(x<t->element) { t->left=insert(x,t->left); return t;} else if(x>t->element){ t->right=insert(x,t->right); return t;}
  • 68. } return t; } void display(node t,int level) { int i; if(t) { display(t->right,level+1); printf("n"); for(i=0;i<level;i++) printf(" "); printf("%d",t->element); display(t->left,level+1); } } 53. Write a function to delete a given item from the Binary Search Tree (BST). #include<stdio.h>
  • 69. #include<stdlib.h> struct bst //bst-->binary search tree { int element; struct bst *left,*right; }*root; typedef struct bst *node; node insert(int,node); node del(int,node); //void display(node,int); void display(node);//to print inorder and postorder traversal node minValue(node); int main() { int ch;node temp;
  • 70. int a; while(1) { printf("n1.Insert n2.Displayn3.Deleten4.ExitnEnter ur choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter an integer element to insert"); scanf("%d",&a); root=insert(a,root); break; case 2: if(root==NULL) printf("nEmpty tree"); else // display(root,1); display(root); break;
  • 71. case 3:printf("Enter an element to delete"); scanf("%d",&a); if(root==NULL) printf("Empty tree"); else root=del(a,root); // printf("Deleted item is %d",root); break; case 4: exit(0); break; default: printf("Exit"); } } } //Insert an element into BST node insert(int x,node t) {
  • 72. if(t==NULL)//if root is null { t=(node)malloc(sizeof(node)); t->element=x; return t; t->left=NULL; t->right=NULL; } else { if(x<t->element) { t->left=insert(x,t->left); return t;} else if(x>t->element){ t->right=insert(x,t->right); return t;} } return t; }
  • 73. //delete an element from the BST node del(int x,node t) { node temp; if(t==NULL) printf("Empty tree"); else { //if the entered element does not have any children if(x<t->element) t->left=del(x,t->left); else if(x>t->element) t->right=del(x,t->right); else { //if the enetered element has two children if(t->left&&t->right) { //replace the deleted node with minvalue of the children temp=minValue(t->right);
  • 74. t->element=temp->element; t->right=del(t->element,t->right); } else if(t->left==NULL) t=t->right; else t=t->left; } }return t; } /*void display(node t,int level)*/ void display(node t) //for inorder and postorder display { int i; if(t) {/* display(t->right,level+1); printf("n"); for(i=0;i<level;i++)
  • 75. printf(" "); printf("%d",t->element); display(t->left,level+1);*/ /* //inorder traversal display(t->left); printf("%d",t->element); display(t->right);*/ //postorder traversal display(t->left); display(t->right); printf("%d",t->element); } } /* find the minimum value..In a BST minimum value will be always present on the left side*/
  • 76. node minValue(node temp) { if(temp==NULL||temp->left==NULL) return temp; return minValue(temp->left); } /*Inorder traversal void inorder(node */ 54. Write a function to find if the given list has duplicate item, if so delete them and sort the list. (Should not create another list) #include <stdio.h> #include <stdlib.h> #include<string.h> #define MAX 10 struct list
  • 77. { int num; struct list * next; }*head,*end; typedef struct list * node; void add(int); void display(); void sort(); void removeDuplicates(node); int main() { int ch,x,y; do { printf("nn1.Add elementn"); printf("n2.Display all the elementsn"); printf("n3.Sort the listn");
  • 78. printf("n4.Find and remove duplicatesn"); printf("n5.EXIT n"); printf("nSelect any one of the above : "); scanf("%d",&ch); switch(ch) { case 1: printf("nEnter the element to add:"); scanf("%d",&x); add(x); break; case 2: display(); break; case 3: sort(); display(); break; case 4: sort(); removeDuplicates(head); display(); break;
  • 79. default: printf("n EXITn"); } }while(ch!=5); return EXIT_SUCCESS; } //insert an element into list void add(int x) { node temp,newnode; if(head==NULL) { head=malloc(sizeof *head); head->num=x; head->next=NULL; end=head; } else {
  • 80. /* temp=head; while(temp->next!=NULL) temp=temp->next;*/ for(temp=head;temp->next!=NULL;temp=temp->next); newnode=(node) malloc(sizeof(node)); temp->next=newnode; newnode->num=x; newnode->next=NULL; end=newnode; } } //sort the element in list void sort() { node a = NULL,b=NULL,c=NULL,e=NULL,tmp=NULL; // the `c' node precedes the `a' and `e' node while(e != head->next) {
  • 81. c = a = head; b = a->next; while(a != e) { if(a->num > b->num) { if(a == head) { tmp = b -> next; b->next = a; a->next = tmp; head = b; c = b; } else { tmp = b->next; b->next = a; a->next = tmp; c->next = b; c = b; } } else { c = a;
  • 82. a = a->next; } b = a->next; if(b == e) e = a; } } } //display the list void display() { node temp=head; if(head==NULL) printf("List is empty"); else { do {
  • 83. printf("%d-> ",temp->num); temp=temp->next; }while(temp!=NULL); } } //remove duplicates in the sorted list void removeDuplicates(node head) { struct list *current=head; node temp1=current->next; if(current==NULL) return; while(temp1!=NULL) { if(current->num==temp1->num)//if the element and the next element are equal { // printf("dup is %d",current->num);
  • 84. current->next=temp1->next;//point that element to the next one and free free(temp1); } else { current=temp1; temp1=temp1->next; } } } 55. Use double linked lists and write functions to insert and delete items into a circular queue. #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define EXIT 0
  • 85. struct node { int num; struct node * next; struct node * prev; }*head=NULL,*end=NULL; typedef struct node * node; void add(int); void display(); void delete(); int i=2; int main() { int ch,x,y; do {
  • 86. printf("n1.Add"); printf("n2.Remove"); printf("n3.Display"); printf("n4.Exit"); printf("nSelect any one of the above : "); scanf("%d",&ch); switch(ch) { case 1: printf("nEnter the element to add:"); scanf("%d",&x); add(x); break; case 2: delete(); break; case 3: display(); break;
  • 87. default: printf("n EXITn"); } }while(ch!=4); return EXIT; } void add(int x) { node temp=head,newnode; newnode=(node) malloc(sizeof(node)); if(head==NULL) { head=(node) malloc(sizeof(node)); head->num=x; head->next=NULL; head->prev=NULL; end=head; }
  • 89. head->prev=newnode; end=newnode; } } void delete() { if(head==NULL) printf("nList is empty, No elements to deleten"); else { node temp=head; head=head->next; head->prev=end; end->next=head; free(temp); printf("Element deleted"); } }
  • 90. void display() { node temp=head; if(head==NULL) printf("List is empty"); else { do { printf("%d-> ",temp->num); temp=temp->next; }while(temp->next!=head->next && head->next!=NULL); } } Output: [pmanne@oradb ~]$ gcc circ_queue.c [pmanne@oradb ~]$ ./a.out 1.Add 2.Remove
  • 91. 3.Display 4.Exit Select any one of the above : 1 Enter the element to add:1 1.Add 2.Remove 3.Display 4.Exit Select any one of the above : 1 Enter the element to add:2 1.Add 2.Remove 3.Display 4.Exit Select any one of the above : 1
  • 92. Enter the element to add:3 1.Add 2.Remove 3.Display 4.Exit Select any one of the above : 3 1-> 2-> 3-> 1.Add 2.Remove 3.Display 4.Exit Select any one of the above : 4 EXIT 56. Write a function to merge two sorted single linked list. ( should not create another new list) 57. Write a C program to multiply two different order polynomials. 58. Use pointers and function pointers to add, subtract and multiply two matrices/real numbers.
  • 93. #include<stdio.h> int *a,*b,*c; int i=0,j=0,k=0; int r1,c1,r2,c2; int *add(int*,int*,int,int,int,int); int *sub(int*,int*,int,int,int,int); int *mul(int*,int*,int,int,int,int); int main() { printf("nMatrix An"); /*Enter the size for matrix A */ printf("nEnter Number Of Rows : "); scanf("%d",&r1); printf("nEnter Number Of Columns : "); scanf("%d",&c1); printf("n Matrix Bn"); /*Enter the size for matrix B */ printf("nEnter Number Of Rows : "); scanf("%d",&r2); printf("nEnter Number Of Columns : ");
  • 94. scanf("%d",&c2); printf("nn MATRIX A : n");/* Enter elements for Matrix A*/ a=(int*) malloc(sizeof(int)*r1*c1); /*allocate memory for a */ for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { printf("Enter Element:"); scanf("%d",(a+i*c1+j)); /*For ex: *(a+i)-->a[i] */ } } printf("nn MATRIX B : n"); /* Enter elements for Matrix B*/ b=(int*) malloc(sizeof(int)*r2*c2);/*allocate memory for b */ for(i=0;i<r2;i++) { for(j=0;j<c2;j++) {
  • 95. printf("Enter Element:"); scanf("%d",(b+i*c2+j)); } } add(a,b,r1,c1,r2,c2); sub(a,b,r1,c1,r2,c2); mul(a,b,r1,c1,r2,c2); } int *add(int *a,int *b,int r1,int c1,int r2,int c2)//ADDITION { if ((r1 != r2) || (c1 != c2)) { printf("size mismatch"); return 0; } int *c=(int *)malloc(r1*c1*sizeof(int)); for (i=0; i<r1; i++)
  • 96. { for (j=0;j<c1; j++) { *(c+(i*c1)+j)=*(a+(i*c1)+j)+*(b+(i*c1)+j); //Adding two matrices and store the result in c } } printf("Addition of two matrices using pointers is:nn"); for(i=0;i<r1;i++) { printf("tt"); for(j=0;j<c1;j++) { printf("%d ",*(c+i*c1+j)); } printf("n"); } }
  • 97. int *sub(int *a,int *b,int r1,int c1,int r2,int c2)//SUBTRACTION { if ((r1 != r2) || (c1 != c2)) { printf("size mismatch"); return 0; } int *c=(int *)malloc(r1*c1*sizeof(int)); for (i=0; i<r1; i++) { for (j=0;j<c1; j++) { *(c+(i*c1)+j)=*(a+(i*c1)+j)-*(b+(i*c1)+j); //Subtracting two matrices and store the result in c } }
  • 98. printf("Subtraction of two matrices using pointers is:nn"); for(i=0;i<r1;i++) { printf("tt"); for(j=0;j<c1;j++) { printf("%d ",*(c+i*c1+j)); } printf("n"); } } int *mul(int *a,int *b,int r1,int c1,int r2,int c2)//MULTIPLICATION { if ((r1 != r2) || (c1 != c2)||(r2!=c1)) { printf("size mismatch..cant multiply"); return 0; }
  • 99. int *c=(int *)malloc(r1*c1*sizeof(int)); for (i=0; i<r1; i++) { for (j=0;j<c2; j++) { *(c+i*c2+j)=0; for(k=0;k<r2;k++) { *(c+(i*c2)+j)+=*(a+(i*c2)+k)*(*(b+(k*c2)+j)); //Multiplicating two matrices and store the result in c } } } printf("Multiplication of two matrices using pointers is:nn"); for(i=0;i<r1;i++) { printf("tt"); for(j=0;j<c1;j++)
  • 100. { printf("%d ",*(c+i*c1+j)); } printf("n"); } } Output: [pmanne@oradb ~]$ gcc matrixp.c [pmanne@oradb ~]$ ./a.out Matrix A Enter Number Of Rows : 2 Enter Number Of Columns : 2 Matrix B
  • 101. Enter Number Of Rows : 2 Enter Number Of Columns : 2 MATRIX A : Enter Element:12 Enter Element:23 Enter Element:45 Enter Element:56 MATRIX B : Enter Element:56 Enter Element:45 Enter Element:23 Enter Element:12 Addition of two matrices using pointers is:
  • 102. 68 68 68 68 Subtraction of two matrices using pointers is: -44 -22 22 44 Multiplication of two matrices using pointers is: 1201 816 3808 2697 59. Implement the Qsort (quick sort) method using callback functions (function pointers) Input and Output 60. Write a C program , which will search for a given string with no special symbols in a given file and print all such No Of occurrences in the file along with line no only. Eg : myGrep CMC CMCLtd.txt Should give the output Word LineNo Occurences CMC 5 2 CMC 8 1
  • 103. #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define EXIT 0 #define MAX 40 int main(int argc, char **argv) { FILE *fp; char filename[MAX],*word; int linenumber=0, wordcount=0; int c,i=0; if(argc==1) { printf("No input filesn"); exit(1); } strcpy(filename, argv[2]); fp=fopen(filename,"r"); if(fp == NULL) { printf("Cannot open the file"); exit(1); }
  • 104. c=fgetc(fp); printf("WORDtLNE NUMBERtOCCURANCESn"); fflush(stdout); do { i=0,strcpy(word,""); fflush(stdout); if(c!=' ') { while(c!=' ') { word[i]=c;i++; c=fgetc(fp); if(c=='n') break; } word[i]='0'; if(strcmp(word,argv[1])==0) wordcount++; } if(c=='n') { linenumber++; printf("%stt%dtt%dn",argv[1],linenumber,wordcount); fflush(stdout); wordcount=0; } c=fgetc(fp);
  • 105. }while(c!=EOF); printf("n"); fclose(fp); return EXIT; } Output: [pmanne@oradb ~]$ ./a.out hello e5 WORD LNE NUMBER OCCURANCES hello 1 1 hello 2 2 hello 3 1 hello 4 1 hello 5 1 hello 6 3 hello 7 0 hello 8 0 hello 9 0 61. Write a C program to print the total word count for given file. The program should have an option argument of “-l” to print total line numbers Eg: WC filename output: words:150 Char: 675 #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define EXIT 0 #define MAX 20
  • 106. int main() { FILE *fp; char filename[MAX]; int linecount=0, wordcount=0, charcount=0; int c; printf("Enter the file name :"); scanf("%s",filename); fp=fopen(filename,"r"); if(fp == NULL) { printf("Cannot open the file"); return EXIT; } c=fgetc(fp); while(c!=EOF) { charcount++; if(c==' ') wordcount++; if(c=='n') { linecount++; wordcount++; charcount--; }
  • 107. c=fgetc(fp); } printf("No of characters is : %dn",charcount); printf("No of words is : %dn",wordcount); printf("No of lines is : %dn",linecount); fclose(fp); return EXIT; } Output: [pmanne@oradb ~]$ gcc totalcount61.c -o total [pmanne@oradb ~]$ ./total Enter the file name :e5 No of characters is : 145 No of words is : 30 No of lines is : 9 62. Write a C program to print only last “n” number of lines from the file passed.(“ n” is passed as argument) #include<stdio.h> #include<ctype.h> #include<stdlib.h> #define EXIT_SUCCESS 0 int main(int argc, char **argv) { FILE *fp,*fopen(); char filename[40];
  • 108. int linecount=0, length=0; int c=0,n=0,k, base=1; if(argc==1) { fprintf(stderr,"No input filesn"); exit(1); } if( argv[1][0]=='-') strcpy(filename, argv[2]); length=strlen(argv[1])-1;//finding length of the argument while(length!=0) { k=argv[1][length]-'0'; n=n+k*base; base=base*10; length--; } fp=fopen(filename,"r"); if(fp == NULL) { printf("Cannot open the file ex:./a.out -n filenamen"); exit(1); } c=fgetc(fp);//get the first character while(c!=EOF) { if(c=='n')
  • 109. linecount++;//count no. of lines i the file c=fgetc(fp); } k=fseek(fp,0,SEEK_SET);//set the position of pointer to the start of file c=fgetc(fp); if(linecount<n) printf("Only %d lines exist in the given filen",linecount); else { while(linecount!=n)//got to the nth line { c=fgetc(fp); if(c=='n') linecount--; } while(c!=EOF)//print the last n lines { printf("%c",c); c=fgetc(fp); } } fclose(fp); return EXIT_SUCCESS; } Output: [pmanne@oradb ~]$ gcc lastn62.c -o last
  • 110. [pmanne@oradb ~]$ ./last 5 e5 Cannot open the file ex:./a.out -n filename [pmanne@oradb ~]$ ./last -5 e5 Hello hello hello hi hello hello abcd efgh hijk lmnop ghjghgh vamsi 63. Write a C program that will compare two text files and prints the differences line wise. Eg: myDiff file1 file2 Output: LineNo difference #include<stdio.h> #include<string.h> #define MAX 1000 int main(int argc,char *argv[]) { FILE *fp,*fp1; char buff1[MAX],buff2[MAX],c1,c2; int n=0,count=0;
  • 111. if(argc!=3) { printf("NOT VALID"); exit(0); } fp=fopen(argv[1],"r"); if(fp==NULL) { printf("Unable to open"); exit(0); } fp1=fopen(argv[2],"r"); if(fp1==NULL) { printf("Unable to open"); exit(0); } while(fgets(buff1,MAX,fp)!=NULL && fgets(buff2,MAX,fp1)!=NULL) { count++; n=strcmp(buff1,buff2); if(n!=0)
  • 112. { printf("nLine number is:%dn",count); printf("nLine where First file doesnot match secnd is:%sn",buff1); printf("n line in second file is:%sn",buff2); fseek(fp,0,SEEK_CUR); fseek(fp1,0,SEEK_CUR); } else { printf("SAME"); fclose(fp); fclose(fp1); } } } Output: [pmanne@oradb ~]$ ./a.out NOT VALID[pmanne@oradb ~]$ ./a.out e1 e2 Line number is:1
  • 113. Line where First file doesnot match secnd is:L|ine|1 abcd line in second file is:line1 Line number is:2 Line where First file doesnot match secnd is:Li|ne|2 line in second file is:line2 Line number is:3 Line where First file doesnot match secnd is:l|i|n|e|3 line in second file is:line3 [pmanne@oradb ~]$ ./a.out e2 e3
  • 114. SAME 64. Write a C program to print only 2nd column words of a given file. 65. Write a program to open a binary file and replace all the contents from middle on wards with reversing words in each line. 66. Write a function in C to find the size of a raw file passed to it. ( Should not use standard library function or system call to get the size) Eg: size = fsize(filename) should print the size of the file. #include <stdio.h> #include <stdlib.h> #define EXIT 0 int main(int argc,char **argv) { FILE *fp; fp=fopen(argv[1],"rb"); long size; if(argc!=2) { printf("Invalid arguments,ENTER FILE NAME ALSO:"); return EXIT; } if(fp==NULL)
  • 115. { printf("Can't open file"); return EXIT; } else { fseek(fp,0,SEEK_END);//seek to the end of the file size=ftell(fp); //get current file pointer //ftell is used for binary files returns the value for the file position pointer printf("Size of the file is:%ldn",size); fclose(fp); return EXIT; } } Output: [pmanne@oradb ~]$ vi f_size.c [pmanne@oradb ~]$ gcc f_size.c -o f [pmanne@oradb ~]$ ./f Invalid arguments,ENTER FILE NAME ALSO:[pmanne@oradb ~]$ ./f e1 Size of the file is:34