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.

Thursday, December 6, 2012

Basic Programs in C

Lets start with the first program in 'C' as to print "Hello World". Its the best example to initiate to write programs in 'C' language.
1. C Program to print Hello World

              #include<stdio.h>
              void main()
              {
                     printf("Hello World\n");
              }

Output:-   Hello World
Note:- If you are using Devcpp to compile C program then use int main()  instead of void main().

Now, lets study the complete program step by step.
#include<stdio.h>
                                  Here, we include a file named as stdio.h (Standard Input/Output Header file). With the help of this file, we can use some certain commands for input or output in the program. Input commands like reading from keyboard and output command like print things to the screen.

void main()
                             Here, void is the return type and every program in 'C' must have a main(). Program actually starts from here only.

{ }
      These are the beginning and closing curly brackets respectively to group all commands together. Here, they are used to mark the beginning and end of the main() function.

printf("Hello World\n");
                                                           printf is used to print the things on the screen. Here, it will print Hello World on the screen. \n is used to break the line. It represents a new line character. Everything written after \n will be printed in a new line. The last ;(semicolon) indicates the termination of the printf line.


2. WAP to take a number as input and print it.

            #include<stdio.h>
            void main()
            {
                    int  a;
                    printf("Enter a number");
                    scanf("%d",&a);
                    printf("Number you entered is %d",a);
             }

       Output:-  Enter a number
                       5
                       Number you entered is 5

      Explanation for the program

                For the starting lines of the program as #include<stdio.h>, main() etc, you can refer the above first example's explanation. Now, we start it after main().

     int  a;
      Here, int  refers to integer and 'a' is variable written after int. It means, 'a' is an integer variable.

     printf("Enter a number")
           Whatever you will write in printf, it will be printed he same. So, on the screen, it will be printed as "Enter a number".

     scanf("%d",&a);
           scanf is used to take inputs from the user. You can say that these values entered by user is stored in computer's memory. Here, %d is used for integer variable.
For character, we use:-  %c
For float, we use:-            %f
After this there is &a. It is the integer variable defined after main().

     printf("Number you entered is %d".a);
                Now, the value of integer variable 'a' is stored in computer's memory. But you have to see it also. For that its necessary to print the value of 'a' on the screen. And, it requires a printf command. So, we have used here printf.
 But, herein this printf, we have also a %d. Actually this is also for the variable a whose value is entered by the user. Note that, after this, there is no '&'. But in scanf, it is necessary to include it.

Tuesday, December 4, 2012

Operators in C

To understand the different operators in 'C' , first let us understand about operators.Operator:- An operator is a symbol that operates on a certain data type and produces the output as the result of  operation. For example:-
                       x = y + z.
                      In this case:  '+' is the operator and y,z are operands.Now, let us know the different operators in 'C'. There are three categories of operators in 'C'. They are:
1. Unary Operators
                      It is an operator which operates on one operand or say it operates on itself. For example: increment and decrement operators. Examples: ++   --    !    etc.
2. Binary Operators
                      These operators are operators which operate on two operands. For example:   x+y. Here, '+' operats on two operands.
3. Ternary Operator
                           An operator which operates on three operands.

                Operators can also be classified on the basis of type of operations performed by them. They are as follows:-

1. Arithmetic Operators
                 Arithmetic operators include the basic addition(+), Subtraction(-), Multiplication(*) and Division(/) operations. One more operator is there called modulus operator(%). Hope, everyone is aware of +,-,*,/ operations. Here, the only new term is modulus operator. Let us understand this operator.
                        Modulus operator gives the remainder left on division operation. It is noted that its symbol is % but its not the percentage. For example:-
        10%3 = 1
Here, we divided 10 by 3 i.e 10/3. In this case, there will be quotient 3 and the remainder 1. So, remainder 1 will be the result. Some more examples are here:
        20%4 = 0
        25%7 = 4
        27%8 = 3

2. Relational Operators
                  These operators compare operands and return 1 for true or 0 for false. Examples of relational operators are:-
                 <    Less than                 >    Greater than
                <=   Less than or equal to
                >=   Greater than or equal to
                ==   Equal to
                !=     Not equal to


3. Logical Operators
                    These operators are used to compare or evaluate logical and relational expressions. There are 3 logical operators in 'C' language. They are:-
        &&  (Logical and) - In this case, if both conditions are true then result will be true.
        ||      (Logical OR) - In this case, if any condition is true between the two, result will be true.
        !       (Logical Not) - It inverts the condition. Makes true to false and false to true.


4. Assignment Operator
                   An assignment operator (=) is used to assign a value to a variable. It may be a constant value or a value of a variable. For example:-
            x = 5;     // Here, value 5 is copied to x
            x = a;    // Here, value of a is copied to x.

               Other assignment operators are:
              +=
              -=
              *=
              /=
             %=
                        These can be understood as follows:- Suppose we write
              x+=5;
               It means as x = x+5;
              Similarly,
              x-=10;   // It means x=x-10;

Monday, December 3, 2012

Data Types in C


Data Types in C Picture
Here, we are going to discuss data types in 'C' programming language. To discuss about the various data types in 'C', first it is necessary to understand what exactly are data types.
Data Type:- It can be defined as an extensive system for declaring
                          variables of different types. These are used to store various
                          types of data that is processed by program. It determines
                          memory to be allocated to a variable.
                 'C' supports various data types such as integer, character, float, real, double etc. Data types are of two types namely primitive and non-primitive data type.
1. Primary or primitive data types
                  These are the predefined data types whose memory sizes are already fixed. For example: integer, character, float etc.

2. Secondary or Non-primitive Data Types
                 These are the user defined data types and its memory size depends on user. For example:- Array, Structure etc. We will discuss these data types in later chapters.

Size and Range of Data Types
                 Here we will see the various primary data types in 'C' with their size(number of bytes required to allocate a variable) and its range.

Actually, its no need to remember the range of these data types. You wonder how they came. Lets see how the range came for the various data types. You only need to remember the bytes required for each data type.
        Suppose, we take the example of integer. As, we see that the bytes required for a character is 2 bytes. And, we know that 1 byte = 8 bits. So, 2 bytes = 8x2 = 16 bits. Raise it in the power of 2. So,
(2)16 = 2 to the power of 16 = 65536.
But, integer can be positive and negative both. So, divide the result by 2 i.e, 65536/2 = 32768.
Hence, its range will be -32768 to 32767.
It is noted here that there will be a zero between the range that's why the maximum is 32767.

                Similarly, range for any data type can be find out. Hope, now its easier for you to calculate and no need to remember it further...

Saturday, December 1, 2012

Introduction to C Programming Language

Picture
                                    'C' is a computer programming language. It was developed by Dennis Ritchie at Bell Laboratories in 1972. Its principle and ideas were mostly taken from B, BCPL(Basic Combined Programming Language) and CPL(Combined Programming Language).
                    'C' programming language becomes so popular because it is simple, reliable and easy to use. To learn other high level programming languages like C++, Java etc, it is advisable that you should know at least the basics of 'C'. Then only you can learn those programming languages perfectly.


Constants, Variables and Keywords
Constant:- A constant can be defined as an entity that doesn't change.
Variable:-  A variable can be defined as an entity that may change.
Keywords:- Keywords can be defined as the words that is already defined to the 'C' compiler.
                          There are 32 keywords in 'C' language. These keywords can't be used as the variable names.

                         Now let us understand about constants and variables with an example. Suppose, we have a statement as
    a = 10;

Then the value of 'a' is changed to 20. So,
   a = 20;
 
Here, we can see that the value of 'a' can be changed as per the user. So, it is a variable. But, numbers like 10, 20 etc are fixed and they are called as constants.

Total Pageviews