Wednesday, August 23, 2017

Loop in C Programming

Loop in C Programming is for beginners.

In childhood, my father told me, “Elliyas, Try this math until solve.” At that time what should I did.  I started trying to solve that math. Since that math was difficult to solve for that time, I was trying and trying but failed every time. After a time, I solved this math. 

If we try to organize the above occurrences step by step then it will be as below:

1. Start to solve the math.
2. Try to solve.
3. Is it end?
If yes then STEP 4, otherwise STEP 2.
4. Compare with answer.
5. Has it matched with answer?
If yes then STEP 6, otherwise STEP 1.
6. Finish.

This is algorithm (Sequence of work to finish successfully) to solve my math. In the above algorithm there has two loop (Repetition)  in STEP 3 and STEP 5 if the answer of question be NO.

Loop in C Programming

Assume another repetition problem to solve. If I tell you to print Hello World about 5 line, what will  be your program? Obviously, you will write code like below.
#include <stdio.h>
int main()
{
    printf("Hello World.\n");
    printf("Hello World.\n");
    printf("Hello World.\n");
    printf("Hello World.\n");
    printf("Hello World.\n");

    return 0;
}
Ok. But if I tell you to print this same message about 10000 line? It is so difficult and bored with this method, isn’t it? Then more, if we use this method, the code will be large.

Since the objective of programming is making life more comfortable, effective then the time is the great fact. To reduce time, labor, cost there has an option in C programming language and it is looping in C.

Different type of loop in C are available. Loops in C are:

1. For loop
2. While loop and
3. Do while loop.

There has another loop is called goto statement, we will discuss later.


Now we will discuss the three major loop in C Programming language.

For loop in C

The general form of for loop in C is:
    for(/*Initialization*/ ; /*Condition Test*/ ; /*Increment*/)
    {
        /*Body of for loop.  */
    }
What is initialization in for loop ?

Initialization in for loop is the lowest limit from start loop. To determine it needs to assign the lowest limit to a variable. This variable is called loop-control variable.

Suppose, we want to print 1 to 100 number with for loop. Then the lowest limit is 1 and we have to assign this value into a variable assume var. Then it will be:
int var = 1; It is called initialization and variable var is called loop-control variable in C.

Initialization in for loop is required.

What is condition test in for loop?

Condition test in for loop is the determination of loop iteration that depends on condition can be made with relational operator (Expressions with relational operator).

For the above example we have to determine the loop iteration. If we want to print 1 to 100 number with for loop, here 100 is our target. So we can make a condition to test for this as “Is the current number is 100? If yes then stop looping, otherwise increment.” For that the condition test with relational operator will be:
var <= 100 and it is called condition test in for loop.

What is increment in for loop?

Increment in for loop is essential to continue repetition/looping with definite interval manually required. To reach at the last number of above example with 1 interval we can do it as below:
var = var + 1 or we can do it with increment operator ++.

Example: var++  
What is body of for loop?

Body of for loop is a block that is enclosed with bracket where we can put any executable statement: if statement, nesting of for loop, break statement, another for loop, any expression etc.

Now the final program of printing 1 to 100 number sequentially with for loop is as below and observe this.
#include <stdio.h>
int main()
{
    int var;
    // Start For Loop
    for(var = 1; var <= 100; var++)
    {
        printf("%d\n", var);
    }
    // End of For Loop
    return 0;
}
if statement within for loop in C

Example:
#include <stdio.h>
int main()
{
    int var;
    // Start For Loop
    for(var = 1; var <= 100; var++)
    {
        if(var % 2 == 0)
        {
            continue;
        }
        printf("%d\n", var);
    }
    // End of For Loop
    return 0;
}
This program will print only odd number 1 to 99 sequentially.

Here continue is another statement that skip the result depending on condition within if statement.

Similarly you can use if else, if else ladder, switch statement within for loop.


More information about For Loop in C:

  • You can use decrement instead of increment.
    Example: x = x -2 or x-- etc.
  • You can use compound test-condition with logical operator.
    Example:  for(i=1; i<=10 && i >=5; i++)
  • You can initial, increment/decrement more than one variable with comma operator.
    Example: for(i=1, j=5; i<=10 && i >=5; i++, j--)
  • If you didn’t declare data type of variable that work in for loop, you must declare its data type when using.
    Example: for(int var = 1; var>=9; ++var)
Now write a program to print 2 to 100 even numbers sequentially with for loop in C.

While loop in C

While loop in C is the best and simplest alternative of for loop. If you don’t understand how for loop works, then you should try while loop.

The general form of while loop is:
/*Initialzation*/

while(/*Test Condition*/)
{
     /*Body of while loop*/

     /*Incrementing/ Decrementing*/
}
It is not necessary to describe about initialization, test condition, incrementing in loop again.

Don’t put any character (including comma, semicolon) after while .

Example of while loop in C:

The following program will print the sum of 1 to 100.
#include <stdio.h>
int main()
{
    int sum, counter;

    sum = 0; /*INITIALIZATION*/
    counter = 1; /*INITIALIZATION*/
    /*START OF LOOP*/
    while(counter<=100) /*TESTING*/
    {
        sum = sum + counter;

        counter++; /*INCREMENTING*/
    }
    /*END OF LOOP*/
    printf("Sum of 1 to 100 is %d.\n",sum); /*PRINT THE SUM OF 1 TO 100*/

    return 0;
}
Similarly for loop you can if, if else, if else ladder, switch statement, continue statement, break statement, nesting of any type loop within body of while loop.

Do while loop in C

The do while loop seems to while loop but different in functionally. Actually do while loop different from for loop also. Because this loop execute statement first within body then it check the condition . So it won’t be bad to say an impatient loop it.

The general form of do while loop in C:
/*Initialzation*/
do
{

   /*Loop Body*/
   /*Incrementing/ Decrementing*/
}
while(/*Test Condition*/);
Remember:
You have to put semicolon after while in do while loop but not after do.
You can put if, if else, if else ladder, switch, break, continue, functions, nesting of any kind of loop, any executable statement within loop of body.

Example of do while loop:

The above problem we have solved with while loop can solve with do while loop as below:
#include <stdio.h>
int main()
{
    int sum, counter;

    sum = 0; /*INITIALIZATION*/
    counter = 1; /*INITIALIZATION*/
    /*START OF LOOP*/
    while(counter<=100) /*TESTING*/
    {
        sum = sum + counter;

        counter++; /*INCREMENTING*/
    }
    /*END OF LOOP*/
    printf("Sum of 1 to 100 is %d.\n",sum); /*PRINT THE SUM OF 1 TO 100*/

    return 0;
}

Looking for more effecive Course?

C Programming For Beginners by Udemy icon
$15 (Original $145)
30-Day Money-Back Guarantee
Buy
Includes:
  • 6 hours on-demand video
  • 1 Article
  • 2 Supplemental Resources
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion
Have got this article helpful or not working? Put your comment below.