Search This Blog

Saturday, May 26, 2012

C Coding

Multiplication of two matrices

#include<stdio.h>
#include<conio.h>
int main(){
  int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
  printf("\nEnter the row and column of first matrix");
  scanf("%d %d",&m,&n);
  printf("\nEnter the row and column of second matrix");
  scanf("%d %d",&o,&p);
  if(n!=o){
      printf("Matrix mutiplication is not possible");
      printf("\nColumn of first matrix must be same as row of second matrix");
  }
  else{
      printf("\nEnter the First matrix->");
      for(i=0;i<m;i++)
      for(j=0;j<n;j++)
           scanf("%d",&a[i][j]);
      printf("\nEnter the Second matrix->");
      for(i=0;i<o;i++)
      for(j=0;j<p;j++)
           scanf("%d",&b[i][j]);
      printf("\nThe First matrix is\n");
      for(i=0;i<m;i++){
      printf("\n");
      for(j=0;j<n;j++){
           printf("%d\t",a[i][j]);
      }
      }
      printf("\nThe Second matrix is\n");
      for(i=0;i<o;i++){
      printf("\n");
      for(j=0;j<p;j++){
           printf("%d\t",b[i][j]);
      }
      }
      for(i=0;i<m;i++)
      for(j=0;j<p;j++)
           c[i][j]=0;
      for(i=0;i<m;i++){ //row of first matrix
      for(j=0;j<p;j++){  //column of second matrix
           sum=0;
           for(k=0;k<n;k++)
               sum=sum+a[i][k]*b[k][j];
           c[i][j]=sum;
      }
      }
  }
  printf("\nThe multiplication of two matrix is\n");
  for(i=0;i<m;i++){
      printf("\n");
      for(j=0;j<p;j++){
           printf("%d\t",c[i][j]);
      }
  }
  getch();
  return 0;
}


TO DELETE "THREE", "BAD" AND "TIME"


#include<stdio.h>
#include<string.h>
int main( )
{
char str[20];
FILE *ptvar1, *ptvar2;
ptvar1=fopen("data1.txt","r");
ptvar2=fopen("data2.txt","w");
while(!feof(ptvar1))
{
fscanf(ptvar1,"%s",str);
if(strcmp(str, "three")==0 || strcmp(str, "bad")==0 || strcmp(str, "time")==0);
continue;
else
fprintf(ptvar2,"%s",str);
}
fclose(ptvar1);
fclose(ptvar2);
return 0;
}

(*the alignments are not proper, please standardize the alignment to run the program)

TO COPY A FILE


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

main()
{
char ch, source_file[20], target_file[20];
FILE *fp1, *fp2;

printf("Enter name of file to copy\n");
gets(source_file);

fp1 = fopen(source_file, "r");

if( fp1 == NULL )
{
printf("Error\n");
}

printf("Enter name of target file\n");
gets(target_file);

fp2= fopen(target_file, "w");

if( fp2 == NULL )
{
fclose(fp1);
printf("Error\n");
}

while( ( ch = fgetc(fp1) ) != EOF )
fputc(ch, fp2);

printf("File copied successfully.\n");

fclose(fp1);
fclose(fp2);

return 0;
}


To calculate the sum, difference, product, quotient and remainder

#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,sum,dif,pro,q,r;
clrscr();
printf("input enter a first greater number ",a);
scanf("%d",&a);
printf("input enter a second smanller number ",b);
scanf("%d",&b);
sum=a+b;
dif=a-b;
pro=a*b;
q=a/b;
r=a%b;
printf("sum of two no= %d",sum);
printf("\ndiffferenceoftwo no= %d",dif);
printf("\nproductoftwo no= %d",pro);
printf("\nquotientoftwo no= %d",q);
printf("\nremainder of two no= %d",r);
getch();
}


To input any two numbers and finding out the greater one

#include<stdio.h>
#include<conio.h>
void main()
{ int num1, num2;
clrscr();
printf(“Enter the first and second number:\n”);
scanf(“%d%d”, &num1, &num2);
if(num1>num2)
printf(“\n%d is greater than %d”, num1, num2);
else
printf(“\n%d is greater than %d”, num2, num1);
getch();
}

To find out whether the number is odd or even

#include<stdio.h>
#include<conio.h>
void main()
{ int num;
clrscr();
printf(“Enter any number:\n”);
scanf(“%d”,&num);
if((num%2)==0)
printf(“\nThe given number is even”);
else
printf(“\nThe given number is odd”);
getch();
}

To generate the multiplication table

#include<stdio.h>
#include<conio.h>
void main()
{ int i, num;
clrscr();
printf(“Enter any number:”);
scanf(“%d”,&num);
for(i=1;i<=10;i++)
printf(“%d X %d = %d”,num,i,num*i);
getch();\
}


To calculate the percentage and division of a student

#include(stdio.h)
#include(conio.h)
void main()
{ float marks, per;
printf("\nEnter the total marks:");
scanf("%d,&marks);
per=marks/5;
if(per>=80)
{ printf("distinction"); }
else if(per>=60 && per<80)
{ printf("\n first division"); }
else if(per>=50 &&per<60)
{ printf("\nsecond division"); }
else if(per>=40 &&per<50)
{ printf("\n pass division"); }
else
{ printf("\n fail"); }
printf("\nThe percentage is %f",per);
getch();
}

To calculate the area and perimeter of a rectangle

#include<stdio.h>
#include<conio.h>
void main()
{ float l,b,area,perimeter;
printf("Enter length and breadth of rectangle");
scanf("%f%f",&l,&b);
area=l*b;
perimeter=2*(l+b);
printf("\nThe area of rectangle is %f\nThe perimeter of rectangle is
%f",area,perimeter);
getch();
}

To swap the values

#include<conio.h>
#include<stdio.h>
void main()
{ int temp, num1, num2;
clrscr();
printf(“Enter two numbers:\n”);
scanf(“%d%d”,&num1,&num2);
printf(“The given numbers are %d and %d”,num1,num2);
temp=num1;
num1=num2;
num2=temp;
printf(“The numbers after swapping are %d and %d”,num1,num2);
getch();
}

To swap the numbers using bubble sort method

#include<stdio.h>
#include<conio.h>
void main()
{ int i,j,n,temp;
intnum[]={4,9,3,7,1,8,6};
n=7;
clrscr();
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)
{ if(num[j]>=num[j+1])
{ temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
printf(“%d\t”,num[i]);
getch();
}

To swap the numbers using selection sort method

#include<stdio.h>
#include<conio.h>
void main()
{ int i,j,n,p,temp,s=0;
intnum[]={4,9,3,7,1,8,6};
n=7;
clrscr();
for(i=0;i<n-1;i++)
{ s=num[i];
for(j=i;j<n;j++)
{ if(num[j]<=s)
{ s=num[j];
p=j;
}
}
temp=num[i];
num[i]=s;
num[p]=temp;
}
for(i=0;i<n;i++)
printf(“%d\t”,num[i]);
getch();
}


To arrange numbers in ascending order

#include<stdio.h>
#include<conio.h>
void main()
{ int i,k,int x[10],temp;
clrscr();
printf("\n Enter the numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&x[i]);
for(i=0;i<10;i++)
{ for(k=0;k<10;k++)
{ if(x[k]>x[k+1])
{ temp=x[k];
x[k]=x[k+1];
x[k+1]=temp;
}
}
}
printf("\nThe numbers in ascending order are:\n”);
for(i=0;i<10;i++)
printf(“%d\t",x[i]);
getch();
}

To find HCF

#include<stdio.h>
#include<conio.h>
void main()
{ int num1,num2,temp;
printf("Enter two numbers:\n");
scanf("%d%d",&num1,&num2);
while(num2!=0)
{ temp=num1%num2;
num1=num2;
num2=temp;
}
printf("\nHCF is %d",num1);
getch();
}

To find the factorial of given number

#include<stdio.h>
#include<conio.h>
void main()
{ int n,i;
longint fact;
clrscr();
fact=1;
printf("enter the number");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact=fact*i;
printf("The factorial of %d is %d", n,fact);
getch();
}

To find the Fibonacci series of given number

#include<stdio.h>
#include<conio.h>
void main()
{ clrscr();
int n, i=0, j=1, k , a;
printf("Enter the number:");
scanf("%d", &n);
printf("\nfibonacci series is 0 1");
for(a=3; a<=n; a++)
{ k=i+j;
i=j;
j=k;
printf("\t %d", k);
}
getch();
}

To reverse the user input integer

#include<stdio.h>
#include<conio.h>
void main()
{ int num, rem, temp=0;
clrscr();
printf(“Enter any number:\n”);
scanf(“%d”,&num);
while(num!=0)
{ rem=num%10;
temp=(temp*10)+rem;
num=num/10;
}
printf(“The reversed number is %d”,temp);
getch();
}

 To reverse the user input string

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ char string1[20], temp;
int len,i,j;
clrscr();
printf(“Enter the string”);
scanf(“%s”,string1);
len=strlen(string1);
for(i=0,j=len-1;i<len,j>(len-1)/2;i++,j--)
{ temp=string1[i];
string1[i]=string1[j];
string1[j]=temp;
}
printf(“The reversed string is %s”,string1);
getch();
}

 To calculate the sum of two 2X2 matrices

#include<stdio.h>
#include<conio.h>
void main()
{ int a[2][2],b[2][2],c[2][2],i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number"); scanf("%d",&a[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",a[i][j]); printf("\n");
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number"); scanf("%d",&b[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",b[i][j]); printf("\n");
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",c[i][j]); printf("\n\n");
}
getch();
}

To multiply two 2X2 matrices

#include<stdio.h>
#include<conio.h>
void main()
{ int a[2][2],b[2][2],c[2][2],i,j,k;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number of matrix a");
scanf("%d",&a[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
printf("\n"); }
printf("\n\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number of matrix b");
scanf("%d",&b[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",b[i][j]);
printf("\n"); }
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ c[i][j]=0;
for(k=0;k<2;k++)
{ c[i][j]=(c[i][j]+(a[i][k]*b[k][j]));
}
}
}
}
}
printf("\n\n");
printf("\nThe multiplication of matrix a and matrix b is:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
getch();
}

To find the power of user input number

#include<stdio.h>
#include<conio.h>
int power(int,int);
void main()
{ int n,p;
clrscr();
printf("enter the base number");
scanf("%d",&n);
printf("Enter the power number");
scanf("%d",&p);
printf("\n%d^%d is %d\n",n,p,power(n,p));
getch();
}
int power(intn,int p)
{ int i;
int c=n;
for(i=1;i<p;i++)
n=n*c;
return n;
}

 To display the user input sentences removing all the spaces

#include<stdio.h>
#include<conio.h>
void main()
{ char line[50],c;
int i=0;
printf(“Enter the sentence:\n”);
gets(line);
while((c=(line[i++]))!=‘.’)
{ if(c==‘ ’)
continue;
else
printf(“%c”,c);
}
printf(“.”);
getch();
}

To count the number of words in a sentence

#include<stdio.h>
#include<conio.h>
void main()
{ char line[80],c;
int i=0,j=1;
printf(“Enter the sentence:”);
gets(line);
while((c=(line[i++]))!=‘.’)
{ if(c==‘ ’)
j=j+1;
}
printf(“\n%d”,j);
getch();
}

Use of pointer passing by reference

#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{ int a=6,b=10;
swap(&a,&b);
printf("The values after swapping are a=%d,b=%d",a,b);
getch();
}
void swap(int*a,int*b)
{ int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}

Use of pointer passing by value

#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
{ int a=6,b=10;
swap(a,b);
getch();
}
void swap(inta,int b)
{ int temp;
temp=a;
a=b;
b=temp;
printf("The value after swapping are a=%d and b=%d",a,b);
}

To enter the details of a book and display it using structure

#include<stdio.h>
#include<conio.h>
void main()
{ struct book
{ charbookname[1];
char author[1];
char publisher[1];
intrate,page;
};
int i;
struct book b1[1];
for(i=0;i<1;i++)
{ printf("\nenter the bookname:");
scanf("%s",b1[i].bookname);
printf("\nenter the author name");
scanf("%s",b1[i].author);
printf("\nenter the publisher name");
scanf("%s",b1[i].publisher);
printf("\nenter the rate");
scanf("%d",&b1[i].rate);
printf("\nenter the page no");
scanf("%d",&b1[i].page);
}
printf("\nbookname\tauthorname\tpublishername\trate\tpageno.");
for(i=0;i<1;i++)
printf("\n%s\t\t%s\t\t%s\t\t%d\t%d\t",b1[i].bookname,b1[i].author,b1[i].publ
isher,b1[i].rate,b1[i].page);
getch();
}

To enter the detail of a person and store the record in a file

#include<stdio.h>
void main()
{ FILE *file;
file=fopen(“abc.txt”, “a+”);
char name[15], add[15];
//reading the file
while(!feof(file))
{ fscanf(file, “\n%s”,name);
printf(“\n%s”,name);
fscanf(file,”\t\t%s”,add);
printf(“\t\t%s”,add);
}
// ading new record
printf(“\n\n Enter name”\n”);
scanf(“%s”,name);
fprintf(file,”\n%s”,name);
printf(“\n Enter addres:\n”);
scanf(“%s”,add);
fprintf(file,”\t\t%s”,add);
fclose(file);
}

To draw a line

#include<stdio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm; initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}


To draw a Circle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
circle(200,200,100);
setcolor(WHITE);
getch();
closegraph();
}

To draw a rectangle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
rectangle(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}

To draw a triangle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(200,100,200,300);
line(200,100,400,300);
line(200,300,400,300);
setcolor(WHITE);
getch();
closegraph();
}



MORE………………..



Switch case statement


 Switch case statement

The switch-case  statement is a multi way decision that tests whether an expression matches one of the number of constant expression and branches accordingly. switch case statements are a substitute for long if statements. The basic format for using switch case is outlined below.
Switch (expression or variable)               
{               
 case constant-expr1:          
   statement sequence;         
  break;       
 case constant-expr2:          
   statement sequence;
  break;               
 case : constant-expr3: 
  statement sequence;
  break;       
  ...          
 default:              
  statement sequence;  
}
The expression or variable has a value. The case says that if the expression or variable has value which  is after that cases then execute the statements that  follows the colon until the break is reached. Only one case is executed since only one value holds for expression or variable inside switch. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block .The break prevents the
program from testing the next case statement also.

            Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.
#include <stdio.h>     
#include <conio.h>     
void main()
{        
  int input;     
  printf("1. Play game");      
  printf("2. Load game");      
  printf("3. Play multiplayer");      
  printf("4. Exit");   
  scanf(“%d”,&input);   
  switch (input)       
  {        /*switch block starts */
   case 1: printf(“Play game is choosen”);  /*note use of  : and ; */
           break;       
   case 2:
           printf(“Load game is choosen”);     
        break; 
   case 3:              
         printf(“Play multiplayer is choosen”);
          break;       
   case 4:
         exit(0);
  default:       
        printf(“Error, bad input “);  
  }         /* end of switch */
  }        /* end of main() */

Another example:
/* this program takes input a alphabetic character and determines that either the character is vowel or consonant  and if other character is found than letter it gives appropriate message */

#include<stdio.h>
void main()
{
 char ch;
 printf(“\nEnter  a character:”);
 scanf(“%c”,&ch);
 if((ch>=’A’&&ch<=’Z’)||(ch>=’a’&&ch<=’z’))
 {
  printf(“This is alphabetic character.”);
  switch(ch)
  {
   case ‘A’: case ‘a’:
   case ‘E’: case ‘e’:
   case ‘I’: case ‘i’:
   case ‘O’: case ‘o’:
   case ‘U’: case ‘u’:
    printf(“\nThe letter is vowel “);
   break;
   default: printf(“\nThe letter is consonant.”);
  }    /* end switch */
 } /*end if */
 else printf(“The character is not alphabetic.”);
}   /*end main() */

String


STRINGS
WHAT IS A STRING?
A string is a group of characters, usually letters of the alphabet. In order to format our printout in such a way that it looks nice, has meaningful names and titles to output of our program, we need the ability to output text data.
·         A complete definition of a string is a series of char type data terminated by a null character.
·         In C there is no special data types for strings, strings are just the array of characters terminated by null ‘\0’ character with ASCII value 0
·         For example, to hold a string of six characters, we need to declare an array of
      type char with seven elements. Arrays of type char are declared like arrays of
      other data types. For example, the statement char string[7]; used to hold six char
When C is going to use a string of data in some way, either to compare it with another string, output it, copy it to another string, or whatever, the functions are set up to do what they are called to do until a null, is detected.
Initializing Character Arrays (String)
·         Like other C data types, character arrays can be initialized when they are
           declared. Character arrays can be assigned values element by element, as shown
           here:
char string[10] = { `K', `a', `t', `h',  `m', `a', ‘n’, ‘d’, ‘u’,`\0' };
·         It's more convenient to use a literal string, which is a sequence of characters enclosed in double quotes:
char string[10] = "Kathmandu"; which is same as above.
·         If you don't specify the number of subscripts when you declare an array, the compiler calculates the size of the array for you. Thus, the following line creates and initializes an six-element array:
char string[] = "Patan";
Strings and Pointer
Since strings are stored in arrays of type char, with the end of the string marked by the null character. So the name of string always points the beginning of the string. We can use array name to access that string. To pass a string to any functions, we pass the array name. The same is true of the string display functions printf() and puts()

Allocating Memory for string:
Static allocation: Declaring string as array
Dynamic Allocation : Declaring string as pointer.

The start of a string is indicated by a pointer to a variable of type char. So we can declare the string with pointer as:
char *str;
This statement declares a pointer to a variable of type char named str. It doesn't point to anything now, but what if we changed the pointer declaration to read
char *str = "This is a string declaration.";
When this statement executes, the string "This is a string declaration." (with a terminating null character) is stored somewhere in memory, and the pointer str is initialized to point to the first character of the string. We needn't worry where in memory the string is stored; it's handled automatically by the compiler.
The preceding declaration/initialization is equivalent to the following, and the two notations *str and str[] also are equivalent; they both mean "a pointer to.".
The malloc() Function
The malloc() function is one of C's memory allocation functions. When we call malloc(), we pass it the number of bytes of memory needed. malloc() finds and reserves a block of memory of the required size and returns the address of the first byte in the block. We don't need to worry about where the memory is found; it's handled automatically. The malloc() function returns an address, and its return type is a pointer to type void. A pointer to type void is compatible with all data types. Because the memory allocated by malloc() can be used to store any of C's data types, the void return type is appropriate.
#include <stdlib.h>
void *malloc(size_t size);
malloc() allocates a block of memory that is the number of bytes stated in size. By allocating memory as needed with malloc() instead of all at once when a program starts, we can use a computer's memory more efficiently. When using malloc(), we need to include the STDLIB.H header file. Some compilers have other header files that can be included; for portability, however, it's best to include STDLIB.H.
malloc() returns a pointer to the allocated block of memory. If malloc() was unable to allocate the required amount of memory, it returns null. Whenever we try to allocate memory, we should always check the return value, even if the amount of memory to be allocated is small.
An example:
#include <stdlib.h>
#include <stdio.h>
void main()
{
   /* allocate memory for a 100-character string */
   char *str;
   if (( str = (char *) malloc(100)) == NULL)
   {
     printf( "Not enough memory to allocate \n");
     exit(1);
   }
   printf( "String was allocated!"\n );
}


Displaying Strings
String display is usually done with either the puts() function or the printf() function.
The puts() Function
The puts() function puts a string on-screen--hence its name. A pointer to the string to be displayed is the only argument puts() takes. puts() can be used to display literal strings as well as string variables. The puts() function automatically inserts a newline character at the end of each string it displays, so each subsequent string displayed with puts() is on its own line.
/* Demonstrates displaying strings with puts(). */

  #include <stdio.h>

  char *message1 = "C";
  char *message2 = "is the";
  char *message3 = "best";
  char *message4 = "programming";
  char *message5 = "language!!";

  main()
  {
     puts(message1);
     puts(message2);
     puts(message3);
     puts(message4);
     puts(message5);

    return 0;
 }

output
C
is the
best
programming
language!!
The printf() Function
            The printf() function can be used to display literal strings as well as string variables but it prints all the string in one line until the \n character is encountered. It takes the argument either literal string or control character %s and corresponding string variable(pointer)
            Example
 char *str = "A message to display";
printf("%s", str);
or
printf(“A message to display “);

Inputting Strings Using the gets() Function
The gets() function gets a string from the keyboard. When gets() is called, it
reads all characters typed at the keyboard up to the first newline character (which we generate by pressing Enter). This function discards the newline, adds a null character, and gives the string to the calling program. The string is stored at the location indicated by a pointer to type char passed to gets(). A program that uses gets() must #include the file STDIO.H.
an example.
 /* Demonstrates using the gets() library function. */

  #include <stdio.h>

  /* Allocate a character array to hold input. */

  char input[81];

  main()
 {
     puts("Enter some text, then press Enter: ");
     gets(input);
     printf("You entered: %s\n", input);
     puts(input);

     return 0;
 }
output
Enter some text, then press Enter:
This is a test
You entered: This is a test
This is a test
Inputting Strings Using the scanf() Function
To read a string, include the specifier %s in scanf()'s format string. Like gets(), scanf() is passed a pointer to the string's storage location.
scanf(“%s”, str);  equivalent to  gets(str);
We can read in multiple strings with scanf() by including more than one %s in the format string. For each %s in the format string, scanf() uses the same  rules as printf() to find the requested number of strings in the input.
For example:
scanf("%s%s%s", s1, s2, s3);

Some useful String Handling functions in C library:
 Header file: <string.h>

  • strlen(s) returns the length of string ‘s’ without taking into account the terminal ‘\0’
  • srtcpy(s1,s2): copies the string s2 to string s1.
/* Demonstrates strlen() and  strcpy().  */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
 void  main()
 {
    char dest1[80];    /*array declaration */
     char dest2;      /* Pointer declaraction */
    printf("\nsource: %s", source );
    printf(“\n Length of source string is %d”, strlen(source));
/*must allocate memory for dest2 since declaration is pointer type */
  /* Copy to dest1 is okay because dest1 points to  80 bytes of allocated space. */
     strcpy(dest1, source);
     printf("\ndest1:  %s", dest1);

     /* To copy to dest2 you must allocate space. */
    dest2 = (char *)malloc(strlen(source) +1);
     strcpy(dest2, source);
     printf("\ndest2:  %s\n", dest2);

}
Output
source: The source string.
Length of Source string is  18
dest1:  The source string.
dest2:  The source string.
  • strcat(s1,s2) : appends string ‘s2’ at the end of  ‘s1’. It also called concatenation. So strcat(s1,s2) concats the strings s1 and s2.
/* Demonstration of the strcat() function. */

  #include <stdio.h>
  #include <string.h>
  char str1[27] = "a";
  char str2[2];
 void main()
 {
     int n;
     /* Put a null character at the end of str2[]. */
     str2[1] = `\0';
     for (n = ‘b’; n<=’z’; n++)
     {
         str2[0] = n;
         strcat(str1, str2);
         puts(str1);
     }
}
The output:
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
abcdefghijk
abcdefghijkl
abcdefghijklm
abcdefghijklmn
abcdefghijklmno
abcdefghijklmnop
abcdefghijklmnopq
abcdefghijklmnopqr
abcdefghijklmnopqrs
abcdefghijklmnopqrst
abcdefghijklmnopqrstu
abcdefghijklmnopqrstuv
abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvwxy
abcdefghijklmnopqrstuvwxyz
  • strcmp(s1, s2) : Compares two strings ‘s1’ and ‘s2’ and returns negative, zero or positive if  ‘s1’ is less than , equal or greater then the string ‘s2’ . It compares all the characters of one string one by one with character of other string. If all the characters of both string  are same, returns 0 . if at any point the characters are different,  it returns the difference of two characters.
  • strncpy(s1,s2,n) : copies first n characters from string s2 to string s1. If string s2 is less than n characters, then the entire string s2 will be copied to s.
/* demo of strncpy() */
#include <stdio.h>
#include <string.h>

  char dest[] = "##########################";
  char source[] = "abcdefghijklmnopqrstuvwxyz";

void  main()
 {
     int  n;
     while (1)
     {
         puts("Enter the number of characters to copy (1-26)");
         scanf("%d", &n);
         if (n > 0 && n< 27)
             break;
     }
    printf("\nBefore strncpy destination = %s", dest);
    strncpy(dest, source, n);
     printf("\nAfter strncpy destination = %s\n", dest);
  }
Enter the number of characters to copy (1-26)
15
Before strncpy destination = ##########################
After strncpy destination = abcdefghijklmno###########

  • strncat(s1,s2,n) : concatenates first n characters of string s2 with string s1.
/* The strncat() function. */

  #include <stdio.h>
  #include <string.h>
  char str2[] = "abcdefghijklmnopqrstuvwxyz";
  main()
  {
     char str1[27];
     int n;
     for (n=1; n< 10; n++)
     {
         strcpy(str1, "");
         strncat(str1, str2, n);
         puts(str1);
     }
 }
The output:
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
  • strncmp(s1,s2,n): compares at most n characters of string s2 with string s1.

  • srdup(s): The library function strdup() is similar to strcpy(), except that strdup()
performs its own memory allocation for the destination string with a call     
to malloc().

/* The strdup() function. */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
  main()
  {
     char *dest;
     if ( (dest = strdup(source)) == NULL)
     {
         printf( "Error allocating memory.");
         exit(1);
     }
     printf("The destination = %s\n", dest);
     return(0);
 }

The destination = The source string.
ANALYSIS: In this program  strdup() allocates the appropriate memory for dest. It then makes a copy of the passed string, source. Line 18 prints the duplicated string.

The Scope and life time of variables in functions


The Scope and life time of variables in functions:
What is scope and lifetime ?
                 The scope of a variable refers that to which different parts of a program have access to the variable in  other words, where the variable is visible. When speaking about scope, the term variable refers to all C data types: simple variables, arrays, structure, pointers, and so forth. It also refers to symbolic constants defined with the const keyword.
The life time of variable refers that how long the variable persists in memory, or when the variable's storage is allocated and de-allocated. Depending upon the scope and lifetime of variable, C has its  four storage classes for variables used in any functions.
  1. Automatic variables
  2. External variables
  3. Static variables
  4. Register variables
The variables may broadly categorized , depending upon the place of their declaration as: internal(local) or External(global).
·         The internal(local) variables are those which are declared inside the function.
·         The external(global) variables are those which are declared outside the  function.
Automatic variables:
            An automatic variable is defined inside the main() or function program. It is created when the function is called and get distroyed when the function segment is exited. Thus the visibility and lifetime of automatic variable is limited to the function execution. The key word ‘auto’ is used to declare the automatic variable. It is declared as:
auto  data_type  variable_name;
            Generally the keyword auto maybe dropped out. The variable declared inside function are default automatic if not any other keywords are used. These are also called local variables.
e.g.
            main()
           {
               int num;        /* num is automatic variable */
                ……..
            }
External variable:
            The external variables are declared outside the main or function block. These variables are set up memory immediately on the declaration and remain active for the entire period of program execution. Its visibility(scope) is that of the source file. It they are not initialized then they are automatically initialized to zero values. External variables are accessed by all the functions in the program. These variables are also known as global variables.
            The keyword ‘extern’ is used  to declare these variables. But it is optional. We can use extern to avoid confusion.
  extern  data_type  variable_name;
e.g.   int  sum,difference;        /* external variable */
         char name[10];
         main()
  {
     ……..
  }

Static variable:
            Static variables are generally defined inside main() or function block with keyword ‘static’ prefixed to it. They are sometimes called static auto variables as they have visibility of local (or auto) variables  and lifetime of external ( or global ) variables. Static variables are initialized once during the first function call.  These variables are declared as
static data_type  variable_name;
e.g. static int counter;

Register variables:
            If we want to tell the compiler that a variable should be kept in one of the machine’s register instead of keeping in the memory( where normal variables are stored), variables should be declared as register. The register access is much faster than memory. So keeping frequently access variables in register makes the execution of program faster. The declaraction is done as:
 register  data_type variable_name;
e.g.  register int count;
Only a few variables can be stored in register. However C compiler converts register variables into non register variables once the limit is reached.

Statements, Expressions, and Operators


Statements, Expressions, and Operators
 
            C programs consist of statements, and most statements are composed of
expressions and operators. We need to understand these three topics in order to
be able to write C programs.
Statements
            A statement is a complete direction instructing the computer to carry out some task. In C, statements are usually written one per line, although some statements span multiple lines. C statements always end with a semicolon (except for preprocessor directives such as #define and #include.
For example:        x = 2 + 3;
is an assignment statement. It instructs the computer to add 2 and 3 and to assign the result to the variable x.

Statements and White Space
            The term white space refers to spaces, tabs, and blank lines in the source code. The C compiler isn't sensitive to white space. When the compiler reads a statement in the source code, it looks for the characters in the statement and for the terminating semicolon, but it ignores white space. Thus, the statement
     x=2+3;
is equivalent to this statement:
     x = 2 + 3;
It is also equivalent to this:
x        =
2
+
3;

This gives us a great deal of flexibility in formatting our source code. We shouldn't use formatting like the previous example, however. Statements should be entered one per line with a standardized scheme for spacing around variables and operators.  The point is to keep our source code readable.
However, the rule that C doesn't care about white space has one exception: Within literal string constants, tabs and spaces aren't ignored; they are considered part of the string. A string is a series of characters. Literal string constants are strings that are enclosed within quotes and interpreted literally by the compiler, space for space. Although it's extremely bad form, the following is legal:
printf(
"Hello, world!"
);

This, however, is not legal:
printf("Hello,
world!");

To break a literal string constant line, you must use the backslash character
(\) just before the break. Thus, the following is legal:
printf("Hello,\
world!");

Null Statements
If we place a semicolon by itself on a line, we create a null statement i.e. a statement that doesn't perform any action. This is perfectly legal in C. Later
  Eg,  the null statement is:            ;
Compound Statements
A compound statement, also called a block, is a group of two or more C statements
enclosed in braces. Here's an example of a block:
{
    printf("Hello, ");
    printf("world!");
}

In C, a block can be used anywhere a single statement can be used. Note that the enclosing braces can be positioned in different ways. The following is equivalent to the preceding
example:
{printf("Hello, ");
printf("world!");}

It's a good idea to place braces on their own lines, making the beginning and end of blocks clearly visible. Placing braces on their own lines also makes it easier to see whether we've left one out. But if  there are large number of statements inside the block , it is not possible to place braces in one lines.
Notes:
·         DO put block braces on their own lines. This makes the code easier to read.
·         DO line up block braces so that it's easy to find the beginning and end of a
      block.
·         DON'T spread a single statement across multiple lines if there's no need to do
      so. Limit statements to one line if possible.



Expressions
In C, an expression is anything that evaluates to a numeric value. C expressions come in all levels of complexity.
Simple Expressions
The simplest C expression consists of a single item: a simple variable, literal
constant, or symbolic constant. Here are four expressions:
      Expression                        Description
      PI                          A symbolic constant (defined in the program)
      20                          A literal constant
      rate                                    A variable
      -1.25                      Another literal constant

A literal constant evaluates to its own value. A symbolic constant evaluates to the value it was given when we created it using the #define directive. A variable evaluates to the current value assigned to it by the program.
Complex Expressions
Complex expressions consist of simpler expressions connected by operators.
For example:
2 + 8
is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. The expression 2 + 8 evaluates 10. we  can also write C expressions of great complexity:

1.25 / 8 + 5 * rate + rate * rate / cost

Consider the following statement:
x = a + 10;
            This statement evaluates the expression a + 10 and assigns the result to x. In addition, the entire statement x = a + 10 is itself an expression that evaluates to the value of the variable on the left side of the equal sign.
Thus, we can write statements such as the following, which assigns the value of the expression
a + 10 to both variables, x and y as:
y = x = a + 10;
We can also write statements such as this:
x = 6 + (y = 4 + 5);
 All of these are complex expression.
Operators
An operator is a symbol that instructs C to perform some operation, or action, on one or more operands. An operand is something that an operator acts on. In C, all operands are expressions. C operators fall into several categories:
·         The assignment operator
·         Mathematical operators
·         Relational operators
·         Logical operators
·         Conditional operators
·         Special operator
·         Cast operator
·         Bitwise operator
The Assignment Operator
The assignment operator is the equal sign (=). Its use in programming is somewhat different from its use in regular math. If we write
x = y;
in a C program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to x." In a C assignment statement, the right side can be any expression, and the left side must be a variable name. Thus, the form is as follows:
variable = expression;
When executed, expression is evaluated, and the resulting value is assigned to variable.


Mathematical Operators
C's mathematical operators perform mathematical operations such as addition and subtraction. C has two unary mathematical operators and five binary mathematical operators.
Unary Mathematical Operators
The unary mathematical operators are so named because they take a single operand. C has two unary mathematical operators
Table : C's unary mathematical operators.
      Operator
Symbol
Action
Examples
      Increment
++
Increments the operand by one
++x, x++
      Decrement
--
Decrements the operand by one
--x, x--

The increment and decrement operators can be used only with variables, not with constants. The operation performed is to add one to or subtract one from the operand. In other words, the statements
++x; --y;
are the equivalent of these statements:
x = x + 1;    y = y - 1;
We  should note from above Table that either unary operator can be placed before its operand (prefix mode) or after its operand (postfix mode). These two modes are not equivalent. They differ in terms of when the increment or decrement is performed:  When used in prefix mode, the increment and decrement operators modify their   operand before it's used.   When used in postfix mode, the increment and decrement operators modify their   operand after it's used.
For example : Consider following statements:
x = 10;
y = x++;
After these statements are executed, x has the value 11, and y has the value 10. The value of x was assigned to y, and then x was incremented. In contrast, the following statements result in both y and x having the value 11. x is incremented, and then its value is assigned to y.
x = 10;
y = ++x;

 illustrates the difference between prefix mode and postfix mode increment.
  /* Demonstrates unary operator prefix and postfix modes */
  #include <stdio.h>
  int a, b;
  main()
  {
      /* Set a and b both equal to 5 */
      a = b = 5;
      /* Print them, decrementing each time. */
      /* Use prefix mode for b, postfix mode for a */
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d", a--, --b);
    printf("\n%d   %d\n", a--, --b);
   return 0;
}
output:
5    4
4    3
3    2
2    1
1    0
ANALYSIS: This program declares two variables, a and b, the variables are set to the value of 5. With the execution of each printf() statement , both a and b are decremented by 1. a is decremented after it  is printed,whereas b is decremented before it is printed.

Binary Mathematical Operators
C's binary operators take two operands. The binary operators, which include the common mathematical operations
Table  C's binary mathematical operators.
      Operator
Symbol
Action
Example
      Addition
+
Adds two operands
x + y
      Subtraction
-
Subtracts the second operand from the first operand
x - y
      Multiplication
*
Multiplies two operands
x * y
      Division
/
Divides the first operand by the second operand
x / y
      Modulus
%
Gives the remainder when the first operand is divided by the second operand
x % y

The first four operators listed in Table  should be familiar to us in general mathematics. The fifth operator, modulus operator  returns the remainder when the first operand is divided by the second operand. For example, 11 modulus 4 equals 3 . Here are some more examples:
100 %9 equals 1          10 %5 equals 0            40 % 6 equals 4

An example to illustrate the  modulus operator to convert a large number of seconds into hours, minutes, and seconds.
   /* Inputs a number of seconds, and converts to hours, minutes, and seconds. */

#include <stdio.h>
                                        /* Define constants */
#define SECS_PER_MIN 60
#define SECS_PER_HOUR 3600

unsigned int seconds, minutes, hours, secs_left, mins_left;

main()
{
          /* Input the number of seconds */
  printf("Enter number of seconds (< 65000): ");
  scanf("%d", &seconds);

  hours = seconds / SECS_PER_HOUR;
  minutes = seconds / SECS_PER_MIN;
  mins_left = minutes % SECS_PER_MIN;
  secs_left = seconds % SECS_PER_MIN;
  printf("%u seconds is equal to ", seconds);
  printf("%u h, %u m, and %u s\n", hours, mins_left,secs_left);

  return 0;
}
Enter number of seconds (< 65000): 60
60 seconds is equal to 0 h, 1 m, and 0 s
Enter number of seconds (< 65000): 10000
10000 seconds is equal to 2 h, 46 m, and 40 s

Operator Precedence and Parentheses
In an expression that contains more than one operator, then the precedence plays the important role for evaluation. Precedence is the  order in which operations are performed.
e.g. x = 4 + 5 * 3;
Performing the addition first results in the following, and x is assigned the value 27:
x = 9 * 3;
 if the multiplication is performed first,  x is assigned the value 19:
x = 4 + 15;

So  some rules are needed about the order in which operations are performed. This order, called operator precedence, is strictly spelled out in C. Each operator has a specific precedence. When an expression is evaluated, operators with higher precedence are performed first. Following Table lists the precedence of C's mathematical operators. Number 1 is the highest precedence and
thus is evaluated first.
Table : The precedence of C's mathematical operators.
      Operators
Relative Precedence
      ++          --
1
      *    /    %
2
      +     -
3

So  in any C expression, operations are performed in the following order:
  Unary increment and decrement
  Multiplication, division, and modulus
  Addition and subtraction
If an expression contains more than one operator with the same precedence level, the operators are performed in left-to-right order as they appear in the expression. For example, in the following expression, the % and * have the same precedence level, but the % is the leftmost operator, so it is performed first:
12 % 5 * 2
A sub-expression enclosed in parentheses is evaluated first, without regard to operator precedence. Thus, you could write
x = (4 + 5) * 3;

The expression 4 + 5 inside parentheses is evaluated first, so the value assigned to x is 27.
We can use multiple and nested parentheses in an expression. When parentheses are nested, evaluation proceeds from the innermost expression outward. Look at the following complex expression:
x = 25 - (2 * (10 + (8 / 2)));
The evaluation of this expression proceeds as follows:
  1. The innermost expression, 8 / 2, is evaluated first, yielding the value 4: 25 - (2 * (10 + 4))
  2. Moving outward, the next expression, 10 + 4, is evaluated, yielding the   value 14: 25 - (2 * 14)
  3. The last, or outermost, expression, 2 * 14, is evaluated, yielding the   value 28: 25 - 28
  4. The final expression, 25 - 28, is evaluated, assigning the value -3 to the   variable x: x = -3

Order of Subexpression Evaluation
C expressions contain more than one operator with the same precedence level, they are evaluated left to right. For example, in the expression
w * x / y * z
w is multiplied by x, the result of the multiplication is then divided by y, and the result of the division is then multiplied by z.
Look at this expression: and try to understand the order of evaluation
w * x / y + z / y
w * x / ++y + z / y
Notes:
·         DO use parentheses to make the order of expression evaluation clear.
·         DON'T overload an expression. It is often more clear to break an expression into two or more statements. This is especially true when you're using the unary operators (--) or (++).

Relational Operators
C's relational operators are used to compare expressions, asking questions such as, "Is x greater than 100?" or "Is y equal to 0?" An expression containing a relational operator evaluates to either true (1) or false (0). .
Table  C's relational operators.
Operator
Symbol
Question Asked
Example
      Equal
==
Is operand 1 equal to operand 2?
x == y
      Greater than
> 
Is operand 1 greater than operand 2?
x > y
      Less than
< 
Is operand 1 less than operand 2?
x < y
      Greater than or equal to
>=
Is operand 1 greater than or equal to operand 2?
x >= y
      Less than or equal to
<=
Is operand 1 less than or equal to operand 2?
x <= y
      Not equal
!=
Is operand 1 not equal to operand 2?
x != y

Table: Relational operators in use.
      Expression
How It Reads
What It Evaluates To
      5 == 1
Is 5 equal to 1?
0 (false)
      5 > 1
Is 5 greater than 1?
1 (true)
      5 != 1
Is 5 not equal to 1?
1 (true)
      (5 + 10) == (3 * 5)
Is (5 + 10) equal to (3 * 5)?
1 (true)




The if Statement(Conditional Statements)
Relational operators are used mainly to construct the relational expressions used in if and while statements. Consider the basics of the if statement to show how relational operators are used to make program control statements.
In its basic form, the if statement evaluates an expression and directs program execution depending on the result of that evaluation. The form of an if statement is as follows:
if (expression)
    statement;
If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed. In either case, execution then passes to whatever code follows the if statement. We can say that execution of statement depends on the result of expression. Both the line if (expression) and the line statement; are considered to comprise the complete if statement; they are not separate statements. An if statement can control the execution of multiple statements through the use of a compound statement, or block. A block can be used anywhere a single statement can be used. Therefore, We can write an if statement as follows:
if (expression)
{
    statement1;
    statement2;
    /* additional code goes here */
    statementn;
}

 An if statement should always end with the conditional statement that follows it. In the following, statement1 executes whether or not x equals 2, because each  line is evaluated as a separate statement, not together as intended:
if( x == 2);          /* semicolon does not belong!  */
statement1;

   An example to demonstrate the use of if statements

   #include <stdio.h>

   int x, y;

   main()
   {
       /* Input the two values to be tested */

      printf("\nInput an integer value for x: ");
      scanf("%d", &x);
      printf("\nInput an integer value for y: ");
      scanf("%d", &y);

      /* Test values and print result */

      if (x == y)
          printf("x is equal to y\n");

      if (x > y)
          printf("x is greater than y\n");

      if (x < y)
          printf("x is smaller than y\n");

      return 0;
  }
Input an integer value for x: 100
Input an integer value for y: 10
x is greater than y
Input an integer value for x: 10
Input an integer value for y: 100
x is smaller than y
Input an integer value for x: 10
Input an integer value for y: 10
x is equal to y

The else Clause
An if statement can optionally include an else clause. The else clause is included as follows:
if (expression)
    statement1;
else
    statement2;

If expression evaluates to true, statement1 is executed. If expression evaluates to false, statement2 is executed. Both statement1 and statement2 can be compound statements or blocks.
An example to demonstrates the use of if statement with else clause

   #include <stdio.h>

   int x, y;

   main()
   {
       /* Input the two values to be tested */

      printf("\nInput an integer value for x: ");
      scanf("%d", &x);
      printf("\nInput an integer value for y: ");
      scanf("%d", &y);

      /* Test values and print result */

      if (x == y)
          printf("x is equal to y\n");
      else
          if (x > y)
              printf("x is greater than y\n");
          else
              printf("x is smaller than y\n");

      return 0;
  }
Input an integer value for x: 99
Input an integer value for y: 8
x is greater than y
Input an integer value for x: 8
Input an integer value for y: 99
x is smaller than y
Input an integer value for x: 99
Input an integer value for y: 99
x is equal to y

The if Statement
Form 1
if( expression )
    statement1;
next_statement;
This is the if statement in its simplest form. If expression is true, statement1 is executed. If expression is not true, statement1 is ignored. And next statement is executed.
Form 2
if( expression )
    statement1;
else
    statement2;
next_statement;
This is the most common form of the if statement. If expression is true, statement1 is executed; otherwise, statement2 is executed.
Form 3
if( expression1 )
    statement1;
else if( expression2 )
    statement2;
else
    statement3;
next_statement;

This is a nested if. If the first expression, expression1, is true, statement1 is executed before the program continues with the next_statement. If the first expression is not true, the second expression, expression2, is checked. If the first expression is not true, and the second is true, statement2 is executed. If both expressions are false, statement3 is executed. . There may be any no of such if statements Only one of the them statements is executed before next statement.
Example 1
if( salary > 45,0000 )
    tax = 0.30*salary;
else
    tax = 0.25*salary;

Example 2
if( age < 13 )
    printf("Child");
else if( age <=19 )
    printf("Teen");
else if(age<65)
    printf(“Adult”);
else
    printf( "Senior Citizen");

Evaluating Relational Expressions
 Relational expressions evaluate to a value of either false (0) or true (1). Although the most common use of relational expressions is within if statements and other conditional constructions, they can be used as purely numeric values.
An example: Demonstrates the evaluation of relational expressions

   #include <stdio.h>
   int a;
   main()
   {
       a = (5 == 5);                 /* Evaluates to 1 */
      printf("\na = (5 == 5) evaluates a = %d", a);

      a = (5 != 5);                 /* Evaluates to 0 */
      printf("\na = (5 != 5) evaluatesa = %d", a);

      a = (12 == 12) + (5 != 1); /* Evaluates to 1 + 1 */
      printf("\na = (12 == 12) + (5 != 1) evaluates a = %d\n", a);
      return 0;
  }
a = (5 == 5) evaluates  a = 1
a = (5 != 5) evaluates a = 0
a = (12 == 12) + (5 != 1)  evaluates a = 2


The Precedence of Relational Operators
Like the mathematical operators, the relational operators each have a precedence that determines the order in which they are performed in a multiple-operator expression. Similarly, We can use parentheses to modify precedence in expressions that use relational operators.
First, all the relational operators have a lower precedence than the mathematical operators. Thus, if we write the following, 2 is added to x, and the result is compared to y:
if (x + 2 > y)
This is the equivalent of the following line, which is a good example of using parentheses for the sake of clarity:
if ((x + 2) > y)
Although they aren't required by the C compiler, the parentheses surrounding (x + 2) make it clear that it is the sum of x and 2 that is to be compared with y.
There is also a two-level precedence within the relational operators, as shown
in Table below:
Table : The order of precedence of C's relational operators.
      Operators
Relative Precedence
      < <= > >=
1
      != ==
2

Thus, if we write            x == y > z
it is the same as           x == (y > z)  because C first evaluates the expression y > z, resulting in a value of 0 or 1. Next, C determines whether x is equal to the 1 or 0 obtained in the first step.

Note:
·         DON'T put assignment statements in if statements.
·         DON'T use the "not equal to" operator (!=) in an if statement containing an else. It's almost always clearer to use the "equal to" operator (==) with an        else. For instance, the following code:
if ( x != 5 )
   statement1;
else
   statement2;

  would be better written as this:
if (x == 5 )
   statement2;
else
   statement1;
Logical Operators
Sometimes we need to ask more than one relational question at once.  C's logical operators let us combine two or more relational expressions into a single expression that evaluates to either true or false. .
Table  C's logical operators.
      Operator
Symbol
Example
      AND
&&
exp1 && exp2 e.g. ( num>100)&&(num%2==0)
      OR
||
exp1 || exp2           e.g. (num<100)||(num%2!=0)
      NOT
!
!exp1        e.g. num!=5


  C's logical operators in use.
      Expression
What It Evaluates To
      (exp1 && exp2)
True (1) only if both exp1 and exp2 are true; false (0) otherwise
      (exp1 || exp2)
True (1) if either exp1 or exp2 is true; false (0) only if both are false
      (!exp1)
False (0) if exp1 is true; true (1) if exp1 is false

We  can see that expressions that use the logical operators evaluate to either true or false, depending on the true/false value of their operand(s). Following Table shows some actual code examples.
Table  Code examples of C's logical operators.
      Expression
What It Evaluates To
      (5 == 5) && (6 != 2)
True (1), because both operands are true
      (5 > 1) || (6 < 1)
True (1), because one operand is true
      (2 == 1) && (5 == 5)
False (0), because one operand is false
      !(5 == 4)
True (1), because the operand is false

We can create expressions that use multiple logical operators. For example, to ask the question "Is x equal to 2, 3, or 4?"  We write
(x == 2) || (x == 3) || (x == 4)

The logical operators often provide more than one way to ask a question. If x is an integer variable, the preceding question also could be written in either of the following ways:
(x > 1) && (x < 5)
(x >= 2) && (x <= 4)

More on True/False Values
C's relational expressions evaluate to 0 to represent false and to 1 to represent true,however,  any numeric value is interpreted as either true or false when it is used in a C expression or statement that is expecting a logical value (that is, a true or false value).
The rules are as follows:
·         A value of zero represents false.
·         Any nonzero value represents true.
This is illustrated by the following example, in which the value of x is printed:
x = 125;
if (x)
   printf("%d", x);    /*   prints 125 */
Because x has a nonzero value, the if statement interprets the expression (x) as true. You can further generalize this because, for any C expression, writing
if(expression)
is equivalent to writing
if(expression != 0)
Both evaluate to true if expression is nonzero and to false if expression is 0. Using the not (!) operator, we can also write
if(!expression)
which is equivalent to
if(expression == 0)

The Precedence of Operators
The ! operator has a precedence equal to the unary mathematical operators ++ and --. Thus, ! has a higher precedence than all the relational operators and all the binary mathematical operators.
In contrast, the && and || operators have much lower precedence, lower than all the mathematical and relational operators, although && has a higher precedence than ||.
 As with all of C's operators, parentheses can be used to modify the evaluation order when using the logical operators. Consider the following example:
We want to write a logical expression that makes three individual comparisons:
  1. Is a less than b?
  2. Is a less than c?
  3. Is c less than d?
we want the entire logical expression to evaluate to true if condition 3 is true and if either condition 1 or condition 2 is true. You might write
a < b || a < c && c < d
However, this won't do what we  intended. Because the && operator has higher precedence than ||, the expression is equivalent to
a < b || (a < c && c < d)
and evaluates to true if (a < b) is true or both a<c and c<d are true. So we need to write
(a < b || a < c) && c < d
which forces the || to be evaluated before the &&.
An example to demostrate Logical operator precedence.
   #include <stdio.h>

   /* Initialize variables. Note that c is not less than d, */
   /* which is one of the conditions to test for. */
   /* Therefore, the entire expression should evaluate as false.*/

   int a = 5, b = 6, c = 5, d = 1;
   int x;
  main()
  {
      /* Evaluate the expression without parentheses */
      x = a < b || a < c && c < d;
      printf("\nWithout parentheses the expression evaluates as %d", x);
      /* Evaluate the expression with parentheses */
     x = (a < b || a < c) && c < d;
      printf("\nWith parentheses the expression evaluates as %d\n", x);
      return 0;
  }
Without parentheses the expression evaluates as 1
With parentheses the expression evaluates as 0


Compound Assignment Operators
C's compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation. For example, if we want to increase the value of x by 5, or, in other words, add 5 to x and assign the result to x. we can write
x = x + 5;
Using a compound assignment operator, which you can think of as a shorthand method of assignment, we can write
x += 5;
In more general notation, the compound assignment operators have the following syntax (where op represents a binary operator):
exp1 op= exp2
This is equivalent to writing
exp1 = exp1 op exp2;
We can create compound assignment operators using the five binary mathematical operators defined before.
Table : Examples of compound assignment operators.
      When we Write This.
It Is Equivalent To This
      x *= y
x = x * y
      y -= z + 1
y = y - z + 1
      a /= b
a = a / b
      x += y / 8
x = x + y / 8
      y %= 3
y = y % 3


The Conditional Operator
The conditional operator is C's only ternary operator, meaning that it takes three operands. Its syntax is
exp1 ? exp2 : exp3;
If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. For example, the following statement
assigns the value 1 to x if exp is true and assigns 100 to x if exp  is false:
x = exp ? 1 : 100;
Likewise, to make z equal to the larger of x and y, we can write
z = (x > y) ? x : y;

Conditional operator functions somewhat like an if statement. The preceding statement could also be written like this:
 if(exp)x = 1; else x=100;
and
if (x > y)
z = x;
else
z = y;

The conditional operator can't be used in all situations in place of an if...else construction, but the conditional operator is more concise. The conditional operator can also be used in places you can't use an if statement, such as inside a single printf() statement:
printf( "The larger value is %d", ((x > y) ? x : y) );

Special Operator: The Comma Operator
The comma is frequently used in C as a simple punctuation mark, serving to separate variable declarations, function arguments, and so on. In certain situations, the comma acts as an operator rather than just as a separator. We can form an expression by separating two sub-expressions with a comma. The result is as follows:
             Both expressions are evaluated, with the left expression being evaluated first.The entire expression evaluates to the value of the right expression.
For example, the following statement assigns the value of b to x, then increments a, and then increments b:
x = (a++ , b++);

Because the ++ operator is used in postfix mode, the value of b,before it is incremented,is assigned to x. Using parentheses is necessary because the comma operator has low precedence, even lower than the assignment operator. The use of comma operator is used in for looping construct as:
 for(n=1,m=10;n<=m;n++,n++)

exchanging values:  t = x,x = y,y = t;

     The other types of special operators used in C are pointer operators(&,*), member operators(.and ->),function operator (), array operator []etc.

The Cast operator:
            C supports another type of operator for data conversion. The cast operator are used to type cast for the data. Once a data are defined as one type and need to convert in to another during calculation rather changing the actual value of the variable , we need to cast operators.
The cast operator is nothing but just the type keyboard of the dada type as int,float,double etc.
The syntax for type casting is
(type-name)expression
 where type-name is one of the C data type. The expression may be constant, variable or any expression. Some example of casts and their action are shown in table below
Table: to show the use of cast operator:
Example
Action
x = (int)7.5
7.5 is converted to integer by truncation
a = (int)21/(int)4.5
Evaluates as 21/4 result is 5
b = (float)sum/n
Division is done in floating point mode
y = (int)(a+b)
The result of a+b is converted in to integer
c=(char)87
returns the character whose ASCII code is 87



Bitwise Operators:
C has special  operators for bit oriented programming known as bitwise operators. They are used for manipulating data in bit level. These are used to testing the bits or shifting the bits left or right.
Bitwise operators are not applied to float and double. Following table shows the bitwise operators and their meanings.
Table: Bitwise operator
Operator
Meaning
&
bitwise AND
|
bitwise OR
^
bitwise X-OR
<< 
shift left
>> 
shift right
~
one’s complement