Welcome to graduate2professional.blogspot.com

Monday, May 11, 2009

Important Programs in C

BIT OPERATIONS
atoi( ) using bit operaion

main()
{
char *s= "12349";
int i=0;
while (*s)
{
i = (i<<3)+(i<<1)+(*s>Coverting decimal to binary

main()
{
int x=10;
int i;
for(i=0;i<32;i++)>To change/Swap value

main()
{
int x=3;
int y=2;

printf("before %d %d\n",x,y);

x = x^y;
y = x^y;
x = y^x;

printf("after %d %d",x,y);
}
To check no is power of two or not
main()
{
int n;
printf("enter the number\n");
scanf ("%d",&n);

if( n & n-1)
printf("not power of two");
else
printf("power of two");
}
To count 1s in number
-main()
{
int b;
int x=15;
for(b=0;x!=0; x&=(x-1))
++b;
printf("%d",b);
}
-main()
{
int i,x;
printf("enter the no\n");
scanf("%d",&x);

for(i=0;x!=0;i++)
x=x>>1;
printf("count = %d",i);
}

-main()
{
int b=0;
int x=15;
for ( b=0; x!=0; x >>=1)
{
if ( x & 01 )
b++;
}
printf(" No on ones :%d",b);
}

Bit invert from postion P, N bits inverted

int temp[32];
void bitshow(int);
main()
{
int x=11;
int p=3;
int n=2;
int z;
printf("no is %d\n",x);
bitshow(x);
z = ( x ^ (~(~0 << lsb="0,p,i;" i="0;i<32;i++)" lsb =" x" x =" x">> 1;
}
for(p=31;p>=0;p--)
{
printf("%d",temp[p]);
}
}
Bit rotate right
/* Program To Right Rotate Bits */

#include
#include

void rotate ( unsigned long int,int ); // Rotate Right function
void bitshow ( unsigned long int ); // To display 32 bits
int temp[32]; // To hold Bit values

main()
{
int n=5;
unsigned long int x=15;
system ( "clear" );
rotate ( x, n );
}

void rotate ( unsigned long int x, int n )
{
int s=1; // counter to know no of rotates
long int mask;
int lsb;

mask = 1 << lsb =" x" x =" x">> 1;

if ( lsb )
{
x = mask;
}
printf ( "\n%d Rotate:",s );
bitshow ( x );
s++;

} // while ends
printf("\n");
} //function ends

void bitshow ( unsigned long int x )
{
int p,i;

for( i=0; i<32; x =" x">> 1;
}

for ( p=31; p>=0; p--)
printf ( "%d",temp[p] );

} //function ends

Program to set bits
int temp[32];
void bitshow(int);
main()
{
int x=10;
int p=3;
int n=2;
int y=1;
int z;

z = (x & ~(~(~0 <<>Bit SWAP
void swap(int p3,int p4)
{
int lsb=0,p,i;
for(i=0;i<32;i++) lsb =" x" x =" x">> 1;
}
p=temp[p3];
temp[p3]=temp[p4];
temp[p4]=p;
for(p=31;p>=0;p--)
printf("%d",temp[p]);
}

Program to get bits
main()
{
int x=10; //number
int p=3; // from which position
int n=2; // n numbers right

printf("%d",(x>>(p+1-n) & ~(~0 <<>To set particular bit

#include
void bitshow(int);
main()
{
int n,pos;
int mask=1;
printf("entre the number\n");
scanf("%d",&n);
printf("enter the position u want to set\n");
scanf("%d",&pos);
bitshow(n);
mask = mask <<(pos-1); n= nmask; // to set use OR printf("\nafter setting bit\n"); bitshow(n); } To reset BIT
#include
void bitshow(int);
main()
{
int n,pos;
int mask=1;
printf("entre the number\n");
scanf("%d",&n);
printf("enter the position u want to reset\n");
scanf("%d",&pos);
bitshow(n);
mask = mask <<(pos-1); n= n ^ mask; //to reset use XOR printf("\nafter resetting bit\n"); bitshow(n); } To check bit is on or not main()
{
int n,pos;
int mask=1;
printf("entre the number\n");
scanf("%d",&n);
printf("enter the position u want to check\n");
scanf("%d",&pos);
bitshow(n);
n= n>>(pos-1);
n = n&1;
if (n ==1 )
printf("\n%d bit is on\n",pos);
else
printf("\n%d bit is off\n",pos);

}
Bit complement
main()
{
int x=3;
x=~x;
printf("%d",x);
} // -4

BIT REVERSE
main()
{
int x,i;
printf("enter the number\n");
scanf("%d",&x);
printf("no is %d:",x);
for(i=0;i<32;i++) prefix =" i&1<<31)?1">>i&1)?1:0);
}
Bit operation to find min max number
main()
{
int x=10; // we want to find the minimum of x and y
int y=20;
int min,max; // the result goes here
min = y + ((x - y) & -(x < max =" x" min =" %d" max =" %d">Multiplication of two number using bit operation
#include
main()
{
int i,n,m,temp=0;
printf ( "enter two num\n" );
scanf ( "%d %d ",&n,&m );
for(i=0;i<31;i++) temp =" temp+(m<
main()
{
long int n;
int sum=0,base =1,rem;
printf("enter binary form\n");
scanf("%ld",&n);

while(n!=0)
{
rem = n %2;
sum = sum+rem * base;
base = base *2;
n= n/10;
}
printf("%d",sum);
}
Decimal to binary
#include
main()
{
int n,i=0;
printf("enter number\n");
scanf("%d",&n);

for(i=0;i<32;i++)>Decimal to hexa
#include
main()
{
int n,i=0,rem=0,j;
char hexa[10];
printf("enter number\n");
scanf("%d",&n);

while(n)
{
rem = n %16;
if ( rem < n="n/16;" j="i-1;j">=0;j--)
printf("%c",hexa[j]);
}
Decimal to octal
#include
main()
{
int n,i=0,rem,j;
char s[10];
printf("enter number\n");
scanf("%d",&n);

while(n)
{
rem = n%8;
s[i++]=rem;
n=n/8;
}
s[i]='\0';

for(j=i-1;j>=0;j--)
printf("%d",s[j]);
}
Hexa to decimal
#include
main()
{
char s[]="OX1a";
int i=0,hex;
int base = 1,sum=0;
if (s[i] == '0' s[i]=='O')
i++;
if (s[i]== 'x' s[i]=='X')
i++;

while (s[i] !='\0')
{
i++;
};
--i;
for(;i>=2;i--)
{
if (s[i]>='0'&& s[i]<='9') hex=(s[i]-'0'); if (s[i]>='a' &&s[i]<='f') hex =(s[i]-'a')+10; if (s[i]>='A' &&s[i]<='F') hex =(s[i]-'A')+10; sum += hex*base; base = base *16; } printf("%d",sum); } Octal to decimal
#include
main()
{
long int n;
int sum=0,base =1,rem;
printf("enter octal form\n");
scanf("%ld",&n);
while(n!=0)
{
rem=n%10;
sum = sum+ rem * base;
base = base *8;
n= n/10;
}
printf("%d",sum);
}
FILE RELATED PROGRAMS
To print content of file:
#include
#include
main()
{
FILE *fp;
int c;
fp = fopen("p1.c","r");
while ((c = getc(fp)) != EOF )
{
putchar(c);
}
}
Cut a file upto some position
#include
#include
main()
{
int pos,i=0,count=0,len,c;
FILE *fp;
printf ("enter the position value\n");
scanf ("%d",&pos);
fp = fopen("p1.c","r");
fseek(fp,-2,2);
len = ftell(fp);
fseek(fp,0,0);
if( pos > len )
printf("file size is less.....content of file is\n");
while ( (c = getc(fp)) !=EOF && (count != pos))
{
putchar(c);
count++;
}
printf("\n");
if(posTo create two file depending on even and odd size of words
#include
#include
#include
char * word;
//int size;
//char* malloc (int);
//char* realloc (char *,int);
main()
{
int fd,fd1,fd2;
int count=0;
char c;
word =(char*) malloc(50);
fd = open ("p1.c",O_RDONLY);
fd1 = open ( "f1.c",O_WRONLY);
fd2 = open ( "f2.c",O_WRONLY);

while ( read (fd,&c,1) == 1 )
{
word[count++]=c;
// if ( count >= size )
// word = realloc(word,(size+20));
if ( c == ' ' c== '\t' c == '\n')
{
if ( count % 2)
write (fd1,word,count);
else
write ( fd2,word,count );
count = 0;
}
}
}

To convert first and last char of each word in file uppercase
#include
#include
main(int argc,char *argv[])
{
FILE *fp;
int c,lastc;
char a[20];
int i=0,x;
lastc = '\t';
fp = fopen("p1.c","r");
while ((c = getc(fp)) != EOF )
{
if( c ==' ' c == '\t')
printf("%c",c);
else
if (( c != ' ' c!= '\t' c!='\n') && (lastc ==' ' lastc == '\t' lastc=='\n'))
{
c= c +'A'-'a';
a[i++]=c;
}
else if (( c == ' ' c== '\t' c=='\n') && (lastc !=' ' lastc != '\t' lastc!='\n'))
{// i--;
lastc=lastc+'A'-'a';
a[i++]=lastc;
}
else
{
a[i++]=c;
}
lastc=c;
}
for(x=0;xLs command implementation…to list all files in directory
#include
#include
#include
#include
int main( int argc,char *argv[])
{
DIR *dp;
struct dirent *drp;
char *name;
name = malloc(30);
if( argc != 2)
printf("error");
getpwd(name);
if ( ( dp = opendir(name) )== NULL )
printf("error in opening dir");
while((drp = readdir(dp)) != NULL)
printf("%s\n",drp->d_name);
closedir(dp);
exit(0);

}
To convert vowel upper
#include
#include
main()
{
FILE *fp;
int c;
fp = fopen("p1.c","r");
while ((c = getc(fp)) != EOF )
{
if(c == 'a' c== 'e' c=='i'c=='o'c=='u')
{
c = c +'A'-'a';
printf("%c",c);
}
else
printf("%c",c);
}
}
Reversing of file contents
#include
#include
main()
{
FILE *fp;
int c;
int x,y;
fp = fopen("p1.c","r");
x= ftell(fp);
printf( "Intial value of fp is %d\n",x);
fseek(fp,-1,2);
y = ftell (fp);
printf ( "length of file is %d",y);
while ( ftell (fp) > x)
{
c = getc(fp);
printf("%c",c);
fseek ( fp,-2,1);
}
c = getc(fp);
printf("%c",c);
}
Reversing of lines in file
#include
main()
{
FILE *fp,*fp1;
int c,i=0,x,j,k,s;
char a[50];
fp = fopen ( "p1.c","r");
fp1 = fopen ("p2.c","w");

while ( (c = getc(fp))!= EOF )
{
a[i++]=c;
}
i--;
for( x = i ; x >= -1 ; x--)
{ int k;

if ( a[x] == '\n' x == -1)
{ int s;
for ( s = (x+1);sReversing of each word in file
#include
#include
main()
{
int c;
FILE *fp;
char a[50];
int i=0,x,j,k;

fp = fopen("p1.c","r");

while ( (c = getc(fp)) !=EOF )
{
a[i++]=c;
}
i--;
for(x=i;x>=-1;x--)
{
int k;
if(a[x]==' ' a[x] == '\t' a[x]== '\n' x == -1)
{ int s;
j=x;
printf(" ");
for(s=(j+1);sIMP PROGRAMS:
TO Remove more that line blank line in input:
#include
#define BLANK 'a'
main()
{
int c,lastc;
lastc = BLANK;

while ( (c=getchar()) != EOF)
{
if ( c!= ' ')
putchar(c);
if ( c == ' ')
if (lastc != ' ')
putchar(c);
lastc = c;
}
}
TO count blanks char tabs etc
#include
main()
{
int c,nl=0,nt=0,nc=0,nb=0;
while((c=getchar())!= EOF)
{
if( c == ' ')
nb++;
else if( c == '\t')
nt++;
else if(c == '\n')
nl++;
else
nc++;
}
printf(" no of char =%d\n",nc);
printf(" no of newlines =%d\n",nl);
printf(" no of tabs =%d\n",nt);
printf(" no of blanks =%d\n",nb);
CHAR count in input
#include

main()
{
int count=0;
while(getchar() != EOF)
++count;

printf("\nchar count is %d",count);
}
String copy fun
void copy ( char to[],char from[])
{
int i;
i=0;
while ((to[i]=from[i]) != '\0')
++i;
}
TO print longest line in input
#include
#define MAXLINE 1000
int getline ( char line[],int max);
void copy( char to[],char from[]);

main()
{
int len,max;
char line[MAXLINE];
char longest[MAXLINE];

max =0;
while ((len = getline(line,MAXLINE)) > 0)
if ( len > max)
{
max = len;
copy ( longest,line );
}
if ( max > 0)
printf("\n %s",longest);
}

int getline( char s[],int lim)
{
int c,i;
for( i=0;iTo print histogram
#include
char word[100];
main()
{
int count=0,c,i;
while((c=getchar())!=EOF)
{
word[count++]=c;
if( c == ' ' c == '\t' c == '\n' )
{
word[--count]='\0';
printf("%s:\t",word);
for(i=0;i
char word[100];
main()
{
int count=0,c,i;
while((c=getchar())!=EOF)
{
word[count++]=c;
if( c == ' ' c == '\t' c == '\n' )
{
word[--count]='\0';
printf("%s:\t",word);
for(i=0;i To count occurance of digits(how many times each digits occure)
#include

main()
{
int c,i,digit[10];

for(i=0;i<10;i++) c="getchar())!="">= '0' && c <= '9') ++digit[c -'0']; } for(i=0;i<10;i++)>ONE word per line
#include
char word[100];
main()
{
int count=0,c,i;
while((c=getchar())!=EOF)
{
word[count++]=c;
if( c == ' ' c == '\t' c == '\n' )
{
word[--count]='\0';
printf("%s\t",word);
printf("length %d\n",count);
count =0;
}
}
}
Reverse string
void reverse(char s[]);
main()
{
char str[]="hello";
reverse(str);
printf("%s",str);
}
void reverse( char s[])
{
int i,j;
char temp;
i=0;
while ( s[i] !='\0')
++i;
--i;
printf(" i value is %d",i);
j=0;
while ( j < temp =" s[j];">Atoi( ) function string to integer
#include

main()
{
int n;
char str[10]="12345";
n = atoi(str);
printf ( "%d",n);
}

int atoi ( char str[])
{
int n = 0 ,i;
for(i = 0; str[i] >= '0' && str [i] <= '9';i++) n = 10 * n +(str[i]-'0'); return n; } TO check leap year
main()
{
int year;
printf("enter the year you want to test\n");
scanf("%d",&year);
if(( year%4 == 0 && year %100 != 0 ) year %400 == 0)
printf("entered year is leap year\n");
else
printf("not leap year\n");
}
To convert lower to upper in file#include
main()
{
FILE *fp;
int c;
fp = fopen ( "abc.c","r+");

while ( (c = fgetc(fp)) != EOF)
{
if ( c >= 'a' && c <= 'z') { c = c+'A'-'a'; printf("%c",c); } else printf("%c",c); } } Shothand notation
main()
{
int x=2,y=3,z;
x *= y+1;
printf("%d",x);
}
// answer is 8
x *= y+1
x = (x)*(y+1)
x = 2 *(3+1)
x = 8

its not equal to x= x*y+1;

SQueez character
main()
{
char s[]="hello";
char c = 'l';
void sq( char s[],char c);

sq(s,c);
}

void sq(char s[],char c)
{
int i,j;

for(i=j=0;s[i]!='\0';i++)
{
if ( s[i] != c)
s[j++]=s[i];
}
s[j]='\0';
printf("%s",s);
}
Squeeze string
main()
{
char s1[]="hello";
char s2[]="ol";
int i,j,k;

for(i=k=0;s1[i]!='\0';i++)
{
for(j=0;(s2[j]!= '\0'&&s2[j]!= s1[i]);j++)
;
if ( s2[j]=='\0')
s1[k++]=s1[i];

}
s1[k]='\0';
printf("%s",s1);
}

// first h is compared with ol condition true when j becomes \0 condition fails
// h is moved to s1[k].... similarly for others


Strcat function
main()
{
char s[]="hello";
char t[]="world";
int i=0,j=0;

while ( s[i] !='\0')
i++;
while ( (s[i++]=t[j++]) != '\0');
s[i]='\0';
printf("%s",s);
}

Atof ( )
main()
{
char s[]=" 1.2234";
int i,sign;
float x,n,pow;

for(i=0;(s[i] == ' ');i++)
;
sign = (s[i] == '-') ? -1 : 1;
if ( s[i]=='+' s[i]=='-')
i++;
for( n = 0.0 ;(s[i] >='0' && s[i] <= '9');i++) n = 10.0 * n + (s[i]-'0'); if( s[i] == '.') i++; for(pow = 1.0;(s[i] >= '0' && s[i] <= '9');i++) { n = 10.0 * n + (s[i]-'0'); pow = pow * 10.0; } x = ((n*sign)/pow); printf("%5.4f",x); }
Atof () exponent string to float

main()
{
char s[]="1.2e+2";
int i,sign,expo;
float x,n,pow;

for(i=0;(s[i] == ' ');i++)
;
sign = (s[i] == '-') ? -1 : 1;
if ( s[i]=='+' s[i]=='-')
i++;
for( n = 0.0 ;(s[i] >='0' && s[i] <= '9');i++) n = 10.0 * n + (s[i]-'0'); if( s[i] == '.') i++; for(pow = 1.0;(s[i] >= '0' && s[i] <= '9');i++) { n = 10.0 * n + (s[i]-'0'); pow = pow * 10.0; } n = ((n*sign)/pow); if( s[i]== 'e' s[i] == 'E') { i++; sign = (s[i]=='-')?-1:1; if (s[i]=='+'s[i]=='-') i++; for( expo = 0; (s[i] >= '0' && s[i] <= '9');i++) expo = expo * 10 + (s[i] - '0'); if ( sign == 1) while ( expo-- > 0 )
n = n *10;
else
while (expo-- > 0)
n = n/10;
}
printf("%f",n);

}
Atoi () new…
main()
{
char s[]=" - 1234";
int i,n,sign;
for(i=0;(s[i] == ' ');i++)
;
sign = (s[i] == '-') ? -1 : 1;
if ( s[i]=='+' s[i]=='-')
i++;
for( n = 0 ;(s[i] >='0' && s[i] <= '9');i++) n = 10 * n + (s[i]-'0'); printf("%d",(n*sign)); } Concatenation files content in standard output
#include
#include
void filecopy(int,int);
#define SIZE 20
main( int argc,char *argv[])
{
int fd;

if(argc == 1)
{
printf("no command line arg,copy stdin to stdout\n");
filecopy(0,1);
}
else
{
while(--argc > 0)
{
fd = open(*++argv,O_RDONLY);
filecopy(fd,1);
}
}

close(fd);
}

void filecopy( int ifd,int ofd)
{
int n;
char buf[SIZE];
while( (n = read(ifd,buf,SIZE)) > 0)
if(write(ofd,buf,n)!= n)
printf("write error");
}
Compare files
#include
#include
#include

main( int argc, char *argv[])
{
FILE *fp1,*fp2;
void filecomp(FILE *fp1,FILE *fp2);

if ( argc != 3 )
{
fprintf ( stderr, "error in input" );
exit(1);
}
else
{
fp1 = fopen ( *++argv,"r" );
fp2 = fopen ( *++argv,"r" );
}

filecomp ( fp1,fp2 );
fclose ( fp1 );
fclose ( fp2 );
}

void filecomp ( FILE *fp1, FILE *fp2 )
{

char *p1,*p2;
char line1[80],line2[80];

do
{
p1 = fgets ( line1,10,fp1 );
p2 = fgets ( line2,10,fp2 );

if ( p1 == line1 && p2 == line2 )
{
if ( strcmp ( line1,line2 ) != 0 )
{
printf("difference in line %s",line1 );
p1 = p2 = NULL;
}
}
else if ( p1 !=line1 && p2 == line2 )
printf("end of first line");
else if ( p1 == line1 && p2 != line2)
printf( " end of second line ");
}
while ( p1 == line1 && p2 == line2 );
}
Expand a-z
main()
{
char s1[]="m-z";
char s2[30];
char c;
int i=0,j=0;

while((c=s1[i++]) !='\0')
{
if ( s1[i] == '-'&& s1[i+1] >= c)
{
i++;
while( c <>itoa ( ) integer to sting
void reverse(char s[]);
main()
{
int n = -123,i=0;
char s[4];
int sign;

if ((sign= n)<0) n =" -n">0);

if ( sign < i="0,j="(strlen(s)-1);i Replace tab with some number of blanks
#include
main()
{
int tab = 0,c,d;
printf("enter how many space you want to replace with tab\n");
scanf("%d",&tab);

while ((c=getchar()) !=EOF)
{
if ( c == '\\')
if (( d = getchar()) == 't')
while(tab-- > 0 )
putchar(' ');
else
{
putchar(c);
putchar(d);
}
else
putchar(c);
}
}
Replace tab by \t and newline by \n
#include
// to replace tab by \t and newline by \n
main()
{
int c,i=0,j;
char t[300],s[300];

while((c=getchar())!=EOF)
t[i++]=c;

for( i=0,j=0;t[i] !='\0';i++) // from t to s
{

switch(t[i])
{
case '\n' : s[j++]='\\';
s[j++]='n';
s[j++]=' ';
break;
case '\t' : s[j++]='\\';
s[j++]='t';
s[j++]=' ';
break;
default: s[j++]=t[i];
break;
}
s[j]='\0';
}
printf("%s",s);
}
Strcmp() implementation
int strcmp1(char *,char *);
main()
{int i=0;
char s[6]="hello";
char t[6]="hello";
i = strcmp1(s,t);
if( i ==0)
{
printf("strings are equal");
}
else if ( i > 0)
printf("first string is greater than secone\n");
else
printf("first string is smaller than second string");
}
int strcmp1(char s[],char t[])
{
int i;
for(i=0;s[i]==t[i];i++)
{
if(s[i]=='\0')
break;
}
return ( s[i]-t[i]);
}
Strcpy() implementation
main()
{
char *s ="hello";
char *t;
t = malloc(20);
while( (*t++ = *s++) !='\0')
;
printf("%s",t);
}
Strncat()implementation
void ncat(char *,char *,int);
main()
{
char s[20]="hello";
char t[]="priya";
int n=6;
ncat(s,t,n);
printf("%s",s);
}
void ncat(char *s,char *t,int n)
{
int i;
while(*s)
s++;
for(i=0;i< s="'\0';">Strncpy() implementation
void ncopy(char *,char *,int);
main()
{
char s[]="hello";
char t[5];
int n=7;
ncopy(s,t,n);
printf("%s",t);
}

void ncopy(char *s,char *t,int n)
{
while ( *s && n-- > 0)
*t++ = *s++;
while( n-- >=0)
*t++='\0';
}
To replace tab by \t
#include

main()
{
int c;

while((c=getchar())!= EOF)
{
if( c == '\t')
printf("\\t");
else if ( c == ' ')
printf("\\b");
if( c!='\t')
putchar(c);
}
}
To check no is prime or not
#include
main()
{
int n,res;
printf("enter the no to check\n");
scanf("%d",&n);
res=isPrime(n);
if ( res == 1)
printf("it is prime number\n");
else
printf("it is not prime number\n");
}
int isPrime(int n)
{
int i;
if (n<1) n="="2)" 2="="0)" i =" 2;" i ="="">Prime generation
#include
main()
{
int n,res,i;
printf("enter the limit\n");
scanf("%d",&n);
for( i=0;imakefile in unix
OUT: make1.o make2.o
cc -o OUT make1.o make2.o
clean: @rm *.o
decimal to binary for any number from 1 to 9999
#include
main()
{
int i,n;
static int x;
for(;;)
{
printf("\nEnter the number\n");
scanf("%d",&n);
if ( n==9999)
return;
else
{
for(i=0;i<32;i++)> To count number of times substring present in string
#include
main()
{
int count=0;
char *src="djahellohellosjdzchellofhkjsahellojf";
char *match="hello";
char *t1,*t2;
while(*src)
{
t1=src;
t2=match;
while((*t1++==*t2++)&&*t1!='\0'&&*t2!='\0');
if(*t2=='\0')
count++;
src++;
}
if(count==0)
printf("substring not present");
else
printf("substring present in %d number of times\n",count);
}

To display like for number 3
a b c b a
a b a
a

#include
main()
{
int i,j,k=0,n;
char ch='a';
scanf("%d",&n);
while(n!=0)
{
for(i=0;i n--;
}
}
To display number is even or odd without loop or test
#include
main()
{
int a=255;
char *A[]={"evn","odd"};
printf("%s",A[a%2]);
}
fork( )
main()
{
fork();
fork();
fork();
fork();
fork();
printf("Welcome to Orkut...\n");
fork();
}
// 2 ^5 (2 power 5 times it will come)
To check little endian or big endian
#include
main()
{
int x=1;
if(*(char*)&x ==1)
printf("little");
else
printf("big");
}

#include
main()
{
union un
{
int x;
char ar[sizeof(int)];
}ob;
ob.x=1;
if(ob.ar[0]==1)
Printf("little");
else
printf("big");
}
To display in n=4
a b c d c b a
a b c * c b a
a b * * * b a
a * * * * * a

main()
{
int i,j,k=0,n;
char ch='a';
printf("enter the number\n");
scanf("%d",&n);
int z=n;
int x=1,y;
while(n!=0)
{
y=x;
for(i=0;i n--;
x=x+2;
}
}
Program without main
#define str(s) #s
#define swap(y,x) x##y
int swap(in,ma)()
{
if (printf(str("Friends"))){}
return(0);
}

Random number generation
#include //printf()
#include //srand(), rand()
#include //time()
main()
{
int i;
srand(time(NULL));
for( i=0; i<10;>To print without semicolon
~ #include
main()
{
if(printf("sanmaya"))
;
}

To find size of variable without using sizeof operator
~ #include
main()
{
char var;
int size;
size = (char*)(&var+1)-(char*)(&var);
printf("%d",size);
}
Ptr problem
#include
int main()
{
char *s1;
char *s2;
s1="vinay";
s2="vinay";
printf("%p\t%p",s1,s2);
if(s1==s2)
printf("yes");
else
printf("No");
return;
}
//in same scope address of vinay is same
// two string literals in same scope shares same memory

TO count no of char
~ #include
int main()
{
int i;
char *str="AAAABCCCDD";
char *p=str+1,c,*st,w[3];
st=(char *)malloc(strlen(str));
while(c=*(--p))
{
int j=0;
while(c==*p++)
j++;
j==1?sprintf(w,"%c",c):sprintf(w,"%d%c",j,c);
strcat (st, w);
}
puts(st);
return 0;
}
Strstr()
#include
#include
main()
{
int count=0;
char *p="djahellosjdzchelfhkjsahellojf";
char *q="hello",*r;
while(1)
{
r = strstr(p,q);
if( r!= NULL)
{
count++;
p=r+strlen(q);
}
else
break;
}
if(count==0)
printf("substring not present");
else
printf("substring present in %d number of times\n",count);
}


Swap word
#include
#include
int main(void)
{
char a[6], b[6];
int j, len_a, len_b, len;
strcpy(a, "hello");
strcpy(b, "hipriya");
printf("Before: a = %s, b = %s\n", a, b);
/ get the max length of the two strings
Len_a = strlen(a);
len_b = strlen(b);
len = len_a > len_b ? len_a : len_b;
19 // for each character in the longer of the two strings, including the terminating '\0'
for (j = 0; j <= len; ++j) { // swap two characters char c = a[j]; a[j] = b[j]; b[j] = c; } printf("After: a = %s, b = %s\n", a, b); return 0; } TO print Armstrong numbers
0 1 153
1^3+5 ^3 +3 ^3 = 153
~ #include
main()
{
int i,x,sum=0,rem;
for(i=0;i<500;i++) x="i;" rem =" x%10;" sum =" sum" x="x/10;" i="="sum" sum="0;">TO remove array duplicate elements
~ void sort( int *a,int n)
{
int i=0,j,m;
for(i=0;iExample for assert( ) fun…..
#include
#include
main()
{
int x=10;
assert(x==1);
printf("hi");
}
a.out: assert.c:7: main: Assertion `x==1' failed.
Aborted
Compiler directive
#include
#if something ==0 //if we assign other than zero it will give error..t showa something s defined but t is not defined by using #define so error
int some =0;
#endif
main()
{
printf("%d",some);
}
---------0
TO delete file after execution automatically
#include
main()
{
unlink(argv[0]); //deletes a.out(executable)
unlink(__FILE__); //deletes source code
}
printf("%d\n",__LINE__); //line number
printf("%s\n",__FILE__); //file name
printf("%s\n",__DATE__); //date
printf("%s\n",__TIME__); // current time
Const example
const x;
x=10;
printf("%d",x);

In c its okay in c++ it s error
Enumeratons
enum { a,b,c,d,e,r,t,y,u,p}op;
printf("%d",sizeof(op)); // 4 bytes always in UNIX t does not depends on number of constants
gcd iteration
main()
{
int m=200,n=20;
int r= gcd(m,n);
printf("%d",r);
}
int gcd(int m,int n)
{
while(m !=n)
{
if (m>n)
m=m-n;
else
n=n-m;
}
return(m);
}
HASH FUNCTION
#include
int list[30],indexpos[30],indexsize,tabsize;
int create_hashtable(int,int);
int search_hash(int,int);
main()
{
int i,n,item;
system("clear");
printf("enter the size of original table\n");
scanf("%d",&n);
printf("entre the elements\n");
for(i=0;i
#define MAX(a,b) (a>b?a:b)
main()
{
int i=40,j=30,k=15;
int res;
res=MAX(i,MAX(j,k));
printf("%d",res);
}
To find little and big endian
#include
main()
{ int x=1;
if(*(char*)&x == 1)
printf ("little");
else
printf ("big");
}
union x
{
int x;
char a[sizeof(int)];
};
main()
{
union x ob;
ob.x=1;
if( ob.a[0]==1)
printf("little");
else
printf("big");
}
Little endian to big endan
void bitshow(int n);
main()
{unsigned long int x=1111;
printf("number is %d:",x);
bitshow(x);
printf("\n");
x= ( ((x & 0X000000FF ) <<>> 8 )+
((x & 0XFF000000 ) >> 24 ));
printf("big endian representation:");
bitshow(x);
}
To print own code
#include
int main ()
{
int c;
FILE *f = fopen (__FILE__, "r");
if (!f) return 1;
for (c=fgetc(f); c!=EOF;c=fgetc(f))
putchar (c);
fclose (f);
return 0;
}
TO print triangle
# include
int main ()
{
int k, j = 0, i, n, s, ll;
printf (" Enter The NUmber \n");
scanf ("%d", &n);
s = n;
while (j < k =" 0;" i =" 0;">Replacing “the” with “those” n file
#include
char str[]="the";
char str1[]="those";
char word[50];
main()
{
int c,count=0;
while((c = getchar()) != EOF)
{
word[count++]=c;
if (c== ' 'c == '\t' c== '\n')
{
word[--count]='\0';
if (! strcmp(word,str))
{
printf(" ");
printf("%s",str1);
}
else
{
printf(" ");
printf("%s",word);
}
count = 0;
}//end of if
}//end of while
}//end of main
Printing special number
25 36 125 216
5 ^2 =25
6 ^2= 36
5 ^3=125

#nclude
#include
main()
{
int i,x,remi,count=0;
int rem1,res;
for(i=10;i<1000;i++) x="i;" x="x/10;" rem1="i%10;" res =" pow(rem1,count);" res ="="" count ="0;">To display triangle (inside holo)
*
* *
* *
* *
* * * * *
#include
main()
{
int n,i,j,x;
static int m=1,p;
system("clear");
printf("entre the number\n");
scanf("%d",&n);
for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { printf(" "); } x =i; if ( x==1) printf("*"); else if ( x Magic square
include
int
main ()
{
int m[3][3], r = 0, c = 1; //if [7][7] c=3
int k = 1;
while (k <= 9) { m[r][c] = k; if (k % 3 == 0) r = r + 1; else { r = r - 1; c = c + 1; } if (c < c =" 2;"> 2)
c = 0;
if (r < r =" 2;"> 2)
r = 0;
k++;
}
for (r = 0; r <= 2; r++) { printf("\n"); for (c = 0; c <=2 ; c++) printf ("%4d\t", m[r][c]); } } 8 1 6 sum is 15 both vertically and horzontaly 3 5 7 4 9 2 String tokenizer
#include
#include
int main()
{
char hold[6][8];
int i=0,j=0,k=0;
// printf("enter the string\n");
// scanf("%s",array);
char array[]= "hello+world+to+hdfhj+fsdfh";
while(array[i] != '\0')
{
if ( array[i]== '+')
{
i++;
hold[k][j]='\0';
j=0;
k++;
}
hold[k][j++]=array[i];
i++;

}
for(i=0;i <=k;i++) { printf("\n%s",hold[i]); } } To print 1 to 100 and 100 to 1 without using loop
#include
#include

void
prin_down ( int i, int min )
{
if ( i % 8 == 0 )
puts ( "" );

printf ( "%-3d\t", i );

if ( i > min )
prin_down( --i, min );

return;
}

void
prin_up ( int i, int max )
{
if ( i % 8 == 0 )
puts ( "" );

printf ( "%-3d\t", i );

if ( i <>Structure comparison

Write a program to compare two objects of a structure.


Ans
#include
#include
#include

int
main ( void )
{
struct A {
int _1; /* sizeof ( int ) == 4 */
int _2;
float _3; /* sizeof ( float ) == 4 */
char _4; /* sizeof ( char ) is always == 1 */
}a, b;

/* initialize a and b */
...

if ( memcmp ( &a, &b, sizeof a ) == 0 )
puts ( "The two structures are equal" );
else
puts ( "The structures are unequal" );

return EXIT_SUCCESS;
}

This program is very general, and might invoke undefined
behaviour. To make a structure object properly aligned,
the compiler inserts padding bytes whenever (or wherever)
necessary. The Standard does not specify what value these
padded bytes should take. In this example, the objects,
a and b, looks like this:

4 bytes 4 bytes 4 bytes 4 bytes (enlarged)
______ ______ ______ ____ ____ ____ ____
_1 _2 _3 _4 P P P
------ ------ ------ ---- ---- ---- ----

Byte # 0 4 8 12 13 14 15

P is a padding byte in the above illustration, whose value
is undefined. Some compilers may initialize such bytes to
zero, or some may leave it untouched. And, memcmp() compares
padding bytes also, even though these bytes have no meaning!

A more portable and dependable solution is to compare structure
members-by-member, i.e.,

if ( a._1 == b._1 &&
a._2 == b._2 &&
a._3 == b._3 &&
a._4 == b._4 )
puts ( "The two structures are equal" );
else
puts ( "The structures are unequal" );


MAX of 4 integers
#include
#include

#define max2( x, y ) (x) > (y) ? (x) : (y)
#define max4(a, b, c, d) max2 ( max2 ( (a), (b) ), max2 ( (c), (d) ) )

int
main ( void )
{
printf ( "Max: %d\n", max4 ( 10, 20, 30, 40 ) );
printf ( "Max: %d\n", max4 ( 10, 0, 3, 4 ) );
return EXIT_SUCCESS;
}
Combination of all strings
#include
#include
#include

void
string_combi ( char * s, int len )
{
int i;
char tmp;
static int j;
static char *p;

if ( !p )
p = s;

for ( i = 1; i <= len; i++ ) { if ( len > 2 )
string_combi ( s+1, len-1 );
else
{
j++;
printf ( "%d: %s\t", j, p );
if ( !( j%10 ) )
puts ( "" );
}
if ( i < tmp =" s[len-i];">GCD recursion
main()
{
int m=200,n=2;
int x= gcd(m,n);
printf("%d",x);
}

int gcd(int m,int n)
{
if (m==n)
return m;
if ( m==0) return n;
if(n==0)return m;

if(m DATA STRUCTURE
Tree:
#include
#include
struct tree
{
struct tree *left;
int data;
struct tree *right;
};

int inorder (struct tree *sr);
int insert (struct tree **sr, int num);
void Mirror( struct tree *s);
main ()
{
struct tree *bt;
int num, req, d, i = 1;
bt = NULL;
printf ("no. of node");
scanf ("%d", &req);
while (i <= req) { printf ("enter data:"); scanf ("%d", &num); insert (&bt, num); i++; } inorder (bt); } int insert (struct tree **sr, int num) { if ((*sr) == NULL) { (*sr) = (struct tree *) malloc (sizeof (struct tree)); (*sr)->left = NULL;
(*sr)->data = num;
(*sr)->right = NULL;
return;
}
else
{
if (num < (*sr)->data)
insert (&(*sr)->left, num);
else
insert (&(*sr)->right, num);
}
return;
}

int inorder(struct tree *sr)
{
if ((sr) != NULL)
{
inorder ((sr)->left);
printf ("%d\n", (sr)->data);
inorder ((sr)->right);
}
return;
}

void Mirror( struct tree *s) // print n preorder
{
struct tree *t;
if( s == NULL)
return;
else
{
Mirror( s->left);
Mirror(s->rght);
t= s->left;
s->left = s->right;
s->right= t;
}
}
Tree copy
#include
#include
struct btnode
{
struct btnode *left;
int data;
struct btnode *right;
};
int insert (struct btnode **sr, int num);
int preorder (struct btnode *sr);
int copy (struct btnode **src, struct btnode **tgt);
int
main ()
{
struct btnode *bt1, *bt2;
int num, req, d, i = 1;
bt1 = NULL;
printf ("no. of node");
scanf ("%d", &req);
while (i <= req) { printf ("enter data:"); scanf ("%d", &num); insert (&bt1, num); i++; } copy (&bt1, &bt2); printf ("\n original tree\n preorder traversal:"); preorder (bt1); printf ("\n\n\n copied tree\npreorder traversal:"); preorder (bt2); } int copy (struct btnode **src, struct btnode **tgt) { if (*src != NULL) { *tgt = (struct btnode *) malloc (sizeof (struct btnode)); (*tgt)->left = NULL;
(*tgt)->data = (*src)->data;
(*tgt)->right = NULL;
copy (&((*src)->left), &((*tgt)->left));
copy (&((*src)->right), &((*tgt)->right));
}
return;
}

int
insert (struct btnode **sr, int num)
{
if (*sr == NULL)
{
(*sr) = (struct btnode *) malloc (sizeof (struct btnode));
(*sr)->left = NULL;
(*sr)->data = num;
(*sr)->right = NULL;
return;
}
else
{
if (num < (*sr)->data)
insert (&((*sr)->left), num);
else
insert (&((*sr)->right), num);
}
return;
}
int
preorder (struct btnode *sr)
{
if (sr != NULL)
{
printf ("%d", sr->data);
preorder (sr->left);
preorder (sr->right);
}
return;
}
Tree compare
#include
#include
struct btnode
{
struct btnode *left;
int data;
struct btnode *right;
};
int insert (struct btnode **sr, int num);
int compare(struct btnode *sr1, struct btnode *sr2);
int flag = 1;
int
main ()
{
struct btnode *bt1, *bt2;
int num, req, d, i = 1;
bt1 = NULL;
bt2 = NULL;
printf ("no. of node for first tree");
scanf ("%d", &req);
while (i <= req) { printf ("enter data:"); scanf ("%d", &num); insert (&bt1, num); i++; } i = 1; printf (" no. of nodes for second tree "); scanf ("%d", &req); while (i <= req) { printf ("enter data:"); scanf ("%d", &num); insert (&bt2, num); i++; } compare (bt1, bt2); if (flag == 1) printf ("\n trees are Identical"); else printf ("\n trees are not Identical"); } int insert (struct btnode **sr, int num) { if (*sr == NULL) { (*sr) = (struct btnode *) malloc (sizeof (struct btnode)); (*sr)->left = NULL;
(*sr)->data = num;
(*sr)->right = NULL;
return;
}
else
{
if (num < (*sr)->data)
insert (&((*sr)->left), num);
else
insert (&((*sr)->right), num);
}
return;
}
int
compare (struct btnode *sr1, struct btnode *sr2)
{
int l, r;
l = (sr1 == NULL ? 1 : 0);
r = (sr2 == NULL ? 1 : 0);
if (l != r)
flag = 0;
if (sr1 != NULL && sr2 != NULL)
{
if (sr1->data != sr2->data)
flag = 0;
compare (sr1->left, sr2->left);
compare (sr1->right, sr2->right);
}
return;
}
To delete particular node in list……………..You have been given a pointer to an arbitrary node in a linked list,which you should delete without corrupting the list. The head of thelist in not given. ptr _____ _____ _____ _____ _____ 1 --> 3 --> 5 --> 7 --> 9 --- ----- ----- ----- ----- ----- ---- -- Solution: void del_node ( node_t *ptr ) { if ( ptr && ptr -> next ) { node_t *arb = ptr -> next; ptr -> data = ptr -> next -> data; ptr -> next = ptr -> next -> next; free ( arb ); } else if ( ptr && ptr -> next == NULL ) //when it is last node { free ( ptr ); ptr = NULL; } return; }
Reversing of linked list…………….
Question:

You have to reverse a linked list, but the condition is that data X which
resides in the node N should not change. For example,

Addr: 100 200 300 400 500
_____ _____ _____ _____ _____
1 --> 3 --> 5 --> 7 --> 9 ---
----- ----- ----- ----- -----
----
--
should become

Addr: 100 200 300 400 500
_____ _____ _____ _____ _____
1 <-- 3 <-- 5 <-- 7 <-- 9 ----- ----- ----- ----- ----- ---- -- Answer: Generally, we give the solution as follows: Addr: 100 200 300 400 500 _____ _____ _____ _____ _____ 9 --> 7 --> 5 --> 3 --> 1 ---
----- ----- ----- ----- -----
----
--

We write a function reverse () which takes two arguments: one a pointer
to the head, and the other, pointer to second node of the list.


void
reverse ( node_t *hd, node_t *nxt )
{
if ( nxt && nxt -> next )
revesre ( nxt, nxt -> next );

nxt -> next = hd;
hd -> next = NULL;
}
Circular linked list…………..
#include
#include

struct node
{
int info;
struct node *link;
};
typedef struct node * NODE;
NODE insert_front(int,NODE);
NODE insert_rear(int,NODE);
NODE delete_front(NODE);
NODE delete_rear(NODE);
NODE getnode();
void freenode(NODE);
void display(NODE);
main()
{ NODE last;
last = NULL;
int choice,item;
system ("clear");
do
{
printf ( "1.INSERT FRONT\n" );
printf ( "2.INSERT REAR\n" );
printf ( "3.DELETE FRONT\n" );
printf ( "4.DELETE REAR\n" );
printf ( "5.DISPLAY\n" );
printf ( "6.EXIT\n" );

printf ("Enter The Choice\n" );
scanf ( "%d", &choice );

switch ( choice )
{
case 1: printf ( "Enter the element to b inserted\n " );
scanf ( "%d", &item );
last = insert_front ( item,last );
break;
case 2: printf ( "Enter the element to b inserted\n " );
scanf ( "%d", &item );
last = insert_rear(item,last);
break;
case 3: last= delete_front(last );
break;
case 4: last = delete_rear(last);
break;
case 5: display(last);
break;
case 6: exit ( 0 );
break;
}
}while ( choice <= 6); } NODE insert_front ( int item, NODE last ) { NODE temp; temp = getnode( ); temp->info = item;
if ( last == NULL)
last = temp;
else
temp->link = last->link;
last->link= temp;
return last;
}

NODE insert_rear ( int item, NODE last )
{
NODE temp;
temp = getnode();
temp->info = item;
if ( last == NULL)
{
last = temp;
last->link = last;
}
else
{
temp->link = last->link;
last->link = temp;
}
return temp; // now temp is last node
}


void display ( NODE last )
{
NODE temp,first;
temp = last;

if ( last == NULL )
{
printf ( "list is empty" );
return;
}
printf ( "\n" );
printf ( "contents of list are\n ");

first= last;
for(temp=last->link;temp!=last;temp= temp->link)
{
printf ( "%d\t",temp->info );
}
printf("%d\n",temp->info); //TO PRINT LAST NODE
}

NODE getnode ()
{
NODE temp;
temp = (NODE)malloc (sizeof ( struct node ));
if ( temp == NULL )
{
printf ( "out of memory ");
exit ( 0 );
}
return temp;
}

NODE delete_front(NODE last)
{
NODE first,temp;
if ( last == NULL)
{
printf("list is empty\n");
return;
}
if ( last->link == last)
{
printf("%d deleted",last->info);
freenode(last);
last = NULL;
return last;
}

first = last->link;
temp = first->link;
printf("%d deleted\n",first->info);
freenode(first);
last->link = temp;
return last;
}
NODE delete_rear(NODE last)
{
NODE prev;

if ( last == NULL)
{
printf("list is empty\n");
return;
}
if ( last->link == last)
{
printf("%d deleted",last->info);
freenode(last);
return NULL;
}

prev = last->link; // to find prev of last node
while( prev->link != last)
{
prev = prev->link;
}
prev->link = last->link;
printf("%d deleted",last->info);
freenode(last);
return prev;
}

void freenode(NODE last)
{
free(last);
}
Double linked list……………….
// implementation of doubly linked list

#include
#include

// structure for doubly linked list
struct node
{
int info;
struct node *rlink;
struct node *llink;
};
typedef struct node *NODE;

//functions used

NODE getnode ( );
NODE insert_front ( int, NODE );
NODE insert_rear ( int, NODE );
NODE delete_front ( NODE );
NODE delete_rear ( NODE );
void display ( NODE );
void freenode ( NODE) ;

// main starts

main()
{
NODE head;
int item,choice;
system ( "clear" );
head = getnode ( );
head->rlink = head;
for ( ;; )
{
printf ( "1.INSERT FRONT\n" );
printf ( "2.INSERT REAR\n" );
printf ( "3.DELETE FRONT\n" );
printf ( "4.DELETE REAR\n" );
printf ( "5.DISPLAY\n" );
printf ( "6.EXIT\n" );
scanf ( "%d",&choice );

switch ( choice )
{
case 1: printf ( "enter the item to be inserted\n" );
scanf ( "%d",&item );
head = insert_front ( item, head );
break;

case 2: printf ( "enter the item to be inserted\n" );
scanf ( "%d",&item );
head = insert_rear ( item, head );
break;

case 3: head = delete_front ( head );
break;

case 4: head = delete_rear ( head );
break;

case 5: display ( head );
break;

case 6: exit ( 0 );
break;

default: exit ( 0 );

}// switch ends

} // for ends
}// main ends

//functions definitions

NODE insert_front ( int item, NODE head )
{
NODE temp,cur;

// node to be inserted

temp = getnode ( );
temp->info = item;

// node is inserted between head and first node
// head new first

cur = head->rlink;
head->rlink = temp;
temp->llink = head;
temp->rlink = cur;
cur->llink = temp;

return head;

}

NODE insert_rear ( int item, NODE head )
{
NODE temp,cur;

// node to be inserted

temp = getnode ( );
temp->info = item;
// node is inserted between head and first node
cur = head->llink;
head->llink = temp;
temp->rlink = head;
temp->llink = cur;
cur->rlink = temp;
return head;
}
NODE delete_front ( NODE head )
{
NODE cur ,next;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->rlink; // first node in list
next = cur->rlink; // second node in list in known
head->rlink = next;
next->llink = head;
printf ( "Deleted item is %d\n",cur->info );
freenode ( cur );
return head;

}
NODE delete_rear ( NODE head )
{
NODE cur, prev;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->llink; // last node
prev = cur->llink;

head->llink = prev;
prev->rlink = head;
printf ( "Deleted item is %d\n", cur->info);
freenode ( cur );
return head;

}
void display ( NODE head )
{
NODE temp;
if ( head->rlink == head )
{
printf ( "list is empty" );
exit ( 0 );

}
printf ( " content of list are\n" );

for ( temp = head->rlink; temp != head ; temp = temp->rlink )
printf ( "%d\t",temp->info );
printf ( "\n" );
}
NODE getnode ( )
{
NODE x;
x = ( NODE ) malloc ( sizeof( struct node) );
return x;
}
void freenode ( NODE x )
{
free ( x );
}
Linked list………………….
#include
#include

struct node
{
int info;
struct node *link;
};
typedef struct node * NODE;

main()
{

NODE first;
first = NULL;
int choice,item;
system ("clear");
do
{
printf ( "1.INSERT\n" );
printf ( "2.DISPLAY\n" );
printf ( "3.EXIT\n" );

printf ("Enter The Choice\n" );
scanf ( "%d", &choice );

switch ( choice )
{
case 1: printf ( "Enter the element to b inserted\n " );
scanf ( "%d", &item );
first = insert ( item,first );
break;
case 2: display ( first );
break;
case 3: exit ( 0 );
break;
}
}while ( choice <= 3); } NODE insert ( int item, NODE first ) { NODE temp; temp = getnode( ); temp->info = item;
temp->link = first;

return temp;
}

void display ( NODE first )
{
NODE temp;
temp = first;

if ( first == NULL )
{
printf ( "list is empty" );
return;
}
printf ( "\n" );
printf ( "contents of list are\n ");

while ( temp != NULL )
{
printf ( "%d\t",temp->info );
temp = temp->link;
}
printf ( "\n" );
}

NODE getnode ()
{
NODE temp;
temp = (NODE)malloc (sizeof ( struct node ));
if ( temp == NULL )
{
printf ( "out of memory ");
exit ( 0 );
}
return temp;
} Important prog in linked list……………
// to find middle node in list
NODE middle_node(NODE first)
{
NODE temp,cur;
temp=first;
cur = first;
while(temp != NULL)
{
temp= temp->link;
if( temp != NULL)
{
temp=temp->link;
cur = cur->link;
}
else
{
break;
}
}
printf("middle node = %d", cur->info);
return first;
}
// insert front in list
NODE insert_front(NODE first,int n)
{
NODE temp;
temp = getnode();
temp->info=n;
temp->link =first;
return temp;
}
// delete front from list
NODE delete_front(NODE first)
{
NODE temp;
temp = first;
first = first->link;
printf("deleted item id %d",temp->info);
freenode(temp);
return first;
}
// display list
void display(NODE first)
{
NODE temp;
if(first == NULL)
printf("empty list\n");
for(temp=first;temp!=NULL;temp=temp->link)
printf("%d\t",temp->info);
printf("\n");
}
// to get node
NODE getnode()
{
NODE temp;
temp =(NODE) malloc(sizeof(struct node));
if( temp== NULL)
printf("no memory\n");
return temp;
}
// insert rear
NODE insert_rear(NODE first,int n)
{
NODE temp,cur;
temp = getnode();
temp->info=n;
temp->link = NULL;
if( first == NULL)
return temp;
cur = first;
while(cur->link !=NULL)
{
cur = cur->link;
}
cur->link = temp;
return first;
}
// delete rear

NODE delete_rear(NODE first)
{
NODE prev,cur;
if ( first == NULL)
{
printf("list is empty\n");
return first;
}
if( first->link == NULL)
{
printf("deleted node is %d\n",first->info);
freenode(first);
first = NULL;
return first;
}
cur = first;
prev = NULL;
while( cur->link != NULL)
{
prev = cur;
cur = cur->link;
}
printf("deleted node is %d\n",cur->info);
freenode(cur);
prev->link = NULL;
return first;
}
// insert after some position

NODE insert_after(int item,NODE first,int n)
{
NODE temp,cur,next;
int count = 1;
temp = getnode();
temp->info = item;
temp->link = NULL;

if( first == NULL)
return temp;
cur = first;
while( cur != NULL && count < cur =" cur">link;
count++;
}
if ( cur == NULL)
{
printf("invalid position no\n");
exit(0);
}
next = cur->link;
cur->link= temp;
temp->link= next;

return first;
}

// insert before
NODE insert_before(int item,NODE first,int n)
{
NODE temp,cur,next,prev;
int count = 1;
temp = getnode();
temp->info = item;
temp->link = NULL;

cur = first;
if( first == NULL)
return temp;
if ( n == 1 ) // to add in first position
{
temp->link = cur;
return temp;
}

while( cur != NULL && (count+1) < prev =" cur;" cur =" cur">link;
count++;
}
if( count+1 == n) // to add in last position
{
prev->link = temp;
return first;
}
if ( count+1 < next =" cur-">link;
cur->link = temp;
temp->link=next;

return first;
}
// to delete after some position

NODE delete_after(int item,NODE first,int n)
{
NODE cur,next,prev;
int count = 1;
if( first == NULL)
{
printf("list is empty");
return;
}
prev = NULL;
cur = first;
while( cur != NULL && count < (n+1)) { prev = cur; cur = cur ->link;
count++;
}
next= cur->link;
prev->link =next;
printf("%d is deleted",cur->info);
freenode(cur);

return first;
}
// delete before some position

NODE delete_before(int item,NODE first,int n)
{
NODE cur,next,prev;
int count = 1;
if( first == NULL)
{
printf("list is empty");
return;
}
next = NULL;
prev = NULL;
cur = first;
if( n == 1 )
{
printf(" no element befor that to delete");
return;
}
if ( n == 2)
{
next = cur->link;
printf("%d is deleted\n",cur->info);
freenode(cur);

return next;
}

while( cur != NULL && (count+1) < prev =" cur;" cur =" cur">link;
count++;
}
next= cur->link;
prev->link =next;
printf("%d is deleted",cur->info);
freenode(cur);

return first;
}
// insert in order list
NODE insert ( int item, NODE first )
{
NODE temp,cur,prev;
// get node to be inserted
temp = getnode();
temp->info = item;
temp->link = NULL;

//if list is empty
if ( first == NULL )
return temp;
//insert at begining
if ( item <>info )
{
temp->link = first;
return temp;
}
cur = first;
prev = NULL;
while ( cur != NULL && item > cur->info )
{
prev = cur;
cur = cur->link;
}
prev->link = temp;
temp->link = cur;
return first;
}

// search a item in list
NODE search(int key ,NODE first)
{
NODE cur;
int pos;

if( first == NULL)
{
printf("list is empty");
return;
}
cur = first;
pos =1;
while (cur != NULL && key != cur->info)
{
pos++;
cur = cur->link;

}

if ( cur == NULL)
{
printf("unsuccessful");
return;
}
else

printf("successfull item found in position %d",pos);
return first;
}

// merge list
NODE merge ( NODE a, NODE b )
{
NODE i,j,k,c;
i = a;
j = b;
c =k= getnode();
while ( i != NULL && j != NULL )
{
if ( i->info <>info )
{
k->link = i;
i = i->link;
}
else
{
k->link = j;
j = j->link;
}
k = k->link;
}
while ( i != NULL )
{
k->link = i;
i= i->link;
}
while ( j != NULL )
{
k->link = j;
j= j->link;
}
return c->link;

}
// concat two lists
NODE concat ( NODE a, NODE b )
{
NODE cur;
if ( a == NULL)
return b;
else if ( b== NULL)
return a;
cur = a;
while( cur->link != NULL)
cur = cur->link;
cur->link = b;
return a;
}
// no of nodes
NODE nodes(NODE first)
{
NODE temp;
int count = 1;
temp = first;
if ( first == NULL)
{
printf("list is empty\n");
return;
}

while( temp->link != NULL)
{
temp = temp->link;
count++;
}
printf("total no of nodes == %d\n",count);
return first;
}
// insert specified position
NODE insert_specified(int item,NODE first,int n)
{
NODE temp,prev,cur;
int count;

temp = getnode();
temp->info = item;
temp->link=NULL;

if( first == NULL && n == 1)// inserting node for first time
return temp;
if ( first == NULL)
{
printf("invalid pos\n");
return first;
}

if ( n == 1)
{
temp->link = first;
return temp;
}
count = 1;
prev = NULL;
cur = first;
while( cur != NULL && count != n)
{
prev = cur;
cur = cur->link;
count++;
}
if ( count == n)
{
prev->link = temp;
temp->link = cur;
return first;
}
printf("invalid position");
return first;
}
// delete from specified position
NODE delete_specified(NODE first,int pos)
{
NODE prev,cur;
int count;

if( first == NULL )
{
printf("list is empty\n");
return first;
}
if (pos == 1)
{
cur = first;
first = first->link;
printf("%d deleted",cur->info);
freenode(cur);
return first;
}
count = 1;
prev = NULL;
cur = first;
while( cur != NULL && count != pos)
{
prev = cur;
cur = cur->link;
count++;
}
if ( cur == NULL)
{
printf("invalid position");
return first;
}

prev->link= cur->link;
return first;
}
// delete node whose info given
NODE delete_specified_info(NODE first,int item)
{
NODE prev,cur;
int count;

if( first == NULL )
{
printf("list is empty\n");
return first;
}
if (item == first->info)
{// delete first node
cur = first;
first = first->link;
printf("%d deleted",cur->info);
freenode(cur);
return first;
}
prev = NULL;
cur = first;

while( cur != NULL && item != cur->info)
{
prev = cur;
cur = cur->link;
}
if ( cur == NULL)
{
printf("item not found");
return first;
}

prev->link= cur->link;
freenode(cur);
return first;
}

// to replace all accurance of given value by other value
NODE replace(int a,int b,NODE first)
{
NODE cur;
int count = 0;
cur = first;
while (cur != NULL )
{
if ( a != cur->info)
cur = cur->link;
else
{
count++;
cur->info = b;
cur = cur->link;
}
}
if ( count == 0)
printf("item nnot found in list\n");

return first;
}
// replace some node value by other value

NODE replace(int a,int b,NODE first)
{
NODE cur;
int count = 0;
cur = first;
count =1;
while (cur != NULL )
{
if ( a != count)
{
cur = cur->link;
count++;
}
else
{
count++;
cur->info = b;
cur = cur->link;
return first;
}
}
if ( cur == NULL)
printf("node not found in list\n");
return first;
}
// sum of all elements in list
NODE sum(NODE first)
{
NODE cur;
int count = 0;
cur = first;
if ( first == NULL)
{
printf("list is empty\n");
return;
}
while (cur != NULL )
{
count = count+cur->info;
cur = cur->link;
}
printf("sum of all elements %d",count);

return first;
}
// delete all duplicate ele with specified info

NODE delete_specified_info(NODE first,int item)
{
NODE prev,cur;
int count=0;

if( first == NULL )
{
printf("list is empty\n");
return first;
}
if (item == first->info)
{// delete first node
cur = first;
first = first->link;
printf("%d deleted",cur->info);
freenode(cur);
}
prev = NULL;
cur = first;
while( cur != NULL)
{
if( item != cur->info)
{
prev = cur;
cur = cur->link;
}
else
{
count++;
prev->link= cur->link;
freenode(cur);
return first;
}
}
if( count == 0)
printf ("item not found in list\n");
return first;
}
// split list... each successive elements should move to seperate list
NODE split(NODE first)
{
NODE i,j,cur;
i = NULL;
j= NULL;
int count=1;
cur = first;
while( cur != NULL)
{
if ( count%2 != 0)
{
i = insert(cur->info,i);
cur = cur->link;
count++;
}
else
{
j= insert(cur->info,j);
cur = cur->link;
count++;
}
}
printf("first list is \n");
display(i);
printf("second list is \n");
display(j);
return first;
}
// split list into two evn odd lists
NODE split(NODE first)
{
NODE i,j,cur;
i = NULL;
j= NULL;

cur = first;
while( cur != NULL)
{
if ( (cur->info)%2 == 0)
{
i = insert(cur->info,i);
cur = cur->link;

}
else
{
j= insert(cur->info,j);
cur = cur->link;

}
}
printf("even list is \n");
display(i);
printf("odd list is \n");
display(j);
return first;
}
// CIRCULAR LIST
// combining two circular list into one circular list
NODE com( NODE a, NODE b )
{
NODE i,j,k,c,m;
i = a->link;
m = a->link;
j = b->link;
c = k = getnode();
while ( i != a)
{
i = i->link;
}
i->link = b->link;
while( i != b)
{
i= i->link;
}
i->link=m;

return i;

}
// insert front
NODE insert_front ( int item, NODE last )
{
NODE temp;
temp = getnode( );
temp->info = item;
if ( last == NULL)
last = temp;
else
temp->link = last->link;
last->link= temp;
return last;
}
// insert rear
NODE insert_rear ( int item, NODE last )
{
NODE temp;
temp = getnode();
temp->info = item;
if ( last == NULL)
{
last = temp;
last->link = last;
}
else
{
temp->link = last->link;
last->link = temp;
}
return temp; // now temp is last node
}
// delete front
NODE delete_front(NODE last)
{
NODE first,temp;
if ( last == NULL)
{
printf("list is empty\n");
return;
}
if ( last->link == last)
{
printf("%d deleted",last->info);
freenode(last);
last = NULL;
return last;
}

first = last->link;
temp = first->link;
printf("%d deleted\n",first->info);
freenode(first);
last->link = temp;
return last;
}
// delete rear
NODE delete_rear(NODE last)
{
NODE prev;

if ( last == NULL)
{
printf("list is empty\n");
return;
}
if ( last->link == last)
{
printf("%d deleted",last->info);
freenode(last);
return NULL;
}

prev = last->link; // to find prev of last node
while( prev->link != last)
{
prev = prev->link;
}
prev->link = last->link;
printf("%d deleted",last->info);
freenode(last);
return prev;
}
// doubly linked list
struct node
{
int info;
struct node *rlink;
struct node *llink;
};
head = getnode ( );
head->rlink = head;
NODE insert_front ( int item, NODE head )
{
NODE temp,cur;

temp = getnode ( );
temp->info = item;
// node is inserted between head and first node
// head new first
cur = head->rlink;
head->rlink = temp;
temp->llink = head;
temp->rlink = cur;
cur->llink = temp;

return head;

}
NODE insert_rear ( int item, NODE head )
{
NODE temp,cur;

// node to be inserted

temp = getnode ( );
temp->info = item;

// node is inserted between head and first node

cur = head->llink;
head->llink = temp;
temp->rlink = head;
temp->llink = cur;
cur->rlink = temp;
return head;
}
NODE delete_front ( NODE head )
{
NODE cur ,next;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->rlink; // first node in list
next = cur->rlink; // second node in list in known
head->rlink = next;
next->llink = head;
printf ( "Deleted item is %d\n",cur->info );
freenode ( cur );
return head;
NODE delete_rear ( NODE head )
{
NODE cur, prev;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->llink; // last node
prev = cur->llink;

head->llink = prev;
prev->rlink = head;
printf ( "Deleted item is %d\n", cur->info);
freenode ( cur );
return head;

}void display ( NODE head )
{
NODE temp;
if ( head->rlink == head )
{
printf ( "list is empty" );
exit ( 0 );

}
printf ( " content of list are\n" );

for ( temp = head->rlink; temp != head ; temp = temp->rlink )
printf ( "%d\t",temp->info );
printf ( "\n" );
}

NODE insert_left ( int item,int pos, NODE head )
{
NODE temp,cur,prev;
if ( head->rlink == head )
{
printf ( "list is empty" );
return head;
}
// search for position

cur = head->rlink;
while ( cur != head && pos != cur->info )
{
cur = cur->rlink;
}

if ( cur == head )
{
printf ( "position not found\n " );
return head;
}
prev = cur->llink;

// node to be inserted

temp = getnode ( );
temp->info = item;

prev->rlink = temp;
temp->llink = prev;
cur->llink = temp;
temp->rlink = cur;

return head;

}

NODE insert_right( int item,int pos, NODE head )
{
NODE temp,cur,next;

if ( head->rlink == head )
{
printf ( "list is empty" );
return head;
}
// search for position

cur = head->rlink;
while ( cur != head && pos != cur->info )
{
cur = cur->rlink;
}

if ( cur == head )
{
printf ( "position not found\n " );
return head;
}
next = cur->rlink;

// node to be inserted

temp = getnode ( );
temp->info = item;

cur->rlink = temp;
temp->llink = cur;
temp->rlink = next;
next->llink = temp;

return head;
}

NODE delete_info ( int item,NODE head )
{
NODE cur ,prev,next;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->rlink; // first node in list

while ( cur != head && item != cur->info )
{
cur = cur->rlink;
}
if ( cur == head )
{
printf ( "item not found\n" );
return head;
}
//item found
prev = cur->llink;
next = cur->rlink;

prev->rlink = next;
next->llink = prev;

freenode( cur );
return head;
}

NODE delete_all ( int item,NODE head )
{
int count=0;
NODE cur, prev,next;
if ( head->rlink == head )
{
printf ( "list is empty\n" );
return head;
}

cur = head->rlink; // last node
while ( cur != head )
{
if ( item != cur->info)
cur = cur->rlink;
else
{
count++;
prev = cur->llink;
next = cur->rlink;
prev ->rlink = next;
next->llink = prev;
freenode ( cur );
cur = next; // next search starts from this point
}
}

if ( count == 0 )
{
printf ( "item not found in list \n" );

}

return head;
}
Reversing of lnked list………
NODE rev ( NODE first)
{
NODE cur,temp;
cur = NULL;
while ( first != NULL )
{
temp = first;
first = first ->link;
temp->link = cur;
cur = temp;
}
return cur;
}
STACK
#define SIZE 20
struct stack
{
int item[SIZE];
int top;
};
void push(struct stack *s,int);
int pop(struct stack *s);
void display(struct stack *s);

main()
{
struct stack *s;
s->top = -1;
int ch,item;

printf("STACK OPETAIONS\n");
do
{

printf("\n 1.PUSH\n");
printf("2.POP\n");
printf("3.DISPLAY\n");
printf("4.EXIT\n");

printf("ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the item to pushed onto stack\n");
scanf("%d",&item);
push(s,item);
break;
case 2: item = pop(s);
printf("deleted item is %d\n",item);
break;
case 3: display(s);
break;
case 4: exit(0);

}
}while( ch <= 4); } void push( struct stack *s,int item) { if( s->top == SIZE-1)
{
printf("stack is overflow\n");
exit(0);
}
s->item[++(s->top)]=item;
printf("top is %d\n",s->top);
}

int pop(struct stack *s)
{
int item;
if ( s->top == -1 )
{
printf("stack is empty\n");
exit(0);
}

item = s->item[s->top--];
return item;
}

void display( struct stack *s)
{
int i;
if ( s->top == -1 )
{
printf("stack is empty\n");
exit(0);
}
printf("stack elements are\n");
for(i=s->top;i>=0;i--)
printf("%d\t",s->item[i]);
}

Stack using array
#define SIZE 20
int item[SIZE];
int top=-1;
int item1; // item to be inserted
void push();
int pop();
void display();
main()
{
int ch;

printf("STACK OPETAIONS\n");
do
{
printf("\n 1.PUSH\n");
printf("2.POP\n");
printf("3.DISPLAY\n");
printf("4.EXIT\n");
printf("ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the item to pushed onto stack\n");
scanf("%d",&item1);
push();
break;
case 2: item1 = pop();
printf("deleted item is %d\n",item1);
break;
case 3: display();
break;
case 4: exit(0);

}
}while( ch <= 4); } void push() { if( top == SIZE-1) { printf("stack is overflow\n"); exit(0); } item[++top]=item1; } int pop() { if ( top == -1 ) { printf("stack is empty\n"); exit(0); } item1 = item[top]; top--; return item1; } void display( ) { int i; if (top == -1 ) { printf("stack is empty\n"); exit(0); } printf("stack elements are\n"); for(i=top;i>=0;i--)
printf("%d\t",item[i]);
}
Copy linked list: insert() display() getnode() are same
void copy(NODE s,NODE *t); // copy from s to t
main()
{
NODE first,first1;
first = NULL;
first1 = NULL;
int choice,item,n;
printf("enter how many elements u want to insert\n");
scanf("%d",&n);

while( n)
{
printf("enter the element\n");
scanf("%d",&item);
first = insert ( item,first );
n--;
}
printf("list before copy\n");
display(first);

copy(first,&first1);
printf("list after copy\n");
display(first1);
}
void copy(NODE s,NODE *t)
{
if ( s != NULL)
{
(*t) = malloc ( sizeof ( struct node));
(*t)->info = s->info;
(*t)->link = NULL;
copy( s->link,&((*t)->link));
}
}
Comparing two list:
int compare (NODE s, NODE t);
main ()
{
NODE first, first1;
first = NULL;
first1 = NULL;
int flag, item, n,n1;

printf ("enter no of lements for first list\n");
scanf ("%d", &n);
while (n)
{
printf ("enter the element\n");
scanf ("%d", &item);
first = insert (item, first);
n--;
}
printf ("enter no of lements for second list\n");
scanf ("%d", &n1);

if( n != n1)
{
printf("unequal\n");
exit(0);
}

while (n1)
{
printf ("enter the element\n");
scanf ("%d", &item);
first1 = insert (item, first1);
n1--;
}
flag = compare (first, first1);
if( flag)
printf("equal");
else
printf("unequal");
}

int
compare (NODE first, NODE first1)
{
static int flag;
if (first == NULL && first1 == NULL)
flag = 1;
else
{
if (first->info != first1->info)
flag = 0;
else
compare (first->link, first1->link);
}
return flag;
}


Recursive reverse linked list

NODE * rev ( NODE * root)
{
If ( root)
{
rev( root->next);
printf(“%d”,root->info);
}
}

To find middle node in list

void middle(NODE first)
{
NODE p,q;
p= first;
q= first;

if( q->link->link != NULL)
{
p= p->link;
q=q->link->link;
}
printf("%middle ele is %d\n",p->info);
}

Delete particular node first pointer not given

struct node
{
int info;
struct node *link;
};
typedef struct node * NODE;

NODE getnode();
NODE insert(int ,NODE);
void display(NODE);
void del(NODE);
NODE a[7];
static int i=0;
main()
{

NODE first;
first = NULL;
int choice,item,n;

printf("enter how many elements u want to insert\n");
scanf("%d",&n);

while( n)
{
printf("enter the element\n");
scanf("%d",&item);
first = insert ( item,first );
n--;
}
printf("list is\n");
display(first);
del(a[1]);
display(first);
}
NODE insert ( int item, NODE first )
{
NODE temp;
temp = getnode( );
a[i++]=temp;
temp->info = item;
temp->link = first;
return temp;
}
void display ( NODE first )
{
NODE temp;
temp = first;
if ( first == NULL )
{
printf ( "list is empty" );
return;
}
printf ( "\n" );
printf ( "contents of list are\n ");

while ( temp != NULL )
{
printf ( "%d %u\n",temp->info,&temp->info );
temp = temp->link;
}
printf ( "\n" );
}


NODE getnode ()
{
NODE temp;
temp = (NODE)malloc (sizeof ( struct node ));
if ( temp == NULL )
{
printf ( "out of memory ");
exit ( 0 );
}
return temp;
}
void del( NODE x)
{
NODE t;
if ( x->link == NULL)
printf("cont delete\n");
else
{
t=x->link;
x->info = t->info;
x->link = t->link;
free(t);
}
}
Reversing of list---iterative
NODE rev( NODE first)
{
NODE p,q,r;
p=first;
q=p->link;
p->link = NULL;
while(q!= NULL)
{
r = q->link;
q->link =p;
p = q;
q = r;
}
return p;
}
Sorting of linked list
void sort (NODE first)
{
NODE tmp,cur;
for (tmp = first; tmp->link != NULL; tmp = tmp->link)
for (cur = tmp->link; cur != NULL; cur = cur->link)
{
if (tmp->info > cur->info)
{
int n;
n = cur->info;
cur->info = tmp->info;
tmp->info = n;
}
}
}


























No comments:

Post a Comment