c sample example

188
Learn C with example Print all even numbers from 1 to 100 Input a number and sum its digits Swap two number using two variables Print the sum of odd number and even number separately of n number Input an alphabet and change its case Accept a number and check is it prime number or not a prime number Check a number is perfect or not,( perfect number is sum of its factor number) Print the multiword string Greatest number of any three given numbers Print your own name n times using for loop Enter a number and show its factor Input a character and check it vowel or not P rint average of n number Print alphabets triangle in C Print alphabet triangle Using C Print Number Triangle in C Print Number Triangle Using C Enter a number and print Star line in Reverse Order

Upload: mano-haran

Post on 18-Apr-2015

168 views

Category:

Documents


2 download

TRANSCRIPT

Learn C with example

 

Print all even numbers from 1 to 100

Input a number and sum its digits

Swap two number using two variables

Print the sum of odd number and even number separately of n number

Input an alphabet and change its case

Accept a number and check is it prime number or not a prime number

Check a number is perfect or not,( perfect number is sum of its factor number)

Print the multiword string

Greatest number of any three given numbers

Print your own name n times using for loop

Enter a number and show its factor

Input a character and check it vowel or not

P rint average of n number

Print alphabets triangle in C

Print alphabet triangle Using C

Print Number Triangle in C

Print Number Triangle Using C

Enter a number and print Star line in Reverse Order

Print Reverse Star Triangle Using C

Print Reverse Star Using C

Print Star Triangle Using C

Print Star Rectangle in C

Print Star triangle C

Print Alphabets Triangle

Input a Number and Count its Digit

Print binary triangle Using C

Input a Number and Print the Following 1*2*3*4*5*6......*n

Print The Reverse Number Using C

Reverse Star Triangle

Print Number Star Triangle

Print all even numbers from 1 to 100

In this program we are going to explain how you can print all even numbers from 1 to 100.

Here we are including two header files stdio.h and conio.h .To include these files we are using #include<stdio.h> and # include<conio.h> .Here we are using one predefined function .That is main() method. The return type of this function is void .That mean this method does not return any value.This method is necessary  to execute any C program. Nearly all languages must have a main() method which execute first by complier.

In this we are using three more methods .These are clrscr(), printf("") and getch().The clrscr() method is used to clear the screen ,the printf ("") is used to print messages or values on screen e.g. in this example printf("Print all even numbers from 1 to 100\n"); is used to print Print all even numbers from 1 to 100 on screen. In the printf() method we are also using \n for new line. This mean the next value will print at new line.The getch() method is used to get character from keyboard.

In this we are using for loop to iterate from 1 to 100 and if is used to check the condition(values from 1 to 100 is divisible by two or not).

Here in example we are declaring int i as integer type. Then we call clrscr() function to clear the screen. Then print the messages and using for loop iterate from 1 to 100 .In for loop we also checking the divisibility by two by checking modulo is equals to Zero or not. As we know when any number is divisible by two then its remainders Zero .And modular operator is used to check remainder. So we are checking the remainder in if (i%2==0).If it is Zero it mean number  is drivable by 2(So print the number )otherwise the number is not divisible by 2 .

/*Print all even numbers from 1 to 100 */#include<stdio.h>#include<conio.h>void main(){int i;clrscr();printf("Print all even numbers from 1 to 100\n");printf("Even Numbers are:\n");for(i=1;i<=100;i++){ if(i%2==0) printf("%d ",i);}getch();}

Output Of Example

Print all even numbers from 1 to 100Even Numbers are:2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 5658 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

 Print the sum of odd number and even number separately of n number

In this example we are going to find sum of all odd and all even between a given number.

To find sum of even and odd enter a number from keyboard. Use for loop to iterate from 1 to n. Use if -else to check the divisibility of  2 .If diviseble by two then add number into even else add number into odd. Finally display sum of odd and even.

/* Print the sum of odd number and even number separately of n number */#include<stdio.h>#include<conio.h>void main(){int a,i,even=0,odd=0;clrscr();printf("Enter a number\t");scanf("%d",&a);for(i=1;i<=a;i++){if(i%2==0)even=even+i;elseodd=odd+i;

}printf("\nsum of the even\t=%d",even);printf("\nsum of the odd\t=%d",odd);getch();}

Output Of Example

Enter a number 12

sum of the even =42sum of the odd =36

Input an alphabet and change its case

In this example we will learn how we can convert cases of an alphabet. In this we have enter an alphabet. If it is character between  (a-z or A-Z). Then case will converted and if not then "Have entered alphabet is not character.....:)" message  will display on screen.

In this we are including two header files of C library  #include<stdio.h> and #include<conio.h>.

In this example we are including five predefined method. These are main(),clrscr(),printf(""),scanf() and getch(). Here we are using scanf() method is used to take input from keyboard.

In this we are declaring  ch as a character variable. Then print a message to enter a alphabet .When you insert a alphabet then check .Is it  between 65 -90?These are ASCII values for A(65) -Z(90).If it is then to make lower case add 32 which gives equivalent lower case of alphabet. else if character is between 97(a)-122(z) then the alphabet is lower case. Then we have subtract  32 else alphabet is not upper or lower character .Then print message   "Have entered alphabet is not character.....:)".

/* input an alphabets and change its case */#include<stdio.h>#include<conio.h>void main(){char ch;clrscr();printf("Enter an alphabet:\t");scanf("%c",&ch);if(ch>=65 && ch<=90){ch=ch+32;printf("You have enter a Caps Latter");printf("/n The lower case is =%c",ch);}else if(ch>=97 && ch<=122){

ch=ch-32;printf("Change in to uppercase=%c",ch);}elseprintf("Have entered alphabet is not character.....:)");getch();}

Output Of Example

Enter an alphabet: aChange in to uppercase=A

 Accept a number and check is it prime number or not a prime number

In this example we are going to accept a number from keyboard then find is it prime number or not?

Here we are taking number from keyboard .Then iterate for loop from 1 to t (number). In for loop check modulo of t with i if it is zero then increase c by one. When iteration  is completed then check c==2 then the number is prime else it is not prime. Here we are checking so because a prime number is divisible by 1 or itself. So c=2.If it is greater than two then it is not prime.

/* accept a number and check it is prime number or not a prime number */

#include<stdio.h>#include<conio.h>void main(){int t,c=0,i;clrscr();printf("Enter a number\t");scanf("%d",&t);for(i=1;i<=t;i++){if(t%i==0)c++;}if(c==2)printf("\nNumber is prime");elseprintf("\nNumber is not prime");getch();}

Output Of Example

Enter a number 23

Number is prime

Learn C with example

Check a number is perfect or not,( perfect number is sum of its factor number)

In this example we will explain how you can find a number is perfect or not. A perfect number is number which is sum of factor is equals to itself.

To check a number is perfect or not .We have first find its factor and add these factors and store into a variable. At last check is it equals to number itself ?If it is equals itself then it is perfect number otherwise it is not perfect number.

/* check a number is perfect or not,( perfect number is sum of its factor number) */#include<stdio.h>#include<conio.h>void main(){int i, p,sum=0;clrscr();printf("Enter a number :\t");scanf("%d", &p);for(i=1;i<=p;i++){if(p%i==0)sum=sum+i;}if(sum==p)printf("Number is perfect");elseprintf("Number is not perfect");getch();}

Output Of Example

Enter a number : 169Number is not perfect

Print the multiword string.

In this section you will learn how you can take multiword string from keyword.

In this we are using two new functions gets(char c[]) and puts(char c[]).The gets(char c[]) is used to get array of character from keyboard and store it into an array variable c[].The  puts(char c[]) method is used to take values from character array c[] and display on screen.

Here we are using getch() method to take a value from keyboard. This is used to halt the screen  until you are not press any key on keyboard.

/* Print the multiword string. */#include<stdio.h>#include<conio.h>void main(){char c[10];clrscr();printf("Here you can enter string with space.\n");printf("Enter the string:\t");gets(c);puts("Your string is:\t");puts(c);getch();}

Output Of Example

Here you can enter string with space.Enter the string: Rajesh Kumar (B.Tech-CS)Your string is:Rajesh Kumar (B.Tech-CS)

Greatest number of any three given numbers

In this example we are going to find the greatest number in any three numbers.

In this we are declaring  three variables a,b,c. We insert values from keyboard into these values. Then check the conditions .Here we are using  && operator two check two condition at a time. This operator is also called short circuit operator. This operator returns true if both value is true else it returns false.

/* Greatest number of any three given numbers */#include<stdio.h>#include<stdio.h>void main(){int a,b,c;clrscr();printf("Enter the three numbers\t");scanf("%d%d%d",&a,&b,&c);if(a>b && a>c)printf("%d is greatest number",a);

else if(b>c && b>a)printf("%d is greatest number",b);elseprintf("%d is greatest number",c);getch();}

Output Of Example

Enter the three numbers 1 2 33 is greatest number

Print your own name n times using for loop

In this example we are going to teach you how you can use for loop and what is use of for loop.

Say We have print Sudhir Yadav  10 times then we need to write printf("Sudhir Yadav"); ten times. To avoid this have a for loop.

Syntax of for loop:

for(initialization ;conditions, increment or decrements )

{

//body of for loop

}  

Here in this we pass first initialize value from where for loop is started .The second is conditions. If this condition is true then loop body will execute else the next statement after loop will execute. Thread is increment or decrements of initialized values value.

The flow of for loop is firs initialize then execute loop body then increment or decrements the value then check conditions then if condition is true then again body will execute and increment or decrements the values again. Do this until condition is

/* print your own name n times */#include<stdio.h>#include<conio.h>void main(){int i,n;clrscr();printf("enter a number");scanf("%d",&n);for(i=1;i<=10;i++)printf("\nSudhir Yadav");getch();

}

Output Of Example

Enter a number 10

Sudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir YadavSudhir Yadav

Enter a number and show its factor

In this example we are going to explain how you can enter a number and how you can find its factor.

To enter a number we first define an integer variable then use a scanf("%d",&a) method .This method is used to take input from keyboard. We can enter number, float or character by using this method. We have use %d,%f and %c reactively at place of first argument. The second argument is used to store the value at variable location.

To find factor we are using for loop which iterate from 1 to a .We are checking the modulo of a and value from 1 to a. If it return zero then this mean the it is factor of a and print it.

/* Enter a number and show its factor */#include<stdio.h>#include<conio.h>void main(){int a,i;clrscr();printf("Enter a number\t");scanf("%d",&a);for(i=1;i<=a;i++){if(a%i==0)printf("\nFactor of the number is\t=%d",i);}getch();}

Output Of Example

Enter a number 12

Factor of the number is =1Factor of the number is =2Factor of the number is =3Factor of the number is =4Factor of the number is =6Factor of the number is =12

Input a character and check it vowel or not

In this example we will learn how we can find a character is vowel or consonant.

In this example we first include two required headers include<stdio.h> and include<conio.h>.These are included to use methods( also call functions ) defined into these header files.

Here we are using five methods main() method ,clrscr() method ,printf() method,scanf method and getch() method.

In this we are using if-else to check vowel or consonant .First enter a alphabet then compare it with five vowels(a,e,i,o,u) if it is true then print vowel else print consonant. Here we are using OR (||) operator to check multiple conditions at a time in if.

/* Input a character and check it vowel or not */#include<stdio.h>#include<stdio.h>void main(){char ch;clrscr();printf("Enter a alphabet \t:");scanf("%c",&ch);if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U')printf("\n\nIt is a vowel");elseprintf("\n\nIt is a consonant");getch();}

Output Of Example

Enter a alphabet :a

It is a vowel

Pint average of n number.

In this example we will learn how to calculate average of n number. You have insert a number from keyboard  then this example will sum all the number from 1 to n then calculate average.

Here we are using  two header files and five predefine methods. In for loop we sum from 1 to n and then finally find average. In this we are using "\t"  for 5 white space.

In this we first declare two integer variable(i,n) ,one float variable(avg) and initialize an integer variable(sum=0).Then to clear the screen we call clrscr()  function. After that pint a message .To insert value from keyboard  we are using scanf() function. To calculate sum start for loop from 1 to n.In first iteration calculate sum(0)+i(i=1) and assign into sum=sum+1.Then In first iteration add sum=sum(sum=1)+i(i=2) similarly  up to n. After completing for loop calculate average (avg=(float)sum/n).Here we are using (float)sum/n) to calculate float value of average. Finally print average as output.  

/* print average of n number. */#include<stdio.h>#include<conio.h>void main(){int i,sum=0,n;float avg;clrscr();printf("Enter a to which you have to calculate the arg:\t");scanf("%d",&n);for(i=1;i<=n;i++)sum=sum+i;avg=(float)sum/n;printf("The average:\t%f",avg);getch();}

Output Of Example

Enter a to which you have to calculate the arg: 12The average: 6.500000

Print alphabets triangle in C

In this example we are going to create an alphabets triangle.

In this example we are going to make a triangle which have A in first row B B into second row ,C C C in second row and so on ..For this we are using two for loops.

 

 

Source Code Of the Examples

* A B B C C C D D D D E E E E E */ #include<stdio.h> #include<conio.h> void main() { int i,j; int n; clrscr(); printf("Enter the ASCII character\t"); scanf("%d",&n); for(i=65;i<=n;i++) { for(j=65;j<=i;j++) printf("%c",i); printf("\n"); } getch(); }

Output Of Example

Enter the ASCII character 70AB BC C CD D D DE E E E E

Print alphabet triangle Using C

In this example we are going to create an alphabets triangle.

In this example we are going to print alphabets triangle which first line has A, second line B C ,third line D E F and so on .For this we are using two for loops.

#include<stdio.h>#include<conio.h> /* A */void main() /* B C */{ /* D E F */int i,j,k=65; /* G H I J */clrscr(); /* K L M N 0 */for(i=65;i<=70;i++){for(j=65;j<=i;j++)printf("%c",k++);

printf("\n");}getch();}

Output Of Example

Triangle from A to UA  B C  D E F  G H I J  K L M N 0

Print Number Triangle in C

In this example we are going to make a program by which we can Print numeric Triangle.

In this example we are going to print a number triangle. In this number triangle we have 1 in first row,1 2 in second row ,1 2 3 in third row and so on....  

 

Source Code of Example

/* print the */#include<stdio.h> /* 1 */#include<conio.h> /* 1 2 */void main() /* 1 2 3 */{ /* 1 2 3 4 */int i,j,n; /* 1 2 3 4 5 */clrscr();printf("Enter the number\t");scanf("%d",&n);for(i=1;i<=n;i++){for(j=1;j<=i;j++)printf("%d",j);printf("\n");}getch();}

Output Of Example

Enter a number 511 2

1 2 31 2 3 41 2 3 4 5

Print Number Triangle Using C

In this example we are going to make a program by which we can Print numeric Triangle.

In this example we are going to print 1 in first line, 2 2 in second line 3 3 3 in third line ,and so on...

 

 

Source Code Of the Example

/* 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 */#include<stdio.h>#include<conio.h>void main(){int i,j,n;clrscr();printf("Enter a number\t");scanf("%d",&n);for(i=1;i<=n;i++){for(j=1;j<=i;j++)printf("%d",i);printf("\n");}getch();}

Output Of Example

Enter a number 512 23 3 34 4 4 45 5 5 5 5

Print Star Triangle Using C

 

In this example we are going to explain how we can make a star triangle.

In this example we are print * in first line ,** into second line,*** into third line ,**** into fourth line and son on...

 

Source Code of Example

#include<stdio.h> /* print the */#include<conio.h> /* * */void main() /* * * */{ /* * * * */int i,j,n; /* * * * * */clrscr(); /* * * * * * */printf("Enter a number\t");scanf("%d",&n);for(i=1;i<=n;i++){for(j=1;j<=i;j++)printf("*");printf("\n");}getch();}

Output Of Example

Enter a number 5** ** * ** * * ** * * * *

Print Star Rectangle in C

 

In this example we are going to explain how we can make a star rectangle using C language.

In this example we are inserting number of rows and columns .Then we are printing stars to make rectangle.

 

Source Code of Example

/* * * * * * * * * * * * * * * * * print it */ #include<stdio.h> #include<conio.h> void main() { int i,j,row,col; clrscr(); printf("Enter the row and column\t"); scanf("%d%d",&row,&col); for(i=1;i<=row;i++) { for(j=1;j<=col;j++) printf("*"); printf("\n"); } getch(); }

Output Of Example

Enter the row and column 4 4* * * ** * * ** * * ** * * *

Print Star triangle C

In this example we are going to print how we can make a star triangle.

 

#include<stdio.h>#include<conio.h> /* * */void main() /* * * */{ /* * * * */int i,j,k,n; /* * * * * */clrscr(); /* * * * * * */printf("Enter a number\t");scanf("%d",&n);for(i=1;i<=n;i++){for(j=1;j<=n-i;j++)printf(" ");for(k=1;k<=i;k++)printf("%2c",'*');printf("\n");}

getch();}

Output Of Example

Enter a number 5 * * * * * * * * * ** * * * *

 

 

Print Alphabets Triangle

In this example we are going to make an alphabetic triangle.

In this example we are going to print A in first row .In second row we are going to print A B , in third line we are going to print A B C and so on .

For this we are using two for loop .First for loop is used for row and second is used to print column. We are using %c to print the character value of integer.

Source Code Of example :

#include<stdio.h>#include<conio.h> /* A */void main() /* A B */{ /* A B C */int i,j; /* A B C D */clrscr(); /* A B C D E */for(i=65;i<=69;i++){for(j=65;j<=i;j++)printf("%c",j);printf("\n");}getch();}

Output Of Example

AABABC

ABCDABCDE

Input a Number and Count its Digit

In this example we are going to find number of digits into a number.

We are using while loop to find the number of digits into a given number .We just find modulo of number and reduce the last digit from original number .While modulo of number is  greater than zero then increase value of p .Finally when the modulo is zero. Then while loop will end and the value of p is equals to number of digits of that number.

 

Source Code Of the Example

/* input a number and count its digit*/#include<stdio.h>#include<conio.h>void main(){int i,p=0;clrscr();printf("Enter a number");scanf("%d",&i);while(i!=0){i=i/10;p++;}printf("Digit is =%d",p);getch();}

Output Of Example

Enter a number12Digit is =2

Print binary triangle Using C

In this example we are going to print binary triangle using C.

We are printing 1 in first line ,0 1 in second line ,1 0 1 in third line ,0 1 0 1 in forth line and so on...

 

 

 

Source Code of Example

/* 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 */ #include<stdio.h> #include<conio.h> void main() { int i,j,n; clrscr(); printf("Enter a number\t"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { if(i%2==0) { if(j%2==0) printf("1"); else printf("0"); } else { if(j%2==0) printf("0"); else printf("1"); } } printf("\n"); } getch(); }

Output Of Example

Enter a number 510 11 0 10 1 0 11 0 1 0 1

Input a Number and Print The Following 1*2*3*4*5*6......*n

In this example we are going to print multiplication from 1 to n .Here n is number which user will enter at run time.

To find multiplication we are using for loop. for loop will iterate from 1 to n and multiply values. Here we have define a variable f and assign 1 into f .In for loop we multiply the values with f and assign the values into f .When for loop will end then the value of multiplications of values from 1 to n will store into f. At last we print value of the f .This is final result.

Source Code Of Example

/*input a no and print the following 1*2*3*4*5*6......*n */#include<stdio.h>#include<conio.h>void main(){int n,i,f=1;clrscr();printf("enter the no");scanf("%d",&n);for(i=1;i<=n;i++)f=f*i;printf("The multiplication from 1 to %d =%d",n,f);getch();}

Output Of Example

enter the no3The multiplication from 1 to3=6

Reverse Star Triangle

In this example we are going to print reverse star triangle using C

In this example we are print *******..n in first line,******..n-1 in second line,*******..n-2 in third line so on...

 

 

Source Code of the Example

/* Rreverse of triangle */#include<stdio.h> /* * * * * *

*/#include<conio.h> /* * * * * */void main() /* * * * */{ /* * * */int i,j,n; /* * */clrscr();printf("Enter a number\t:");scanf("%d",&n);for(i=n;i>=1;i--){for(j=1;j<=i;j++)printf("*");printf("\n");}getch();}

Output Of Example

Enter a number :5 * * * * *  * * * *  * * * * *  * 

Print Number Star Triangle

In this example we are going to print a number star triangle using C.

In this we are going to print 1 in line one, 2 3 in line two, 4 5 6 into line three,7 8 9 10 and so on...

Source Code of Example

*12 34 5 67 8 9 10*/#include<stdio.h>#include<conio.h>void main(){int i,j,k=1,n;clrscr();printf("Enter a number\t");scanf("%d",&n);

for(i=1;i<=n;i++){for(j=1;j<=i;j++)printf("%d ",k++);printf("\n");}getch();}

Output Of Example

Enter an alphabet: aChange in to uppercase=A

  C Programming Examples

If-Else Using   C

Nested If Else Using C

Logical Operators In C

Break Statement In C

Continue Statement In C

Nested Loops In C

Odd Loops In C

Making Table Using Do While

Writing Table Using For Loop

Program Of Simple Array

Program To Get the Array Length

Calculate Average Using Array

A Program On Two Dimensional Array

Switch Case Statement In C

Program For Reverse Number

Accept Number Until It Becomes Zero

Converting Upper Case To Lower Case

Sum Of String In C

Sorting Elements Using Array

Pointer In C

Call By Value

Call By Reference 

A Simple Programming Example Of If Else

/* Calculation Of Gross Salary */

In this program we are using #include<stdio.h> and #include<conio.h>header files.

main() is a predefined function here.

bs, gs, da, hra are the variables of float type..

printf() is used as a output function and scanf() is used as input function.

 if is used as a conditional statement. if the condition is true then if condition will execute and if  condition is false then else condition will execute.

 

#include <stdio.h>#include <conio.h>main(){float bs, gs, da, hra;printf ("Enter basic salary");scanf ("%f",&bs);if (bs<1500){hra=bs*10/100;da=bs*90/100;}else{hra=500;da=bs*98/100;}gs=bs+ hra+ da;printf ("gross salary=Rs. %f ",gs);}

 Output : Enter basic salary                2000              gross salary=Rs. 4460.0

A Program Using Nested If Else

/* To Calculate Student's Status*/

In this program m1, m2, m3, m4, m5 and per are the variable of integer type. And we are using here the concept of nested if which means if inside if.

 

#include <stdio.h>#include <conio.h>main(){int m1,m2,m3,m4,m5,per;clrscr();printf ("Enter marks in five subjects");scanf ("%d %d %d %d %d" , &m1,&m2,&m3,&m4,&m5);per=(m1++m2+m3+m4+m5)/500*100;if(per>=60)printf ("First Division");elseif(per>=50)printf ("Second Division");else{if(per>=40)printf ("Third Division");elseprintf ("Fail");}}} 

Output : Enter marks in 5 subjects               75,65,73,48,80               First Division

Program Using Logical Operator

/*Use of Logical Operator*/

In this program sex and ms are the variable of char type and age is the variable of integer type. and operator is denoted as && and or operator is denoted as ||

#include <stdio.h>#include <conio.h>main(){char sex, ms;int age;clrscr();printf ("Enter Age, Sex, Merital Status");scanf ("%d %c %c" &age,&sex,&ms);if ((ms=='M')||(ms=='U'&&sex=='M'&&age>30)||(ms=='M')||(ms=='M'&&sex=='F'&&age>25))printf ("Driver is insured");}elseprintf ("Driver is not insured");}

 Output : Enter Age, Sex, Marital Status               35 F M               Driver is insured

Program For Break Statement

#include <stdio.h>#include <conio.h>int main (){clrscr(); for (int i = 0; i<100; i++)  {    printf ("\n %d", i);    if (i == 10); // This code prints value only upto 10.    break;  }

 return 0;} 

Output : 12345678910

Program Of Continue Using C

#include <stdio.h>#include <conio.h>void main(){int i, j;clrscr();for (i=1;i<=2;i++){for (j=1;j<=2;j++){if (i=j)continue;printf("\n %d %d",i,j);}}}

Output : 1 2               2 1

Nesting Of Loops Using C

/* Demonstration Of Nesting Loops*/

In this program r, c, sum are the variables of integer type. We are using the concept of nested loop here. Nested loop means loop inside loop. The first loop is called outer loop and the second one is called inner loop.

#include <stdio.h>#include <conio.h>main(){int r,c,sum;clrscr();for(r=1;r<=3;r++) // Outer Loop{for(c=1;c<=2;c++) // Inner Loop{sum=r+c;printf("r=%d c=%d sum=%d\n",r,c,sum);}}}

Output : r=1c=1sum=2               r=1c=2sum=3               r=2c=1sum=3               r=2c=2sum=4               r=3c=1sum=4               r=3c=2sum=5

Program Of Odd Loop Using C

#include<stdio.h>#include<conio.h>main(){char name='p';int a,c;clrscr();while(name=='p'){printf("enter any no. a");scanf("\n%d",&a);c=a*a;printf("%d",c);printf("\nenter the another char ");scanf("\n%c",&p);}getch();} 

Output :Enter any no. a24enter the another charaEnter any no. a5

25enter the another charp 

Table Print Of Any Number Using Do While Loop

#include<stdio.h>#include<conio.h>void main(){int n, i, product;i=1;clrscr();printf("enter the number to make the table .");scanf("%d",&n);do{product=n*i;printf ("\n %d*%d=%d",n, i, product);i++;}while(i<=10);getch();}

Output : enter the number to make the table .55*1=55*2=105*3=155*4=205*5=255*6=305*7=355*8=405*9=455*10=50

Table Print Of Any Number Using For Loop

#include<stdio.h>#include<conio.h>void main(){int n,i,product;

i=1;clrscr();printf("enter the number to make the table .");scanf("%d",&n);for(i=1;i<=10;i++){product=n*i;printf("\n%d*%d=%d",n,i,product);getch();}}

Output : enter the number to make the table .33*1=33*2=63*3=93*4=123*5=153*6=183*7=213*8=243*9=273*10=30

A Simple Array Example

#include<stdio.h>#include<conio.h>void main(){int a[] = {20, 30, 50, 70, 100};int n, sum=0;

{ for ( n=0 ; n<5 ; n++ ) { sum += a[n]; } printf ("%d", sum); return 0;}

Output : 270

Program For Printing The Length Of The Array

#include <stdio.h>

#include <conio.h>int a[6]= { 10, 29, 36, 44, 53, 62 };void main()

{ clrscr(); int l=sizeof(int)/sizeof(a); printf ("Length Of Array is=%d", l); getch();}

Output : 6

Program To Find The Average By Using Array

#include<stdio.h>#include<conio.h>void main(){int mark[5];int i, n, sum;sum=0;clrscr();for (i=0;i<5;i++){printf ("Enter marks %d",i+1);scanf("%d",&mark [i]);sum+=mark [i];}printf ("mark entered\n");for(i=0;i<5;i++)printf ("%d\n", mark [i]);printf("\n\n The average is %d \n", sum/5);getch();}

Output : Enter marks 1 34Enter marks 2 78Enter marks 3 69Enter marks 4 80Enter marks 5 90marks entered 3478698090The avrage is 70

A Simple Program Of Two Dimensional Array

#include<stdio.h> #include<conio.h> void main() { int i, j; int num[3][3]={ {20, 48, 65}, {89, 34, 70}, {90, 75, 49} }; clrscr(); printf(" Elements of 2D array\n\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf ("%d\t", num[i][j]); } printf("\n"); } getch(); }

Output : Elements of 2D array20          48        6589          34        7090         75         49

Example Of Switch Case In C

 

#include<stdio.h>#include <conio.h>main(){int menu, num1, num2, total;clrscr();printf ("enter any two numbers ");scanf ("%d %d", &num1, &num2 );printf ("enter your choice\n");printf("1=addition\n");printf("2=subtraction\n");printf("3=multiplication\n");scanf ("%d", &menu );switch( menu ) {case 1: total = num1 + num2; break;

case 2: total = num1 - num2; break;case 3: total = num1* num; break;default: printf ("Invalid option selected\n");}if( menu == 1 )printf ("%d plus %d is %d\n", numb1, numb2, total );else if( menu == 2 )printf ("%d minus %d is %d\n", num1, num2, total );else (menu==3)printf ("%d cross %d is %d\n", num1, num2, total );}

Output : enter any two number              45 40              1=addition              2=subtraction              3=multiplication              enter your choice              2              minus is 5      

Program To Reverse The Digits Of A Given Number

#include<stdio.h>#include<conio.h>void main(){long int num, a, b;long int ctr=0,s=0;clrscr();printf ("Enter the digit ");scanf ("%ld",&num);while (num!=0){a=num%10;num=num/10;s=s*10;s=s + a;ctr++;}printf ("The reverse No. is=%ld" ,s);printf("\n count=%ld", ctr);getch();}

Output : Enter the digit62415The reverse No. is = 51426count=5

Program That Accept The Number Until It Becomes Zero

#include<stdio.h>#include<conio.h>void main(){int num;clrscr();do{printf("Enter number");scanf("%d",&num);fflush(stdin);}while(num>0);getch();}

Output : Enter number34Enter number65Enter numberghjEnter number9876Enter number0

Program To Convert Upper Case To Lower Case

#include<stdio.h>#include<conio.h>void main(){char l[45];int i;clrscr();printf("Enter text in upper case");scanf("%s",l);printf("\n\n\n Uppercase text converted to lower case \n");for(i=0;l[i]!='\0';i++)

{printf("%c",tolower(l[i]));}getch();}

Output : Enter text in upper case MYNAMEISPRIYAUppercase text converted to lower casemynameispriya

Sum Of Starting 10 Numbers

#include<stdio.h>#include<conio.h>void main(){int sum,n;sum=0;n=1;clrscr();while(n<=10){sum=sum+n;n=n+1;}printf("sum=%d\n",sum);getch();}

Output : sum=55

Program Of Sorting Using Array In C

#include <stdio.h>#include <conio.h>#include <stdlib.h>int array[] = { 9, 3, 30, 25, 89, 40, 8, 50, 6, 65 };int sort (const void *x, const void *y) {return (*(int*)x - *(int*)y);}void main() {clrscr();int i;qsort(array, 10, sizeof(int), sort);for (i=0; i<10; i++) {printf("%d ", array[i]);}

getch();}

Output : 3,6,8,9,25,30,40,50,65,89

A Simple Program Of Pointer Using C

#include<stdio.h>#include<conio.h>void main(){int j=45;int *i;i=&j;clrscr();printf("\n Address of i= %u",&j);printf("\n Address of i=%u",i);printf("\n Address of i=%u",&j);printf("\n Address of i=%u",j);getch();}

Output :65524655246552445

Program That Call A Function By Value

#include<stdio.h>#include<conio.h>void main(){int a=23,b=45;void addab(int x,int y);clrscr();printf("\n Before function call a=%d,b=%d",a,b);addab(a,b);printf("\n\nAfter function calla=%d,b=%d",a,b);getch();}void addab(int x,int y){x=x+10;

y=y+10;printf("\n\ninside the functiona=%d,b=%d",x,y);}

Output : Before function call23 45inside the function call33 55After function call23 45

Program That Call A Function By Value

#include<stdio.h>#include<conio.h>void main(){int a=34,b=12;void addab(int *x,int *y);clrscr();printf("\nBefore function call a=%d,b=%d",a,b);addab(&a,&b);printf("\n\nAfter function calla=%d,b=%d",a,b);getch();}void addab(int *x,int *y){*x=*x+10;*y=*y+10;printf("\n\ninside the functiona=%d,b=%d",x,y);}

Output : Before Function call 34 12Inside the function -12 -14After function call 44  

C Interview Questions And Answers

Ques: 1 What is C language?Ans:programming languageAns:C is a middle level programing language. C is a

structured, procedural programming language.c widely used both for operating systems and applications.C is also called a system progmming languageAns:The c language is a programming languageAns:C is high level language.Ans: C is a Structured Oriented Programming LanguageAns:c is structure programing language.Ques: 2 What is the output of printf("%d")?Ans:0Ans:0Ans:Any integer valueAns:Any integer valueAns:the output of this statement depends on data types %d is the data type of int type variabe if you will declare the variable in declaration part suppose u will declare int i so the output of this statement is i...............Ans:the output of this statement depends on data types %d is the data type of int type variabe if you will declare the variable in declaration part suppose u will declare int i so the output of this statement is i...............Ans:garbegge valueAns:garbage integer valueAns:Garbage ValueQues: 3 What is the difference between "calloc(...)" and "malloc(...)"?Ans:Some important distance between calloc and malloc are given below: malloc: malloc takes only the "size" of the memory block to be allocated as input parameter.malloc allocates memory as a single contiguous block.if a single contiguous block cannot be allocated then malloc would fail.

calloc:

calloc takes two parameters: the number of memory blocks and the size of each block of memorycalloc allocates memory which may/may not be contiguous.all the memory blocks are initialized to 0.it follows from point 2 that, calloc will not fail if memory can beallocated in non-contiguous blocks when a single contiguous blockcannot be allocated.Ans:malloc: malloc create the single block of given size by user

calloc: calloc creates multiple blocks of given sizeboth return void pointer(void *)so boh requires type castingmalloc: eg:int *p;p=(int*)malloc(sizeof(int)*5)above syntax tells that malloc occupies the 10 bytes memeory and assign the address of first byte to P

calloc: eg:p=(int*)calloc(5,sizeof(int)*5)above syntax tells that calloc occupies 5 blocks each of the 10 bytes memeory and assign the address of first byte of first block to P

Ques: 4 What is the difference between "printf(...)" and "sprintf(...)"?Ans:the printf() function is supposed to print the output to stdout.In sprintf() function we store the formatted o/p on a string buffer.Ans:"printf(....)" is standard output statement and "sprintf(......)" is formatted output statementQues: 5 How to reduce a final size of executable?Ans:Do not include unnecessary header files and Do not link with unneccesary object files.

Ans:Use dynamic linking. Ques: 6 Can you tell me how to check whether a linked list is circular?Ans:First you have to Create two pointers, each set to the start of the list. And Update each as below:

while (pointer1) { pointer1 = pointer1->next; pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;if (pointer1 == pointer2) { print (\"circular\n\");}}Ques: 7 What is the difference between String and Array?Ans:Main difference between String and Arrays are:

A string is a specific kind of an array with a well-known convention to determine its length where as An array is an array of anything.

In C, a string is just an array of characters (type char)and always ends with a NULL character. The �value� of an array is the same as the address of (or a pointer to) thefirst element; so, frequently, a C string and a pointer to char are used to mean the same thing.

An array can be any length. If it�s passed to a function, there�s no way the function can tell how long the array is supposed to be, unless some convention is used. The convention for strings is NULL termination; the last character is an ASCII NULL character. Ans:Array can hold group of element of the same the type, and which allocates the memeory for each element in the array,if we want we can obtain the particular value from an array by giving index value.

Ex: int a[10];

a variable holds the values of integer at max 10.

String can hold any type of data, but it makes together we can't obtain the particular value of the string.

String s="Pra12";Ques: 8 What is a modulus operator?Ans:it gives reminder of any division operationAns:It is an binary arithmetic operator which returns the remainder of division operation. It can used in both floating-point values and integer values.

Use of the modulus operator is given below:

opLeft % opRight

where, opLeft is the left operand and opRight is the right operand. This expression is equivalent to the expression opLeft - ((int) (opLeft / opRight) * opRight)Ans:in c language it is used to determine the remainder of any no by deviding the operator if both of them is not float no.Ans:it gives remainder part of divisoneg. printf("%d",5%2) output 1Ques: 9 What are the restrictions of a modulus operator?Ans:The modulus operator is denoted in c by symbol %.

we have two integer values x and y and then the operation x % y called as x modulus y gives the result as (x- (x / y) * y).

Say if x=18 and y =5 the x % y gives value as (18- (18 / 5) * 5) which gives (18-15) which results in 3 in other words the remainder of the division operation.

But there is a restriction in C language while using the modulus operator. There are two types of numerical data types namely integers, floats, double. But modulus operator can operator only on integers and cannot operate on floats or double. If anyone tries to use the modulus operator on floats then the compiler would display error message as �Illegal use of Floating Point�.

Ans:1)modulus operator works as a%b=reminder (sign as reminder is the sign of a). eg: a)3%2=1,b)3%-2=1,c)-3%2=-1,d)-3%-2=-1in case a only the answer is correct but not in b,c,and d .that's the limitation of modulus operator .2) it can't works with float and double Ques: 10 Which one is faster n++ or n+1?Why??Ans:The expression n++ requires a single machine instruction. n+1 requires more instructions to carry out this operation.

Ques: 11 What is equivalent expression for x%8?Ans:while(x>8){ x=x-8;}printf("%d",x); Get the remainderQues: 12 Which expression always return true?and Which always return false?Ans:Expression are given below; if (a=0) always return false.if (a=1) always return true.

Ques: 13 What is Storage class ?Ans:There are four type of storage class in C:

1.static2.auto3.register4.externAns:storage classes in c gives property of the variable,

1.scope of the variable2.life time3.memory(either CPU register or memory)

four types of C storage classes,

1.automatic2.register3.static4.externQues: 14 what are storage variable ?Ans:A storage class changes the behavior of a variable. It use to controls the lifetime, scope and linkage.

There are five types of storage classes :1.auto 2.static 3.extern 4.register 5.typedef

Ques: 15 What are the advantages of auto variables? Ans:Some main advantages of auto variables are given below:

1.we can use the same auto variable name in different blocks.2.No side effect by changing the values in the blocks.3.It used memory economically.4.Because of local scope auto variables have inherent protection.

Ques: 16 What is auto variables? Ans:by default variables are auto.as we know that variable changes its character according to the strage class . Ans:Auto variable are the default variables. Static memory allocation will happenQues: 17 Diffenentiate between an internal static and external static variable?Ans:Some main difference between internal static and external static are given below:

We declare the internal static variable inside a block with static storage class. External static variable is declared outside all the blocks in a file.In internal static variable has persistent storage,no linkage and block scope, where as in external static variable has permanent storage,internal linkage and file scope.Ques: 18 What are advantages and disadvantages of external storage class?Ans:Some main advantages and disadvantages of external storage class are given below:

advantage:

1.In Persistent storage of a variable retains the updated value.2.The value is globally available. Disadvantage:

1. Even we does not need the variable the storage for an external variable exists.2.Side effect may be produce unexpected output.3.We can not modify the program easily.

Ques: 19 What are the characteristics of arrays in C?Ans:some main characteristics of arrays are given below:

1.all entry in array should have same data type.2.tables can store values of difference datatypes.

Ques: 20 When does the compiler not implicitly generate the address of the first element of an array?Ans:When array name appears in an expression such as:

1.array as an operand of the sizeof operator.2.array as an operand of & operator.3.array as a string literal initializer for a character array.Then the compiler not implicitly generate the address of the first element of an array.

C Interview Questions And Answers

Ques: 1 Which of the following is the structure of an if statement?

A. if (conditional expression is true) thenexecute this codeend if B. if (conditional expression is true)execute this codeend if C. if (conditional expression is true) {then execute this code>->}D. if (conditional expression is true) then {execute this code}Ans:dAns:BQues: 2 string constants should be enclosed with a.single quotesb.double quotesAns:double quotes

Ans:bAns:b).double quotesAns:b).double quotesAns:b.double quotesAns: double quotesAns:double quotesQues: 3 What is C?Ans:c is super set of all languageAns: c is a structured programing languageQues: 4 write a c program to accept a number between 3 & 10 & print a square of stars. if user enters 4 the output should be as shown **** * * * * ****Ans:#include <stdio.h>main()

{ int count; printf("\n**************");

for( count = 1 ; count <= 8 ; ++count) print f("\n* *");

printf("\n**************\n"); }Ans:#include<stdio.h>#include<conio.h>void main(){int row,i,j,k;printf("enter the no of row::");scanf("%d",&row);for(i=0;i<row;i++){if(i==0||i==row-1) { for(j=0;j<row;j++) printf("*"); }else { for(j=0;j<row;i++) { if(j==0||j==row-1)printf("*"); else printf("*"); }printf("\n");}getch();}Ans:#include <stdio.h>void main(){ int count,a; printf("\n-------------------------\n"); printf("\n enter the number="); scanf("%d",&a); if(9<a>2) { for( count = 1 ; count <= a ; ++count) print f("\n* "); } else printf("number must be in between 3 to 8"); printf("\n-------------------------\n"); }

Ques: 5 Is that possible to pass a structure variable to a function/ If so,explain the detailed ways?Ans:yes it is possible to pass structure variable to a functionstruct emp{ int eno;

};void disp(struct emp e){printf(e.eno);}void main(){struct emp e;e.eno=10;disp(e);}

Ans:We can pass a structure variable to a function.for that a variable of type structure is taken as argument in fn and structure variable is passed in fn call.

Ques: 6 Write a C program to compute the maximum depth in a tree?Ques: 7 Write a C program to find the minimum value in a binary search tree.Ques: 8 Write C code to determine if two trees are identical.Ques: 9 Write a C program to delete a tree (i.e, free up its nodes)Ques: 10 Write a C program to determine the number of elements (or size) in a tree.Ques: 11 Write a C program to find the depth or height of a tree.Ques: 12 How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.

Ques: 13 How do you reverse a linked list without using any C pointers?Ques: 14 Write a C program to sort a linked list.Ques: 15 How do you sort a linked list?Ques: 16 How do you reverse a doubly linked list?Ques: 17 How do you reverse a singly linked list?Ques: 18 What is the difference between malloc() and calloc()?Ques: 19 How is a NULL pointer defined?Ans:Int *p=NULL:Ques: 20 How is it different from an unutilized pointer?

C Interview Questions And Answers                                  

Q1:What is result of following code? main() {char *ch1=“rajesh”; char *ch2; ch2=(char*)malloc(20); memset (ch2, 0, 20);

while(*ch2++ = *ch1++); printf(“%s\n”,ch2); } Ans:empty string. Q2:What is result of the following code?main(){ int x=20,y=35; x=y++ + x++; y= ++y + ++x; printf(“%d%d\n”,x,y); }Ans : 5794 Q3:What will be printed as the result of the following code?                                                             main(){ int x=5; printf(“%d,%d,%d\n”,x,x< <2,x>>2); }Ans: 5,20,1

Q4:What will be result of the following code?

#define swap(x,y) x=x+y;y=x-b;x=x-y; void main(){ int a=5, b=10; swap (a,b); printf(“%d %d\n”,a,b); swap2(a,b); printf(“%d %d\n”,a,b);}int swap2(int x, inty){ int temp; temp=x; y=x; x=temp; return 0;}Ans: 10, 510, 5 Q5:What is result of following code?main(){ char *ptr = ” Hi How r U?”; *ptr++; printf(“%s\n”,ptr); ptr++; printf(“%s\n”,ptr); } Ans:Hi How r U?i How r U?Q6:What will be result of following code?

main(){ char s1[]=“HI”; char s2[]= “How r u?”; printf(“%s”,s1); }

Ans:Hi

Q7:What will be result of following code?main(){ char *ch1; char *ch2; ch1=(char *)malloc(25); ch2=(char *)malloc(25); strcpy(ch1,”Hi How R U”); strcpy(ch2,“?”); strcat(ch1,ch2); printf(“%s”,ch1);}Ans:Hi How R U?

Q8: The following variable is available in file1.c, who can access it?

static int averg;Ans: All the functions in the file1.c can access the variable. Because it is global variable. Q9:What will be the result of the following code?#define TRUE 1 while(TRUE) {printf("Hi how r u?");}

Ans: Hi how r u?

Q10:What will be output of following code?int x; int modifyvalue() { return(x+=10); } int changevalue(int x) { return(x+=1); } void main(){ int x=10; x++; changevalue(x); x++; modifyvalue(); printf("Ist output:%d\n",x); x++; changevalue(x); printf("IInd output:%d\n",x); modifyvalue(); printf("IIIrd output:%d\n",x); } Ans: Ist output:12 , IInd output:13 , IIIrd output:13

C Interview Questions And Answers

Q:What is C language?Ans: The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. 

Q:What is the output of printf("%d")? ANS:1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after �%d� so compiler will show in output window garbage value.

2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.

3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).

Q: What is the difference between "calloc(...)" and "malloc(...)"? ANS:1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).

malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).

2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.

calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.

Q: What is the difference between "printf(...)" and "sprintf(...)"? ANS:sprintf(...) writes data to the character array whereas printf(...) writes data to the standard output device.

Q: Compilation How to reduce a final size of executable?

ANS: Size of the final executable can be reduced using dynamic linking for libraries.

Q:Can you tell me how to check whether a linked list is circular? ANS:Create two pointers, and set both to the start of the list. Update each as follows:

while (pointer1) {pointer1 = pointer1->next;

pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;if (pointer1 == pointer2) {print ("circular");}}

If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet.

Q:"union" Data Type What is the output of the following program? Why?

#include main() {typedef union {int a;char b[10];float c;}Union;

Union x,y = {100};x.a = 50;strcpy(x.b,"hello");x.c = 21.50;printf("Union x : %d %s %f n",x.a,x.b,x.c);printf("Union y : %d %s %f n",y.a,y.b,y.c);}

Q: Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba.

void PrintPermu (char *sBegin, char* sRest) {int iLoop;char cTmp;char cFLetter[1];char *sNewBegin;char *sCur;int iLen;static int iCount;

iLen = strlen(sRest);if (iLen == 2) {iCount++;printf("%d: %s%s\n",iCount,sBegin,sRest);iCount++;printf("%d: %s%c%c\n",iCount,sBegin,sRest[1],sRest[0]);return;} else if (iLen == 1) {iCount++;printf("%d: %s%s\n", iCount, sBegin, sRest);return;} else {// swap the first character of sRest with each of

// the remaining chars recursively call debug printsCur = (char*)malloc(iLen);sNewBegin = (char*)malloc(iLen);for (iLoop = 0; iLoop < iLen; iLoop ++) {strcpy(sCur, sRest);strcpy(sNewBegin, sBegin);cTmp = sCur[iLoop];sCur[iLoop] = sCur[0];sCur[0] = cTmp;sprintf(cFLetter, "%c", sCur[0]);strcat(sNewBegin, cFLetter);debugprint(sNewBegin, sCur+1);}}}

void main() {char s[255];char sIn[255];printf("\nEnter a string:");scanf("%s%*c",sIn);memset(s,0,255);PrintPermu(s, sIn);}

Q:What will print out?main(){char *p1=“name”;char *p2;p2=(char*)malloc(20);memset (p2, 0, 20);while(*p2++ = *p1++);printf(“%s\n”,p2);} The pointer p2 value is also increasing with p1 .*p2++ = *p1++ means copy value of *p1 to *p2 , then increment both addresses (p1,p2) by one , so that they can point to next address . So when the loop exits (ie when address p1 reaches next character to “name” ie null) p2 address also points to next location to “name” . When we try to print string with p2 as starting address , it will try to print string from location after “name” … hence it is null string ….

e.g. :initially p1 = 2000 (address) , p2 = 3000*p1 has value “n” ..after 4 increments , loop exits … at that time p1 value will be 2004 , p2 =3004 … the actual result is stored in 3000 - n , 3001 - a , 3002 - m , 3003 -e … we r trying to print from 3004 …. where no data is present … that's why its printing null .

Answer: empty string.

              C Basic Array

1. What is array  

2. Access Elements of Array  

3. Array Representation in Memory  

4. Array Representation in Memory Contd.  

5. Multi Dimensional Array  

6. Array as Variable to Function

7. Pointer with Array

8.Array of Pointers  

9.Array of Structures  

10.Array of Structures Example  

11.Array Example112. Array Example2

What is an Array ?

An Array may defined as the collection of the homogeneous (same type) elements that are stored in the contiguous memory locations. For example, if we have to store 7 values of any type, lets say, integer values we don't have to declare 5 variables with different identifiers but we can define an array of integer type and can store the values in array directly with a unique identifier. Thus, an array named arr created in memory having 5 values can be represented as :

  1   2   3   4   5  

 0        1       2      3      4

Cells have been assigned values from 0 to 4 as in arrays values are stored from a base index of 0.

How to declare an Array ?

An Array can be declared with the help of an unique identifier specifying its data type and also by specifying the number of elements it must contain. The number of elements are declared inside a square bracket i.e. []. Thus when an array of integers having 5 elements considering the above figure can be declared as :

int arr[5];   /*the element field within the [] should be a constant value as the are the blocks of static memory whose size must be declared before execution. For variable length array dynamic memory is required which we will discuss later.*/

How to initialize an Array ?

While declaring the array for a local scope e.g. for a particular function its contents will not be initialized by default and will remain undetermined till we initialized it separately. In case of array of global scope the values are initialized but having the default values of 0's for each element.

Thus, for the array of both scopes we can initialize an array by enclosing the elements within the {} brackets. For example,

int arr[5] = {1,2,3,4,5};  /* This array will be created as which one is shown in the above figure. */

The no of elements declared within the {} must not exceeds the numbers of elements defined in the [], else it could some serious trouble to your program.

What are the advantages of using an Array ?

Following are main advantages of using an array :

1. Arrays are the most convenient way of storing the fixed amount of data that can be accessed in an unpredictable fashion.

2. Arrays are also one of the most compact data structures as in for storing the 50 elements in an array of integer type it will take the memory equivalent to the amount of memory required to store 50 elements in addition to that a few overhead bytes for whole array.

3. Another advantage of array is that iterating through an array is more faster than compared to other data structure types like linked list because of its good locality of reference.

What are the disadvantages of using an Array ?

Following are the main disadvantages of using an Array :

1. Performing various operations like insertion and deletion is quite a stiff task in arrays as after inserting or deleting an item from an array every other element in array have to move forward or backwards prior to your operation, which is a costly affair.

2. In case of the static arrays the size of the array should be know up priori i.e. before the compile time.

3. C language does not have a checking mechanism for the array sizes.

How to access the elements of an Array ?

The elements of an array can be accessed easily by providing its index within [] with the identifier and can modify or read its value.

int arr[5] = {34, 78, 98, 45, 56}

  34 78 98 45 56

 The format of accessing the array element is simple as arr[index]. To fetch a value from the above array which is placed in the position 3 we can use the following syntax :

int a = arr[2];        /* where a is an integer variable which will hold the value of element to be fetched 8 */

and to write a value in an empty we can use the following syntax :

arr[index] = value;

That's how we can access the elements of an array.

Also consider that it  is syntactically incorrect to exceed the valid range of indices for an array. If you do so, accessing the elements out of bounds of an array will not  cause any compilation error but would result in the runtime error and it can lead to hang up your system.

A simple program using array

#include<stdio.h>#include<conio.h>void main(){int arr[5] = {1,2,3,4,5}; /*declaring and initializing the array */int sum=0, i;for(i=0;i<5;i++) { sum=sum+arr[i]; /*adding the individual elements of the array*/ } printf("The value of the sum of all elements of the array is : %d", sum); getch();}

Output of the program : The value of the sum of all elements of the array is : 15

 

How arrays are represented in the memory ?

Mainly arrays are categorized in

One dimensional array. Multidimensional array.

One   dimensional arrays are the simple arrays that we have so far discussed. In previous examples we have shown how to initialize and declare one dimensional array, now we will discuss how it is represented in the memory. As we know now 1-d array are linear array in which elements are stored in the successive memory locations. The element at the very first position in the array is called its base address. Now consider the following example :

     int arr[5];                  

  34 78 98 45 56

arr[0] = 100                arr[1]                arr[2]                 arr[3]                arr[4]

Here we have defined an array of five elements of integer type whose first index element is at base address 100. That is, the element arr[0] is stored at base address 100. Now for calculating the starting address of the next element i.e. of a[1], we can use the following formula :                       

Base Address (B)+ No. of bytes occupied by element (C) * index of the element (i) 

/* Here C is constant integer and vary according to the data type of the array, for e.g. for integer the value of C will be 4 bytes, since an integer occupies 4 bytes of memory. */

Now, we can calculate the starting address of second element of the array as :

arr[1] = 100 + 4 * 1 = 104    /*Thus starting address of second element of array is 104 */

Similarly other addresses can be calculated in the same manner as :

arr[2] = 100 + 4 * 2 = 108

arr[3] = 100 + 4 * 3 = 112

arr[4] = 100 + 4 * 4 = 116

Multidimensional arrays are often known as  array of the array. In multidimensional arrays the array is divided into rows and columns, mainly while considering multidimensional arrays we will be discussing mainly about two dimensional arrays and a bit about three dimensional arrays. In 2-D array we can declare an array as :

int arr[3][3];

where first index value shows the number of the rows and second index value shows the no. of the columns in the array. We will learn about the 2-D array in detail in the next section, but now emphasize more on how these are stored in the memory.

Mainly multidimensional arrays are stored  in the memory in the following two ways :

1. Row-Major order Implementation2. Column-Major order Implementation

 In Row-Major Implementation of the arrays, the arrays are stored in the memory in terms of the row design, i.e. first the first row of the array is stored in the memory then second and so on. Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the memory in the following manner :

int arr[3][3];

  arr[0][0]

arr[0][1]

arr[0][2]

  arr[1][0]

arr[1][1]

arr[1][2]

  arr[2][0]

arr[2][1]

arr[2][2]

Thus an array of 3*3 can be declared as follows :

arr[3][3] = { 1, 2, 3,

              4, 5, 6,

              7, 8, 9 };

and it will be represented in the memory with row major implementation as follows :

   1   2   3   4   5     6   7   8   9

In Column-Major Implementation of the arrays, the arrays are stored in the memory in the term of the column design, i.e. the first column of the array is stored in the memory then the second and so on. By taking above eg. we can show it as follows :

arr[3][3] = { 1, 2, 3,

              4, 5, 6,

              7, 8, 9 };

and it will be represented in the memory with column major implementation as follows :

   1   4   7   2   5     8   3   6   9

What are Multidimensional arrays ?

Multidimensional arrays are often known as  array of the arrays. In multidimensional arrays the array is divided into rows and columns, mainly while considering multidimensional arrays we will be discussing mainly about two dimensional arrays and a bit about three dimensional arrays. In 2-D array we can declare an array as :

int arr[3][3] = { 1, 2, 3,

                  4, 5, 6,

                  7, 8, 9                };where first index value shows the number of the rows and second index value shows the no. of the columns in the array. To access the various elements in 2-D we can access it like this:

 printf("%d", a[2][3]);  /* its output will be 6, as a[2][3] means third element of the second row of the array */

In 3-D we can declare the array in the following manner :

int arr[3][3][3] = { 1, 2, 3,                     4, 5, 6,                     7, 8, 9,

                     10, 11, 12,                     13, 14, 15,                     16, 17, 18,

                     19, 20, 21,                     22, 23, 24,                     25, 26, 27                  }; 

 /* here we have divided array into grid for sake of convenience as in above declaration we have created 3 different grids, each have rows and columns */

If we want to access the element the in 3-D array we can do it as follows :

printf("%d", a[2][2][2]);                                /* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no. i.e. 3 and the second value in [] means third row in the corresponding grid and last [] means third column  */

Can we pass an array to a function just like we pass any variable ?

The answer to the above question is definitely YES, we can pass array to function just like we pass any other variable. But the only difference would that the array is passed via call by reference method  inside the function as we know that array as itself like a pointer in which base element acts like a pointer for the entire array

Just like any other normal we can pass an array to a function as :

void funarr(int arr[])

The above function funarr accepts an array of integers as its parameter. For passing the array as function we must declare array as,

int arr[10];

Equivalently we can also pass only the name of the array as parameter in the calling function as

void funarr(arr);

The following code snippet will demonstrate how can we pass array as a parameter to a function :

#include <stdio.h>#include<conio.h>void funarr(int arr[], int len){printf("\nEnter the length of array :");scanf("%\nd",&len);printf("\nEnter the elements of the array :");for(i=0; i<len; i++){     scanf("%d",&arr[i]);}printf("\nThe elements of the array are as follows :");for(i=0; i<len; i++){    printf("\n%d",arr[i]);}}void main(){int myarr[100];clrscr();funarr(myarr, 7);getch();}

Output : The output of the following program will be as follow :

Enter the length of array :

7

Enter the elements of the array :

1

3

4

5

3

2

6

The elements of the array are as follows :

1

3

4

5

3

2

6

How arrays and pointer are linked ?

As we know that a pointer is a variable that contains the address the another variable. That is, a pointer a special kind of variable that is containing the address of another variable and we can define a pointer in the following manner,

int *ptr;

which means that the ptr is a pointer type variable that is pointing to a address where an integer type value is stored.

Also, we know that in an array elements are stored in sequential manner in which the very first index corresponds to the base address of first element which acts as a base address of the entire array, i.e. we can say that an array  is a kind of pointer itself in which elements are stored according to their addresses.

we can declare a pointer to an array in the following way :

int a[5];

int *ptr;

ptr = &a[0];

in above example we have defined an array of five elements and a pointer is defined which  is pointing to the  first element of the array

A simple example of   how to use 2-D array with pointer :

The following example takes a two dimensional array as input from the user and display  its contents via using pointer.

#include <stdio.h>#include<conio.h>void main(){int i=0, j=0;int arr[3][3];int *ptr1;ptr1 = &arr[0][0];clrscr();printf("\nEnter the elements of the array :")for(int i=0; i<=2; i++){     for(int j=0; j<=2; j++){     scanf("\n%d", &arr[i][j]);  /* taking the input 2-D array or matrix from the user */    }    }printf("Following are the elements of the array :");for(int i=0; i<=2; i++){     for(int j=0; j<=2; j++){     printf("\n%d", *ptr1);     /* displaying the content of the matrix */ ptr1++;    }    }getch();} 

Output : The output of the following program would be as follows :

Enter the elements of the array :

1 2 3

4 5 6

7 8 9

Following are the elements  of the array :

1 2 3

4 5 6

7 8 9

Array of pointers :

Just like the array of the various types of the datatypes like integer, floats, we can also define an array of pointers. In the array of the pointers we can stores the addresses of the values as the elements, we can declare an array  of pointer in the following way :

int *arr[7];

the above declaration tells us that arr is an array that contains the address of the 7 integers as its elements.

Following a little code snippet depicting the usage of the array of pointer :

#include <stdio.h>#include<conio.h>void main(){char *ptr1[3]; /* declared a array of character pointers */ptr1[0]="hello ! "; /* first address corresponds to value hello */ ptr1[1]="how are"; /* second address corresponds to value how are */ptr1[2]="you"; /* third address corresponds to value you */printf("%s%s%s",ptr1[0], ptr1[1], ptr1[2]);getch();}

Output : The output of the following program will be as follows :

hello! how are you

How we use Array of Structures in C data structures ?

As we are aware of the fact that the structures in the C language provides a mechanism to incorporate different data types within a same structure like integers, floats and character values which are known as structure members. As a fact, structures are simple to  define if there are only one or two elements but in case if too many objects are needed e.g.. to show the data of each student of a class, in that case we introduces the concept of the array of the structures. We can declare an array of structures as follows :

#include <stdio.h>

struct studentinfo{int rollno.;char name[21];char sex;};

studentinfo detail[35];

In the above declaration, we have defined a structure named studentinfo which keeps the information about a particular student like rollno. of the student , name and sex. Then after defining the structure we have declared an array of structures we can contain 35 objects of such structure and can incorporate the details of 35 students.

Initializing the array of structures :

An array of structure can initialized in the same manner as we initialize a simple array. It must be kept in mind that only the static and external variables are initialized, lets understand to initialize a array of structure by taking this example :

#include <stdio.h>

/* we have taken a structure which stores the information about the information about a particular employee */

struct employeeinfo {int emp_id;char sex;int salary;};

/* here we have declared an array of structure i.e. data which is of employeeinfo type and contains the 3 objects of above defined structure i.e. of employeeinfo */ employeeinfo data[3] = { {1001, 'M', 10000}, {1002, 'F', 8000}, {1003, 'M', 15000}};

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001          data[0].sex = 'M'            data[0].salary = 10000

data[1].emp_id = 1002          data[1].sex = 'F'            data[1].salary = 8000

data[2].emp_id = 1003          data[2].sex = 'M'            data[2].salary = 15000

 If some of the values of the structures elements are not initialized then they are initialized to a default value of '0'. For example, if above declared structure is lacking some initialized elements then,

employeeinfo data[3] = { {1001, 'M'}, {1002, 'F'}, {1003, 'M'}};

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001               data[0].sex = 'M'               data[0].salary = 0

data[1].emp_id = 1002               data[1].sex = 'F'                data[1].salary = 0

data[2].emp_id = 1003               data[2].sex = 'M'               data[2].salary =0       /* where uninitialized element i.e. salary is provided with the default value of zero */

A simple program showing the usage of the array of structure :

#include <stdio.h>#include<conio.h>

void main(){int i=0; /* defining a structure for employee record */struct employeeinfo { int emp_id; char name[21]; char sex; int salary; }; /*initializing the record values in an array of structure of type employeeinfo */employeeinfo data[3] = {{1001,"Ashish", 'M', 10000}, {1002,"Swati", 'F', 8000}, {1003,"Praveen", 'M', 15000}}; clrscr();printf("\nThe content of record of employee are as follows :"); /* displaying the record of the employees */for (i=0;i<=2;i++) { printf("\n Record number %d", i+1 );  printf("\n Employee id is : %d", data[i].emp_id); /* accessing the records of array data */  printf("\n Employee name is : %s", data[i].name);  printf("\t Employee gender is : %c", data[i].sex);  printf("\t Employee salary is : %d", data[i].salary); } getch();}

The above program shows how to an array of structure which can hold record of 3 employees simultaneously and how we can access those records via using the concept of array of structures.

Output : Following would be the desired output of the above  written program

The content of record of employee are as follows :

Record number 1

Employee id is 1001    Employee name is Ashish    Employee gender is M     Employee salary is 10000

Record number 2

Employee id is 1002    Employee name is Swati     Employee gender is F     Employee salary is 8000

Record number 3

Employee id is 1003    Employee name is Praveen   Employee gender is M     Employee salary is 15000

A simple traversing program in 2-D array : 

#include<stdio.h>#include<conio.h>void main(){int a[3][3], i=0, j=0;clrscr();printf("Enter the elements of the array :");for (i=0;i<=2 ;i++ ){     for(j=0; j<=2; j++){    scanf("%d\n", &a[i][j]);   /* taking array elements as input from the user */        }}printf("\nThe elements of the array you have enetered are as follows :")for(i=0; i<=2; i++)    {    for(j=0; j<=2; j++){    printf("%d", a[i][j]);     /* diplaying the elements of the array */}}getch();}

Output : Its output will be as follows

Enter the elements of array :

1

2

3

4

5

6

7

8

9

The elements of the array you have entered are as follows :

1

2

3

4

5

6

7

8

9

A program to add   two 2-d array and place the result in the third array :

The following program demonstrates the addition of the two dimensional array  or matrix and store their result in the third matrix as their result.

#include<stdio.h>#include<conio.h>void main(){int a[3][3],b[3][3], sum[3][3], i=0, j=0;clrscr();printf("Enter the elements of the first array :");for (i=0;i<=2 ;i++ ){

     for(j=0; j<=2; j++){    scanf("%d\n", &a[i][j]);        printf("\n");}}printf("Enter the elements of the second array :")for(i=0; i<=2; i++)    {    for(j=0; j<=2; j++){    scanf("%d", &b[i][j]);

}}/*Now placing the sum of the two matrices in the third one */for (i=0;i<=2 ;i++ ){     for(j=0; j<=2; j++){    sum[i][j] = a[i][j] + b[i][j];        }}/* Now displaying the sum of the two matrices by following code snippet */printf("\nThe sum of the matrices obtained is as follows :");for(i=0; i<=2; i++)    {    for(j=0; j<=2; j++){    printf("\n%d", sum[i][j]);printf("\n");}}

getch();}

Output : Its output will be as follows :

Enter the elements of the first array :

1 2 3

3 4 5

4 3 7

Enter the elements of the second array :

2 4 5

5 6 1

1 3 7

The sum of the matrices obtained is as follows :

3 6 8

8 10 6

5 6 14

    Function in C

1. What Is A Function  

2. Types Of Function In C  

3. Some Other Types Of Functions In C

 4. Function Declaration And Prototype In C

  

5.Nesting Of Function In C

  

6.Calling Function In C

  

7.Recursive Function In C

What is Function In C

Functions are a powerful programming tool. A function is a block of code that performs a specific task. It has a name and it is reusable . it can be executed from as many different parts in a Program as required, it can also return a value to calling program. All executable code resides within a function. It takes in input, does something with it, then give the answer. A C program consists of one or more functions. A computer program cannot handle all the tasks by it self. It requests other program like entities called functions in C. We pass information to the function called arguments which  specified when the function is called. A function either can return a value or returns nothing.Function is a subprogram that helps to reduce coding.NOTE :  If a program has only one function then it must be the main() function.

A Simple Example Of Function In C

#include<stdio.h>#include <conio.h>int adition (int, int); //Function Declarationint addition (int a, int b) //Function Definition{int r;r=a + b;return (r);}int main(){int z;z= addion(10,3); //Function Call printf ("The Result Is", %z);return 0;}

Output : The Result Is 13

Types Of Function In C

1. Library Function 2. User Defined Function

Library Function In C

C  provides library functions for performing some operations. These functions are present in

the c library and they  are predefined for example. Sqrt() is a mathematical library function

which is used for finding the square root of any number The function scanf and printf() are

input and output library function  similarly we have strcmp() and strlen() for string

manipulations.

To use a library function we have to include some header file using the preprocessor

directive #include . for example : to use input and output function like printf() and scanf()

we have to include stdio.h, for math library function we have to include math.h for string

library string.h should be included .

User Defined Function In C

A user can create their own functions for performing any specific task of program. These

types are called user defined function. to create and use these function we have to know

these 3 things.

1. Function Declaration

2. Function Definition

3. Function Call

Function Definition

The function definition consists of the  whole description and code of a function. It tells that

what the function is doing and what are the input output for that.  A function is called by

simply writing the name of the function followed by the argument list inside the parenthesis.

A function definition have two parts :

1. Function Header

2. Function Body

Structure Of A Function In C

There are two main parts of the function. The function header and the function body. 

int sum(int x, int y){int ans = 0; //holds the answer that will be returnedans = x + y; //calculate the sumreturn ans //return the answer}

Function Header

The first line of the above code is called Function Header.

int sum( int x, int y)

It has three parts

1. The name of the function i.e. sum

2. The parameters of the function enclosed in parenthesis

3.  Return value type i.e. int

Function Body

What ever is written with in { } in the above example is the body of the function.

Some Properties Of Functions

1. Every function has a unique name. This name is used to call function from “main()” function.

2. A function performs a specific task.

3. A function returns a value to the calling program.

Advantages Of Using Functions In C

1. Functions has top down programming model. In this style of programming, the high level logic of the overall problem is solved first while the details of each lower level functions is solved later.

2. A C programmer can use function written by others

3. Debugging is easier in function

4. It is easier to understand the logic involved in the program

5. Testing is easier

Why We Use Function

1. Writing function avoids  rewriting the same code  over and over. Suppose we have a

section of code that is calculating the area of triangle, if later we want to calculate

the area of other triangle then we don't need to write the code again.

2. By using function it becomes  easier to write programs in c language.  

Some Other Types Of Function

 Functions with no arguments and no return values.

Example Of Function With No Return Type And No Argument

#include <stdio.h>#include <conio.h>void printmsg(){printf ("Hello ! I Am A Function .");}int main(){printmsg();return 0;};

Output : Hello ! I Am A Function .

OR

#include <stdio.h>#include <conio.h>

void msg (void){puts ("Hello");};

Output : Hello

Functions with arguments and no return values.

Example Of Function With Argument And No Return Type

#include <stdio.h>#include <conio.h>void sub (int a, int b){int s;clrscr();s=a-b;}void main(){sub(45,40);printf ("The subtraction is =",s);}

Output : The subtraction is 5

Functions with arguments and return values.

Example Of Function With Argument And Return Type

#include <stdio.h>#include <conio.h>int addition( int, int); main(){ int i=1; i = add(1, 1);clrscr(); }int add( int a, int b) { int c; c = a + b; return c;};

Output : 2

Functions that return multiple values. Example Of Function Returning Multiple Values

#include <stdio.h>#include <conio.h>

main(){int a[5]={2,4,,6,8,10};int b[8]={1,3,5,7,9,11,13,15};int c[10]={1,2,3,4,5,6,7,8,9,10};clrscr();printf ("sum of the array a : %d \n",add(a,5));printf ("sum of the array b : %d \n",add(b,8));printf ("sum of the array c : %d \n",add(c,10));}add (int arr[], int n){int i, sum=0;for (i=0;i<n; i++)sum+=arr [i];getch();return sum;}

Output : sum of array a : 30sum of array b : 64sum of array c : 55

Function Declaration and Function PrototypesC always needs declaration before use. This is also true for functions. For functions the declaration needs to be before the first call of the function. A full declaration includes the return type and the number and type of the arguments.

This is also called the function prototype.

For Example :

int add( int, int);

This statement declares a function called add, it has two integer arguments and returns an integer.Main Function In CA main function is placed where the execution of the starts.main() cannot return anything. can I run a program in c without main if yes how? Answer is "NO".

The reason is, main() is a function called by another function, which is the start-routine. This routine is created by the compiler and will be same for all the programs that you write.Nesting Of Function Using C C permits nesting of two functions. There is no limit how deeply functions can be nested. Suppose a function abc can call function bca and function bca can call function cab and so on.Example Of Nesting Of FunctionCalling Functions In C Call By Value

1.[2.] Call By Reference

Call By Value

Whenever we called a function and passed something to it we have always passed the 'Values' of variables to the called function. Such function is called Call By Value.

Example Of Call By Value Using C

#include <stdio.h>#include <conio.h>main() { int a=50, b=70; interchange (a, b); printf (“a=%d b=%d”, a, b); }

interchange(a1,b1) int a1,b1; { int t; t=a1; a1=b1; b1=t; printf(“a1=%d b1=%d”,a1,b1); }

Output : a=50 b=70a1=70 b1=50

Call By Reference

We know that variables are stored somewhere in memory. So instead of passing the value of a variable to a function, can we not pass the location number ?If  we are able to do so, then it is called 'Call By Reference'.

For Example : 

#include <stdio.h>

void swap (int &a, int &b) // a and b are reference variables{int t=a;a=b;b=t;}This is also accomplished using pointers.For Example :void swap1(int t *a, int  *b) {int  t;

t= *a;*a=*b;*b=t;}

This function can be called as following swap1(&x, &y);  

Example of call by reference 

#include <stdio.h>#include <conio.h>main() { int num1=20, num2=30; interchange(&num1,&num2); printf("num1=%d num2=%d",num1,num2); } interchange(num3,num4) int *num3,*num4; { int t; t=*num3; *num3=*num4; *y1num4=t; printf("*num1=%d *num2=%d",num3,num4); };

*num1=70 *num2=50 num1=70 num2=50

In case of call by reference address of the variable got passed and therefore what ever changes that happened in function interchange got reflected in the address location and therefore the got reflected in original function call in main also without explicit return value.  

#include <stdio.h>#include <conio.h>int factorial (int);void main{int a, fact;clrscr();printf("\n Enter any number");scanf ("%d",&a);fact=fatorial(a);

printf("factorial value=%d",fact);}int factorial(int x){int f=1,i;for(i=x; i>=1; i--)f=f*i;return(f);};

Recursion In C

Recursion is the property of function, in which function calls itself. In C, it is possible for the  functions to call themselves. A function is called 'recursive' if a statement within the body of a function calls  the same function. Let us now see an example of recursion. Suppose we wan to calculate the factorial of an integer. As we know the factorial of a number is the product of all the integers between 1 and that number.

For Example : 4 factorial = 4*3*2*1. This also be expressed as 4!= 4*3!. Thus factorial of a number can be expressed in form of itself.  

#include <stdio.h>#include <conio.h>int factorial (int);void main{int a, fact;clrscr();printf("\n Enter any number");scanf ("%d",&a);fact=fatorial(a);printf("factorial value=%d",fact);}int factorial(int x){int f=1,i;for(i=x; i>=1; i--)f=f*i;return(f);} 

Output :Enter nay number=3Factorial Value=6

 Memory  Management

1. Memory Management in C 2. Memory function in C

Memory Management

 In c two types of memory management are-

1. Static Memory Allocation2. Dynamic Memory Allocation

Static Memory Allocation

Union

union is used to group a number of different variables together. In structure number of different variables of different data type stored in different memory places but in union different variable of different data type are store in same place.

Example:

struct student{int rollno;char name[50];float salary;};

 

 

union student{int rollno;char name[50];float salary;};

 

Dynamic  Memory Allocation

In dynamic memory management memory will be allocate at runtime. This is also known as  heap memory. Some language at the run time have ability to calculate and assign the memory space at run time for an array but c can't have this feature. But in C there is some function which provide the facility to allocate and deallocate the memory. In ,Local Memory, when these function will call memory will allocate automatically and when function will exit memory will deallocated automatically . In dynamic memory allocation ,allocation of memory is explicitly requested for a  particular size of block .For deallocation of memory explicitly requested.

the function through which the dynamic memory allocation and deallocation will performed are :

1. malloc()2. calloc()

3. free()

4. realloc()

malloc()

malloc()function allocate a block of byte of memory in byte. In this when the memory block needed explicitly requested. The malloc() function is same as a function is request for RAM in the system  memory. If the request is grant then a void pointer return and the pointer point start of that block. If the request fail then a NULL pointer return.

Example:

malloc( number of element * size of each element);

int * ptr;ptr = malloc(10*sizeof(int));

Where size represents the memory required in bytes .The memory which is provided is contiguous memory. But malloc function return void pointer so it needed type casting of that pointer.Examlpe:(type cast)malloc( number of element * size of each element);

int * ptr;ptr =(int*) malloc(10*sizeof(int));

similarly for allocation of memory to a structure variable :Examlpe:

(struct name)malloc( sizeof(struct name));

struct employee{

int emp_id;char emp_name[20];float emp_contact_no;

};struct employee *ptrptr=(struct employee*)malloc(sizeof(struct employee));

calloc()

In malloc requested memory is provided a block of contiguous memory . calloc() function is similar to the malloc rather then calloc() function allocated the memory block for an array of elements. Memory for a group of objects used calloc() function. If calloc() function is executed succesfully then its allocated memory is set as zero and a pointer returned and if the function failed then a NULL pointer return.

Example:

void *calloc(size_t

number,size_t size);

size_t used for unsigned on most compilers.The number is the number of objects which is allocate, and size is the size (in bytes) of each object.

int main () {       int number,i;                 printf("Enter the number ");       scanf("%d",&number);   printf("Number which is here are",number);        int *ptr = (int *) calloc (number,sizeof(int));        for (i=0; i<number;i++) {                ptr[i] = i +i; }for (i=0; i<number;i++) {               printf("Result is %d %d\n",i,ptr[i]); }}

free()

For deallocation of the memory which is allocated through the malloc() function and calloc() function used free() function.

Example:

free(ptr);

int main () {       int number,i;               printf("Enter the number ");               scanf("%d",&number);               printf("Number which is here are",number);               for (i=0; i<number;i++) {

ptr[i] = i +i;}

for (i=0; i<number;i++) {

               printf("Result is %d %d\n",i,ptr[i]);                }

     free(ptr);

}

realloc()

realloc() function is used  for resize the size of memory block which is allocated by the malloc() and calloc () function.

Two situation where use realloc() function.

When allocated block is insufficient need more memory then use realloc(). When allocated memory is much more then the required application then use realloc().

Example:

realloc(ptr, new size);

/* Through realloc() resize the memory . */

#include <stdio.h>#include <stdlib.h>#include <string.h>  {

         char buffer[80], *msg;         /* Input a string. */   

puts("Enter the text line");            gets(buffer);         /* The string copied in to initial allocated block */         msg = realloc(NULL, strlen(buffur)+1);             strcpy(msg, buffer);             /* Display the message which copied. */

    

    

puts(message);         /* Get another string from the user. */            puts("Enter another text line.");    ;         gets(buffer);         /* Resize the memory and also concatenate the string to it. */         msg = realloc(msg,(strlen(msg) + strlen(buffer)+1));    

         strcat(msg, buffer);     };

  Pointer in C

1. What is Pointer ? 

2. Some point of Pointer And Array: 

3. Array of Pointers  

4. Pointers to Functions:

5. Pointer to Structure: 

6. Advantage or Disadvantage of Pointer:

        What is Pointer ?

Pointer is a address variable that hold the address of another variable. We can have a pointer to any variable type. The  & is a unary  operator that gives the address of a variable. The * (indirection or dereference operator), that  gives the contents of an object that pointed to by a pointer.

To declare a pointer to a variable do:

//Declare a pointer data_type_name * variable name int *ptr;

Example:

main( ){int a = 5 ;printf ( "\nAddress of a = %u", &a );printf ( "\nValue of a = %d", a );};

Output: The output of the above program would be: address of a=1444 value of a=5

Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The expression &a returns the address of the variable a, which in this case happens to be 1444 .Hence it is printed out using %u, which is a format specified for printing an unsigned integer.

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator. that is showing in the program. main(){int a = 5 ;printf ( "\nAddress of a = %u", &a );printf ( "\nValue of a = %d", a ) ;printf ( "\nValue of a = %d", *( &a ) );};

Output: The output of the above program would be:

Address of a = 1444Value of a = 5Value of a = 5Another example of Pointer

#include <stdio.h>

int a, b;int *p;

int main(void){    a= 1;    b = 2;    p = &b;    printf("\n");    printf("a has the value %d and is stored at %u\n", a, (void *)&a);    printf("b has the value %d and is stored at %u\n", b, (void *)&b);    printf("p has the value %d and is stored at %u\n", p, (void *)&p);    printf(" the value of the integer pointed to by p is %u\n", *p);

    return 0;};

Output: The output of the above program would be:

a has the value 1 and is stored at 170

b has the value 2 and is stored at 172 p has the value 00AC and is stored at 174 the value of the integer pointed to by p is 2 Note- here (Void *): Pointers can also declare as a void. void pointers can't be dereference without explicit casting. this is because the compiler can't determine the size of the object. size of all type of pointer (near) in c is two byte either it is char pointer, double pointer, function pointer or null pointer. Void pointer is not exception of this rule and size of void pointer is also two byte.

Some point of Pointer And Array

Here we are not discussing about only pointer. we are also discussing here about array. we telling u what is the relationship between Pointer and Array. We know that what is pointer pointer is an address variable that hold the address of another variable or another type we can say that a pointer is a tool used for keeping track of a certain spot in memory and the simply array is the groups of data stored sequentially in memory.

 in array we can keep track the first item with a pointer to that item and use that as an index point for every other item in the array.an array is declared by using it's type, here We declare the type of the array and the size of array.

array specified inside brackets []. 

suppose we have to declare char array. so we declare this type , char array[25];

All we had to do was change int to char. Simple, isn't it?

  Array of Pointers

we are creating  an array of pointers of maximum size 2. Then we have assigned the objects of array pointer.

arr[0] = &a; arr[1] = &b;

 

Example: #include <stdio.h>#include <conio.h>main() {

clrscr(); int *arr[2]; int a = 5, b = 10; int i; arr[0] = &a; arr[1] = &b; for (i=0; i< 2; i++) { printf("The value of %d= %d ,address is %u\t \n", i, *(arr[i]),arr[i]); } getch(); return 0;};

Output: The output of the above program would be:the value of 0=5 , address is 6523the value of 1=10 , address is 6521

 Note - If we write  int *p[10]; are we declaring an array of pointers, or a pointer to an array? In declarations, the brackets [] which describe arrays have higher precedence than the * which describes pointers.It looks like the * and the [] are both next to the identifier p, but since [] has higher precedence it means that the brackets are ``closer'' --p is an array first, and what it's an array of is pointers.

If you really wanted a pointer to an array (though usually you do not) you once again override the default precedence using explicit parentheses:

 int (*p)[10];

says that p is a pointer first, and what it's a pointer to is an array.

       Pointers to Functions

The function pointer is a powerful feature in c. In memory a function has a physical location  that can be assigned to a pointer. This address is the entry point of the function and it is the address used when the function is called. Once a pointer points to a function, the function can be called through that pointer. Function pointers also allow functions to be passed as arguments to other functions.  or function pointers is a pointers, that point to the address of a function. now we can se that when we run the any program than that running program gets a certain space in the main-memory. than the executable compiled program code and variables are put inside this memory. Thus that program code have a functions than that  function in the program code is, like e.g. a character field, nothing else than an address. It is only important how you, or better your compiler/processor, interpret the memory a pointer points to.

Example of function-1

 

#include<stdio.h>#include<conio.h>

void my_int_func(int x){    printf( "%d\n", x );}int main(){    void (*yes)(int);    yes = &my_int_func;  /* call my_int_func (note that you do not need to write (*yes)(2) ) */    yes( 2 );    /* but if you want to, you may */    (*yes)( 2 );

    return 0;};

Output: The output of the above program would be:2 2 Example of function-2 #include<stdio.h>     #include<conio.h>     int show();     void main()     {     int (*fP)();     clrscr();     fP=show;        printf("Address of function :%u",show);         (*fP)();         getch();     }          int show()     {     printf("\nFunction called using pointer!");     return 0;     }

Output: The output of the above program would be:  Address of function : 694 Function called using pointer! 

Pointer to Structure

In structure we can access multiple data types under a single name for easy manipulation. example we want to refer to address with multiple data like house number, street, zip code, country. C is support structure which allows that we want to wrap one or more variables with different data types. A

structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member. Example struct address{    unsigned int house_number;     char street_name[50];     int zip_code;     char country[50];  };

A structure can contain pointers as structure members and we can create a pointer to a structure as follows:

struct invoice { char* code; char date[12]; };

struct address billing_addr; struct address *pa = &billing_addr;

Example of pointer to structure

#include <stdio.h>#include <string.h>

struct man{ /* the structure type */ char lastname[20]; /* last name */ char firstname[20]; /* first name */ int age; /* age */ float rate; /* e.g. 12.75 per hour */};

struct man my_struct; /* define the structure */void show_name(struct man *p); /* function prototype */

int main(void){ struct man *st_ptr; /* a pointer to a structure */ st_ptr = &my_struct; /* point the pointer to my_struct */

strcpy(my_struct.lastname,"tiger"); strcpy(my_struct.firstname,"rakesh"); printf("%s ",my_struct.firstname); printf("%s",my_struct.lastname); my_struct.age = 30; show_name(st_ptr); /* pass the pointer */ return 0;}

void show_name(struct man *p){ printf("%s ", p->firstname); /* p points to a structure */ printf("%s ", p->lastname); printf("%d", p->age);};Output: rakesh tigerrakesh tiger 30

Advantage or Disadvantage of Pointer 

Advantage

1. We can achieved dynamic allocation of memory via pointers. because pointers are generally useful in the context where we want a continuous memory allocation.

2. Pointers is address variable that hold the address of another variable. they are mainly used as function parameters to pass  values of parameters as references rather than values.

Disadvantage

1. During runtime sufficient memory is not available for the storage of pointers, the program may crash.

2. If the programmer is not careful and consistent with the use of pointers, the program may crash.

DataStructure Using C with Examples

1. What is data Structures  

2. Classify Data Structures  

3. Memory alloc DS  

4. Memory alloc DS contd  

5. Operations on DS  

6. What is array  

7. Access elements array  

8. Pointer with array  

9. Array of Pointers  

10. Traverse array  

11. Array insert  

12. Array delete  

13. Array of structures  

14. Example arrof structures  

15. What is linkedlist  

16. Representing list  

17. Insert singlylinkedlist  

18. Delete singlylinkedlist 

19. Circular linkedlist  

20.   Insert circularlinkedlist

  

21.   Delete circularlinkedlist

  

22.   Doubly linkedlist

  

23.   CodeInsertion doublylinkedlist

  

24.   Deletion doublylinkedlist

  

25.   What is stack

  

26.   Operations static implemented stack

  

27.   Operation linkedlist implemented stack

  

28.   What is Queue

  

29.   Queue static implementation

  

30.   Queue dynamic implementation

  

31.   Circular Queue

  

32.   Insertion deletion circularQueue

What is a Data Structure ?

1. A data structure is a way of storing and organizing data in computer so that it can used efficiently. In other words, we can say that the data structure is the representation of the logical relationship existing between the individual elements of data or, Equivalently we can say that, A data structure  is a way of organizing all data items that considers not only the elements stored but also their relationship to each other. Data structures mainly concerns with the following four things :  Organization of data

2.  Accessing methods

3.  Degree of Associatively

4.  Processing alternatives for information

Data Structures are almost used in every software and every program. Some specific data structures are for used generating efficient algorithms, and maintaining huge amounts of data by providing the large databases and internet indexing services. Having a sound knowledge of data structures plays a crucial role during the software design. Different kinds of data structures  are used for different types of application depending upon their

properties, say for e.g.., binary-trees are mostly found useful in creating databases compiler uses hash tables for look up for the  identifiers. The main principle of the data structure is based on the ability of the computer to store and fetch the data at any place in its memory.

Now we know that the data structures are the building blocks of a program, and hence the selection of the particular data structure depends on the following factors :

1. The data structure must be rich enough in its structure so that it may be able to fathom the relationship between the data.

2. The data structure must be efficient and simple enough so that it may be processed conveniently as per requirement.

How do we classify  the data structure ?

The data structures mainly are classified in the following categories:

Primitive and Non-Primitive Data Structures

1. Primitive data- Primitive data structures are those data structures that can be directly operated upon the machine instructions. These data structures include int, char, float type of data structures.

2. Non-Primitive data- Non-Primitive data structures are those data structures that are derived directly from the primitive data structures. Examples of Non-Primitive data structures include class, structure, array, linked lists.

Homogeneous and Heterogeneous Data Structures

1. Homogeneous data- Homogeneous data structures are those data structures that contain only similar type of data e.g. like a data structure containing only integral values or float values. The simplest example of such type of data structures is an Array.

2. Heterogeneous Data- Heterogeneous Data Structures are those data structures that contains a variety or dissimilar type of data, for e.g. a data structure that can contain various data of different data types like integer, float and character. The examples of such data structures include structures, class etc.

Static and Dynamic Data Structures

1. Static data- Static data structures are those data structures to which the memory is  assigned at the compile time, means the size of such data structures has to be predefined in the program and their memory can be increased or decreased during the execution. The simplest example of static data structure is an array.

2. Dynamic data- Dynamic Data Structures are those data structures to which memory  is assigned at the runtime or execution time and hence their size can be increased or decreased dynamically as per requirement of the program. The example of such data structures include class, linked lists etc.

Linear and Non-Linear Data Structures

1. Linear data- In linear data structures the data is kept in the sequential manner which means that the previous data has knowledge of next data or we can say that

the data is interrelated. The example such data structures include arrays, linked lists etc.

2. Non-linear data- Non-linear data structures does not maintain any kind of relationship among the data. The data is stored in non-sequential manner and examples of these types of data structures includes graphs, trees etc.

How Memory allocated to the Data Structures ?

Mainly Memory allocated to the Data Structures in following two ways :

1. Static or compile time allocation2. Dynamic or runtime allocation

Static or compile time allocation refers to the allocation of the memory to the program elements like identifiers, variables at the very beginning of the program. The amount of the memory allocated in this allocation scheme is fixed and cannot be manipulated. For example,

int x, y;float arr[5];

In the above declarations memory allocated to the variables x and y are a block of 2 bytes respectively where for the arr a memory block of 20 bytes is allocated consecutively, as we know in array  elements are stored consecutively. This allocation of memory is determined by the compiler at the compile time.

But this type of allocation scheme suffers from some limitations, for e.g. as we know that there is no bounds checking on the arrays  in the C language, so if we store more than five elements in the above declared array then there will not be any type of error but the elements that are defined outside the bounds of the array will not be given consecutive memory locations infact they will be given some random memory locations for their storage, which will certainly violate the property of an array. On the other hand, if we define a lesser no. of elements than the actual containing capacity of an array then there will be sheer wastage of the memory which is not desired.

So to overcome the above  mentioned flaws of the static memory allocation scheme the concept of dynamic memory allocation came into existence.

Dynamic or runtime allocation means to allocate the memory to program elements during the runtime or the execution time of the program. In this type of allocation scheme the size of the program element  can be increased or decreased dynamically according to the program requirement. In C language the dynamic memory allocation is done via using pointers. This allocation scheme is best suited where we don't know the memory requirement in advance, which is the case with most of real life problems, which gives flexibility to the programmer. There are following main functions used for allocating and deallocating memory  dynamically  to the data structures.

1. malloc() function :  The malloc() function allocates a block of memory in bytes. The programmer should explicitly give the block size it requires to use, we can consider the malloc() function as a request to the RAM of the system to allocate memory and if request is granted then it will return a pointer( of type void, means we can assign it any type of pointer)  which will point to the first block  of  that memory, if not the malloc() function will return NULL. The malloc() function is available in <malloc.h> header file.

The basic syntax for allocating memory using malloc() function is :

malloc (number of elements * size of each element);

for eg.,

int *ptr1;/* * here size refers to the size of the data type like int, float etc., here sizeof (int) will * return 2 bytes as integer takes in C  */ptr1 = malloc(7 * sizeof(int));       

As told earlier that malloc() function returns a  void type of pointer so we should type cast it properly according to our requirement. As  in above eg. we have taken an int pointer so we can reform the above declaration as :

ptr1 = (int *) malloc (7 * sizeof(int ));

After the execution of this statement a block of 14 bytes consecutively will be created in the memory, as integer takes 2 bytes in the memory and we have defined 7 elements of integer type.

Similarly for allocating memory  for a structure variable we can do it in following way :

#include <stdio.h>#include<conio.h>

struct employeeinfo{ int emp_id; char name[21]; char sex; float salary;} ;

struct employeeinfo *ptr1;

The above is the declaration of a structure and it can be allocated memory via malloc() in the following manner :

ptr1 = (struct employeeinfo *) malloc (sizeof(employeeinfo));

When the above statement is executed a block of 28 bytes will created in the memory viz. 2 bytes for integer, 21 bytes for name element , 1 byte for sex element, and 4 bytes for salary element of the structure.

2.  calloc() function : The calloc() function  is  quite very much similar to malloc() function except for the difference that calloc() takes two arguments against the one argument

passed in the malloc() function. The following shows how we can allocate memory using calloc() function :

int ptr1;ptr1 = (int *) calloc( number of element required, size of each element);

for eg. to create a memory  block for 7 elements each requiring 2 bytes of storage, we can allocate memory using calloc()  as

ptr1 = (int *) calloc (7, 2);

3.  free() function : The free() function is mainly used for deallocating the memory which has been allocated previously. When your function is finished with dynamically  allocated memory you must deallocate it by using free(), as memory is a vital resource and should not be wasted since it is limited resource which should be kept in spare for future use.

You can free an allocated memory by the following syntax :

ptr1 = (int *) calloc (7, 2);free(ptr1);

in above code we have deallocated a block of 14 bytes from the memory.

4. realloc() function : This function is used to reallocate or change the size of the memory block that has been created using via malloc() or calloc(). This function is generally used in two situations :

1. When the block of memory allocated does not have sufficient space to perform a certain funtion.

2. When the block of memory allocated have galore space to perform a certain function which will lead to memory wastage.

In other words, we can say that realloc is a precise and efficient way of allocating memory and can be done in following manner :

ptr1 = (int *) realloc(ptr1, new size in bytes);

In the above illustration, we are reallocating the memory allocated to an integer type pointer by calling realloc on ptr1 and specifying its new size in bytes. But please do remember, it must be first allocated memory by using the malloc() function as,

int ptr1;ptr1 = (int *) malloc(7 * sizeof(int ));

An example showing how to use above mentioned functions in a program :

#include <stdio.h>#include<conio.h> /*please do include header files <malloc.h> and <alloc.h> in this program */#define NULL 0 /* here we have defined the NULL value equals to 0 */void main()

{char *msg; /* declared a character type pointer which is capable of holding 1 byte of memory */clrscr();msg = (char *)malloc(21 * sizeof(char)); /* allocated memory to msg via using malloc() function */strcpy(msg, "hi ! how r U"); /* copying a random message to msg */printf("\nThe current message is %s", msg); /* displaying the message contained in msg */msg = (char *)realloc(msg, 30); /* reallocating the memory to msg*/strcpy(msg, "hey r u there ?"); /*copying a new random message to msg */printf("\nNow the message is %s", msg); /* displaying the new message contained in msg */free(msg); /* now we are freeing the memory allocated to msg using free() function */getch();}

Output : The output of the above program will the following

The current message is hi ! how r U

Now the message is hey r u there

What is an Array ?

An Array may defined as the collection of the homogeneous (same type) elements that are stored in the contiguous memory locations. For example, if we have to store 7 values of any type, lets say, integer values we don't have to declare 5 variables with different identifiers but we can define an array of integer type and can store the values in array directly with a unique identifier. Thus, an array named arr created in memory having 5 values can be represented as :

  1   2   3   4   5  

 0        1       2      3      4

Cells have been assigned values from 0 to 4 as in arrays values are stored from a base index of 0.

How to declare an Array ?

An Array can be declared with the help of an unique identifier specifying its data type and also by specifying the number of elements it must contain. The number of elements are declared inside a square bracket i.e. []. Thus when an array of integers having 5 elements considering the above figure can be declared as :

int arr[5];  /*the element field within the [] should be a constant value as the are the blocks of static memory whose size must be declared before execution. For variable length array dynamic memory is required which we will discuss later.*/

How to initialize an Array ?

While declaring the array for a local scope e.g. for a particular function its contents will not be initialized by default and will remain undetermined till we initialized it separately. In case of array of global scope the values are initialized but having the default values of 0's for each element.

Thus, for the array of both scopes we can initialize an array by enclosing the elements within the {} brackets. For example,

int arr[5] = {1,2,3,4,5};  /* This array will be created as which one is shown in the above figure. */

The no of elements declared within the {} must not exceeds the numbers of elements defined in the [], else it could some serious trouble to your program.

What are the advantages of using an Array ?

Following are main advantages of using an array :

1. Arrays are the most convenient way of storing the fixed amount of data that  can be accessed in an unpredictable fashion.

2. Arrays are also one of the most compact data structures as in for storing the 50 elements in an array of integer type it will take the memory equivalent to the amount of memory required to store 50 elements in addition to that a few overhead  bytes for whole array.

3. Another advantage of array is that iterating through an array is more faster than compared to other data structure types like linked list because of its good locality of reference.

What are the disadvantages of using an Array ?

Following are the main disadvantages of using an Array :

1. Performing various operations like insertion and deletion is quite a stiff task in arrays as after inserting or deleting an item from an array every other element in array have to move forward or backwards prior to your operation, which is a costly affair.

2. In case of the static arrays the size of the array should be know up priori i.e. before the compile time.

3. C language does not have a checking mechanism for the array sizes.

How to access the elements of an Array ?

The elements of an array can be accessed easily by providing its index within [] with the identifier and can modify or read its value.

int arr[5] = {34, 78, 98, 45, 56}

  34 78 98 45 56

The format of accessing the array element is simple as arr[index].

To fetch a value from the above array which is placed in the position 3 we can use the following syntax :

int a = arr[2];/* where a is an integer variable which will hold the value of element to be fetched 8 */

and to write a value in an empty we can use the following syntax :

arr[index] = value;

That's how we can access the elements of an array.

Also consider that it  is syntactically incorrect to exceed the valid range of indices for an array. If you do so, accessing the elements out of bounds of an array will not  cause any compilation error but would result in the runtime error and it can lead to hang up your system.

A simple program using array

#include<stdio.h>#include<conio.h>void main(){int arr[5] = {1,2,3,4,5};   /*declaring and initializing the array */int sum=0, i;for(i=0;i<5;i++) {  sum=sum+arr[i];          /*adding the individual elements of the array*/ } printf("The value of the sum of all elements of the array is : %d", sum);  getch();}

Output of the program : The value of the sum of all elements of the array is : 15

How arrays and pointer are linked ?

As we know that a pointer is a variable that contains the address the another variable. That is, a pointer a special kind of variable that is containing the address of another variable and we can define a pointer in the following manner,

int *ptr;

which means that the ptr is a pointer type variable that is pointing to a address where an integer type value is stored.

Also, we know that in an array elements are stored in sequential manner in which the very first index corresponds to the base address of first element which acts as a base address of the entire array, i.e. we can say that an array  is a kind of pointer itself in which elements are stored according to their addresses.

we can declare a pointer to an array in the following way :

int a[5];int *ptr;ptr = &a[0];

in above example we have defined an array of five elements and a pointer is defined which  is pointing to the first element of the array

A simple example of   how to use 2-D array with pointer :

The following example takes a two dimensional array as input from the user and display its contents via using pointer.

#include <stdio.h>#include<conio.h>void main(){int i=0, j=0;int arr[3][3];int *ptr1;ptr1 = &arr[0][0];clrscr();printf("\nEnter the elements of the array :")for(int i=0; i<=2; i++){     for(int j=0; j<=2; j++){     scanf("\n%d", &arr[i][j]);     /* taking the input 2-D array or matrix from the user */    }

}

printf("Following are the elements of the array :");for(int i=0; i<=2; i++){     for(int j=0; j<=2; j++){     printf("\n%d", *ptr1);          /* diplaying the content of the matrix */ ptr1++;    }    }getch();}

Output : The output of the following program would be as follows :

Enter the elements of the array :

1 2 3

4 5 6

7 8 9

Following are the elements  of the array :

1 2 3

4 5 6

7 8 9

Array of pointers :

Just like the array of the various types of the datatypes like integer, floats, we can also define an array of pointers. In the array of the pointers we can stores the addresses of the values as the elements, we can declare an array  of pointer in the following way :

int *arr[7];

the above declaration tells us that arr is an array that contains the address of the 7 integers as its elements.

Following a little code snippet depicting the usage of the array of pointer :

#include <stdio.h>#include<conio.h>void main(){char *ptr1[3];           /* declared a array of character pointers */ptr1[0]="hello ! ";       /* first address corresponds to value hello */  

ptr1[1]="how are";       /* second address corresponds to value how are */ptr1[2]="you";           /* third address corresponds to value you */printf("%s%s%s",ptr1[0], ptr1[1], ptr1[2]);getch();}

Output : The output of the following program will be as follows :

hello! how are you

How traversing is done in the array data structures ?

First of all, we should know what is traversing ?

Traversing basically means the accessing the each and every element of the array at least once. Traversing is usually done to be aware of the data elements which are present in the array. After insertion or deletion operation you would usually want to check whether it has been successfully  or not, to check this we can use traversing, and can make sure that whether the element is successfully  inserted or deleted. Following below is a code snippet which shows how we can do traversing in an linear array.

A program to traverse or read a linear or 1-D array :

#include<stdio.h>#include<conio.h>void main(){int a[7], i=0;clrscr();printf("Enter the elements of the array :");for (i=0;i<=6 ;i++ ){     scanf("%d\n", &a[i]);     /* taking input array from the user */    }printf("\nThe elements of the array you have enetered are as follows :")for(i=0; i<=6; i++)    {    printf("%d", a[i]);        /* printing the array elements or traversing the array */}getch();}

How can we insert values in an Array?

The values in an array can be inserted in the following two manner :

1. Insertion at the end of the array.2. Insertion at the specified location in the array.

Insertion at the end of the Array can be carried out very easily. As value has to be inserted at the end so we just need to traverse the whole array till the end and then inserted our desired value at the end by setting the value pointed by the last element of the array to the new node which we desired to insert.

A program to insert value at a specified location in   the array :

To insert a value in an array  at a desired position firstly we will have to shift all the elements forward so as to accommodate the new element, then we  place the element at the required place.

#include <stdio.h> #include<conio.h>int i, len, num, num_pos; /* declared some global variables */void main(){int arr[50];

clrscr();add_element(arr, len, num, num_pos); /* calling the function to add an element in the array */getch();}void add_element(int a[], len, num, num_pos){printf("Enter the length of the array :");scanf("\n%d", &len);printf("\nEnter the array elements :");scanf("\n%d",&a[i]);printf("\nEnter the number you want to insert :");scanf("%d",&num);printf("\nEnter the position of the number at you want to insert :");scanf("%d", &num_pos);--num_pos;if(num_pos>len)/*checking whether insertion outside array*/  {    printf("insertion outside the array");}else{     for(i=len; i>=num_pos; i--){     a[i]=a[i+1];/* shifting all the elements backwards to create a space for new element */}a[num_pos]=num; len=len+1;printf("\n After insertiion now the array is :");for(i=0; i<len; i++){     printf("%d", a[i]);/* printing the newly formed array */}}}

Output : The output of the above program would something like this

Enter the length of the array :

5

Enter the array elements :

1

2

3

4

5

Enter the number you want to insert :

7

Enter the position of the number at you want to insert :

3

After insertion now the array is :

1

2

7

3

4

5

A program to delete an element from an array :

To delete an element from a specified position we just have to shift the position of every element upward that are coming after the specified position, and when the element is deleted the array is resized to its now size i.e. one less than its actual size, here is a code snippet that shows how to delete an element from an array.

#include <stdio.h> #include<conio.h>int i, len,num, num_pos;void main(){int arr[50];clrscr();del_element(arr, len, num, num_pos);getch();}void del_element(int a[], len, num_pos){printf("Enter the length of the array :");scanf("\n%d", &len);printf("\nEnter the array elements :");scanf("\n%d",&a[i]);printf("\nEnter the position of the number you want to delete :");scanf("%d", &num_pos);--num_pos;if(num_pos>len){    printf("deletion outside the array");

}else{     for(i=num_pos; i<len; i++){     a[i+1]=a[i];                    /* shifting all elements upwards */}num=a[num_pos];len=len-1;                           /* resizing the newly formed array */printf("\n After deletion now the array is :");for(i=0; i<len; i++){     printf("%d", a[i]);}}}

Output : The output of the above program might be like this

Enter the length of the array :

4

Enter the array elements :

1

2

3

4

Enter the position of the number you want to delete :

3

After deletion now the array is :

1

2

4

How we use Array of Structures in C data structures ?

As we are aware of the fact that the structures in the C language provides a mechanism to incorporate different data types within a same structure like integers, floats and character values which are known as structure members. As a fact, structures are simple to  define if there are only one or two elements but in case if too many objects are needed e.g.. to show the data of

each student of a class, in that case we introduces the concept of the array of the structures. We can declare an array of structures as follows :

#include <stdio.h>

struct studentinfo{int rollno.;char name[21];char sex;};

studentinfo detail[35];

In the above declaration, we have defined a structure named studentinfo which keeps the information about a particular student like rollno. of the student , name and sex. Then after defining the structure we have declared an array of structures we can contain 35 objects of such structure and can incorporate the details of 35 students.

Initializing the array of structures :

An array of structure can initialized in the same manner as we initialize a simple array. It must be kept in mind that only the static and external variables are initialized, lets understand to initialize a array of structure by taking this example :

#include <stdio.h>

/* we have taken a structure which stores the information about the information about a particular employee */

struct employeeinfo {int emp_id;char sex;int salary;};

/* here we have declared an array of structure i.e. data which is of employeeinfo type and contains the 3 objects of above defined structure i.e. of employeeinfo */ employeeinfo data[3] = { {1001, 'M', 10000}, {1002, 'F', 8000}, {1003, 'M', 15000}};

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001          data[0].sex = 'M'            data[0].salary = 10000

data[1].emp_id = 1002          data[1].sex = 'F'            data[1].salary = 8000

data[2].emp_id = 1003          data[2].sex = 'M'            data[2].salary = 15000

 If some of the values of the structures elements are not initialized then they are initialized to a default value of '0'. For example, if above declared structure is lacking some initialized elements then,

employeeinfo data[3] = { {1001, 'M'}, {1002, 'F'}, {1003, 'M'}};

The above initialized values will be considered or assigned by the compiler in the following manner :

data[0].emp_id = 1001               data[0].sex = 'M'               data[0].salary = 0

data[1].emp_id = 1002               data[1].sex = 'F'                data[1].salary = 0

data[2].emp_id = 1003               data[2].sex = 'M'               data[2].salary =0       /* where uninitialized element i.e. salary is provided with the default value of zero */

A simple program showing the usage of the array of structure :

#include <stdio.h>#include<conio.h>

void main(){int i=0; /* defining a structure for employee record */struct employeeinfo { int emp_id; char name[21]; char sex; int salary; }; /*initializing the record values in an array of structure of type employeeinfo */employeeinfo data[3] = {{1001,"Ashish", 'M', 10000}, {1002,"Swati", 'F', 8000}, {1003,"Praveen", 'M', 15000}}; clrscr();printf("\nThe content of record of employee are as follows :"); /* displaying the record of the employees */for (i=0;i<=2;i++) {

printf("\n Record number %d", i+1 );  printf("\n Employee id is : %d", data[i].emp_id); /* accessing the records of array data */  printf("\n Employee name is : %s", data[i].name);  printf("\t Employee gender is : %c", data[i].sex);  printf("\t Employee salary is : %d", data[i].salary); } getch();}

The above program shows how to an array of structure which can hold record of 3 employees simultaneously and how we can access those records via using the concept of array of structures.

Output : Following would be the desired output of the above  written program

The content of record of employee are as follows :

Record number 1

Employee id is 1001    Employee name is Ashish    Employee gender is M     Employee salary is 10000

Record number 2

Employee id is 1002    Employee name is Swati     Employee gender is F     Employee salary is 8000

Record number 3

Employee id is 1003    Employee name is Praveen   Employee gender is M     Employee salary is 15000

What is a linked list ?

A Linked List is a special kind of list in which the each element of the list is linked to another element of the list. In a linked list each element of the linked list knows the  address of the next element via a pointer. In general, a linked list element or node consists of two fields , one field is called num field in which the data value which has to be inserted is contained and second field is called next, which is a pointer which usually contains the address of the next element in the list. Thus, a linked list node can be showed graphically as :

What are the advantages of using the linked lists ?

Following the main advantages of using the linked lists :

1. Dynamic Memory Allocation : While using the linked lists we can increase or decrease the size of the list as per our requirement, as the memory is allocated dynamically, so we can say that is it is a efficient way of utilizing the memory and prevent memory wastage.

2. Various operations like insertion, deletions, traversing, sorting are much more easier to perform than in comparison to the other data structures and in quick time as well.

What are the various types of linked lists ?

The various types of linked list which are used commonly are as follows :

1. Singly Linked List2. Circular Linked List

3. Doubly Linked List

In SinglyLinked List the element or node of the list contains two fields viz. num field and the next pointer field. This can be shown as :

In a singly linked list the last node of the list will always point to the NULL.

In Circular Linked List, the list element are arranged in the same way as in the singly linked list having only one difference that the last element of the circular linked list always point to the first node of the list i.e. it means that last node does not point to NULL. In other words, we can say that the circular list is a list which does not have an end.

In Doubly Linked List the node of the list generally consists of the the three fields i.e. one num field which contains the data value, and two pointer fields viz. next pointer and previous pointer. As we know next pointer contains the address of the next element in the list, and previous pointer would be containing the address of the previous node in the list. The double linked list can be shown graphically as:

What is a NULL pointer, external pointer and empty list in context to the linked list ?

The next field  of the last element of the list contains NULL rather than a valid address, this indicates the end of the list.

External pointer is a pointer that points to the very first node in the linked list, it enables us to access the entire linked list.

An empty list is a list that contains no nodes in the list, it is also called a null list. The value of external pointer will zero for an empty list. A list can be made an empty list by assigning a NULL value to the external pointer. i.e.

head = NULL;

where head is an external pointer.

Representation of Linear Linked List :

Suppose we want to create a linked list of integers, we can represent a linked in the memory with the following declarations:

#include <stdio.h>

struct node{int a;struct node *next;};

typedef struct node NODE;NODE *head;

The above declaration creates a new data type whose each element is of type node_type and gives it a name NODE. And here head created acts as an external pointer to the list.

Insertion in the (singly) linked list :

Based upon various type of insertions, the insertion in a singly linked list can be done in three ways :

1. Insertion at the end of the list.2. Insertion at the beginning of the list.

3. Insertion at the specified position in the list.

Now, following below is a program that incorporates all the tree types of insertion methods and shows how to do all these types of insertions.

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;};                            /* declaring a global node of type struct */typedef struct node NODE;    /* providing a type definition to the above created structure */NODE *head=NULL;             /* declaring some of the global variable that would be used thought out the program */NODE *temp, *first;int info;void display();void insert_at_end();void insert_at_begin();void insert_at_specifiedpos();void main()                                 /* starting the main method() */{int i;clrscr();printf("\nprogram for insertion in a singly linked list :\n");do{printf("\nEnter your choice :\n");      /* creating menu for various insertion operations on the list */printf("\n1.Insert element at the end of the linklist :");printf("\n2.Insert element at the begin of the linklist :");printf("\n3.Insert at any specified position in the linked list :");printf("\n4.Exit\n");fflush(stdin);scanf("\n%d",&i);switch(i){case 1:insert_at_end();display();break;case 2:insert_at_begin();display();

break;

case 3:insert_at_specifiedpos();display();break;case 4:exit(0);}}while(i<=4);getch();}void insert_at_end(){printf("\nEnter your element in the linked list :");scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE));         /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;if(head==NULL)                            /* checking whether list is empty */{head=temp;}else{first=head;while(first->next!=NULL){first=first->next;}first->next=temp;}}void display(){first=head;printf("\nStatus of the linked list is as follows :\n");while(first->next!=NULL)                    /* traversing the linked list */{printf("\n%d",first->num);first=first->next;}}void insert_at_begin(){printf("\nEnter the value which do you want to insert at begining\n");scanf("\n%d"&info);first=head;temp=(NODE *)malloc(sizeof(NODE));temp->num=info;temp->next=first;head=temp;}void insert_at_specifiedpos(){

int info1,info2;printf("\nEnter the value after which you want to insert new node\n");scanf("%d",&info1);printf("\nEnter the value of new node\n");scanf("\n%d",&info2);temp=(NODE *)malloc(sizeof(NODE));temp->num=info2;temp->next=NULL;first=head;while(first->num!=info1){first=first->next;}temp->next=first->next;first->next=temp;}}

How can we delete elements from a (singly) linked list ?

Similarly, like insertion we can  perform deletion in the following three manners :

1. Deleting element from the front.2. Deleting element from the end.

3. Deleting element from the specified position.

Following is a small code snippet which suggest how we can perform deletion in a singly linked list :

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;};                           /* declaring a global node of type struct */typedef struct node NODE;    /* providing a type definition to the above created structure */NODE *head=NULL;            /* declaring some of the global variable that would be used throughtout the program */NODE *temp, *first;int info;void display();void create_list();void del_at_begin();void del_at_end();void del_at_specifiedpos();void main()                 /* starting the main method() */{int i;clrscr();

printf("\nprogram for deletion in a singly linked list :\n");do{printf("\nEnter your choice :\n");        /*    creating menu for various deletion operations on the list */printf("\n1.Create a linked list :");printf("\n2.Delete from the front in the linked list :");printf("\n3.Delete from the end position in the linked list :");printf("\n4.Delete at any specified position in the linked list :");printf("\n5.Exit\n");fflush(stdin);scanf("\n%d",&i);switch(i){case 1:create_list();display();case 2:del_at_begin();display();break;case 3:del_at_end();display();break;case 4:del_at_specifiedpos();display();break;case 5:exit(0);}}while(i!=5);getch();}void create_list(){printf("\nEnter your element in the linked list :");scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE));         /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;if(head==NULL)                            /* checking whether list is empty */{head=temp;}else{first=head;while(first->next!=NULL){first=first->next;

}

first->next=temp;}}void display(){first=head;printf("\nStatus of the linked list is as follows :\n");while(first->next!=NULL)                           /* traversing the linked list */{printf("\n%d",first->num);first=first->next;}}void del_at_begin(){ if(head==NULL){     printf("linked list is empty");} else{    temp=head;head=temp->next;free(temp);}

}void del_at_end(){ if(head==NULL)

 {  printf("\nlinked list is empty"); }else{     head=temp; while(temp->next!=NULL){     first=temp; temp=temp->next;}    first->next=NULL;free(temp);}}void del_at_specifiedpos(){ int node_num; if(head==NULL){    printf("\nlinked list is empty");

}else{    temp=head; printf("\nEnter the position of the node you want to delete"); scanf("\n%d",&node_num);    for(int i=1;i<node_num;i++){     first=temp; temp=temp->next;}first->next=temp->next;free(temp);}}

What is a circular linked list?

In Circular Linked List, the list element are arranged in the same way as in the singly linked list having only one difference that the last element of the circular linked list always point to the first node of the list i.e. it means that last node does not point to NULL. In other words, we can say that the circular list is a list which does not have an end.

Thus, it is necessary in case of  circular linked to establish the first node and last node. It is useful if we set external pointer i.e. head to point to the last node in the list.

 We declare the structure for the circular linked list in the same way as we declare it for the singly or linear linked lists.

#include <stdio.h>

struct node{int num;node*next;};

typedef struct node NODE;NODE *head,*first,*last;

Now, we will find out how can we create a circular linked list and perform various other operations like traversing, insertion, and deletions.

How the various insertion operations are performed in a circular linked list?

Insertion in the circular linked list can be performed in the following ways :

1. Insertion from the front i.e. insertion from the beginning of the list.2. Insertion from the back i.e. insertion from the last node of the list.

3. Insertion from the specified position.

First two types of insertion operations are different than those of that of linear  lists, but third one is exactly similar. So now we will write a program to show how can we perform these functions in a circular list.

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;};                            /* declaring a global node of type struct */typedef struct node NODE;    /* providing a type definition to the above created structure */NODE *head=NULL;            /* declaring some of the global variable that would be used throughout the program */NODE *temp, *first, *last;int info;void display();void insert_at_end();void insert_at_begin();void main()                /* starting the main method() */{int i;clrscr();printf("\nprogram for insertion in a circular linked list :\n");do{printf("\nEnter your choice :\n");     /*creating menu for various insertion operations on the list */printf("\n1.Insert element at the end of the linklist :");printf("\n2.Insert element at the begin of the linklist :");printf("\n3.Exit\n");fflush(stdin);scanf("\n%d",&i);switch(i){case 1:insert_at_end();display();break;case 2:insert_at_begin();display();break;case 3:exit(0);}

while(i<=3);getch();}void insert_at_end(){

printf("\nEnter your element in the linked list :");scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE)); /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;if(head==NULL)                   /* checking whether list is empty */{temp->next=temp;head=temp;last=temp;}else{last->next=temp;last=temp;last->next=head;}}void display(){if(head==NULL){    printf("linked list is empty");}else{     first=head;     printf("\nStatus of the linked list is as follows :\n"); while(first->next!=head)        /* traversing the linked list */      {       printf("\n%d",first->num);       first=first->next;      }}}void insert_at_begin(){printf("\nEnter the value which do you want to insert at begining\n");scanf("\n%d"&info);temp=(NODE *)malloc(sizeof(NODE));temp->num=info;if(head==NULL){    temp->next=temp;head=temp;last=temp;}else{    temp->next=head;head=temp;last->next=head;    }}

How can we perform deletion in a circular linked list?

Just as in case of the singly or linear linked lists, deletions can be performed in the three ways too :

1. Deletion from the front of the linked list.2. Deletion from the end of the linked list.

3. Deletion from the specified position in the linked list.

Now we will see how we can perform all types  of deletion operations on a linked list through the following code snippet :

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;};                       /* declaring a global node of type struct */typedef struct node NODE;  /* providing a type definition to the above created structure */NODE *head=NULL;          /* declaring some of the global variable that would be used throughout the program */NODE *temp, *first, *last;int info;void display();void create_list();void del_at_begin();void del_at_end();void del_at_specifiedpos();void main()                              /* starting the main method() */{int i;clrscr();printf("\nprogram for deletion in a singly linked list :\n");do{printf("\nEnter your choice :\n");     /*    creating menu for various insertion operations on the list */printf("\n1.Create a linked list :");printf("\n2.Delete from the front in the linked list :");printf("\n3.Delete from the end position in the linked list :");printf("\n4.Delete at any specified position in the linked list :");printf("\n5.Exit\n");fflush(stdin);scanf("\n%d",&i);switch(i){case 1:create_list();display();

case 2:del_at_begin();display();break;case 3:del_at_end();display();break;case 4:del_at_specifiedpos();display();break;case 5:exit(0);}}while(i!=5);getch();}

void create_list()

{printf("\nEnter your element in the linked list :");scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE));    /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;if(head==NULL)                     /* checking whether list is empty */{temp->next=temp;head=temp;last=temp;}else{last->next=temp;last=temp;last->next=head;}}void display(){if(head==NULL)printf("linked list is empty");else{    first=head;    printf("\nStatus of the linked list is as follows :\n");     while(first->next!=head)                /* traversing the linked list */     {      printf("\n%d",first->num);      first=first->next;     }

    }}void del_at_begin(){ if(head==NULL){     printf("linked list is empty");} else{    temp=head;head=head->next;last->next=head;free(temp);}

}void del_at_end(){ if(head==NULL)

 {  printf("\nlinked list is empty"); }else{     temp=head; while(temp->next!=last){     first=temp; temp=temp->next;}    first->next=temp->next;last=first;free(temp);}}void del_at_specifiedpos(){ int node_num; if(head==NULL){    printf("\nlinked list is empty");}else{    temp=head; printf("\nEnter the position of the node you want to delete"); scanf("\n%d",&node_num);    for(int i=1;i<node_num;i++){     first=temp; temp=temp->next;}first->next=temp->next;

free(temp);}}

What is a Doubly Linked List?

In the various types of linked list like singly list and circular lists only forward traversing is possible but in the real world application it is necessary to traverse the list both in the forward direction and the backward direction. The most appropriate data structure for such an application is a doubly  linked list

A doubly linked list is a list in which all the nodes are connected to each other by  the means of multiple links which helps in accessing both the predecessor and the successor node from the given node position. It provideds bi-directional traversing.

Each node in the doubly linked list has two link fields. These are used to point the next node in the list and the previous node in the list. The following figure show how can we represent graphically  as:

Here, the next  pointer will point to its successor node, while the prev pointer will point to its predecessor node.

The structure declaration for the above node will be as :

#include <stdio.h>

struct node{int num;struct node *next;struct node *prev;};

typedef struct node NODE;

Now we know how to declare a doubly linked list node, now we will see how to perform various insertion and deletion operations on the doubly linked list.

Advantages of using the doubly linked lists :

1. Insertion and deletion are easier to perform as compare to other types of lists like singly linked lists and circular lists.

2. Efficient utilization of the memory.

3. Bi-directional traversal helps in efficient and easy accessibility of nodes.

How can we perform various insertion operations on a doubly linked list ?

There are various insertion operations that are performed on a doubly linked list which are as follows :

1. Insertion at the front of the list.2. Insertion from the end of the list.

3. Insertion at any specified position in the list.

A program to insert node in a doubly linked list ?

The following below a code that shows how to perform various insertion operations on the linked list.

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;struct node *prev;};                           /* declaring a global node of type struct */typedef struct node NODE;   /* providing a type definition to the above created structure */NODE *head=NULL; /* declaring some of the global variable that would be used throughout the program */NODE *temp, *first, last;int info;void display();void insert_at_end();void insert_at_begin();void insert_at_specifiedpos();void main()            /* starting the main method() */{int i;clrscr();printf("\nprogram for insertion in a doubly linked list :\n");do{printf("\nEnter your choice :\n");printf("\n1.Insert element at the end of the linkedlist :");printf("\n2.Insert element at the begin of the linkedlist :");printf("\n3.Insert at any specified position in the linkedlist :");printf("\n4.Exit\n");fflush(stdin);scanf("\n%d",&i);

switch(i){case 1:insert_at_end();display();break;case 2:insert_at_begin();display();break;case 3:insert_at_specifiedpos();display();break;case 4:exit(0);}}while(i<=4);getch();}void insert_at_end(){printf("\nEnter your element in the linked list :");scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE));   /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;temp->prev=NULL;if(head==NULL)                      /* checking whether list is empty */{head=temp;first=temp;last=temp;}else{first=head;while(first->next!=last){first=first->next;}

first->next=temp;temp->prev=first;temp->next=NULL;last=temp;}}void display(){first=head;printf("\nStatus of the doubly linked list is as follows :\n");while(first->next!=NULL)                  /* traversing the linked list */

{printf("\n%d",first->num);first=first->next;}}void insert_at_begin(){printf("\nEnter the value which do you want to insert at begining\n");scanf("\n%d"&info);temp=(NODE *)malloc(sizeof(NODE));temp->num=info;temp->next=NULL;temp->prev=NULL;if(head=NULL){head=temp;last=temp;}else{temp->next=head;head->prev=temp;temp->prev=NULLhead=temp;}}void insert_at_specifiedpos(){NODE *second;int node_num,info;int i=1;printf("\nEnter the nodenumber after which you want to insert new node\n");scanf("%d",&node_num);printf("\nEnter the value of new node\n");scanf("\n%d",&info);temp=(NODE *)malloc(sizeof(NODE));temp->num=info;temp->next=NULL;temp->prev=NULL;first=head;while(i<node_num){second=first;first=first->next;}temp->next=first;temp->prev=second;first->prev=temp;second->next=temp;

}}

What are the  various deletion operations that can be perform on a doubly linked list ?

Just like the insertion operations the deletion operations in a doubly linked list can be done in the following ways :

1. Deletion from the front.2. Deletion from the end.

3. Deletion from the specified position in the list.

Since by using doubly linked list the deletion of the nodes or elements have become quite very easy in  a list. Just by doing few minor pointer changes we can perform various deletion operations. Following is the program which shows how we can delete a node from the list.

#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node    {int num;struct node *next;struct node *prev;};                             /* declaring a global node of type struct */typedef struct node NODE;     /* providing a type definition to the above created structure */NODE *head=NULL;             /* declaring some of the global variable that would be used throughout the program */NODE *temp, *first, *last;int info;void display();void create_list();void del_at_begin();void del_at_end();void del_at_specifiedpos();void main()                                           /* starting the main method() */{int i;clrscr();printf("\nprogram for deletion in a doubly linked list :\n");do{printf("\nEnter your choice :\n");          /*    creating menu for various insertion operations on the list */printf("\n1.Create a linked list :");printf("\n2.Delete from the front in the linked list :");printf("\n3.Delete from the end position in the linked list :");printf("\n4.Delete at any specified position in the linked list :");printf("\n5.Exit\n");fflush(stdin);scanf("\n%d",&i);switch(i){case 1:create_list();display();case 2:

del_at_begin();display();break;case 3:del_at_end();display();break;case 4:del_at_specifiedpos();display();break;case 5:exit(0);}}while(i<=5);getch();}void create_list(){printf("\nEnter your element in the linked list :");         /*creating a doubly linked list */scanf("%d",&info);temp=(NODE *)malloc(sizeof(NODE));  /* allocating memory for the node to be inserted */temp->num=info;temp->next=NULL;temp->prev=NULL;if(head==NULL)                       /* checking whether list is empty */{head=temp;first=temp;

last=temp;                                                             }else                             /*inserting at the end of the list*/{first=head;while(first->next!=last)   {first=first->next;}first->next=temp;temp->prev=first;temp->next=NULL;last=temp;}}void display(){if(head==NULL)printf("linked list is empty");else{    first=head;    printf("\nStatus of the linked list is as follows :\n");     while(first->next!=last)           /* traversing the linked list */

     {      printf("\n%d",first->num);      first=first->next;     }    }}void del_at_begin(){ if(head==NULL){     printf("linked list is empty");} else{    temp=head;head=head->next;head->prev=NULL;free(temp);}

}void del_at_end(){ if(head==NULL)

 {  printf("\nlinked list is empty"); }else{     temp=head; while(temp->next!=last){ temp=temp->next;}    last=temp->prev;last->next=NULLfree(temp);}}void del_at_specifiedpos(){ int node_num; if(head==NULL){    printf("\nlinked list is empty");}else{    temp=head; printf("\nEnter the position of the node you want to delete"); scanf("\n%d",&node_num);    for(int i=1;i<node_num;i++){     second=temp;

 temp=temp->next;}first=temp->next;second->next=temp->next;first->prev=temp->prev;free(temp);}}

What are Stacks?

A stack is non-primitive data structure. It is an ordered list in which the addition of new element or deletion of the existing element is done only from one end which called as TOP of Stack. As all the insertion and deletion is performed from only one end, the last added element will be deleted first, so the stack is also  known as Last In First Out (LIFO) data structure. The most frequently accessed element in the stack is the top most element, whereas least accessed element is the bottom of the stack.

Whenever a stack is created, the stack base or the bottom remains fixed while whenever a new element is added only the  top is increased and goes on increasing whenever a new element is added to the stack and decreases whenever a particular element is deleted.

How stacks can be implemented in the data structures?

Stacks can be implemented in the following two ways in the data structures :

1. Static Implementation2. Dynamic Implementation

Static Implementation uses arrays  to create a stack. Static implementation is a very simple technique but it is not a flexible  way of creation, as the size of the stack has to be declared in advance and after which its size can't be  modified.

Dynamic Implementation is also called the linked list representation and use pointers to implement stack type of data structure.

Operation on the stacks :

The basic operations that can be performed on the  stack are as follows :

1. PUSH : The  process of addition of new element to the stack is called the PUSH operation. As we know already whenever an element is added it will add to the top of the stack and the value of top will be incremented by one.

2. POP : The process of deleting an existing element from the top of the stack is called the POP operation. Whenever an element is popped up from the top of stack the value of top is decremented by one.

3. Implementation of Stack using Array or Static Implementation of Stack :

4. The  implementation of the stack using array with various operations that can be applied on stacks is given as following. The following is a code that shows how  can we implement stacks while using arrays.

#include <stdio.h>#include<conio.h>#define<stdlib.h>#define MAXSIZE 17void push();void pop();void display();int stck[MAXSIZE];int top=-1;void main(){int choice;char ch;clrscr();printf("Program for various operations on stack using arrays");do{ printf("\n1. PUSH"); printf("\n2. POP"); printf("\n3. Display"); printf("Enter your choice :"); scanf("%d",&choice); switch(choice){     case 1: push();         break;     case 2: pop();         break;     case 3: display();         break; default : printf("\nwrong choice made");    }printf("\ndo you want to continue y/n");fflush(stdin);scanf("%c",&ch);}while ((char=='y')||(char=='Y'));getch();

}void push(){int info;if(top==MAXSIZE-1){    printf("\nStack Overflow");}else{     printf("\nEnter the element you want to add to stack"); scanf("\n%d", &info); top=top+1;                   /* increasing top to accommodate new element*/ stck[top]=info;              /* placing the new element to the top */     }

}

void pop(){int info;if(top==-1){     printf("\n the stack is empty");}else{     info=stack[top];                        /*placing top element to info */ top=top-1;                                  /*decreasing the top value */ printf("\n the deleted item is %d", info); /* returning the deleted value*/     }}void display(){ int i; if(top==-1) printf("\n stack is empty"); else{     printf("\nthe stack is displayed as :") for(i=top;i>=0;i--){     printf("%d",stck[i]);}    }}

Implementation of Stack using Pointer or linked list implementation of Stack :

As we know apart from static implementation, the stacks can be implemented by using pointers as follows:

#include <stdio.h>#include<conio.h>#define<stdlib.h>void push();void pop();void display();struct stack{ int num; struct stack *next;};typedef struct stack stck;stck *head==NULL;stck *temp, first;void main(){int choice;char ch;clrscr();printf("Program for various operations on stack using arrays");do{ printf("\n1. PUSH"); printf("\n2. POP"); printf("\n3. Display"); printf("Enter your choice :"); scanf("%d",&choice); switch(choice){     case 1: push();         break;     case 2: pop();         break;     case 3: display();         break; default : printf("\nwrong choice made");    }printf("\ndo you want to continue y/n");fflush(stdin);scanf("%c",&ch);}while ((char=='y')||(char=='Y'));getch();}void push(){int info;temp=(stck *)malloc(sizeof(stck));printf("\nEnter the element in the  stack :");scanf("%d",&info);

temp->num=info;temp->next=NULLif(head==NULL){    printf("\nStack is empty");head=temp;}else{     first=head; while(first!=NULL) first=first->next; first->next=temp;    }}void pop(){if(head==NULL){     printf("\n the stack is empty");}else{     temp=head; while(temp->next!=NULL){     first=temp;

temp=temp->next;    }     first->next=NULL; free(temp); }}void display(){ int i; if(head==NULL) printf("\n stack is empty"); else{     temp=head; printf("\nThe status of the stack is :"); while(temp!=NULL){     printf("%d",temp->num);    }}}

What is a Queue ?

A queue is a non-primitive data structure. It is an homogeneous collection of elements in which new elements are added at one end called the Rear end, and the existing elements are can be deleted from other end called the Front end of the queue. Basically, a queue is a First In First Out type of list data structure. Literally queue means a line, we came across a queue in our daily  life like for reservation, we have to stand in a reservation queue.

Application of Queues :

1. Round Robin technique for processor scheduling is implemented using queues.2. All types of customer services like (reservation system) software are designed using

queues to store customers information.

3. Printer server routines are implemented by using the queue data structure.

Implementation of Queues :

The queue can be implemented in the following two ways :

1.  Static Implementation : Static Implementation of queue is generally done by using arrays. So we must be sure about the exact number of the elements we want to store in the queue, as it is static implementation is done through arrays, so memory is to be allocated as static and we cannot change the capacity of the queue dynamically. In this implementation the beginning of the queue will become Front and the last element will be Rear.

So we can say by seeing the following relation between the front and rear the total no. of elements that are contained in a queue can be calculated as

(Rear-Front) + 1;

and if rear<front, it means the queue will always be empty.

2.  Dynamic Implementation : Dynamic Implementation of the queue is generally done by using the pointers, infact we will be using a linked list for creating and storing elements in a queue. Linked List implementation allows better memory utilization, and we can increase and decrease the size of the queue as per our requirement.

Static Implementation of Queue using array :

As we know that the static implementation of the queue is done by using array data structure. So a code snippet  shows how we can delete and add an element in a queue using array  data structure.

#include <stdio.h>#include<conio.h>#define<stdlib.h>#define MAXSIZE 17void enqueue();void dequeue();void display();int queue[MAXSIZE];

int front=-1;int rear=-1;void main(){int choice;char ch;clrscr();printf("Program for various operations on Queue using arrays");do{ printf("\n1. Enqueue"); printf("\n2. Dequeue"); printf("\n3. Display"); printf("Enter your choice :"); scanf("%d",&choice); switch(choice){     case 1: enqueue();         break;     case 2: dequeue();         break;     case 3: display();         break; default : printf("\nwrong choice made");    }printf("\ndo you want to continue y/n");fflush(stdin);scanf("%c",&ch);}while ((char=='y')||(char=='Y'));getch();}void enqueue(){int info;if(rear>=MAXSIZE){    printf("\nQueue Overflow");break;}else{     printf("\nEnter the element you want to insert to queue"); scanf("\n%d", &info); rear=rear+1;                     /* increasing rear to accommodate new element*/ queue[rear]=info;                  /* placing the new element to the rear */

}

}void dequeue(){int info;if(front==-1)                                        /*checking the underflow condition */

{     printf("\n the queue is empty"); break;}else{     info=queue[front];                               /*placing front element to info */ front=front+1;                               /*incrementing the front value */ printf("\n the deleted item is %d", info);   /*returning the deleted value*/     }}void display(){ int i; if(rear==-1)                                        /*checking the underflow condition */ printf("\n queue is empty"); else{     printf("\nthe queue is diplayed as :") for(i=front;i<=rear;i++)                    /*traversing the queue */{     printf("%d",queue[i]);}    }}

Dynamic Implementation of Queues using pointers :

As we know that the dynamic implementation is achieved through pointers using the linked list. The following is a code  snippet that illustrates how we can dynamically implement the queue using linked lists. In this approach we take the first element of list as front and last element of the as the rear of the queue.

#include <stdio.h>#include<conio.h>#define<stdlib.h>void enqueue();void dequeue();void display();struct queue{ int num; struct queue *next;};typedef struct queue Q;Q *head==NULL;Q *temp, *first;void main(){int choice;char ch;clrscr();printf("Program for various operations on Queue using linked

list");do{ printf("\n1. Enqueue"); printf("\n2. Dequeue"); printf("\n3. Display"); printf("Enter your choice :"); scanf("%d",&choice); switch(choice){     case 1: enqueue();         break;     case 2: dequeue();         break;     case 3: display();         break; default : printf("\nwrong choice made");    }printf("\ndo you want to continue y/n");fflush(stdin);scanf("%c",&ch);}while ((char=='y')||(char=='Y'));getch();}void enqueue(){int info;temp=(Q *)malloc(sizeof(stck));printf("\nEnter the element in the  Queue :");scanf("%d",&info);temp->num=info;temp->next=NULLif(head==NULL){    printf("\nQueue is empty");head=temp;}else{     first=head; while(first!=NULL) first=first->next; first->next=temp;

}

}void dequeue(){if(head==NULL){     printf("\n the stack is empty");}

else{     temp=head; head=head->next; free(temp); }}void display(){ int i; if(head==NULL) printf("\n stack is empty"); else{     temp=head; printf("\nThe status of the stack is :"); while(temp!=NULL){     printf("%d",temp->num);    }}}

What are Circular Queues ?

A circular queue is one in which the insertion of new element is done at the very first location of the queue if the last location of the queue is full. Suppose if we have a Queue of n elements then after adding the element at the last index i.e. (n-1)th , as queue is starting with 0 index, the next element will be inserted at the very first location of the queue which was not possible  in the simple linear queue. That's why linear queue leads to wastage of the memory, and this flaw of linear queue is overcome by circular queue.

So, in all we can say that the circular queue is a queue in which first element come right after the last element, that means a circular queue has a starting point but no end point.

While dealing with the circular queue we will use the following assumptions :

1. Front will always be pointing to the first element of the queue.2. If  Front=Rear, the queue will be empty.

3. Each time a new element is inserted into the queue, the value of rear is incremented by one i.e. Rear = (Rear + 1);

4. Each time when an existing element is deleted from the queue, the value of rear is incremented by one i.e. Front = (Front + 1);

Operations on a Queue :

Just like various other homogeneous data structures the main operations that can be performed on a circular queue are:

1. Insertion2. Deletion

3. Traversing

Code for Insertion in a queue using a simple linear array :

#include <stdio.h>#include<conio.h>#define<stdlib.h>#define MAXSIZE 17void enqueue();void dequeue();void display();int queue[MAXSIZE];int front=-1;int rear=-1;void main(){int choice;char ch;clrscr();printf("Program for various operations on Queue using arrays");do{ printf("\n1. Enqueue"); printf("\n2. Dequeue"); printf("\n3. Display"); printf("Enter your choice :"); scanf("%d",&choice); switch(choice){     case 1: enqueue();         break;     case 2: dequeue();         break;     case 3: display();         break; default : printf("\nwrong choice made");    }printf("\ndo you want to continue y/n");fflush(stdin);scanf("%c",&ch);}while ((char=='y')||(char=='Y'));getch();}void enqueue(){int info;if((rear+1)%MAXSIZE==front){    printf("\nQueue Overflow");

break;}else{     printf("\nEnter the element you want to insert to queue"); scanf("\n%d", &info); rear=(rear+1)%MAXSIZE; /*increasing rear to accommodate new element and making a circular queue*/ queue[rear]=info;                      /*placing the new element to the rear */     }}void dequeue(){int info;if((front==rear)||(front==-1))                  /*checking the underflow condition */{     printf("\n the queue is empty"); break;}else{     info=queue[front];                         /*placing front element to info */ front=(front+1)%MAXSIZE;               /*incrementing the front value */ printf("\n the deleted item is %d", info);    /* returning the deleted value*/     }}

void display()

{ int i; if((front==rear)||(front==-1))                 /*checking the underflow condition */ printf("\n queue is empty"); else{     printf("\nthe queue is diplayed as :") for(i=front;i!=rear;i=(i+1)%MAXSIZE)   /*traversing the queue */{     printf("%d",queue[i]);}    }}

C File Handling

1.Introduction of File Handling

2.Way of Storing data in File

3.File Operation in C programming

4. How to Write a file in C

5.How to Read a File In C

6.How to Close a file and File Modes

7.General Structure of Program and Some function Used for File Handling

8.How to use fputc( ) Function in C

9.How to use fgetc( ) Function in C

10.How to use putc( ) Function and getc( ) Function in C

11. How to use putw( ) Function in C

12.How to use getw( ) Function in C

13.How to use fputs( ) Function in C

14.How to use fgets( ) Function   in C

15.What is formatted Input/Output and How to use fprintf( ) Function

16.How to use fscanf( ) Function in C

17.What is Block Read/Write and How to use fwrite( ) Function in C

18.How to use fread( ) Function in C

19.How to use Random access File in C

20.How to use ftell( ) Function in C

21.Some Other Program of File Handling

What is  File Handling:

We frequently use files for storing information which can be processed by our programs. In order to store information permanently and retrieve it  we need to use files .A file is collection of related data .Placed on the disk.Files are not only used for data. Our programs are also stored in files.

Why we use file Handling:

The input and out operation that we have performed so far were done through screen and  keyboard only . after the termination of program all the entered data is lost because primary memory is volatile . if the data has to be used later ,then it becomes necessary to keep it in permanent storage device. so the c language provide the concept of file through which data can be stored on the disk or secondary storage device . the stored data can be read whenever required.

Types of File Handling in C:

The file handling in c can be categorized in two types-

1. High level (Standard files or stream oriented files)- High level file handling is managed by library function. High level file handling commonly used because it  is  easier  and hide most of the details from the programmer.

2. Low level (system oriented files)-  low level files handling is managed by system calls.

Ways of storing data in files

There are two ways of storing data in files.

1. Text Format- I n text format data is stored as a line of character with each line  terminated by a new line character ('\n'). Text files are in human readable form they can be created and read using any text editor.

1.Binary Format -- In binary format data is stored on the disk same way as it is represented in the computer memory . binary files are not in human readable form they can be created and read by a specific program  written for them .The binary data stored in the file can-t be read by any editor.

The input and output operation in binary files take less time as compared to that of the text files because in binary files no conversion have to take place .However the data written using binary format is not very portable since the size of data types and byte order may be different on different  machine. In text format , these problem do not arise. so it is more portable.

Concept of Buffer in file Handling:

Buffer is an area in memory where the data is temporarily stored before being written to the file .when we open a file , a buffer is automatically associated with its file pointer. whatever data  be send to the file  is not immediately written to the file .First it send to the buffer and when the buffer is full then its contents are written to the file .when the file is closed  all the contents of buffer are automatically written to the file even is buffer is not full .this is called flushing  the buffer. we can also explicitly flush the buffer by a function  fflush( ). The concept of buffer is used to increase the efficiency.

Step for file operation in C programming:

1. Open a file 2. Read the file or write data in the file

3. Close the file

Opening a file - A file must be open before any I/O operation can be performed on that file. the structure named File is defined in the file stdio.h that contains all information  about the

file like name, status, buffer size, current position, end of the file status.    A file pointer is a pointer to a structure of type FILE. whenever a  file opened, a structure of type FILE is associated with it, and the file pointer that points to the Structure identifies this file. Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable.

You declare these file pointer variables as follows.

FILE  *fopen(), *fp1, *fp2, *fp3;

The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.

Declaration of  fopen() function.

FILE * fopen( const char * filename ,const char *mode);

fopen( ) function  takes two strings as arguments.

1. Name of the file to be opened2. The Mode that decide which operations( read ,write , append) are to be performed on the file.

FILE *fp1, *fp2;

fp1=fopen( "ashish.txt", "w");

fp2=fopen( "anurag.txt", "r");

After opening the file with fopen( ) function, the name of the file is not used in the program for any operation on it.

Writing a file in C :

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the 'w' indicates that the file is assumed to be a text file.  /* * program to create

a file and write some data into the file */

#include<stdio.h> void main(){FILE *p;char ch;if((p==fopen("myfile.txt","w"))==NULL)

{printf("this file does not exist\n");exit()}else{

printf("enter the text")

while((ch==getchar())!=EOF) /*press control z in Dos to stop reading character*/

fputc(ch,p);}

Fclose(p);

}

Reading a file using C :   Once The file has been opened for reading using fopen( ) function .

file’s contents are brought into

 memory and a pointer points to the very first character. To read the file’s contents from memory there exists a function called

 fgetc( ) . 

/* a simple program to Read a file/*

#include<stdio.h>void main(){

FILE *fp1;char a;if

((fp1=fopen("myfile.txt","r"))==NULL)

printf("this file does not exist\n");

else{

while((a==fgetc(fp1))!EOF)

printf("%c",a);}}

output: I am ashish kumar

gupta .I have completed MCA from ajay kumar garg engg. college gzb.

Closing the File When we have finished reading from the file, we need to close it .This is done using the function fclose( ) through the statement.

fclose ( fp ) ;

Once we close the file we can no longer read from it using getc( ) unless we reopen the file.

Declaration of fclose( ) function :

int fclose(FILE * fptr);

The fclose() function is used for closing opened files. The only argument it accepts is the file pointer.

File modes

         File mode                     Description

             r Open a text file for reading.

            w Create a text file for writing, if it exists, it is overwritten.

             a Open a text file and append text to the end of the file.

             rb Open a binary file for reading.

            wb Create a binary file for writing, if it exists, it is overwritten.

            ab Open a binary file and append data to the end of the file

General structure of file program

#include <stdio.h>

main( ){

FILE * fp1;/** Open any file .txt format file and mode( read, write, append)*/fp1=fopen("filename","mode" ); ------------------------------------------------------- -------------------------------fclose(fp1);};

End of  file - The file reading function  need to know  the end of file so that they can stop reading .when the end of file is reached , the operating signal  send s an end of file signal to the program. when the program receive this signal , the file reading function return EOF which is constant defined in the file  stdio.h  an its value -1 . EOF is an integer value so make sure the return value of the function is assigned to a integer variables.

Some Function used for file Handling

1. Character I/O   -    fgetc( ), fputc( ), getc( ), putc( ).2. String I/O        -    fgets( ), fputs( ).

3. Integer I/O      -    getw( ), putw( ).

4. Formatted I/O  -    fscanf( ), fprintf( ).

5. Record I/O      -     fread( ), fwrite( ).

1. Character I/O:     fputc( ), fgetc(), getc(), putc() .

fputc() Function:  this function writes a character to a specified file at the current file position and then increment the file position pointer .The putc() macro acts essentially identically to fputc(), but is a macro  that expands in-line.  It may evaluate stream more than once, so arguments given to putc() should not be expressions with potential side effects.

int fputc(int c, FILE *fp);

The fputc() function returns an integer representing  the character written. If a write error occurs the error indicator is set and fputc returns EOF.

/* * program to  understand the use of fputc( ) function */#include<stdio.h>void main(){FILE *p;char ch;if((p==fopen("myfile.txt","w"))== NULL){

printf("this file does not exist\n");exit()}else{

printf("enter the text")

while((ch==getchar())!=EOF)fputc(ch,p);}fclose(p);};

fgetc() Function: fgetc() is a character oriented function. this function reads the single character  from a given file and increment the file pointer position. On success it return the character after converting it. it to an int without sign extension. on error it return EOF . 

int fgetc(FILE *stream );

If successful,  it  return the next requested object from the stream. Character values are returned as an unsigned char converted to an int. If the stream is at end-of-file or a read error occurs, then it  return EOF.

/* * program to understand the use of fgetc( ) function */

#include <stdio.h>

void main(){ int c; /* * Pointer to the file. FILE is a structure defined in <stdio.h> */ FILE *ptr; ptr = fopen("Ritu.txt","r"); //Open the file/* * Read one character at a time, checking for the End of File. * EOF is defined in <stdio.h> as -1 */

while ((c = fgetc(ptr)) != EOF) { printf("%c",c); // O/P the character to the screen } fclose(ptr); // Close the file. });

getc( ) function and putc( ) function :   The getc( ) and putc( ) are exactly similar to that of fgetc( ) and fputc( ). The putc function writes the character contained in character variable c to the file associated with the pointer fp1.

int putc (int ch, FILE *file) // define putc() method

int getc (FILE *file)        // define getc() method

The getc() function takes the file pointer as its argument, reads in the next character from the file and returns that character as a integer or EOF when it reaches the end of the file. The integer returned can easily type cast into a character variable for your use.The getc function acts essentially identically to fgetc, but is a macro that expands in-line.  /* * Program to Read/Write using getc( ) and putc( )  */ #include<stdio.h>void main(){file *fp1;char c;fp1=fopen("myfile.txt","w")while((c=getchar())!=EOF){putc(c,fp1);}fclose(fp1);

fp1=fopen("myfile.txt","r")while((c=getc(fp1))!=EOF){printf("%c",c)}fclose(fp1);};

putw( ) functions: The putw() function is used to write integer into file.

int putw(int value, FILE *fptr);

 It return the integer written to the file on success and EOF on error.

/* * Program the understand the use of putw( ) function */

#include<stdio.h>void main(){

FILE *fp1;int a ;fp1=fopen("rajesh.dat","wb") // open file for(int a=1; a<=10;a++) // Start loop with 1 and end with 10 { putw(a,fp1) // function is use to write an integer into a file }

fclose(fp1) // close file};

Output: This program will write integer from 1 to 10 and store data into the file name "rajesh.dat"

12345678910

getw( ) functions: The gettw() function is used to read the integer from file..

int getw(FILE *fp1);

This function return the  integer value from the file associated with pointer fp1. it return the next integer from the input files on success and EOF on error.

/* * program to understand the use of getw( ) function */#include<stdio.h>void main(){FILE *fp1;int a;fp1=fopen("rajesh.dat","rb");while((a=getw(fp1)!=EOF)) //Read integer form fileprintf("%d\t",a);fclose(fp1);};

Output: This program read the integer from the file name "rajesh.dat"

1

2345678910

2. String I/O

fputs( ) function :

char * fputs(const char *str , FILE *stream);

The fputs( ) function writes the content of the string pointed to by str to the specified stream. The null terminator is not written. The fputs( ) function returns the last character written on success and EOF on failure.

/*  * program to understand the use of fputs( ) */

#include<stdio.h>void main(){FILE *fp1;char str[100];fp1=fopen("rajesh.txt","w");printf("enter the text\n")if((gets(str)!=NULL))fputs(str,fp1);fclose(fp1);

};

Output: suppose we enter this text after running the program-

ashish kumar gupta master of computer applicationpress ctrl Z when the first line of text is entered and enter key is pressed the functions gets() converts the newline character and array str contains "ashish kumar gupta"(18 character + 1 null character). the null character is not written to the file , so only 18 character are written.

fgets() Function: 

char  *fgets(char *str, int n, FILE *fptr);

Here str is the base address where the string is to be stored, n is the number of characters to be stored and fptr is a file pointer of type FILE structure which specifies the name of the file to which the input has to be read .The fgets() function reads characters from the current file pointer position upto and including the first new line character ‘\n’, upto the end of the stream, or until the number of characters read is equal to (n-1), whichever comes first. Now look at the second argument of fgets() function more carefully. This second argument is used to prevent fgets() from reading a too long string and overflowing the array. 

fgets( ) function: This function is used to read character from a file  and these characters are store in the string pointed to by str . Characters are read until either a newline or an EOF is received or until the specified limit is reached. After the character has been read, a null is stored in the array immediately after the last character is read. A newline character will be retained and will be a part of the array pointed to by str.

/** program to understand the use of fgets( ) */#include<stdio.h>#include<conio.h>void main(){FILE *FP1;char name[100];

fp1=fopen("rohit.txt","r");printf("enter the data") while(fgets(name,80,fp1)!=NULL) puts(name);fclose(fp1);};

Output: Hello! welcome to r4r.co.in

3. Formatted I/O   

C provide two type of formatted function.

1. fprintf( ) function2. fscanf( ) function

fprintf( ) function: printf( ) function used for Write data to text file.

fprintf (FILE *fptr , const char  *format[argu1,argu2 .... argun  ]);

Here fptr is a file pointer of type FILE structure. Each argument, if any, is converted and output according to the corresponding format specifier in the format string. The fprint() returns the

number of characters printed. This function is similar to printf(), except that a FILE pointer is included as the first argument. Like printf(), you can format the data in a variety of ways by using fprintf( ). As far as the format conversion is concerned, the fprintf() works same as printf().  

/* * program to understand the use of fprintf() */#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<ctype.h> void main(){

//Delclare valiable FILE *fptr; char name[25]; int age; float salary; char ch; fptr = fopen("Emp.txt", "w"); //Open fileif (fptr == NULL) { printf("\nUnable to open a file."); exit(0); } ch = 'y';

while (ch=='y') { printf("\nEnter name : "); gets(name); printf("Enter age : "); scanf("%d", &age); printf("Enter salary : "); scanf("%f", &salary); fprintf(fptr, "%s %d %f", name, age, salary); //Display variablesfflush(stdin); printf("\nAny more input (y/n) : "); ch = tolower(getche()); } fclose(fptr); //close file};

Output: Here is the sample run of this program….

Enter name : AshishEnter age : 24Enter salary : 12000.50

Any more input (y/n) : yEnter name : shashiEnter age : 25Enter salary : 24600.60

Any more input (y/n) : yEnter name : RahulEnter age : 21Enter salary : 15800.50

Any more input (y/n) : yEnter name : AnuragEnter age : 23Enter salary : 21500.50

Any more input (y/n) : n

 In this program i have used fflush(). The reason behind the use of fflush() is that after reading data for an employee an Enter key is being hit. The scanf() function assigns name, age and salary to appropriate variables and keeps the Enter key unread inthe keyboard buffer (stdin). Therefore when getche() function is waiting for a character it reads the Enter key from the keyboard thinking that user has entered the key. To overcome this problem we use fflush(). The fflush() function is used to flush out any pending data in the buffer.

fscanf () function: fscanf function Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

fscanf (FILE *fptr , const char *format [,address,.....]);

The fscanf function works exactly like the scanf function except that it reads the information from the stream specified by stream instead of standard input device.

fscanf function Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

/* *program to understand the use of fscanff() */#include<stdio.h>#include<conio.h>#include<stdlib.h>

void main( ){clrscr();FILE *fp ;struct emp

{

char name[50] ;int age ;float sal ;} ;struct emp e ;fp = fopen ( "employee.txt", "r" ) ;if ( fp == NULL ){puts ( "Cannot open file" ) ;exit( ) ;}while ( fscanf ( fp, "%s %d %f", e.name, &e.age, &e.sal ) != EOF )printf ( "\n%s %d %f", e.name, e.age, e.sal ) ;fclose ( fp ) ;};

Output:

Ashish 34 1250.500000Anurag 21 1300.500000Rajesh 27 1400.500000

3. Block Read Write in C

It is useful to store block of data into file rather than individual elements . Each block has some fixed size, it may be structure and array. It is easy to to read the entire block from a file or write a entire block to the file.

There are to useful function for this purpose.

1. fwrite ( ) function2. fread ( ) function

Although we can read and write any type of data varying from a single character to array through these function, these function are mainly used for binary files or binary modes. ( wb, rb )

fwrite () function: fwrite function writes a block of data to the given file.

size_t fwrite (const void *ptr, size_t size, size_t count, FILE *stream) ;

size_t is  defined in stdio.h .void means that it is a pointer that can be used for any type variable. ptr is  points to the block of  memory that contains the information to be written to the file ,size denotes the length of each items in bytes

n is the number of items to be written to the file . fptr is a file pointer which points to the file to which the  data is written .if successful , fwrite will return n items.on error it will return a number less then n.

#include <stdio.h>

struct emp{char name[40] ;int age ;float sal ;}employee ;fwrite(&employee,sizeof(employee),1,fp);

this will write single structure to the file.    

/* * Receives records from keyboard and writes them to a file in binary mode */

#include<stdio.h>main( ){FILE *fp ;char another = 'Y' ;struct emp{char name[40] ;int age ;float sal ;} ;struct emp e ;fp = fopen ( "EMP.DAT", "wb" ) ;if ( fp == NULL ){puts ( "Cannot open file" ) ;exit( ) ;}while ( another == 'Y' ){printf ( "\nEnter name, age and basic salary: " ) ;scanf ( "%s %d %f", e.name, &e.age, &e.sal ) ;fwrite ( &e, sizeof ( e ), 1, fp ) ;printf ( "Add another record (Y/N) " ) ;Chapter 12: File Input/Output 439fflush ( stdin ) ;another = getche( ) ;}fclose ( fp ) ;};

fread() function: The fread() is a block oriented function and used to read a block of data from the file. It provide as much control as fgetc() in the program, and has the advantage of being able to read more than one character in a single I/O operation.

fread (ptr, size, n, fptr);

Here ptr is the address of data item (an array or a structure) where the block of data will be stored after reading, size is the size of the data item in bytes to be read, n is the number of data items and fptr is the file pointer of type FILE structure. The fread( ) function returns the number of full data items actually read, which may be less than ‘n’ (possibly 0) if function causes any error.

/* * program to understand the use of fread() */#include<stdio.h>#include<conio.h>void main( ){

clrscr();FILE *fp ;struct emp{char name[40] ;int age ;float bs ;} ;struct emp e ;fp = fopen ( "EMP.DAT", "rb" ) ;if ( fp == NULL ){puts ( "Cannot open file" ) ;exit( ) ;

}while ( fread ( &e, sizeof ( e ), 1, fp ) == 1 )printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;fclose ( fp ) ;getch();};

Output:

Ashish 24 1250.500000rajesh 21 1300.500000shashi 25 1400.500000

Random Access to file in C

 Random access means we can move to any part of a file and read or write data from it without having to read through the entire file. we can access the data stored in the file in two ways.

1. Sequentially2. Randomly

if we want to access the forty fourth record then first forty three record read sequentially to reach forty four record. In random access data can be accessed  and processed directly .There is no need to read each record sequentially. If we want to access a particular record random access takes less time than the sequential access.

C supports these function for random access file.

1. fseek( ) Function2. ftell ( ) Function

How to use   fseek() function in C

This function is used for setting the file position pointer at the specified bytes . fseek is a function  belonging to the ANCI C standard Library and included in the file stdio.h. Its purpose is to change the file position indicator for the specified stream.

int fseek(FILE *stream_pointer, long offset, int origin);

Argument meaning: stream_pointer is a pointer to the stream FILE structure of which the position

indicator should be changed; offset is a long integer which specifies the number of bytes from origin where the

position indicator should be placed;

origin is an integer which specifies the origin position. It can be: 

SEEK_SET: origin is the start of the stream.

SEEK_CUR: origin is the current position.

SEEK_END: origin is the end of the stream.

/*  * Program to understand the use of fseek function  */

#include<stdio.h>#include<conio.h>#include<stdlib.h>struct emprecord{char name[30];int age;float sal;}emp;void main(){int n;FILE *fp;fp=fopen("employee.dat","rb");if (fp==NULL){

printf("/n error in opening file");exit(1);}printf("enter the record no to be read");scanf("%d",&n);fseek(fp,(n-1)*sizeof(emp),0);freed(&emp,sizeof(emp),1,fp);printf("%s\t,emp.name);printf("%d\t",emp.age);printf("%f\n",emp.sal);fclose(fp);getch();};

How to use ftell() Function in C

This function return the current position of the file position pointer. The value is counted from the beginning of the file.

long ftell (file * fptr);

 

/* * program to understand the use of ftell() */

#include<stdio.h>#include<conio.h>#include<stdlib.h>struct emprecord{char name[30];int age;float sal;}emp;void main(){FILE *fp;fp=fopen("employee.dat","rb");if (fp==NULL){

printf("/n error in opening file");exit(1);}printf("position pointer in the beginning -> %1d ",ftell(fp));while("fread(position pointer -> 1%d\n",ftell(fp));printf("position pointer -> %1d\n",ftell(fp));

printf("%s\t",emp.name);printf("%d\t",emp.age);printf("%f",emp.sal);}printf("size of the file in bytes is %1d\n",ftell(fp));fclose(fp);getch();};

Some Other Program :

/* * Program to append record to a file */

#include<stdio.h>#include<conio.h>#include<stdlib.h>

void main(){

struct emprecord{char name[30];int age;float sal;}emp;FILE *fp;int choice=1;fp=fopen("employee.dat","ab");if (fp==NULL){

printf("/n error in opening file");exit(1);}

while(choice==1{printf("enter the name")

scanff("%s\t",&emp.name);printf("enter the age");scanf("%d\t",&emp.age);printf("enter the salery");

scanf("%f",&emp.sal);fwrite(&emp,sizeof(emp),1,fp);

printf("want to enter more choice");scanf("%d",&choice);

}fclose(fp);getch();

};