Social Icons

Monday, December 24, 2012

For loop in C

for loop is also a kind of loop and used to execute a block of code for a specified number of times. It is the most widely used loop.


Syntax of 'for' loop


           for(initialization counter;loop condition;increment counter)
           {
                --------------------------------
                Some code to execute
                --------------------------------
           }


 Explanation of the syntax:


 There are 3 parts in the for loop written in a single line itself. They are:
  •  initialization counter - It is used to initialize the counter before execution of the loop starts.
  • loop condition - As the loop condition will be true, the execution of the loop will be continued. Its execution will be stopped when the loop condition is false.
  • increment counter - It is used to increase or decrease the value of counter each time after the end of each loop iteration. In other words, it will increase(or decrease) every time after the f block of code inside for loop will execute once.


 Now, lets see an example of for loop with a program.


 WAP to print numbers between 1 to 100 using for loop.


      #include<stdio.h>
      void main()
      {
           int i=1;
           for(i=1;i<100;i++)
           {
                 printf("%d\t",i);
           }
       }


   Explanation for the program:


           Here, we have initialized a variable i and set its value equal to 1. Now, it will come in for loop statement. Firstly, the initialization counter is there i.e, i=1. Then, it will check for the loop condition as i<100 i.e, currently 1<100 which is true. Then, it will execute the block of code written inside for loop i.e, printf statement. Now, it will print the value of i. Then, it will go to for loop statement again and will increase the value of i by 1 as i++ is there. So, now i=2. Again, it will check 2<=100 i.e, true. And value of i will be printed. Similarly, it will print from 1 to 100. \t is provided in the print statement as provide a tab space between each number.

Wednesday, December 19, 2012

do while loop in C

In the previous chapter, we read about while loop and its working. Herein this chapter, we shall read about the next loop in C i.e, do while loop. This loop is similar to while loop. But, the only difference is that do while loop at least execute the block of code once irrespective of the condition either true or false. In do while loop, firstly the block of code gets executed then the evaluation of condition takes place. If the condition is true then the block of code will again execute.


Syntax of do while Loop


            do
            {
                   --------------------------
                   Some Statements
                   --------------------------
            }
            while(condition);
             
Above is the syntax for do while loop. Now lets understand it with an example program.


 WAP to print 1 to 10 using 'do while' loop


          #include<stdio.h>
          void main()
          {
                 int no = 10, i=0;
                 do
                 {
                        i++;
                        printf("%d \n",i);
                 }
                 while(i < no);
          }


 Output :  1
                2
                3
                4
                5
                6
                7
                8
                9
                10


 Explanation for the above program:
 
                Here, we have taken two integer variables as no(//number) and i. Variable no is initialized to 10 and variable i is initialized to 0 as you can see in the program.  Then, it will come inside do and perform i++ i.e, value of i will be incremented by 1.  In the next line, with the printf statement, it will print the value of i i.e, 1 and goes to next line as \n is there. Now, it will come to while and check the condition if i<no. Till here, i = 1 and no = 10. So, it will check as while(1<10) means the condition is true and it will again go to the do statement and again execute the block of code inside do. So, value of i will be 2 now and it will be printed. Similarly, it will print upto 10 and then check for while(10 < 10) i.e false and come out of the loop.

Thursday, December 13, 2012

While Loop in C

While loop is one of the type of loops in C and used to repeat a block of code.

Syntax of while loop

          while (some condition)
          {
                 ---------------------
                 Some code to execute
                 ---------------------
                 increment/decrement
          }

     This loop will execute as long as the condition written in parentheses after while is correct. When the condition gets wrong, it will come out of the loop. If the condition is false in the very first then the block of code of while will not execute. Now, lets see an example of while loop using a program.

 WAP to print numbers between 1 to 100

             #include<stdio.h>
             void main()
             {
                   int  i=1;
                   while(i <= 100)
                   {
                          printf("%d \t", i);
                          i++;
                    }
               }

    Explanation:- Here, we have taken an integer variable 'i' initialized by 1. Now, it will come in while loop and will check its condition for the first time as i <= 100 means 1 <= 100. As the condition is true, it will go inside the loop and will print the value of i as 1. Again, there is an increment in i (i++). It will give one plus to the value of i. Now, i = 2. Again, it will check the condition of while as i <= 100. This time, it will check as 2 <= 100. Again, the condition is true and 2 will be printed. Similarly, it will be printed as  1 to 100. When value of i will be 101. It will check the condition as 101 <= 100. As the condition is false and it will come out of the loop.

Monday, December 10, 2012

Loops in C

Before discussing various loops in 'C', it is necessary to understand about loop, what exactly it is. We use loop when we have to repeat a block of code. For many times, it is required to execute the same code a number of times for some cases. Then we take the help of loop. 
                         There are three types of loop:- 
                          1.  while
                          2.  dowhile
                          3.   for

                 There are two keywords which are important in loop. So, before studying loops in deep, lets see these two keywords. They are:-
 1. break
 2. continue

 1. Break
               We use break to terminate the loop. In other words, we can say that it is useful to get exit from a loop under some circumstances. This will be more clear in using loops in next chapters.

2. Continue
                  Continue is a keyword that controls the flow of loops. Sippose we are executing a loop and hit a continue statement, the loop will stop its current iteration, update itself (in case of for loops) and begin to execute again from the top.

Sunday, December 9, 2012

If, Else, Else if Statements in C

If Statement
                     We use if statement when we have to enter in a section of code on the basis of some condition. For example, we use if statement to check if the username & password entered by user is correct then we allow him to do the particular task. Otherwise that area is restricted for him/her.
                          Whatever we write inside the if statement will execute only when the condition is true. If the condition is false, it will not execute. True returns a non-zero number(say 1) and false evaluates to zero.

If Syntax
                   The structure if if statement is as follows:-

          if (some condition)
          {
               ---------
               some code
               ---------
          }


Note:-  dashed lines show that some code will be there.

          Now, if the condition is true then only the code written inside of if will execute. Otherwise it will not execute.

Example:-   if ( 20 > 6)
                      {
                             printf("Condition is true");
                      }

 Now, here we see that 20 > 6 is true. So, it will go inside of if and will execute the printf statement and print the statement 'Condition is true'.

Else
          We use else when the condition in if evaluates to zero. But, its not necessary to put else everywhere you used if. It depends on your requirement. Suppose there is a condition. On the basis of that condition, you want to perform some operations. If the condition is true then some operations and if the condition is false then some different operations.

  Syntax for if else
              if (some condition)
              {                                                 // <- if condition is true, it will execute
                       ---------
                       Some code
                       ----------
               }
               else
               {                                               // <- if condition is false, it will execute.
                        ---------
                        some code
                       ----------
                }

      Example:-
                          if (20 < 6)
                          {
                                    printf("condition is true");
                           }
                           else
                           {
                                     printf("condition is false");
                            }

 Output:-  As here, the condition in if is not true, so else part will execute and it will print "condition is false" on the screen.

 Else If
       We use elseif when we have to execute some different instructions on the basis of some different conditions. Syntax for if, else, else if is as follows:-

      if ( condition 1)                      // It will check for this condition first
                                                     // If above condition is true, compiler will 

                                                      execute this block of code
      {

           -----------
           statement 1
           ------------
      }
      elseif ( condition 2)                   // if above condition is false, compiler will 

                                                            check this condition
     {                                                 // if this condition is true, compiler will 

                                                           execute this block of code.
          -------------
          statement 2
          ------------
     }
     elseif ( condition 3 )                   // if 2nd condition is false, compiler will 

                                                            check this condition.
     {                                                   // if this condition is true, compiler will execute this block of code.
           ------------
           statement 3
           ------------
     }
     else                                             // if none of condition is true, compiler will 

                                                            come here and execute it.
     {
           ------------
           statement 4
           ------------
     }

Example with a program using if, else, else if

WAP to enter percentage of marks and assign grade accordingly.

                 #include<stdio.h>
                 void main()
                 {
                       int no;
                       printf(" Enter your marks in percentage");
                       scanf("%d",&no);
                       if (no >=90)
                      {
                               printf("Your grade is A");
                      }
                      elseif (no >=75 && <90)
                      {
                               printf("Your grade is B");
                      }
                      elseif ("no >= 60 && < 75)
                      {
                               printf("Your grade is C");
                      }
                      else
                      {
                              printf("You didn't qualify");
                       }
                }

        
    Another Example for if else - WAP to check a number is odd or even

              #include<stdio.h>
              void main()
              {
                    int no;
                    printf ("Enter a number");
                    scanf ("%d",&no);
                    if (no % 2 == 0)
                   {
                         printf("Number entered is even");
                   }
                   else
                   {
                         printf("Number entered is odd");
                   }
              }

Saturday, December 8, 2012

C Program to swap two integers

 To start with the program, first its good to understand about swapping. Its possible that many people may not aware of this term. If you know, its good. Swap means interchange. Swap two numbers means to interchange the values of two numbers from each other. Suppose, x=15 and y=20. Then after swapping it will be x=20 and y=15. We have to write the program for the same. So, here we go:

                #include<stdio.h>
                void main()
                {
                       int x, y, temp;
                       printf("Enter two numbers");
                       scanf("%d%d",&x,&y);
                       printf("Before swapping, x=%d and y = %d \n",x,y);
                       temp = x;
                       x = y;
                       y = temp;
                       printf("After swapping, x=%d and y = %d",x,y);
               }

Ouptut: Before swapping, x=15 and y=20    (15 and 20 are the examples.. lets say these values are entered by user)
                 After Swapping, x=20 and y=15

Explanation for the program
                  Here, x and y are the two variables between which swapping has to be done. But, if we do first x=y. It means that value of y will be stored to x. But, now we have to get value of x stored in y. But, now its not possible because original value of x is lost as it holds now value of y. So, here we have used a third variable called temp(or say temporary). In this variable, firstly we have stored the value of x so that original value of x is not lost and then this value is assigned to y. In this way, these numbers are swapped.
                  Now, lets say you do it(swapping) without using third variable('temp' here). Wondering how is it possible. No need to wonder more... Here, I see you, how to do it???

WAP to swap two numbers without using third variable
        #include<stdio.h>
        void main()
        {
            int x,y;
            printf("Enter the two numbers to swap:");
            scanf("%d%d",&x,&y);
            printf("Before Swapping: x=%d \n y=%d \n",x,y);
            x = x+y;
            y = x-y;
            x=x-y;
            printf("After Swapping: x=%d \n y=%d \n",x,y);
        }
 Output:- Before swapping: x=15
                                                        y=20
                   After swapping: x=20
                                                    y=15
Explanation for the program
              Suppose we have two variables as x=15 and y=20. Now, according to the program  x = x+y;   => x = 15+20   => x = 35  y = x-y;    => y = 35-20    => y=15  x = x-y;    => x = 35-15    => x=20So, finally we get x=20 and y=15 which are the swapped values....

Friday, December 7, 2012

C Program to add subtract multiply and divide two integers

Lets understand the logic first for the program and then write it. Its a good practice to think about the logic before to write the program. So, here we have to perform algebraic operations like addition, subtraction, multiplication and division. It is obvious that we need two integers between which you have to perform various operations. Suppose, say it as x and y. Now, we need four integers here as the result each for addition, subtraction, multiplication and division. So, now start with the program:

               #include<stdio.h>
               void main()
               {
                       int x,y;
                       int sum, sub, mul, div;
                       printf("Enter two integer numbers");
                       scanf("%d",&x,&y);
                       sum = x+y;
                       sub = x-y;
                       mul = x*y;
                       div = int(x/y);
                       printf("Sum of the numbers=%d \n",sum);
                       printf("Subtraction = %d \n",sub);
                      printf("Multiplication of the numbers = %d \n",mul);
                      printf("Division between two numbers = %d \n",div);
               }

Explanation for the above program
                For the explanation of program from starting, you need to go to previous program. Here, I am explaining the other parts which is not explained earlier. Lets understand the program through an example. Suppose, two numbers enterd by user are 5 and 2.
Now, x = 5 and y = 4.
sum = x+y;  => sum = 5+4 = 9 .
sub = x-y;    => sub = 5-4 = 1.
mul = x*y    => mul = 5*4 = 20.
div = x/y      => div = 5/4 = 1.25 But, we have used div = int(x/y). So, it will take the division result into integer i.e, it will display the result as div = 1 instead of div = 1.25
This process is called type casting. Remember that type casting always occurs in right side as in above example. You can't use it in left side.

Total Pageviews