Professional Documents
Culture Documents
Useful C Programs
Useful C Programs
Useful C Programs
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);
}
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;
int_part=num;
real_part=num-int_part;
printf("integral part is %d\n real part is %f",int_part,real_part);
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 %d\n",CHAR_MAX);
printf("Min value of type char is %d\n",CHAR_MIN);
printf("Max value of type SIGNED char is %d\n",SCHAR_MAX);
printf("Min value of type SIGNED char is %d\n",SCHAR_MIN);
printf("Max value of type UNSIGNED char is %u\n",UCHAR_MAX);
printf("Max value of short is %d\n",SHRT_MAX);
printf("Min value of short is %d\n",SHRT_MIN);
printf("Max value of UNSIGNED short is%u\n",USHRT_MAX);
printf("Max&MIN value of type int is%d%d\n",INT_MAX,INT_MIN);
printf("Max value of type UNSIGNED int is %d\n",UINT_MAX);
printf("Max value of type long is %ld\n",LONG_MAX);
printf("Min value of type long is %ld\n",LONG_MIN);
printf("Max value of UNSIGNED long is%ld\n",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 ||
#include<stdio.h>
#define exit 0
int main()
long base=1,number,snum,count=0,rem,bin=0;
scanf("%d",&number);
snum=number;
while(number>0)
rem=number%2;
count++;
bin=bin+rem*base;
number=number/2;
base=base*10;
return exit;
Output:
9. Write a program to get product of 2 pow n and a given number without using “*’ operation
myProduct(25, 4) = 25 * 16 = 400
#include<stdio.h>
#define exit 0
int main()
int x,y,prod;
scanf("%d%d",&x,&y);
prod=x<<y;
printf("Product is %d\n",prod);
return exit;
Output:
Product is 128
10. Write a program to get 1’s compliment of a given number without using “~” operator.
#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);
while(num>0)
bin[i]=('1'-1)+(num%2);
i++;
num=num/2;
for(j=i-1;j>=0;j--)
printf("%c",bin[j]);
for(j=i;j>=0;j--)
if(j==i)
if(bin[j]=='0')
bin[j]='1';
else if(bin[j]=='1')
bin[j]='0';
}
l=strlen(bin);
l--;
for(i=l;bin[i]>=0;i--)
if(bin[i]=='1')
s=pow(2,k)+s;
k++;
else
k++;
Output:
Enter an integer:170
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;
scanf("%d",&a);
hexconv(a);
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;
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:
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.
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
int main()
{
long number=0;
char inputstr[30];
printf("Enter a hexadecimal string ");
scanf("%s",inputstr);
printf("string is %s\n",inputstr);
number=htoi(inputstr);
printf("Integer is %ld\n",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("%ld\n",hnumber);
return hnumber;
}
length = strlen(string);
begin = string;
end = string;
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 %s\n",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
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=”Encapsulation\nInheritance\tpolymorphism”;
#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=”Encapsulation\nInheritance\tpolymorphism”;
b. output : - S1=” Encapsulation
c. Inheritance polymorphism”
#include<stdio.h>
#define exit 0
void escapetoreal(char *s,char *t);
int main()
{
char s1[100]="\nEncapsulation\nInheritance\t\tPolymorphism";
char s2[100]="";
printf("Entered string is %s\n:",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
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
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 %s\n",snum,b,result);
}
length = strlen(string);
begin = string;
end = string;
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;
}
length = strlen(string);
begin = string;
end = string;
begin++;
end--;
}
}
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 %d\n",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
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 %.*f\n",pr,number);
return EXIT_SUCCESS;
}
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("%4d\n",stack[0]);
}
void display2()
{
int i=0;
if(top==-1)
printf("empty stack");
for(i=0;i<2;i++)
printf("%4d\n",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("%4d\n",stack[j]);
}
void displayall()
{
int i=0;
if(top==-1)
printf("empty stack");
for(i=0;i<=top;i++)
printf("%4d\n",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("\n\n1.Push a element using a stack\n");
printf("\n2.clear all elements using stack\n");
printf("\n3.Display all the elements\n");
printf("\n4.Exit Program\n");
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]);
}
#define EXIT 0
#define MAX 50
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 %s\n",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);
}
length = strlen(string);
begin = string;
end = string;
begin++;
end--;
}
}
}
}
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
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;
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
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++;
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”
#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.
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>
#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);
int main()
{
int ch,x,y;
do
{
printf("\n\n1.Add element\n");
printf("\n2.Add element in the middle\n");
printf("\n3.Remove element\n");
printf("\n4.Display all the elements\n");
printf("\n5.Exit Program\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 4: display();
break;
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 empty\n");
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("\n\n1.Push\n");
printf("\n2.Pop\n");
printf("\n3.Display\n");
printf("\n4.Exit\n");
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)
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>
node insert(int,node);
void display(node,int);
int main()
{
int ch;
int a;
// node temp;
while(1)
{
printf("\n1.Insert \n2.Display\n3.Exit\nEnter 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");
}
}
}
53. Write a function to delete a given item from the Binary Search Tree (BST).
#include<stdio.h>
#include<stdlib.h>
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.Display\n3.Delete\n4.Exit\nEnter 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;
}
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("\n\n1.Add element\n");
printf("\n2.Display all the elements\n");
printf("\n3.Sort the list\n");
printf("\n4.Find and remove duplicates\n");
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 EXIT\n");
}
}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;
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;
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;
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 delete\n");
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
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 1
1.Add
2.Remove
3.Display
4.Exit
Select any one of the above : 1
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 A\n"); /*Enter the size for matrix A */
printf("\nEnter Number Of Rows : ");
scanf("%d",&r1);
printf("\nEnter Number Of Columns : ");
scanf("%d",&c1);
the result in c
}
}
printf("Subtraction of two matrices using pointers is:\n\n");
for(i=0;i<r1;i++)
{
printf("\t\t");
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));
}
Output:
[pmanne@oradb ~]$ gcc matrixp.c
[pmanne@oradb ~]$ ./a.out
Matrix A
Matrix B
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)
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
#define EXIT 0
#define MAX 40
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>
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:%d\n",count);
printf("\nLine where First file doesnot match secnd is:%s\n",buff1);
printf("\n line in second file is:%s\n",buff2);
fseek(fp,0,SEEK_CUR);
fseek(fp1,0,SEEK_CUR);
}
else
{
printf("SAME");
fclose(fp);
fclose(fp1);
}
}
Output:
#define EXIT 0