Iteration Statements (Frequently Called Loops)

Well, friends today we discuss about loops in C /C++. Iteration statements (Loops) allow a set of instruction to be executed repeatedly until a certain condition meets. The condition may be predefined or open ended like (for loop and do-while or while loop)

For Loop

In general for loop is constitute with three parts initialization, condition and increment or decrement. It provides unexpected flexibility and power to control program iteration. The for loop allows many variations, but its most common works like this. The initialization is an assignment statement that is used to set loop control variable. The condition is a relational expression that determines when the loop exits. And the last one increment defines how loop control variable changes each time the loop repeated.

Flowchart of for loop:

for-loop

Example of for loop:

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

In above case, you can view a variable ‘i’ initially set to 1 and compared with 50, until i is less than or equal to 50 .It repeatedly do the job printf() which print the value of i itself and it increased by 1 and again tested to see whether its value still less than 50 or reached 50 . Here we set a predefined condition  “i<=50

While loop:

The general form of a while loop is while(condition)statement; here statement can be empty, single or block of statement.

Flowchart of while loop:

c-while-loop

Example of while loop:

 #include<studio.h>
void main()
{
   int i;
   i=1;
   while(i<=50)
   {
      printf("%d",i);
   }
}

 The do-while loop:

Unlike for and while loops, which check the loop condition at the beginning, the do-while loop checks its condition at the end of the loop. The basic defiance is the do-while always executes at least once. The general form of do-while loop is :

do{
statement;
}while(condition);

Although {} are not necessary for a single statement but best practice is to use the curly braces to avoid confusion.

Flowchart of do-while loop:

c-do-while-loop

Example of do-while loop:

 #include<studio.h>
void main()
{
    char ch; // this variable used for input user choice
    int a,b,c; // we can declare variable in one line also. 
    
    do
    {
       printf("Enter any Integer for variable A"); 
       scanf("%d",&a); 
       printf("Enter any Integer for variable B"); 
       scanf("%d", &b);       
       c=a+b;
       printf("The Sum of A and B is =%d",c);
       printf("To Continue press 1 and To exit press any other key")
       ch=getchar();
    }while(ch=='1');
}

In this case, iteration will happen as per user’s choice when the user put value 1 it continue again to do the same job else it terminates the program.  Hence it is open ended.

The Infinite Loop:

The infinite loop is a loop that’s run forever, in case of for() its looks like for(; ; ) 

#include<studio.h>
void main(void)
{
    for( ; ; ) printf("This loop will run forever.\n");
} 

When the conditional expression is absent, it assumed to be true. Although you can use any loop statement to create an infinite loop, for is traditionally used for this purpose.

Here some other infinite loop example:

 #include<studio.h>
void main(void)
{
    while(1)
    {
        printf("This loop will run forever.\n");
    }

}

 

 #include<stdio.h>
void main()
{
int num=20;
  while(num>10) {
      printf("Hello");
  }
}

The output will print “Hello” forever.

Explanation :

  1. The condition is specified in while Loop, but terminating condition is not specified and even we haven’t modified the condition variable.
  2. In this case, our subscript variable (Variable used to Repeat action) is not either incremented or decremented
  3. so while remains true forever.

How to Come out from the infinite loop?

If you haven’t set any brake statement inside the loop then you have to force brake through Ctrl+Brake/Pause Brake key from the keyboard. If you have set a break statement then you can terminate loop by using break or exit function like that.

 #include <stdio.h>
int main()
{
 int count;
 count = 0;
 while(1)
 {
 printf("%d, ",count);
 count = count+1;
 if( count > 50)
 break;
 }
 putchar('\n');
 return(0);
}

or

 #include<studio.h>
void main() //here main function should not have any return type thus its void.
{
  ch = '\0';   // \0 is called NULL character in c / c++ 
  for( ; ; ) 
  {
     ch = getchar(); /* get a character */
     if(ch=='A') break; /* exit the loop */
  }
}

Program to calculate the sum of first n natural numbers Positive integers 1,2,3…n are known as natural numbers

 

#include <stdio.h>
int main()
{
 int n, count, sum = 0;

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

 // for loop terminates when n is less than count
 for(count = 1; count <= n; ++count)
 {
 sum += count;
 }

 printf("Sum = %d", sum);

 return 0;
}

 

The following two tabs change content below.

Subroto Mondal

Chief Coordinator HR&CR
I like Programming and New Technologies. And work with Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.