Loop Control Structures

Loop Control Structures in 'C' language: 

  • Loop control structures are used to perform particular task repetitively. 
  • If we want certain statements to be execute multiple times then effective solution rather than writing them multiple times just insert them inside a loop.
  • Loop saves our time and efforts of writing. 
  • In general all programming languages supports three types of loop control structures namely for, while and non-white.
  • Let's see them one by one

 1) For loop : As it is a loop it is used to execute some statements repeatedly.

Syntax :
for(intialization;conditional statement;increment/decrement)
{
  //statements to execute 
 }

  • Initialization statement is executed only once at the starting of loop.
  • It then checks for conditional statement if it evaluates to true then only statements inside the body of loop is executed otherwise program execution continues with statement followed by loop.
  • After executing body of loop it either increments or increments value of loop control variable as specified then again check condition and repeat the task until condition becomes false.
  • Even though body of loop is enclosed between {} they are optional if body contains only one statement.
Example : Program to print first 100 natural numbers.

#include<stdio.h>
int main()
{ 

 int i; //loop variable declaration      for(i=1;i<=100;i++)      
    Printf(" %d ",i);
 return 0;

}

Output:
1 2 3 4 5.........100

2) While Loop :  It works same as for loop only syntax is different. Initialization is done outside the loop before writing loop. Increment/decrement is done inside the loop itself. It is top controlled loop.

Syntax :
initialization statement;
While(conditional statement)
{
   //statement to execute 
   Increment/decrement
}
  • While loop also executes statements with in body repeatedly until condition becomes false.
Example : Program to print first 100 natural numbers.
#include<stdio.h>
int main()
{
  int i=1;
  while(i<=100)
  {
      Printf(" %d ",i);
      i++;
  }
return 0;
}

Output :
1 2 3 4 5 ....... 100

3) do-while loop : Do-while loop same as while loop but it executes the body of loop first time without checking condition. That means condition is checked at the end of loop. Thus it is bottom controlled loop.

Syntax : 
initialization statement;
do
 {
    //statements to execute
    increment/decrement;
 }while(condition);

Example : Program to print first 100 natural numbers.
#include<stdio.h>
int main()
{
   int i=1;
   do
   {
       Printf(" %d ",i);
       i++;
    }while(i<=100);
return 0;
}

Output:
1 2 3 4 5...... 100

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.