Thursday, September 27, 2012

File Handling in C

In C programming, file is a place on disk where a group of related data is stored.
High level file I/O functions can be categorized as:
  1. Text file
  2. Binary file
File Operations
  1. Creating a new file
  2. Opening an existing file
  3. Reading from and writing information to a file
  4. Closing a file

Working with file
While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program.
FILE *ptr;

Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\program.txt","w");
 
/*
 E:\\cprogram\program.txt is the location to create file.  
 "w" represents the mode for writing.
*/
Here, the program.txt file is opened for writing mode

File Mode Meaning of Mode During Non-existence of file
r Open for reading If the file does not exist, fopen() returns NULL
w Open for writing If the file exists, its contents are overwritten. If the file does not exist, it will be created
a Open for append. i.e, Data is added to end of file If the file does not exists, it will be created
r+ Open for both reading and writing If the file does not exist, fopen() returns NULL
w+ Open for both reading and writing If the file exists, its contents are overwritten. If the file does not exist, it will be created
a+ Open for both reading and appending. If the file does not exists, it will be created

Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE

Writing to a file
#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   fptr=fopen("C:\\program.txt","w");
   if(fptr==NULL){
      printf("Error!");   
      exit(1);             
   }
   printf("Enter n: ");
   scanf("%d",&n);
   fprintf(fptr,"%d",n);  
/* first argument is pointer to the structure file,
  i.e, fptr in this case. */ 
   fclose(fptr);
   return 0;
}
This program takes the number from user and stores in file. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open that file, you can see the integer you entered.
Similarly, fscanf() can be used to read data from file.

Reading from file
#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   if ((fptr=fopen("C:\\program.txt","r"))==NULL){
       printf("Error! opening file");
       exit(1);  /* Program exits if file pointer returns NULL. */
   }
   fscanf(fptr,"%d",&n);
   printf("Value of n=%d",n); 
   fclose(fptr);   
   return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file

Opening modes of binary files:
Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between opening modes of text and binary files is that, b is appended to indicate that, it is binary file.

Reading and writing of a binary file:
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.

Example code:

1. C program to read name and marks of n number of students from user and store them in a file

#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","w"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}

2. C program to read name and marks of n number of students from user and store them in a file. If the file previously exits, add the information of n students.

#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","a"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}

Important questions:

Q.What is the difference between the functions memmove() and memcpy()?
Ans:The arguments of memmove() can overlap in memory.The arguments of memcpy() cannot.

Q.What is a file pointer?
Ans: The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer points to the block of information of the stream that had just been opened.

Q.What is the purpose of rewind() ?
Ans: The function rewind is used to bring the file pointer to the beginning of the file.
Rewind(fp);

Structure in C

Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.
Structure Definition in C : Keyword struct is used for creating a structure.

Syntax of structure :
struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};

We can create the structure for a person as mentioned above as:

struct person
{
    char name[50];
    int cit_no;
    float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:

This declaration above creates the derived data type struct person.

Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:
struct person
{
    char name[50];
    int cit_no;
    float salary;
};

Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
    char name[50];
    int cit_no;
    float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created.

Accessing members of a structure :
There are two types of operators used for accessing members of a structure.
Member operator(.)
Structure pointer operator(->)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary

Example code:

C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot)
#include <stdio.h>
struct Distance{
    int feet;
    float inch;
}d1,d2,sum;
int main(){
    printf("1st distance\n");
    printf("Enter feet: ");
    scanf("%d",&d1.feet);  /* input of feet for structure variable d1 */
    printf("Enter inch: ");
    scanf("%f",&d1.inch);  /* input of inch for structure variable d1 */
    printf("2nd distance\n");
    printf("Enter feet: ");
    scanf("%d",&d2.feet);  /* input of feet for structure variable d2 */
    printf("Enter inch: ");
    scanf("%f",&d2.inch);  /* input of inch for structure variable d2 */
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;
    if (sum.inch>12){  //If inch is greater than 12, changing it to feet.
        ++sum.feet;
        sum.inch=sum.inch-12;
    }
    printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); 
/* printing sum of distance d1 and d2 */
    return 0;
}
Output
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"

Keyword typedef while using structure
Programmer generally use typedef while using structure in C language. For example:
typedef struct complex{
  int imag;
  float real;
}comp;

Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1 and c2 are created by this comp type.
Structures within structures
Structures can be nested within other structures in C programming.
struct complex
{
 int imag_value;
 float real_value;
};
struct number{
   struct complex c1;
   int real;
}n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure member n1.c1.imag_value is used.
Structure and Pointer
Pointers can be accessed along with structures. A pointer variable of structure can be created as below:
1st distance
struct name {
    member1;
    member2;
    .
    .
};
Inside function 
struct name *ptr;
Here, the pointer variable of type struct name is created.
Structure's member through pointer can be used in two ways:
Referencing pointer to another address to access memory
Using dynamic memory allocation

Consider an example to access structure's member through pointer.
#include <stdio.h>
struct name{
   int a;
   float b;
};
int main(){
    struct name *ptr,p;
    ptr=&p;            /* Referencing pointer to memory address of p */
    printf("Enter integer: ");
    scanf("%d",&(*ptr).a);
    printf("Enter number: ");
    scanf("%f",&(*ptr).b);
    printf("Displaying: ");
    printf("%d%f",(*ptr).a,(*ptr).b);
    return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using ->operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic memory allocation
To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.
Syntax to use malloc()
ptr=(cast-type*)malloc(byte-size)

Example to use structure's member through pointer using malloc() function
#include <stdio.h>
#include<stdlib.h>
struct name {
   int a;
   float b;
   char c[30];
};
int main(){
   struct name *ptr;
   int i,n;
   printf("Enter n: ");
   scanf("%d",&n);
   ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
   for(i=0;i<n;++i){
       printf("Enter string, integer and floating number  respectively:\n");
       scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
   }
   printf("Displaying Infromation:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
   return 0;
}

Output
Enter n: 2
Enter string, integer and floating number  respectively:
Programming
2
3.2
Enter string, integer and floating number  respectively:
Structure
6
2.3
Displaying Information
Programming      2      3.20
Structure      6      2.30

Structure and Function
In C, structure can be passed to functions by two methods:
  1. Passing by value (passing actual value as argument)
  2. Passing by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an argument as normal variable. If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function.
Write a C program to create a structure student, containing name and roll. Ask user the name and roll of a student in main function. Pass this structure to a function and display the information in that function.

#include <stdio.h>
struct student{
    char name[50];
    int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure 
declaration otherwise compiler shows error */
int main(){
    struct student s1;
    printf("Enter student's name: ");
    scanf("%s",&s1.name);
    printf("Enter roll number:");
    scanf("%d",&s1.roll);
    Display(s1);   // passing structure variable s1 as argument
    return 0;
}
void Display(struct student stu){
  printf("Output\nName: %s",stu.name);
  printf("\nRoll: %d",stu.roll);
}

Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149

Passing structure by reference
The address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function.
example:
C program to add two distances(feet-inch system) entered by user. To solve this program, make a structure. Pass two structure variable (containing distance in feet and inch) to add function by reference and display the result in main function without returning it.
#include <stdio.h>
struct distance{
    int feet;
    float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3); 
int main()
{
    struct distance dist1, dist2, dist3;
    printf("First distance\n");
    printf("Enter feet: ");
    scanf("%d",&dist1.feet);
    printf("Enter inch: ");
    scanf("%f",&dist1.inch);
    printf("Second distance\n");
    printf("Enter feet: ");
    scanf("%d",&dist2.feet);
    printf("Enter inch: ");
    scanf("%f",&dist2.inch);
    Add(dist1, dist2, &dist3); 

/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference */
    printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
    return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3) 
{
/* Adding distances d1 and d2 and storing it in d3 */
     d3->feet=d1.feet+d2.feet; 
     d3->inch=d1.inch+d2.inch;
     if (d3->inch>=12) {     /* if inch is greater or equal to 12, converting it to feet. */
         d3->inch-=12;
         ++d3->feet;
    }
}

Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5

Sum of distances = 18'-2.3"

Explanation :
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3 variable in main function.

Union :
Union is user defined data type used to stored data under unique variable name at single memory location.
Union is similar to that of stucture. Syntax of union is similar to stucture. But the major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:
union union_name
	{
		<data-type>element 1;
		<data-type>element 2;
		<data-type>element 3;
	}union_variable;

Difference between union and structure
Though unions are similar to structure in so many ways, the difference between them is crucial to understand. This can be demonstrated by this
Example :
#include <stdio.h>
union job {    //defining a union
   char name[32];
   float salary;
   int worker_no;
}u;
struct job1 {
   char name[32];
   float salary;
   int worker_no;
}s;
int main(){
   printf("size of union = %d",sizeof(u));
   printf("\nsize of structure = %d", sizeof(s));
   return 0;
}

Output
size of union = 32
size of structure = 40

There is difference in memory allocation between union and structure as suggested in above example. The amount of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union

Important questions:

Q. What the advantages of using Unions?
Ans: When the C compiler is allocating memory for unions it will always reserve enough room for the largest member.

Q. What are bit fields? What is the use of bit fields in a Structure declaration?

Ans:A bit field is a set of adjacent bits within a single implementation based storage unit that we
will call a “word”.
The syntax of field definition and access is based on structure.
Struct
{
unsigned int k :1;
unsigned int l :1;
unsigned int m :1;
}
flags;
the number following the colon represents the field width in bits.Flag is a variable that contains three bit fields.

Thursday, September 20, 2012

Pointer in C

Pointer is a variable which holds the memory address of another variable. Pointers are represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Reference operator(&)
If var is a variable then, &var is the address in memory.

Example program :
/* Example to demonstrate use of reference 
 operator in C programming. */
#include <stdio.h>
int main(){
  int var=5;
  printf("Value: %d\n",var);
  printf("Address: %d",&var);  //Notice, the ampersand(&) before var.
  return 0;
}

Output
Value: 5 
Address: 2686778

In above source code, value 5 is stored in the memory location 2686778. var is just the name given to that location.
You, have already used reference operator in C program while using scanf() function.
scanf("%d",&var);

Reference operator(*) and Pointer variables
Pointers variables are used for taking addresses as values, i.e., a variable that holds address value is called a pointer variable or simply a pointer.
Syntax:
          <data_type>*pointer_name;

Example To Demonstrate Working of Pointers

/* Source code to demonstrate, handling of pointers in C program */
#include <stdio.h>
int main(){
   int *pc,c;
   c=22;
   printf("Address of c:%d\n",&c);
   printf("Value of c:%d\n\n",c);
   pc=&c;
   printf("Address of pointer pc:%d\n",pc);
   printf("Content of pointer pc:%d\n\n",*pc);
   c=11;
   printf("Address of pointer pc:%d\n",pc);
   printf("Content of pointer pc:%d\n\n",*pc);
   *pc=2;
   printf("Address of c:%d\n",&c);
   printf("Value of c:%d\n\n",c);
   return 0;
}


Output
Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Value of pc: 22

Address of c: 2686784
Value of c: 11

Address of pointer pc: 2686784
Value of pc: 2 


Explanation of program and figure

  1.  Code int *pc, p; creates a pointer pc and a variable c. Pointer pc points to some address and that address has garbage value. Similarly, variable c also has garbage value at this point.
  2. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable c.
  3. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable c (because c is normal variable) and pc is the address of pc (because pc is the pointer variable). Since the address of pc and address of c is same, *pc (value of pointer pc) will be equal to the value of c.
  4. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value of *pc will also be 11.
  5. Code *pc=2; change the address pointed by pointer pc to change to 2. Since, address of pointer pc is same as address of c, value of c also changes to 2.
Pointers and Arrays
Arrays are closely related to pointers in C programming. Arrays and pointers are synonymous in terms of how they use to access memory. But, the important difference between them is that, a pointer variable can take different addresses as value whereas, in case of array it is fixed. This can be demonstrated by an example:

#include <stdio.h>
int main(){
   char c[4];
   int i;
   for(i=0;i<4;++i){
      printf("Address of c[%d]=%x\n",i,&c[i]);
   }
   return 0;
}

Output
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47

Relation between Arrays and Pointers
Consider and array:
int arr[4];

 In arrays of C programming, name of the array always points to the first element of an array. Here, address of first element of an array is &arr[0]. Also, arr represents the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent to (a+1)  AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2)  AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1)  AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i)  AND, a[i] is equivalent to *(a+i).
In C, you can declare an array and can use pointer to alter the data of an array.

Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main(){
  int i,class[6],sum=0;
  printf("Enter 6 numbers:\n");
  for(i=0;i<6;++i){
      scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
      sum += *(class+i); // *(class+i) is equivalent to class[i]
  }
  printf("Sum=%d",sum);
  return 0;
}

Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21

Pointers and Functions - Call by Reference
When, argument is passed using pointer, address of the memory location is passed instead of value.

Example of Pointer And Functions

 C Program to swap two numbers using pointers and function. 
#include <stdio.h>
void swap(int *a,int *b);
int main(){
  int num1=5,num2=10;
/* address of num1 and num2 is passed to swap function */
  swap(&num1,&num2);  
  printf("Number1 = %d\n",num1);
  printf("Number2 = %d",num2);
  return 0;
}
/* pointer a and b points to address of num1 and num2 respectively */
void swap(int *a,int *b){ 
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}

Output
Number1 = 10
Number2 = 5

Explanation
The address of memory location num1 and num2 are passed to function and the pointers *a and *b accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer are changed, the value in memory location also changed correspondingly. Hence, change made to *a and *b was reflected in num1 and num2 in main function.
This technique is known as call by reference in C programming.

Dynamic Memory Allocation
The exact size of array is unknown until the compile time,i.e., time when a compiler compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.

Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free() dellocate the previously allocated space
realloc() Change the size of previously allocated space

malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.

Examples of calloc() and malloc()

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int n,i,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d",&n);
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc
    if(ptr==NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
    return 0;
}

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int n,i,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d",&n);
    ptr=(int*)calloc(n,sizeof(int));
    if(ptr==NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
    return 0;
}

realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int *ptr,i,n1,n2;
    printf("Enter size of array: ");
    scanf("%d",&n1);
    ptr=(int*)malloc(n1*sizeof(int));
    printf("Address of previously allocated memory: ");
    for(i=0;i<n1;++i)
         printf("%u\t",ptr+i);
    printf("\nEnter new size of array: ");
    scanf("%d",&n2);
    ptr=realloc(ptr,n2);
    for(i=0;i<n2;++i)
         printf("%u\t",ptr+i);
    return 0;
}


Pointer Examples C program to find average of n numbers using pointers 

#include <stdio.h>
#include <stdio.h>
int main(){
    float n[100],sum=0.0;
    int i,num;
    printf("Enter the total number: ");
    scanf("%d",&num);
    for(i=0;i<num;++i){
        printf("Number %d: ",i+1);
        scanf("%f",(n+i));
        sum+=*(n+i);
    }
    printf("Average=%.2f",sum/num);
    return 0;
}


Write a C program to multiply matrix using pointers 

#include <stdio.h>
void multiply(int a[][50],int b[][50],int c[][50],int r1,int c2,int c1);
int main(){
    int i,j,k,a[50][50],b[50][50],c[50][50],r1,c1,r2,c2;
    printf("For first matrix: Enter rows and column respectively.");
    scanf("%d%d",&r1,&c1);
    printf("For second matrix: Enter rows and column respectively.");
    scanf("%d%d",&r2,&c2);
    if(c1==r2)
    {
        for(i=0;i<r1;++i)
            for(j=0;j<c1;++j)
            {
                printf("Enter element a%d%d: ",i+1,j+1);
                scanf("%d",(*(a+i)+j));
            }
        for(i=0;i<r1;++i)
            for(j=0;j<c1;++j)
            {
                printf("Enter element b%d%d: ",i+1,j+1);
                scanf("%d",(*(b+i)+j));
            }
        for(i=0;i<r1;++i)
            for(j=0;j<c2;++j)
                  *(*(c+i)+j)=0;
        for(i=0;i<r1;++i)
         for(j=0;j<c2;++j)
            for(k=0;k<c1;++k)
                 *(*(c+i)+j)+=(*(*(a+i)+k))*(*(*(b+k)+j));
        for(i=0;i<r1;++i)
            for(j=0;j<c2;++j)
            {
                printf("%d  ",*(*(c+i)+j));
                if(j==c2-1)
                   printf("\n");
            }
    }
    else
       printf("Error! column of 1st matrix not equal to row of 2nd");
    return 0;
}

C program to swap numbers in cyclic order using call by reference. 

#include <stdio.h>

void Cycle(int *a,int *b,int *c);
int main(){
    int a,b,c;
    printf("Enter value of a, b and c respectively: ");
    scanf("%d%d%d",&a,&b,&c);
    printf("Value before swamping:\n");
    printf("a=%d\nb=%d\nc=%d\n",a,b,c);
    Cycle(&a,&b,&c);
    printf("Value after swaping numbers in cycle:\n");
    printf("a=%d\nb=%d\nc=%d\n",a,b,c);
    return 0;
}
void Cycle(int *a,int *b,int *c){
    int temp;
    temp=*b;
    *b=*a;
    *a=*c;
    *c=temp;
}

Important questions:

1.What is the difference between const char* p and char const* p?

In const char* p, the character pointed by ‘p’ is constant, so u cant
change the value of character pointed by p but u can make ‘p’ refer to
some other location.
in char const* p, the ptr ‘p’ is constant not the character referenced by
it, so u cant make ‘p’ to reference to any other location but u can
change the value of the char pointed by ‘p’.

2.What is a null pointer?
A null pointer does not point to any object.
NULL and 0 are interchangeable in pointer contexts.Usage of NULL should be considered a gentle reminder that a pointer is involved.
It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required

3.What is generic pointer in C?

In C void* acts as a generic pointer. When other pointer types are assigned to generic pointer, conversions are applied automatically (implicit conversion).

Functions in C

The function is a self contained block of statements which performs a coherent task of a same kind.
C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call function whenever we want to process that functions statements.

Types of functions :

There are 2(two) types of functions as:

1. Built in function
2. User defined function


1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g.
  • scanf()
  • printf()
  • strcpy
  • strlwr
  • strcmp
  • strlen
  • strcat
2. User Defined Functions :
The functions which are created by user for program are known as 'User defined functions'.
Syntax:

void main()
{
 // Function prototype
 <return_type><function_name>([<argu_list>]);
 
 // Function Call
 <function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
 <function_body>;
}

Example program :
#include <stdio.h>
#include <conio.h>
void add()
{
 int a, b, c;
 clrscr();
 printf("\n Enter Any 2 Numbers : ");
 scanf("%d %d",&a,&b);
 c = a + b;
 printf("\n Addition is : %d",c);
}
void main()
{
 void add();
 add();
 getch();
}

Output:
Enter Any 2 Numbers : 23 6
Addition is : 29

Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type.

Syntax of function prototype:
return_type function_name(type(1) argument(1),....,type(n) argument(n));

Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked).
function_name(argument(1),....argument(n));

Function definition
Function definition contains programming codes to perform specific task.
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
                //body of function
}
Function definition has two major components:

1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function.
return_type function_name(type(1) argument(1),....,type(n) argument(n))

2. Function body
Function declarator is followed by body of function which is composed of statements.

Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or  variable) passed from a program to the function.



In above example two variable, num1 and num2 are passed to function during function call and these arguments are accepted by arguments a and b in function definition.

Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same.
A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to calling function.
return (expression);
          OR
     return;

For example:
return;
return a;
return (a+b);


Types of User-defined Functions in C Programming
For better understanding of arguments and return in functions, user-defined functions can be categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 categories of user defined functions.

Function with no arguments and no return value.
/*C program to check whether a number entered by user 
   is prime or not using function with no arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
    prime();      //No argument is passed to prime().
    return 0;
}
void prime(){  
/* There is no return value to calling function main(). Hence,
   return type of prime() is void */
    int num,i,flag=0;
    printf("Enter positive integer enter to check:\n");
    scanf("%d",&num);
    for(i=2;i <=num/2;++i){
        if(num%i==0){
             flag=1;
         }
    }
    if (flag==1)
        printf("%d is not prime",num);
    else
       printf("%d is prime",num);  
    }

Function prime() is used for asking user a input, check for whether it is prime of not and display it accordingly. No argument is passed and returned form prime() function.

Function with no arguments but return value
/*C program to check whether a number entered by user 
is prime or not using function with no arguments but having return value */
#include <stdio.h>
int input();
int main(){
    int num,i,flag;
    num=input();     /* No argument is passed to input() */
    for(i=2,flag=i;i<=num/2;++i,flag=i){
    if(num%i==0){
        printf("%d is not prime",num);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",num);
    return 0;
}
/* Integer value is returned from input() to calling function */
int input(){  
    int n;
    printf("Enter positive enter to check:\n");
    scanf("%d",&n);
    return n;
}
There is no argument passed to input() function But, the value of n is returned from input() to main() function.
Function with arguments and no return value
/*Program to check whether a number entered by user is prime or  not using function with arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
    int num;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
    check_display(num);  /* Argument num is passed to function. */
    return 0;
}
void check_display(int n){     
/* There is no return value to calling function.
Hence, return type of function is void. */
    int i,flag;
    for(i=2,flag=i;i<=n/2;++i,flag=i){
    if(n%i==0){
        printf("%d is not prime",n);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",n);
}
Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function.

Function with argument and a return value
/* Program to check whether a number entered by user is prime or not using function with argument and return value */
#include <stdio.h>
int check(int n);
int main(){
    int num,num_check=0;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
  /* Argument num is passed to check() function. */ 
   num_check=check(num); 
    if(num_check==1)
       printf("%d in not prime",num);
    else
       printf("%d is prime",num);
    return 0;
}
int check(int n){   
/* Integer value is returned from function check() */ 
    int i;
    for(i=2;i<=n/2;++i){
    if(n%i==0)
        return 1;
}
   return 0;
}
Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

Recursion :
A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.
Example of recursion
Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main(){
    int num,add;
    printf("Enter a positive integer:\n");
    scanf("%d",&num);
    add=sum(num);
    printf("sum=%d",add);
}
int sum(int n){
    if(n==0)
       return n;
    else
       return n+sum(n-1);    /*self call  to function sum() */
}

Output
Enter a positive integer:
5
15

In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15

Storage Class
Every variable and function in C programming has two properties: type and storage class. Type refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:
  • automatic
  • external
  • static
  • register
Automatic storage class
Keyword for automatic variable
auto
Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
External storage class
External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.

Example to demonstrate working of external variable

#include <stdio.h>
#include <conio.h>
void Check();
int a=5;    
/* a is global variable because it is outside every function */
int main(){
    a+=4;
    Check();
    return 0;
}

void Check(){
   ++a;
/*  ----- Variable a is not declared in this function but, 
works in any function as they are global variable -------  */
   printf("a=%d\n",a);
}

Output:
 a=10

Register Storage Class
Keyword to declare register variable
register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it in memory.

Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
#include <conio.h>
void Check();
int main(){
   Check();
   Check();
   Check();
}
void Check(){
    static int c=0;
    printf("%d\t",c);
    c+=5;
}

Output
0      5     10

During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0     0     0

Function Examples programs:
Write a C program to reverse a number entered by user. Make function Reverse() to reverse the numbers.
#include <stdio.h>
#include <stdio.h>
int Reverse(int n);
int main()
{
    int num,i;
    printf("Enter number to reverse\n");
    scanf("%d",&num);
    printf("Reverse of %d=%d",num,Reverse(num));
    return 0;
}
int Reverse(int n)
{
    int rem,rev=0;
    while(n!=0){
       rem=(n%10);
       n=(n/10);
       rev=rev*10+rem;
    }
    return rev;
}

Output:
Enter number to reverse
56
Reverse of 56=65

Write a C program to reverse a sentence using recursive function. 

#include <stdio.h>
void Reverse(char c);
int main(){
   char c;
   printf("Enter sentence to reverse: \n");
   Reverse(c);
   return 0;
}
void Reverse(char c){
    scanf("%c",&c);
    if(c!='\n'){
        Reverse(c);
        printf("%c",c);
      }
}

output:
Enter sentence to reverse:
dog
god

C program to find hcf and lcm using recursion 

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}

C program to find hcf and lcm using function 

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long x, long y) {
  if (x == 0) {
    return y;
  }
 
  while (y != 0) {
    if (x >y) {
      x = x - y;
    }
    else {
      y = y - x;
    }
  }
 
  return x;
}

Output:
Enter two integers
9  15
Greatest common divisor of 9 and 15 = 3
Least common multiple of 9 and 15 = 45

Important questions:

Q. What are built in functions?
Ans: The functions that are predefined and supplied along with the compiler are known as built-in functions.They are also known as library functions.

Q. What do the ‘c’ and ‘v’ in argc and argv stand for?
Ans: The c in argc(argument count) stands for the number of command line argument the program is invoked with and v in argv(argument vector) is a pointer to an array of character string that contain the arguments.

Q. In header files whether functions are declared or defined?
Ans: Functions are declared within header file. That is function prototypes exist in a header file,not function bodies. They are defined in library .

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

Sunday, September 16, 2012

Arrays in C

Array is a collection of homogenous data stored under unique name. The values in an array is called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.
Array is also called as 'sub scripted variable.'

Types of an Array :

1. One / Single Dimensional Array
2. Two Dimensional Array


Single / One Dimensional Array :
The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'
Declaration of one-dimensional array
data_type array_name[array_size];
For example,
int age[5];
Array elements
Size of array defines the number of elements in an array. Each element of array can be accessed and used by user according to the need of program.
 For example:     int age[5];



Note that, the first element is numbered 0 and so  on.
Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes. Then, the next address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.

Initialization:
Arrays can be initialized at declaration time in  this source code as,
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of an array.


Accessing array elements:
In C programming, arrays can be accessed and treated like variables in C.
For example:
scanf("%d",&age[2]);
/* statement to insert value in the third element of array age[]. */

scanf("%d",&age[i]);
/* Statement to insert value in (i+1)th element of array age[]. */
/* Because, the first element of array is age[0], second is age[1], ith is age[i-1] and (i+1)th is age[i]. */

printf("%d",age[0]);
/* statement to print first element of an array. */

printf("%d",age[i]);
/* statement to print (i+1)th element of an array. */

Example program :

#include <stdio.h>
#include <conio.h>
int main(){
     int marks[10],i,n,sum=0;
     printf("Enter number of students: ");
     scanf("%d",&n);
     for(i=0;i<n;++i){
          printf("Enter marks of student%d: ",i+1);
          scanf("%d",&marks[i]);
          sum+=marks[i];
     }
     printf("Sum= %d",sum);
return 0;
}

output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

Multidimensional Arrays:

The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
<data-type> <array_nm> [row_subscript][column-subscript];

figure :

Initialization of Multidimensional Arrays:
In C, multidimensional arrays can be initialized in different number of ways.
int c[2][3]={{1,3,0}, {-1,5,9}};
                 OR
int c[][3]={{1,3,0}, {-1,5,9}};
                 OR
int c[2][3]={1,3,0,-1,5,9};

Initialization Of three-dimensional Array:

double c3d[3][2][4]={
{{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}},
 {{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},
 {{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}}
};
Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers of data.
Similarly, the array of any dimension can be initialized in C programming.

Example program 1 :

#include <stdio.h>
#include <conio.h>
int main(){
   float a[2][2], b[2][2], c[2][2];
   int i,j;
   printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/   
   for(i=0;i<2;++i)      
       for(j=0;j<2;++j){
       printf("Enter a%d%d: ",i+1,j+1);
       scanf("%f",&a[i][j]);
       }
   printf("Enter the elements of 2nd matrix\n");
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
       printf("Enter b%d%d: ",i+1,j+1);
       scanf("%f",&b[i][j]);
       }
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
       c[i][j]=a[i][j]+b[i][j];  /* Sum of corresponding elements of two arrays. */
       }
   printf("\nSum Of Matrix:");
   for(i=0;i<2;++i)
       for(j=0;j<2;++j){
       printf("%.1f\t",c[i][j]);  
           if(j==1)             /* To display matrix sum in order. */
              printf("\n");
      }
return 0;
}

output:
Enter the elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter the elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2     0.5
-0.9    25.0
Example program 2 :
#include <stdio.h>
#include <conio.h>
main()
{
   int m, n, c, d, matrix[10][10], transpose[10][10];
 
   printf("Enter the number of rows and columns of matrix ");
   scanf("%d%d",&m,&n);
   printf("Enter the elements of matrix \n");
 
   for( c = 0 ; c < m ; c++ )
   {
      for( d = 0 ; d < n ; d++ )
      {
         scanf("%d",&matrix[c][d]);
      }
   }
 
   for( c = 0 ; c < m ; c++ )
   {
      for( d = 0 ; d < n ; d++ )
      {
         transpose[d][c] = matrix[c][d];
      }
   }
 
   printf("Transpose of entered matrix :-\n");
 
   for( c = 0 ; c < n ; c++ )
   {
      for( d = 0 ; d < m ; d++ )
      {
         printf("%d\t",transpose[c][d]);
      }  
      printf("\n");
   }
 
   return 0;
}

output:
Enter the number of rows and columns of matrix
3  3
Enter the elements of matrix
2  5  7
8  3  4
1  4  7
Transpose of entered matrix :-
2  8  1
5  3  4
7  4  7

Limitations of two dimensional array :

1.We cannot delete any element from an array.
2.If we don't know that how many elements have to be stored in a memory in advance, then there will be memory wastage if large array size is specified.


Important questions:

Q. Why is it necessary to give the size of an array in an array declaration?
Ans: When an array is declared, the compiler allocates a base address and reserves enough space in memory for all the elements of the array. The size is required to allocate the required space and hence size must be mentioned.
Q.Is it possible to have negative index in an array?
Ans: Yes it is possible to index with negative value provided there are data stored in this location. Even if it is illegal to refer to the elements that are out of array bounds, the compiler will not produce error because C has no check on the bounds of an array.
Q.Difference between a array name and a pointer variable?
Ans: A pointer variable is a variable where as an array name is a fixed address and is not a variable.
 A pointer variable must be initialized but an array name cannot be initialized. An array name being a constant value , ++ and — operators cannot be applied to it.

Control Statements in C

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Followings are the different conditional statements used in C.

  1.  If Statement
  2.  If-Else Statement
  3.  Nested If-Else Statement
  4.  Switch Case


If Statement :
This is a conditional statement used in C to check condition or to control the flow of execution of statements. This is also called as 'decision making statement or control statement.' The execution of a whole program is done in one direction only.
Syntax:


if(condition)
{
	statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is not necessary to use.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
a=5;
if(a>4)
printf("\nValue of A is greater than 4 !");
if(a==4)
printf("\n\n Value of A is 4 !");
getch();
}

If-Else Statement :
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
	true statements;
}
else
{
	false statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
printf("\n\n Number is even !");
else
printf("\n\n Number is odd !");
getch();
}

Nested If-Else Statement :

It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute.
Syntax:
if(condition)
{
        if(condition)
{
        statements;
          }
else
{
         statements;
            }
}
else
{
      statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
	}
else
{
if(no==0)
	{
	printf("\n\n It is 0 !");
		}
	else
	{
	printf("Number is less than 0 !");
		}
	}
	getch();
}
 
Switch case Statement :
This is a multiple or multi-path branching decision making statement.
When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.

This is the flow chart of the C switch statement:


Syntax:
switch(expression)
{
	case expr1:
		statements;
		break;
	case expr2:
		statements;
		break;
case exprn:
		statements;
		break;						
	default:
		statements;
}

In this syntax
1.in C switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value, which is returned by expression, must be an integer value otherwise the compiler will issue an error message.
2.The case constant expression must be a constant integer value.
3.When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. The break statement is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logic happens.
3.The default statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.

Rules for declaring switch case :

1. The case label should be integer or character constant.
2. Each compound statement of a switch case should contain break statement to exit from case.
3. Case labels must end with (:) colon.

Advantages of switch case :
1. Easy to use.
2. Easy to find out errors.
3. Debugging is made easy in switch case.
4. Complexity of a program is minimized.

Example code:
1.
#include <stdio.h>
main()
{
     int  Grade = 'L';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}

2.
#include <stdio.h>
int main()
{
     char operator;
     float num1,num2;
     printf("Enter operator +, - , * or / :\n");
     operator=getche();
     printf("\nEnter two operands:\n");
     scanf("%f%f",&num1,&num2);
     switch(operator)                              
     {
     case '+':
              printf("num1+num2=%.2f",num1+num2);
              break;
     case '-':
              printf("num1-num2=%.2f",num1-num2);
              break;
     case '*':
              printf("num1*num2=%.2f",num1*num2);
              break;
     case '/':
              printf("num2/num1=%.2f",num1/num2);
              break;
     default:                                 
              printf(Error! operator is not correct");
              break;
     }
     return 0;
}

3.
#include <stdio.h>
#include <conio.h>
int main(){
     char check;
     int i, flag, num,temp,sum=0;
     printf("Enter number: ");
     scanf("%d",&num);
     printf("-----------------------Instructions--------\n");
     printf("Enter 'a' to check for Armstrong number.\n");
     printf("Enter 'p' to check for prime number.\n");
     printf("Enter 'f' to check for Fibonacci sequence.\n");
     printf("------------------------------------------\n");
     printf("Enter a character according to instruction specified: ");
     check=getche();
     switch(check)
     {
     case 'a':
              temp=num;
            while(num!=0){
                 sum+=(num%10)*(num%10)*(num%10);
                 num=num/10;
               }
               if(sum==temp)
                  printf("\n\nResult: %d is Armstrong\n",temp);
               else
                  printf("\n\nResult: %d is not Armstrong\n",temp);
               break;
     case 'p':
              flag=0;
              for(i=2;i<=(num/2);++i){
                  if((num%i)==0){
                    printf("\n\nResult: %d in not prime.",num);
                     flag=1;
                     break;
                  }
              }
              if(flag==0)
                 printf("\n\nResult: %d is prime.",num);
              break;
     case 'f':
          i=0,flag=1;
          while(flag<=num) {
             if (flag==num){
                printf("\n\nResult: %d lies in Fibonacci.",num);
                  break;
               }
                 temp=flag;
                 flag+=i;
                 i=temp;
            }
          if (flag!=num)
            printf("\n\nResult: %d does not lies in Fibonacci.",num);
          break;
    default:
            printf("Error! ");
            break;
     }
     return 0;
}

in this program we can check for, whether a number is a prime number or Armstrong number or lies on Fibonacci sequence according to instruction from user in one program using switch...case statement.

Looping Statements / Iterative Statements :

A loop is a part of code of a program which is executed repeatedly.
A loop is used using condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
           Check condition to start a loop
           Initialize loop with declaring a variable.
           Executing statements inside loop.
           Increment or decrement of value of a variable.
Types of looping statements :
Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.

1. Entry controlled loop
2. Exit controlled loop


1. Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
  • while loop
  • for loop
2.  Exit controlled loop :
In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed at least one time compulsorily.
Some common example of this looping statement is :
  • do-while loop

For loop:

syntax
for(initial expression; test expression; update expression)
{ 
 code/s to be executed; 
}
 
How for loop works in C programming?
This flowchart describes the working of for loop in C programming.

Example program :
#include <stdio.h>

int main(){
    int n, count, sum=0;
    printf("Enter the value of n.\n");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  //for loop terminates if count>n
    {
        sum+=count;    /* this statement is equivalent to sum=sum+count */
    }
    printf("Sum=%d",sum);
    return 0;
}

Output :
Enter the value of n.
19
Sum=190

While loop:
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
while ( expression )
{
   Single statement 
   or
   Block of statements;
}

Flowchart of while loop:


 Example code:
C program to find the factorial of a number, where the number is entered by user.
#include <stdio.h>
#include <conio.h>
void main()
{
     int number,factorial;
     printf("Enter a number.\n");
     scanf("%d",&number);
     factorial=1;
     while (number>0)
{                  
           factorial=factorial*number;
           --number;
}

printf("Factorial=%d",factorial);
return 0;
}

Output :
Enter a number.
5
Factorial=120 
do...while loop:
In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.
Syntax of do...while loops
do {
   some code/s;
}
while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside body of do are executed again and the process continues until test expression becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Flow chart

Example program :
#include <stdio.h>
#include <conio.h>
int main(){
   int sum=0,num;
   do{                
        printf("Enter a number\n");
        scanf("%d",&num);
        sum+=num;      
   }
   while(num!=0);
   printf("sum=%d",sum);
return 0;
}
Output :
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is again executed until num equals to zero.

Break Statement :

Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.
Syntax
break;

The break statement can be used in terminating all three loops for, while and do...while loops.
Flow chart:
The figure below explains the working of break statement in all three type of loops.


Example program :

#include <stdio.h>
#include <conio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs\n");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       break;                     //for loop breaks if num<0.0
       sum=sum+num;
}
  average=sum/(i-1);       
  printf("Average=%.2f",average);
  return 0;
}
output:
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
 
Continue Statement :
Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this anomaly.
The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. It causes the loop to be continued with next iteration after skipping statements in between. Continue statement simply skips statements and continues next iteration. Just like break, continue is also used with conditional if statement.
Syntax

Flowchart



Goto Statement :
It is a well known as 'jumping statement.' It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used.
Syntax :
goto [expr];

Example program :
Code 1.
#include <stdio.h>
#include <conio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs: ");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       goto jump;             /* control of the program jumps to label jump */ 
       sum=sum+num;
}
jump:
  average=sum/(i-1);       
  printf("Average: %.2f",average);
  return 0;
}
output:
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Code 2
#include <stdio.h>
#include <conio.h>

void main()
{
	int i=1, j;
	clrscr();
	while(i<=3)
	{
		for(j=1; j<=3; j++)
		{
			printf(" * ");
			if(j==2)
			goto stop;
		}
		i = i + 1;
	}
	stop:
		printf("\n\n Exited !");
	getch();
}
output:
**
Exited

Some important Questions:

Q.What is the difference between the two operators = and ==  ?
= assignment operator which is used to asign value to the operand.
exp:
a=10;
== equality operator which is used to compare two operands.
exp:
a==b
Q.what is the difference between entry control and exit control statement?
Entry Comtrolled will check the Condition at First and doesn't execute if it is False.
Exit Comtrolled will check the Condition at Last and at least once the statement will execute though it is False .    
Q.What's  the difference between ++i and i++?
++i adds one to the stored value of i and ``returns'' the new, incremented value to the surrounding expression; i++ adds one to i but returns the prior, unincremented value.