Thursday, December 29, 2011

POINTER

Introduction

Pointer is one of the smartest and strongest part of C. To understand pointer we just have to revise the BASICS part of our blog like

Declaration

Any Variables used in a program has to be declared before using it in a statement and while declaration we can also initialize it.
For example :
                       int a = 5 ;

int is one of that 32 keywords, ' a ' is the variable which is initialized with value 5.

Now int a = 5 ; means that the compiler will allocate space in memory to store the integer number 5 and assign the variable name ' a ' with it as shown below :
There are thousands of memory blocks and each of them has a location number or we can call it an address. That location number always is a whole number. Here 1310588 is the address of the variable ' a '. 
%u is used to print the variable address.
    For example :

    #include "stdio.h"
    main()
    {
            int a=5;

            printf("Value of a = %d  \n", a);

            printf("Address of a = %u  \n\n\n", &a);
    }

    The & "address of" operator is also used before the variable name just like in case of scanf().

    We can also store the address of ' a ' into another variable ' b ', we just have to declare ' b ' as a pointer variable. Syntax for pointer is very simple that is :

    int *b = &a ;

    * is called "value at address"

    int *b ; does not mean that b is declared as integer, it means that b is going to store the address of a variable whose value is an integer number. Because memory location numbers are always a whole number.
    For example :

    #include "stdio.h"
    main()
    {
        int a=5;
        int *b = &a ;

        printf("Address of a = %u  \n\n",&a);
        printf("Address of b = %u  \n\n",&b);

        printf("Value of a = %d  \n\n",a);

        printf("Value at b = %d  \n\n",*b);  /* b is a pointer variable which means
                                                                  b is pointing towards a. */

        printf("Value of b = %u ie address of a  \n\n",b);
        printf("Value of b = %d ie address of a  \n\n",b);
    }

    After executing the program the following output will be shown :

    Note that the variable address will not be same in other computers.

    A pointer variable can also be declared as :

    int **c=&b;

    where **c is a pointer to an integer pointer.
    For example :

    #include"stdio.h"
    void main()
    {
        int a=5;
        int *b=&a;
        int **c=&b;

        printf("Address of a = %u \n\n",&a);
        printf("Address of b = %u \n\n",&b);
        printf("Address of c = %u \n\n",&c);

        printf("--------------------------------------------- \n\n");

        printf("a = %d , *b = %d , **c = %d  \n\n", a, *b, **c);

        printf("&a = %u , b = %u , *c = %u  \n\n", &a, b, *c);

        printf("*c = %u , c = %u , &c = %u  \n\n", *c, c, &c);

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

    After executing the program the following output will be shown :


    float and char :

    #include"stdio.h"
    void main()
    {
        float a=5.5;
        char b='x';
        float *az=&a;
        char *bz=&b;

        printf("a = %f  \n",*az);
        printf("b = %c  \n",*bz);
    }

    Addition of Two Numbers :

    #include"stdio.h"
    void main()
    {
        int a=5;
        int b=5;
        int *az=&a;
        int *bz=&b;
        int c = *az + *bz;
        printf("Answer = %d  \n",c);
    }

    Now Getting Back To Functions :

    Call By Value

    #include"stdio.h"
    void swap (int, int);
    main()
    {
        int a,b;

        printf("Enter value for A : ");
        scanf("%d",&a);

        printf("Enter value for B : ");
        scanf("%d",&b);

        swap(a,b);  //  Here only the values of ' a ' and ' b ' are passed

        printf("Now See This ! \n");
        printf("\nA=%d    B=%d  \n\n",*(&a),*(&b));
    }

    void swap (int a, int b)
    {
        int c;
        c=a;
        a=b;
        b=c;

        printf("\nFrom Function ! \n");
        printf("\nA=%d    B=%d  \n\n",a,b);
    }

    Call By Reference

    #include"stdio.h"
    void swap (int *, int *);
    main()
    {
        int a,b;

        printf("Enter value for A : ");
        scanf("%d",&a);

        printf("Enter value for B : ");
        scanf("%d",&b);

        swap(&a,&b);  //  Here the address of ' a ' and ' b ' are passed

        printf("Now See This ! \n");
        printf("\nA=%d    B=%d  \n\n",*(&a),*(&b));
    }

    void swap (int *a, int *b)
    {
        int c;
         c=*a;
        *a=*b;
        *b=c;

        printf("\nFrom Function ! \n");
        printf("\nA=%d    B=%d  \n\n",*a,*b);
    }

    • So with the help of pointer we can directly hit the address of a variable and make changes from another function.
    • A Function returns a single value, with the help of this we can manipulate more than one variables.
    For example :

    #include"stdio.h"
    void cal (int, int, int *, int *);
    main()
    {
        int a, b, sum, sub;

        printf("Enter value for A : ");
        scanf("%d",&a);

        printf("Enter value for B : ");
        scanf("%d",&b);

        cal(a,b,&sum, &sub);

        printf("A + B = %d  \n", sum);
        printf("A - B = %d  \n", sub);
    }

    void cal (int a, int b, int *sum, int *sub)
    {
        *sum=a+b;
        *sub=a-b;
    }



    Saturday, December 24, 2011

    FUNCTIONS

    Introduction

    Each functions have their own nature of work like the task of pow(x,y) function is to take two parameters or arguments (x,y) and return a value that is x to the power y, pow() is defined under  math.h header file. Function of sqrt(x) is to take a value and return its square root. The function name should be unique.
    main() itself is a function, the program execution starts from main(). We can write it as void main(), int main() etc.
    The keyword void means it will not return a value and the keyword return is used to pass a value from function body to the main() or any other calling program.
    printf() and scanf() are standard library functions. Here we will be creating user defined functions.

    Usually structure of functions looks like this :
    • no return type   function_name   ( no parameter )
    • no return type   function_name   ( with parameter)
    • return type        function_name   ( with parameter)
    return type or parameters can be a int, float, char, array etc.

    Syntax for Function is :

    #include"stdio.h"

    void function_name(void);   //  Function Prototype

    main()
    {
        statement 1;
        statement 2;

        function_name();  //  Call of Function

        statement 3;      //  After the execution of the function next statement will be executed.
    }

    void function_name()   // Function Definition or Body, here the function is defined.
    {
        statement 1;
        statement 2;
        statement 3;
    }


    Example :

    #include"stdio.h"
    void test(void);
    main()
    {
        printf("I am inside main function ! \n");
        test();
        printf("I am inside main function ! \n");;
        test();
        printf("I am inside main function ! \n");
        test();
        printf("DONE ! \n");
    }

    void test()
    {
        printf("I am inside test function ! \n");
    }

    Another example :

    #include"stdio.h"
    void printline(void);
    main()
    {
        printf("1st line:\n");
        printline();
        printf("2nd line:\n");
        printline();
        printf("3rd line:\n");
        printline();
    }

    void printline()
    {   
        int i;

        for( i=0 ; i<60 ; i++ )
            printf("_");

        printf("\n");
    }

    We can also send a single value or multiple values to a function as a parameter or argument.
    For example :

    #include"stdio.h"
    void sum(int,int);
    void main()
    {
        int a,b;

        printf("Enter 2 Numbers : ");
        scanf("%d%d",&a,&b);

        sum(a,b);
    }

    void sum(int a,int b)
    {   
        int i;
        i=a+b;
        printf("The sum of %d and %d (which came from the main()) is %d \n",a,b,i);
    }

      The keyword return passes the result to the calling program.
      For example :

      #include"stdio.h"
      int sum(int,int);
      void main()
      {
          int a,b,c;

          printf("Enter 2 Numbers : ");
          scanf("%d%d",&a,&b);

          c=sum(a,b);

          printf("The sum of %d and %d is %d \n",a,b,c);
          printf("The sum of %d and %d is %d \n",a,b,sum(a,b));
      }

      int sum(int a,int b)
      {
          int i;
          i=a+b;
          return (i); // or we can write it as return(a+b);
      }

      Multiple Functions in a Program :

      #include"stdio.h"
      int sum(int,int);
      int sub(int,int);
      int mult(int,int);
      int div(int,int);
      void printline();
      void main()
      {
          int a,b;

          printf("Enter 2 Numbers:");
          scanf("%d%d",&a,&b);

              printline();
              printf("ADD = %d\n",sum(a,b));
              printline();
              printf("SUB = %d\n",sub(a,b));
              printline();
              printf("MULT = %d\n",mult(a,b));
              printline();
              printf("DIV = %d\n",div(a,b));
              printline();
      }

      int sum(int a,int b)
      {
          return (a+b);
      }

      int sub(int a,int b)
      {
          return (a-b);
      }

      int mult(int a,int b)
      {
          return (a*b);
      }

      int div(int a,int b)
      {
          return (float(a/b));
      }

      void printline()
      {
          int i;
          for( i=0 ; i<60 ; i++ )
              printf("_");
          printf("\n");
      }

      Demo of getchar, getche, getch Functions :

      #include"stdio.h"
      #include"conio.h"  //  To use this functions we have to include conio.h file
      void main()
      {
          char ch;

          printf("Enter a Letter : ");

          ch=getchar();

          printf("\nCh = %c \n",ch);

          ch=getche();

          printf("\nCh= %c \n",ch);

          ch=getch();

          printf("\nCh= %c \n\n",ch);
      }

      Recursion

      A function calling itself is called Recursion.

      Call By Value

      Till now we had been passing the value of a variable to a function, which can be said as call by value.
      For example :
      sum ( a, b ) ;  //  Values of a and b are passed to the function sum().

      Call By Reference

      Each variable are stored in memory and holds a value. We can also pass the address of that memory location to a function which can be said as call by reference.
      For example :
      sum ( address of a, address of b ) ; /* Address of a and b are passed to the function sum().*/

      To know more about this we have to understand Pointer.


      Thursday, December 22, 2011

      SWITCH CASE STATEMENTS

      Introduction

      In short instead of using many if else statements in a program we can use Switch Case statements.
      For example:

      #include"stdio.h"
      main()
      {
          int a;

          printf("Just Enter a Number : ");
          scanf("%d",&a);

          if ( a == 1)
              printf("You Entered 1 ! \n");

          else if ( a == 2)
              printf("You Entered 2 ! \n");

          else if ( a == 3)
              printf("You Entered 3 ! \n");

          else if ( a == 4)
              printf("You Entered 4 ! \n");

             /* So On.............
             .......................*/

          else
              printf("Your Entry was Wrong !\n");
      }

      We can also write the program in the following way :

      #include"stdio.h"
      main()
      {
          int a;

          printf("Just Enter a Number : ");
          scanf("%d",&a);

          switch(a)
          {
          case 1:
              printf("You Entered 1 ! \n");
              break;

          case 2:
              printf("You Entered 2 ! \n");
              break;

          case 3:
              printf("You Entered 3 ! \n");
              break;

          case 4:
              printf("You Entered 4 ! \n");
              break;

          default:
              printf("Your Entry was Wrong ! \n");
              break;       
          }
      }

      Syntax for switch case is :

      switch ( integer variable )
          {

          case ( option 1 ) :

                  statement 1;
                  statement 2;
                  break;

          case ( option 2 ):

                  statement 1;
                  statement 2;
                  break;

          case ( option 3 ) :

                  statement 1;
                  statement 2;
                  break;

          case ( option 4 ) :

                  statement 1;
                  statement 2;
                  break;

          default :
                  default statement;
                  break;

          }

      Here the options under cases are dependent on the integer variable under switch.
      If the value of the variable matches with the case value then the statements under that case will be executed.
      For example :

      #include"stdio.h"
      main()
      {
          switch ( 65 )
          {
          case 32:
              printf("Case 32 !\n");
              break;

          case 65:
              printf("This one will be executed !\n");
              break;

          case 100:
              printf("Case 100 !\n");
              break;
          }
      }

      The Output will be : This one will be executed !

      break has to be written under every statements inside a case. If we do not put it then the next case statement will also be executed.
      For example :

      #include"stdio.h"
      main()
      {
          switch ( 65 )
          {

          case 32:
              printf("Case 32 !\n");
              break;

          case 65:
              printf("This one will be executed !\n");
              // Without break;

          case 100:
              printf("Case 100 !\n");
              break;
          }
      }

      The Output will be : This one will be executed !
                                    Case 100 !

      If no values are matched with switch and case then the statement under default will be executed.
      For example :

      #include"stdio.h"
      main()
      {
          switch ( 2 )
          {
          case 32:
              printf("Case 32 !\n");
              break;

          case 65:
              printf("This one will be executed !\n");
              break;

          case 100:
              printf("Case 100 !\n");
              break;
         
          default:
              printf("Default statement !\n");
              break;
          }
      }

      The Output will be : Default statement !

      Few More Examples

      #include"stdio.h"
      main()
      {
          int a,b,c,r;

          printf("Enter 2 Numbers:");
          scanf("%d%d",&a,&b);

          printf("\n1...ADD:");
          printf("\n2...SUB:");
          printf("\n3...MUL:");
          printf("\n4...DIV:");

          printf("\nEnter your choice (1/2/3/4) : ");
          scanf("%d",&c);

          switch(c)
          {
          case 1: r=a+b;
              printf("ANSWER = %d\n",r);
              break;

          case 2: r=a-b;
              printf("ANSWER = %d\n",r);
              break;

          case 3: r=a*b;
              printf("ANSWER = %d\n",r);
              break;

          case 4: r=(float)a/b;
              printf("ANSWER = %d\n",r);
              break;

          default:
              printf("Wrong Entry !\n");
              break;
          }
      }

      A Very Useful Program :

      #include"stdio.h"
      main()
      {
          int flag=1;

          while(flag==1)
          {

              static int totalbalance=100;
              int deposit,withdraw,cal;

              printf("\n1...DEPOSIT");
              printf("\n2...WITHDRAWL");
              printf("\n3...ENQUIRY");
              printf("\n4...EXIT \n");   

              printf("\nPlease Enter Your Choice (1/2/3/4) : ");
              scanf("%d",&cal);

              switch(cal)
              {
              case 1:

                  printf("\nDEPOSIT \n");
                  printf("ENTER AMOUNT : ");
                  scanf("%d",&deposit);
                  totalbalance=totalbalance+deposit;
                  printf("TOTAL BALANCE = %d\n",totalbalance);   
                  break;

              case 2:

                  printf("\nWITHDRAWL \n");
                  printf("ENTER AMOUNT : ");
                  scanf("%d",&withdraw);
             
                  if(withdraw>totalbalance)
                      printf("\nYOU DO NOT HAVE ENOUGH BALANCE !\n");
                  else
                  {
                      totalbalance=totalbalance-withdraw;
                      printf("\nTOTAL BALANCE = %d\n",totalbalance);
                  }
                  break;

              case 3:

                  printf("\nTOTAL BALANCE = %d\n",totalbalance);
                  break;

              case 4:
                  printf("\nTHANK YOU !\n\n");
                  flag=0;
                  break;

              default:
                  printf("\nWRONG ENTRY !\n");
                  break;   
              }
          }
      }


      Saturday, December 17, 2011

      LOOP

      Introduction

      I will always do my home work !
      When there is a provision of printing it 100 times with the help of a program.
      Either we can do it in the following way :

      #include"stdio.h"
      main()
      {
          printf("I will always do my home work ! \n");
          printf("I will always do my home work ! \n");
          printf("I will always do my home work ! \n");
          /*...................
          .....................
          .....................
          till 100 times */
      }

      Or do it in this way :

      #include"stdio.h"
      main()
      {
          int i=1;

          while(i<=100)
          {
              printf("I will always do my home work ! \n");
          i++;
          }
      }

      Loop is used to repeat a single or a set of statements several times in a program. Statement inside {} of  any loop will remain executed until the condition gets false.There are three kinds of Loops, which are :
      • while
      • for
      • do while 

      While Loop

      Syntax for while is :

          while(condition)
          {
              Statement 1;
              Statement 2;

          increment;
          }


      For example :

      #include"stdio.h"
      main()
      {
          int counter, i=1;

          printf("Enter a Number : ");
          scanf("%d",&counter);

              while(i<=counter)
              {
                  printf("%d I Wanted to Repeat This Statement %d times \n",i,counter);

              i++;
              }

          printf("Out from the loop ! \n");
          printf("Now the statements here will be executed once ! \n");
          printf("Because we are out from the while loop ! \n");
      }

      If we have to exit from a loop on a certain condition then we have to use a keyword called break
      For example :

      #include"stdio.h"
      main()
      {
          int i=1;

          printf("The loop will run till 100 ! \n");

              while(i<=100)
              {
                  printf("i = %d I am inside the loop but will exit when value of i becomes 50 \n",i);

                  if(i==50)
                  {
                      printf("Good Bye Friends ! \n");
                      break;  // Exit from the loop
                  }

              i++;
              }

          printf("Out from the loop ! \n");
      }

      Opposite of break is continue which is also a keyword.

      For Loop

      Function of for is also same as while but the syntax is different as shown below :

          for ( initialization ; condition ; increment )
              {
                      statement 1 ;
                      statement 2 ;
              }

      Lets construct the previously made programs with the help of for.

      #include"stdio.h"
      main()
      {
          int counter, i;

          printf("Enter a Number : ");
          scanf("%d",&counter);

              for(i=1;i<=counter;i++)
              {
                  printf("%d I Wanted to Repeat This Statement %d times \n",i,counter);
              }

          printf("Out from the loop ! \n");
          printf("Now the statements here will be executed once ! \n");
          printf("Because we are out from the for loop ! \n");
      }

      #include"stdio.h"
      main()
      {
          int i;

          printf("The loop will run till 100 ! \n");

              for(i=1;i<=100;i++)
              {
                  printf("i = %d I am inside the loop but will exit when value of i becomes 50 \n",i);

                  if(i==50)
                  {
                      printf("Good Bye Friends ! \n");
                      break;  // Exit from the loop
                  }
              }

          printf("Out from the loop ! \n");
      }

      Do While Loop

      Like in while and for, conditions are checked at the starting point of the loop but here it is checked at the ending point of the loop. That will make one difference that is for at least once the statements inside the loop will be executed and then the condition will be checked. Syntax for do while is :

          do
          {
              Statement 1;
              Statement 2;

          }while(condition);

      For example :

      Addition of Two Numbers :

      #include"stdio.h"
      main()
      {
          int a,b;
          char c='y';

          do
          {
              printf("Enter First Number : ");
              scanf("%d",&a);
              printf("Enter Second Number : ");
              scanf("%d",&b);
              printf("Addition of %d and %d is %d \n",a,b,a+b);

              printf("Want to continue(y/n) : ");
              fflush(stdin);
              scanf("%c",&c);

          }while(c=='y');
      }

      Here the program will not be terminated until we press any other key except "y". This kind of loop is also called as Odd Loop.

      Odd Loop

      In some programs we have to decide when to get exit from the loop during the run time, for this odd loops are created.
      For example :

      #include"stdio.h"
      main()
      {
          int i,f=0;

          do
          {

          printf("To Exit from this Loop a Negative Number has to be Entered : ");
          scanf("%d",&i);

              if(i>=1)
                  f=f+i;

          }while(i>=0);

      printf("Sum of all Positive Numbers You Entered is %d \n",f);
      }

      It can be done with for and while as well.

      Nested Loop

      There can be a loop inside a loop, just be careful with the braces {}, sometimes it gets confusing in case of a complicated program.
      Syntax for Nested While :

      while(condition)
      {

          while(condition)
          {
              Statement 1;
              Statement 2;
          }

      Statement 1;
      Statement 2;
      }

      Syntax for Nested For :

      for(condition)
      {

          for(condition)
          {
              Statement 1;
              Statement 2;
          }

      Statement 1;
      Statement 2;
      }

      Or all kinds of loops can be nested as well.

      For example :

      Multiplication of 1 to 20 :

      #include"stdio.h"
      main()
      {
          int cal, i, j=1, a=1;

          while(a<=20)
          {
              i=1;
              j=a;

              for(i=1;i<=10;i++)
              {
                  cal=j * i;
                  printf("%d * %d = %d \n",j,i,cal);

               }  //   End of For

          printf("\n");
          a++;

          }  //  End of While

          printf("Done \n");

      }  //  End of Main

      Lets add do while to it :

      #include"stdio.h"
      main()
      {
          char ch ='y';

          do
          {
              int cal, i, j=1, a=1;

              while(a<=20)
              {
                  i=1;
                  j=a;

                  for(i=1;i<=10;i++)
                  {
                      cal=j * i;

                      printf("%d * %d = %d \n",j,i,cal);

                  }

              printf("\n");
              a++;

               }

          printf("Want to run this again (y/n) : ");
          fflush(stdin);
          scanf("%c",&ch);

          }while(ch=='y');  //   End of do while

          printf("Finally Done \n");
      }

      Infinite Loop

      When the condition is not set or the variable is not initialized properly, the loop does not gets terminated and keeps on executing the statements under it.
      For example : (No need to run this two programs below)

      #include"stdio.h"
      main()
      {
          int i;

              for(i=1;  ;i++)
              {
                 printf("It will keep on Run ! \n");
                  printf("Cant Stop It \n");
              }
      }

      #include"stdio.h"
      main()
      {
              for(int i;i<=2;i++)
              {
                  printf("It will keep on Run ! \n");
                  printf("Cant Stop It \n");
              }
      }

      Few More Examples

      Addition of First 10 Numbers :

      #include"stdio.h"
      main()
      {
          int i,sum=0;

              for(i=1;i<=10;i++)
              {
                  sum=sum+i;
              }

          printf("Addition of First 10 Numbers is %d \n",sum);
      }

      First 10 Even Numbers :

      #include"stdio.h"
      main()
      {
          int i,sum=0;

          printf("First 10 Even Numbers are :");

          for(i=2;i<=10;i=i+2)
              {
                  printf(" %d, ",i);
              sum=sum+i;
              }

          printf("\nAddition of First 10 Even Numbers is %d \n",sum);
      }

      Display 10 to 1 :

      #include"stdio.h"
      main()
      {
          int i;

          printf("Display 10 to 1 :");
             
          for(i=10;i>=1;i--)
              {
                  printf(" %d, ",i);
              }
           printf("\n");
      }

      Reversed Number :

      #include"stdio.h"
      main()
      {
          int i,f=0;

          printf("Enter a Number : ");
          scanf("%d",&i);

          while(i>0)
          {
              f=f*10+i%10;
              i=i/10;
          }

          printf("Reversed Number is %d \n",f);
      }

      Print All Prime Numbers :

      #include"stdio.h"
      main()
      {
          int n,i=2,j;

          printf("Enter a Number : ");
          scanf("%d",&n);

          for(j=1;j<=n;j++)
          {
              i=2;
              while(i<j)
              {
                  if(j%i==0)
                  break;
              i++;
              }
                  if(i==j)
                  printf("%d, ",j);
          }
          printf("\n");
      }

      Factorial of a Number :

      #include"stdio.h"
      main()
      {
          int i,f=1;

          printf("Enter a Number : ");
          scanf("%d",&i);

          while(i>=1)
          {
              f=f*i;
          i=i-1;
          }

          printf("Factorial is %d \n",f);
      }

      Print 1 to 15 in a Different Way :

      #include"stdio.h"
      main()
      {
          int i,j;

          for(i=1;i<=15;i++)
          {
              for(j=1;j<i;j++)
                  printf("%d",j);

          printf("\n");
          }
      }

      Print ASCII :

      #include"stdio.h"
      main()
      {
          int i;

          printf("Print ASCII : ");

          for(i=0;i<=255;i++)
              printf("\n  %d = %c ",i,i);

          printf("\n");
      }

      Friday, December 16, 2011

      ASCII VALUE

      Introduction

      ASCII (American Standard Code for Information Interchange)
      Every character or number has there own ASCII value starting from 1 to 255. To see the ASCII value of a particular character through a C program we have to write a simple program.

      char ch='A'; means it is declared as a character. We can print this 'A' that is value of ch on screen with the help of %c like

      #include"stdio.h"
      main()
      {
          char ch='A';
          printf("ch is initialized with %c \n",ch);
      }

      To print its ASCII just replace %c with %d as shown below :

      #include"stdio.h"
      main()
      {
          char ch='A';
          printf("ASCII Value of 'A' is %d \n",ch);
      }

      Or it can be written as :

      #include"stdio.h"
      main()
      {
          char ch='A';
          printf("ASCII Value of %c is %d \n",ch,ch);
      }

      After a little modification the total program can be written as :

      #include"stdio.h"
      main()
      {
          char ch;
          printf("Hit Any Character : ");
          scanf("%c",&ch);

              printf("ASCII Value of %c is %d \n",ch,ch);
      }

      Uppercase Lowercase :

      There are 25 alphabets.
      • ASCII Value of "A" is 65 and "Z" is 90
      • ASCII Value of "a" is 97 and "z" is 122
      So the difference between uppercase "A" and lowercase "a" is 32 and even for rest of the alphabets, with the help of this we can transfer uppercase into lowercase or lower to upper vise verse.
      For example :

      #include"stdio.h"
      main()
      {
          char ch;
          printf("Enter a Character from A to Z or a to z : ");
          scanf("%c",&ch);

          if(ch>='A'&&ch<='Z')
              printf("You Entered '%c' Uppercase into Lowercase : %c \n",ch,(ch+32));

          else if(ch>='a'&&ch<='z')
              printf("You Entered '%c' Lowercase into Uppercase : %c \n",ch,(ch-32));

          else
              printf("Your Entry was Wrong ! \n");
      }

      Monday, December 12, 2011

      IF ELSE STATEMENTS

      Introduction

      C program cannot think ! but we can make it think to some extend with the help of if, else statement. Technically this both are keywords but holds a very important part in programming. With out if else no complicated program can be made easily. If statement gives power to a program to take decision, it instruct the compiler which set of instruction has to be executed. For that we have to know very few important things like 

      Relational Operator
      •  = =   Equal to
      • ! =     Not Equal to
      •  <      Less than
      •  >      Greater than
      •  <=    Less than or equal to
      •  >=   Greater than or equal to
      We can also use arithmetic expression in the if statement. A non-zero value is always true where as 0 is considered as false in C.
      Syntax for if statement is :

      if(a= =b)
      {
          statement 1;
          statement 2;
      }

      For more than one line statement {} braces are needed.
      if(Variable Name Relational Operator Variable Name)

      x = y means value of y goes to x.
      x= =y means value of x is equal to value of y.

      For example :

      #include"stdio.h"
      main()
      {
          int x=5, y=6;

              if(x == y)

                printf("Both are Equal Numbers\n");

              else

                printf("Both are Not Equal Numbers\n");
      }

      Output will be : Both are Not Equal Numbers

      x!=y means value of x is not equal to value of y.
      For example :

      #include"stdio.h"
      main()
      {
          int x=6, y=7;

              if(x != y)

                printf("Not Equal Numbers\n");

              else

                printf("Equal Numbers\n");
      }

      Output will be : Not Equal Numbers

      x<y means value of x is lesser than value of y.
      For example :

      #include"stdio.h"
      main()
      {
          int x=10, y=7;

              if(x < y)

                printf("X is Less Than Y\n");

              else

                printf("Y is Less Than X\n");
      }

      Output will be : Y is Less Than X

      x>y means value of x is greater than value of y.
      For example :

      #include"stdio.h"
      main()
      {
          int x=10, y=7;

              if(x > y)

                printf("X is Greater Than Y\n");

              else

                printf("Y is Greater Than X\n");
      }

      Output will be : X is Greater Than Y

      x<=y means value of x is lesser than or equal to value of y.
      For example :

      #include"stdio.h"
      main()
      {
          int x=10, y=7;

              if(x <= y)

                printf("X is Lesser or Equal to Y\n");

              else

                printf("X is Greater Than Y\n");
      }

      Output will be : X is Greater Than Y

      x>=y means value of x is greater than or equal to value of y.
      For example :

      #include"stdio.h"
      main()
      {
          int x=10, y=7;

              if(x >= y)

                printf("X is Greater or Equal to Y\n");

              else

                printf("Y is Greater Than X\n");
      }

      Output will be : X is Greater or Equal to Y

      Arithmetic Expression

      Inside if(....... ) Arithmetic Expression can be done.
      For example :

      #include"stdio.h"
      main()
      {
                 int x=2, y=3, z=10;

              if((x+2-2)*10 > (y*z)/2)
                 printf("X is Greater \n");

              else
                 printf("Y is Greater \n");
      }

      Output will be : X is Greater

      Which Entered Number is Greater :

      #include"stdio.h"
      main()
      {
          int a, b;
          printf("Enter First Number : ");
          scanf("%d",&a);
          printf("Enter Second Number : ");
          scanf("%d",&b);

              if(a>b)
                  printf("First Number is Greater\n");
              else
                  printf("Second Number is Greater\n");
      }

      This program will work right but if we feed two same number then second one will come which is not right. To make it right we can make a few add of statement like

      #include"stdio.h"
      main()
      {
          int a, b;

          printf("Enter First Number : ");
          scanf("%d",&a);
          printf("Enter Second Number : ");
          scanf("%d",&b);

              if(a>b)
                  printf("First Number is Greater\n");

              else
              {
                  if(a<b)
                      printf("Second Number is Greater\n");
                  else
                      printf("Both Numbers are Same\n");
              }
      }

      Or it can be written in the following way :

      #include"stdio.h"
      main()
      {
          int a, b;

          printf("Enter First Number : ");
          scanf("%d",&a);
          printf("Enter Second Number : ");
          scanf("%d",&b);

              if(a>b)
                  printf("First Number is Greater\n");
              else if(a<b)
                  printf("Second Number is Greater\n");
              else
                  printf("Both Numbers are Same\n");
      }

      Is the Entered Number Even or Odd :

      #include"stdio.h"
      main()
      {
          int a;
          printf("Enter a number : ");
          scanf("%d",&a);

              if(a%2==0)
                  printf("This Number is Even\n");
              else
                  printf("This Number is Odd\n");
      }

      Nested if else

      A set or more if else written under a if or else block is called Nested if else as shown below :

      Estimate a Person's Age :

      #include"stdio.h"
      main()
      {
          int a;
          printf("Enter the Age Please : ");
          scanf("%d",&a);

          if(a<=18)
                  printf("Child \n");
          else
          {
              if(a<=50)
                  printf("Adult \n");
              else
                  printf("Old \n");
          }
      }

      Below 1000 - No Discount
      Between 1001 to 2000 - 20% Discount
      Above 2001 - 30% Discount


      #include"stdio.h"
      main()
      {
          int amount;
          float discount;

          printf("Please Enter the Total Amount : ");
          scanf("%d",&amount);

          if(amount<=1000)
          {
              printf("Sorry No Discount \n");
          }   //  End of first if
          else
          {
               if(amount<=2000)
               {
                     discount =amount*20/100;
                     printf("You are getting Discount of $ %f \n",discount);
                }   //  End of second if
               else
               {
                      discount =amount*30/100;
                      printf("You are getting Discount of $ %f \n",discount);
                }   //  End of second else
           }   //  End of first else
      }   // End of main

      else if Clause

      Syntax for else if :

            if(condition 1)
              {
                  statement 1;
                  statement 2;
              }
            else if(condition 2)
              {
                  statement 1;
                  statement 2;
              }
            else if(condition 3)
              {
                  statement 1;
                  statement 2;
              }
            else if(condition 4)
              {
                  statement 1;
                  statement 2;
              }
            else
              {
                  statement 1;
                  statement 2;
              }

      Same work in a different style.
      For example :

      #include"stdio.h"
      main()
      {
          int num;

          printf("Just Enter a Number From 1 to 5 : ");
          scanf("%d",&num);
         
          if(num==1)
          {
              printf("You Entered : %d \n",num);
              printf("You Are In First Block \n");
          }
        else if(num==2)
          {
              printf("You Entered : %d \n",num);
              printf("You Are In Second Block \n");
          }
        else if(num==3)
          {
              printf("You Entered : %d \n",num);
              printf("You Are In Third Block \n");
          }
        else if(num==4)
          {
              printf("You Entered : %d \n",num);
              printf("You Are In Forth Block \n");
          }
        else
          {
              printf("You Entered : %d \n",num);
              printf("This is My Favorite ! \n");
          }
      }

      Logical Operator
      •    &&     AND
      •      ||       OR
      •      !       NOT
      One more important thing is Logical Operator. With the help of Logical Operators we can put two or more condition inside if like :

      AND (All conditions have to be true), the syntax is :

      if(num>=1 && num<=50)

      Example :

      #include"stdio.h"
      main()
      {
          int num;

          printf("Please Enter a Number : ");
          scanf("%d",&num);

          if(num<1)
              printf("Number You Entered Is Below 1 \n");
          else
          {

          if(num>=1 && num<=50)    // Here both the conditions have to be true.

              printf("Number You Entered Is From 1 to 50 \n");
          else
              printf("Number You Entered Is Above 50 \n");
          }
      }

      OR (Any one condition has to be true), the syntax is :

      if(num==1 || num==10 || num==100)

      Example :

      #include"stdio.h"
      main()
      {
          int num;

          printf("Please Enter a Number : ");
          scanf("%d",&num);

          if(num<1)
              printf("Number You Entered Is Below 1 \n");
          else
          {

          if(num==1 || num==10 || num==100)    // Here any one condition has to be true.

              printf("Number You Entered Is Either 1, 10 or 100 \n");
          else
              printf("Number You Entered Is Unknown to Us \n");
          }
      }

      NOT (Reverse the condition), the syntax is :

      if (!(num<=10))

      Example :

      #include"stdio.h"
      main()
      {
          int num;

          printf("Please Enter a Number : ");
          scanf("%d",&num);

          if(!(num<=10))    // Here the condition gets reversed.

              printf("Number You Entered Is Below 10 \n");
          else
              printf("Number You Entered Is Above 10 \n");
      }

      if(!(num<=10)) is same as if(num>10)

      Conditional Operator
      • ?
      • :
      Syntax is :

      Condition ? Result 1 : Result 2

      if Condition is true then Result 1 will be executed
      if Condition is false then Result 2 will be executed
      For example :

      #include"stdio.h"
      main()
      {
          int num;

          printf("How Much Can You Pay : ");
          scanf("%d",&num);

          (num>=1 && num<=100 ? printf("Sorry I am Busy \n") : printf("You are Welcome \n"));
      }

      num>=1 && num<=100 if this condition is true then
      printf("Sorry I am Busy \n") will be executed
      otherwise printf("You are Welcome \n") will be executed.

      #include"stdio.h"
      main()
      {
          char ch = 'y';

          printf("Am I Good ? (y/n) Enter y or n : ");
          scanf("%c",&ch);

          (ch=='y' ? printf("You Are My Friend \n") : printf("You Could Be My Friend \n"));
      }

      Conditional Operators can also be nested and arithmetic expression
      can also be done inside.

      Thursday, December 01, 2011

      BASICS

      Introduction

      C is a programming language which was developed by Dennis Ritchie at Bell Laboratory in 1972. Many parts of Windows, Unix, Linux are written in C. In the programming world C holds a major part. To learn C#, C++ or Java one must know C well.

      First Program :

      #include"stdio.h"
      main()
      {
             printf("Hello Friends ! \n");
      }

      Compile the program and then execute it.

      #include"stdio.h"

      It is a pre-processor directive, to use some functions like printf(), scanf() etc this directive is used. This should be written at the beginning of the program.

      main()

      All sets of statements are written under main() function starting with { and closing with }
      For example :
                                    main()
                                    {
                                        statement 1 ;
                                        statement 2 ;
                                    }

      printf()

      This is a function which is always used to achieve the output to the screen.
      For example :
                            printf("Hello");         // Only Hello will be displayed.

                            printf("\nHello");      /* Hello will be displayed in the next line.
                                                               \n is called new line. */

                            printf("\nSum of 1+1 = %d ",1+1);   // Sum of 1+1 will be displayed.

      In C all statements are ended with ; or it can be called as statement terminator after that we can write anything for our own understanding just putting  // before the line. For multi-line comment we can write within :
         /*
             As much
             line we can
             write.
         */

      There are 32 keywords in C which are :

      auto           break          case              char
      const        continue      default             do
      double        else           enum             extern
      float            for             goto                if
      int              long           register           return
      short         signed         sizeof             static
      struct         switch        typedef           union
      unsigned     void           volatile            while

      Among which break, case, char, default, do, double, else, float, for, goto, if, int, long, return, short, switch, void and while are very commonly used keyword in basic programming.

      Declaration

      Besides keyword there are Constant and Variables. Any Variables used in a program has to be declared before using it in a statement and while declaration we can also initialize it.
      For example :
                             int a = 5 ;
      • int is one of that 32 keywords, ' a ' is the variable which is initialized with value 5.
      • So a short definition of int would be, it is used to declare a variable which will be initialized with a whole number.
      • Just like that, float is used to declare a variable which will be initialized with a decimal number.
      • And char is used to declare a variable which will be initialized with a single character.
      • Memory allocation for int is 2 byte, float is 4 byte and char is 1 byte.
      • Variable names should not be same with each other in a program.
      Time for few examples :

      #include "stdio.h"
      main()
      {
              int a ;

              printf("Value of a = %d \n",a);   // A garbage value will be displayed.

              a= 5;   // a is initialized with a integer value.

              printf("After initializing value of a = %d \n", a);

              float b = 5.5;   // b is initialized with a decimal value.

              printf("Value of b = %f \n", b);

              char c = 'x';   // c is initialized with a single character.
                                  //  That single character should be written within ' '

              printf("Value of c = %c \n", c);

      }

      After executing the program the following output will be shown :


      Same program above can also be done in different way as shown below :

      #include "stdio.h"
      main()
      {
              int a;
              float b = 5.5;
              char c = 'x';

              printf("Value of a = %d \n",a);

              a= 5;

       printf("After initializing value of a = %d \nValue of b = %f \nValue of c = %c \n", a, b, c);

      }

      The output will be same.

      • %d is used to print integer value.
      • %f is used to print real value.
      • %c is used to print character.
      For example :

      #include "stdio.h"
      main()
      {
              int a=5;
              float b = 5.5;
              char c = 'x';

              printf("  %d  \n  %f   \n  %c  \n  ", a, b, c);

      }

      Here %d is responsible for a, %f for b and %c for c.
      Variable names should be written respectively.

      printf("  %f  \n  %d   \n  %c  \n  ", b, a, c);   // is correct.
      printf("  %d  \n  %f   \n  %c  \n  ", b, a, c);   // is wrong, it will not show any syntax error but values will be displayed wrong.

      Addition, Subtraction, Multiplication and Division of Two Numbers :

      #include "stdio.h"
      main()
      {
              int a, b, c;

              a=10;
              b=5;

              c=a+b;
              printf("a + b is = %d \n", c);

              c=a-b;
              printf("a - b is = %d \n", c);
             
              c=a*b;
              printf("a * b is = %d \n", c);

              c=a/b;
              printf("a / b is = %d \n", c);
       }

      Or in short it can be written as :

      #include "stdio.h"
      main()
      {
              int a=10, b=5;
               
      printf("a + b is = %d \na - b is = %d \na * b is = %d \na / b is = %d \n", a+b,a-b,a*b,a/b);

      }

      In both the cases output will be same.

      When we can't estimate whether the processing result will be real or integer in case of division, we can write the program as shown below :

      #include "stdio.h"
      main()
      {
              int a=26, b=5, c;   // c is declared as integer.
              c=a/b;
              printf("a / b is = %f \n",(float)c);
      }

      scanf()

      As we know printf() is used to output the result on sceen like that scanf() is used to take input from keyboard while the program is running.
      Syntax for scanf() is :

      scanf("%d",&a);

      Here every thing are familiar with us except & which is called ampersand which has to be given before the variable name. It gives the location of the variable where the value taken from keyboard has to be assigned.
      For example :

      #include "stdio.h"
      main()
      {
              int i;
              printf("Enter a integer number for i : ");
              scanf("%d",&i);
              printf("Integer number is : %d \n ", i);
      }

      If i was declared as float then the statement would be :
      scanf("%f",&i);

      Some Examples of Basic Programs

      Swap of Two Numbers :

      #include"stdio.h"
      main()
      {
          int a,b,c;

          printf("Enter value for A : ");
          scanf("%d",&a);

          printf("Enter value for B : ");
          scanf("%d",&b);

          c=a;
          a=b;
          b=c;

          printf("\nA=%d    B=%d \n",a,b);
      }

      Converting Degrees From Fahrenheit to Centigrade :

      #include"stdio.h"
      main()
      {
          int f;
          float c;

          printf("Enter value in Fahrenheit : ");
          scanf("%d",&f);

          c=5*(f-32)/9;

          printf("Centigrade : %f \n",c);
      }

      Demo of Power Function :

      #include"stdio.h"
      #include"math.h"
      main()
      {
          int a,b,c;

          printf("Enter value in A : ");
          scanf("%d",&a);

          printf("Enter value in B : ");
          scanf("%d",&b);

          c=pow(a,b);
          printf("A (%d) to the power B (%d) is: %d \n",a,b,c);
      }

      pow(x,y) is a function which is defined under "math.h" header file, to use this function in a program we have to include that header file at the beginning just like "stdio.h".

      Demo of Square Root Function :

      #include"stdio.h"
      #include"math.h"
      main()
      {
          int a;
          float c;
          printf("Enter a Number : ");
          scanf("%d",&a);

          c=sqrt(a);
          printf("Square Root of %d is %f \n",a,c);
      }

      This function is also defined under math header file, to use this "math.h" has to be included at the beginning of the program.

      Increment :

      #include"stdio.h"
      main()
      {
          int a=1,b=1;

          printf("Value of A is : %d \nValue of B is : %d \n",a,b);
       
          a++;   // Post Increment
          ++b;   // Pre Increment

          printf("After Increment \n");
          printf("Value of A is : %d \nValue of B is : %d \n",a,b);
      }

      a=a+1; can also be written as a++; or ++a which are called Post Increment and Pre Increment respectively.

      Followers