Loops in C18 min read

1. Need for Looping/Iteration Statements

  • Loops in C programming language are used to repeatedly execute a line or a block of code until it obtains the value that the programmer desires.
  • There are three types of loops in C programming: For Loop, While Loop, and Do While Loop.
  • In C, loops can also be used with additional control statements such as the Break, Goto, and Control statements.
  • These loops can be used as entry or exit control units at any point in the program.
  • When we need to run a block of statements repeatedly in programming, we utilize Loops in C.

Consider the problem where we want to print a message Hello five times, one of the solutions is given below,

Example:

Program to print the message ‘Hello’ five times

#include<stdio.h>

void main(void) {
  printf("Hello \n"); 
  printf("Hello \n"); 
  printf("Hello \n"); 
  printf("Hello \n");
  printf("Hello");
}

Output:

Hello
Hello
Hello
Hello
Hello

That’s fine, we have written a print statement with the message “Hello” 5 times, but now if you want to print the message “Hello” 50 times then, writing a printf(” Hello”) 50 times can be a good solution? Of course not, observe that we are executing the same set of instructions repeatedly and a better solution for such a problem is an iterative or looping statement.

Looping statements are those statements that execute the same set of instruction(s) repeatedly as long as the condition is true. There are three types of loops in c and they are:

  • for
  • while
  • do-while

2. for statement

  • It is one of the simplest loops in C language to execute the statement(s) repetitively as long as the condition is true is ‘for loop’.
  • It is also known as a counter loop as it will execute the condition for some fixed number of times.
  • This loop is suitable when one knows in advance how many times the loop is to be executed.
  • If the loop body consists of only one instruction then braces are rot required.

Syntax:

for ( Expression1; Expression2; Expression3 ) 
/* C code to be executed as long as expression 2 is true */ 
Statement (s);

Where,

  • Expression1 (Initialization): It is the initialization part. It always executes just once, as the 1st step in the execution process. For many programs in “C’, the expression! is an assignment statement. One may initialize more than one variable using a comma and known as Multiple initializations.
  • Expression 2 (Condition Evaluation): It is the Test expression condition and executes the body of for statement as long as the expression is true. After every execution of expression3, expression2 is evaluated except for the 1st time where it will be executed after the initialization of the statement. Expression2 may consist of more than one logical condition.
  • Expression3 (Re-Initialization): It is the part that prepares for the next iteration of the loop i.e. New value of expression3 will be closer to the condition value specified in expression2. It is executed each time after the body of for loop is executed. For many programs in ‘C’, an expression3 is a re-assignment statement. Though it is not good practice one can also write an expression3 anywhere within the loop block.

Example:

Consider the problem where we want to print a message Hello five times using for loop,

#include <stdio.h>

void main(void){
  int i;
  for ( i = 1; i<=5; ++i ) {
    printf( "Hello \n" );
  }
}

Output:

Hello
Hello
Hello
Hello
Hello
  • Here, initially, the value 1 is assigned to the counter/Induction variable ‘i’ afterward this value is evaluated in the expression2.
  • Expression2 will result in the true and hence a message “Hello” will be printed for 1M time.
  • After execution of the body, control is transferred to the Re-Initialization part where the value of i is incremented by 1 and transfer the control again to expression2 for further evaluation this way body of the loop will be executed 5 times.

Note:

In computer science, an induction variable is a variable that gets increased or decreased by a fixed amount on every iteration of a loop.

3. COMMA OPERATOR

The comma operator is used to combine two statements and evaluate the expression from left to right. The comma operator is generally used for variable separation.

Eg.

  1. int a = 5, b = 7;
  2. printf ("a = %d b = %d", a, b);

It is also used in for loop, either in expression1 or in expression3 or in both parts to assign or re-assign more than one variable

Example:

Consider the example where we want to compute the sum of five numbers.

/* Addition of 5 Numbers */

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

Output:

1
3 
6 
10 
15

Observe in the above program, there is more than one statement written in Expression1 and in Expression3 and each statement is terminated by comma (,) operator.

Example:

Consider another example, where the use of a comma operator is useful, where we want to compute the following function for the following set of numbers.

F(x, y) = (x + y) / (x * y)

X24681012
Y1357911
#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int x,y;
  float f; 
  
  for(x = 2, y = 1; x <= 12 && y <= 11; x = x+2, y = y+2) {
    f = (float)(x + y) / (x * y);
    printf(" For f(%d,%d) = %f\n", x ,y ,f);
  }
  
  getch();
}

Output:

For f(2,1) = 1.500000
For f(4,3) = 0.583333
For f(6,5) = 0.366667
For f(8,7) = 0.267857
For f(10,9) = 0.211111
For f(12,11) = 0.174242
  • Observe in the above program, there is more than one statement written in Expression) and in Expression3 and each statement is separated by a comma (, ) operator.
  • In the absence of this operator, the program might look as follows which is more inconvenient i.e. writing one of the initiation statements before the loop and a re-initiation statement at the end of the looping statement

Example:

The above problem without comma operator using for loop

#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int x,y; 
  float f; 
  clrscr(); //to clear the previous output in the output console
  
  x = 2;
  
  for(y = 1; x<= 12 && y <= 11; y = y + 2) {
    f = (float)(x + y)/(x * y); 
    printf("For f(%d,%d) = %f\n", x, y, f);
    x = x + 2; 
  }
  getch(); 
}

Output:

For f(2,1) = 1.500000
For f(4,3) = 0.583333
For f(6,5) = 0.366667
For f(8,7) = 0.267857
For f(10,9) = 0.211111
For f(12,11) = 0.174242

4. while statement

  • The while statement is a loop statement that allows its body of instructions to be executed repeatedly as long as the test expression or base condition remains true. The body of instructions in a while loop does not execute if the Initialization expression is false.
  • The expression is evaluated prior to each execution of the body of the while statement
  • As the expression is evaluated at the beginning of the loop, this iterative loop is also called the top-tested loop or begin-tested loop.
  • If the loop body consists of only one instruction then braces are rot required.
  • The loop variable should be updated inside the body of a while, otherwise, the loop may fall into infinite.

Syntax:

while (expression) { 
  /* code that executes as long as expression in while remains true */
}

Example:

Consider the example where we want to find the sum of each digit of a number

#include<stdio.h> 
#include<conio.h>
typedef long unsigned int lui;

void main(void) {
  lui number; 
  int rem, sum=0; 
  clrscr(); 
  
  printf("Enter a number "); 
  scanf("%lu",&number); 
  
  while(number >0) { 
    rem = number % 10;      /* Find the remainder */ 
    sum = sum + rem;        /* Sum the remainders */
    number = number / 10;   /* Get new number */
  } 
  printf("Sum of digit of number %d", sum);
}

Output:

Enter a number 23
Sum of digit of number 5

5. do-while statement

  • The do-while statement is a loop statement that allows its body of instructions to be executed one or more times i.e. the body of instruction in a do-while loop is always executed at least once.
  • As the expression is evaluated at the end of the execution of a block of the statement, this iterative loop is also called a bottom-tested or end-tested loop.
  • This loop is ideally suited when it is impossible to determine in advance exactly how many executions are necessary except one.

Syntax:

do {
/* execute instruction once, and then repeat while expression remains true */
  statement 1; 
  statement 2; 
} while (expression);

Example:

Consider the example where the user would like to find out the sum of two different sets of numbers as long as the user wishes,

#include<stdio.h> 
#include<conio.h> 
typedef long unsigned int lui; 
void main(void) {
  lui a, b, c; 
  char cho;
  do {
  сlrscr();  

    printf("\nEnter two numbers: "); 
    scanf("%lu %lu", &a, &b);
    
    c = a + b;
  
    printf("Sum = %lu", c); 
    printf("\nWant to Continue (y/n): "); 
    cho = getch();
  } while (cho == 'y' || cho == 'Y');
}

Output:

Enter two numbers: 4 5
Sum = 9
Want to Continue (y/n): y
Enter two numbers: 2 9
Sum = 11
Want to Continue (y/n):   /*program terminates if you press 'n' or any other character than 'y' */

Here, obviously, for the first time whether the user likes it or not a program will find the sum of two numbers, Alter the calculation and display the result, the program will ask the user for continuation, On confirmation, it will again execute the same set of instructions.


6. VALIDATING INPUT using DO-WHILE

  • While inputting the values user may commit a mistake for example inputting the marks of paper beyond range. Sometimes it is impossible to compute the value depending upon the inputted values.
  • For example, finding the square root of a negative number.
  • Thus it is a burden for programmers to write code to overcome such a situation known as validation.

Example:

A program to compute the sum of the marks of 3 papers after validating the marks of papers within the range (0-100)

#include <stdio.h> 
#include <conio.h>

void main(void) { 
  int p, c, m, tm;
  //clrscr(); 
  do {
    printf("Enter marks of 3 papers: "); 
    scanf("%d %d %d", &p, &c, &m); 
  } while(p<0 || c<0 || m<0 || p>100 || 0>100 || m>100); 
  tm = p + c + m; 
  printf("Total marks %d",tm); 
  getch();
}

Output:

Enter marks of 3 papers: 85 71 93
Total marks 249

Here, after entering the marks of the 3 papers code will evaluate whether the marks are within the range (0-100) or not. Otherwise, it will again ask the user to enter marks.


7. DIFFERENCE BETWEEN WHILE LOOP and DO WHILE LOOP

S.N.WHILE LOOPDO WHILE LOOP
1)The expression is tested at the beginning of the loop. The expression is tested at the end of the loop.
2)If the condition is false at the beginning, the body of the loop is terminated without the loop being executed at least even once.If the condition is false, the body of the loop is executed at least once.
3)Any initialization should be made before the beginning of the loop.Setting up loop parameter initialization can be made in the loop.
Difference between while and do-while loop

ENTRY CONTROL LOOP:- When the control is transferred into the body of the loop only after checking some condition then it is referred to as an entry control loop i.e. there is a checkpoint at the entry control of the loop. The for and while loops are entry-controlled loops.

EXIT CONTROL LOOP: – When the control is transferred out of the body loop i.e. to the next statement after the body of the loop only after checking the condition then it is referred to as an exit control loop. do-while is an exit-controlled loop.


8. Infinite Loop

When the same set of instructions is carried out again and again without any method of terminating then such a control loop is known as an infinite loop. For example, assume the user wants to print the message hello 5 times and write the following code,

for (i=1;i<=5; i=1) {
  printf("Hello"); 
}

In the above example, the loop will be executed continuously without having a way to terminate it because the expression3 of for loop contains i = 1 instead of i = i +1.

Note:

The only way to stop executing loop infinitely is to terminate it by pressing Ctrl + Break and then pressing a key. This will return the control to the program code.

9. Jump Constructs

‘C’ supports two types of jump constructing statements either conditional or unconditional statements. Conditional statements are usually associated with if statements while unconditional statements are associated with goto statements.

9.1. break Statement

It is often used with the conditional control structure. The break statement causes an immediate exit from the do, for, while, or switch statement in which it appears. The program continues executing with the next program statement following it.

Syntax: break;

Example 1:

Consider the example where we want to check number is prime or not

#include<stdio.h>
#include<conio.h>

void main(void) {
  int i, n, r; 
  clrscr (); 
  
  printf ("Enter a Number: "); 
  scanf("%d",&n); 
  
  for (i=2; i<n; ++i) { 
    r = n%i;
    if (r == 0) { 
      break;       /* Terminate the loop */
    }
  }
         
  if ( i==n || r!=0)
    printf ("\nNumber %d is prime", n); 
  else
    printf("\nNumber %d is not prime", n); 
  
  getch(); 
} 

Output:

Enter a Number: 77

Number 77 is not prime

Example 2:

A program to find the number of terms of series S = 1 + 2 +3 +4 +5 ….. + n must be summed before the total exceeds say 100

#include <stdio.h> 
#include <conio.h> 

void main(void) { 
  int k = 1, sum = 0;
  clrscr(); 
  
  while (1) {
    if (sum > 100)
       break; 
    sum = sum + k;
    k = k + 1; 
  }
  printf("Sum = %d, Total terms required = %d",sum,k);
}

Output:

Sum = 105, Total terms required = 15

Here, the break statement is handy since it is the only way to terminate the loop once the sum exceeds 100.

9.2. continue Statement

  • The continue statement is used with the loop instruction do, for, and while. It transfers program control to the next iteration of the loop skipping the statements written after the continue statement is mostly associated with a conditional control structure called if statement within the loop.
  • Writing a continue statement as the last statement within the looping statement is optional

Syntax : continue;

Example:

A program to find the sum of all numbers from 10 to 35 that are not divisible by 5 or 7

#include <stdio.h> 
#include <conio.h> 

void main(void) {
  unsigned int n, sum = 0;
  clrscr();
  
  for (n = 10; n <= 35; ++n ) {
    if (n % 5 == 0 || n % 7 == 0 )
      continue;
    sum = sum + n;
  }
  printf("Sum = %u", sum);
  
  getch();
}

Output:

Sum = 387

9.3. DIFFERENCE BETWEEN BREAK & CONTINUE STATEMENT

S.N.breakcontinue
1)This statement causes an immediate exit from the innermost loop.This statement causes the next iteration of the loop structure.
2)This statement is used when exiting from the loop is required.This statement is used as the inverse operation of a break statement.
3)This can be used with switch, while, do-while, and for statement.This cannot be used with a switch however can be used with while, do-while, and for loop.
Difference between break and continue

9.4. goto statement

  • A goto statement is an unconditional jumping statement and transfers the control to a specified ‘C’ statement. In ‘C’ goto statement allows you to transfer control from one point in a function (say main() ) to any other point in that function only.
  • This action is usually called unconditional branching. There is normally no need to use the goto statement because of some alternative method provided by the C language.
  • A complicated situation can be managed with break and continue statements. If we want to come out of several nested loops at one stroke then a goto statement may be useful.

Syntax:- goto LABEL;

Where: LABEL is an identifier used to label the target statement to which control will be transferred and LABEL can be placed, either before or after goto. A LABEL: if used must be placed after the declaration of the variable.

Example:

To find the Area of the Circle, accept the radius as long as it is not positive

#include<stdio.h> 
#include<conio.h> 
#include<math.h> 

void main(void) {
  float rad, area; 
back :
  //clrscr(); 
  printf("Enter the value of radius: "); 
  scanf("%f", &rad); 
  
  if (rad < 0) {
    printf("\nRadius value should not be Negative"); 
    getch();
    goto back; 
  }
  area = 3.14 * pow( rad, 2);
  printf("Area of Circle = %f", area );
  
  getch();
}

Output:

Enter the value of radius: 24
Area of Circle = 1808.640015

9.5. exit() statement

  • The exit() function is the program termination call i.e. this function is useful to stop the further execution of the program and transfer the control back to an operating system.
  • Any statement written after exit() will be ignored by the compiler and simply returns back. It closes all open files if any before returning control to the operating system.
  • The exit() function is optional when it is the last statement in the main function.
  • When the ‘C’ compiler eaches the closing braces in the main function, it calls the exit () to end the execution.
  • This function is generally associated with some error handling situations. It returns some status to the operating system indicating whether the program execution is successful or not.
  • For example, exit value o indicates a normal exit. One must include a header file process.h or stdlib.h to include exit() in a program.

Syntax:- exit();

Example:

To find the Area of the Circle, if the radius value is negative then terminate the program

#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 
#include<math.h> 

void main(void) {
  float rad, area; 
  clrscr;
  
  printf("Enter the value of radius: ");
  scanf("%f",&rad); 
  
  if (rad < 0) {
    printf("\nRadius value should not be Negative");
    exit(1);      /* Terminate program */ 
  }
  
  area = 3.14 * pow(rad,2); 
  printf ("Area of Circle = %f",area); 
  
  getch(); 
}

Output:

Enter the value of radius: 36
Area of Circle = 4069.439941

10. NESTED LOOPS

  • A loop within another loop is known as a nested loop or embedded loop.
  • In nested loops, one or more loops say for or while or do-while loop can be nested within another for or while or do-while loop.
  • Here inner loop will be executed for every outer induction variable until the outer condition becomes false.
  • The number of iterations in these types of structures will be equal to the number of iterations in the outer loop (Parent Loop) multiplied by the number of iterations in the inner loop (Child Loop).
  • There is no limit to the depth of the nested loop.

Note:

In a nested loop, the inner loop must terminate before the outer loop.

Example:

Consider the example where we want to print all the prime numbers between 10 to 100

#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int i, n, r, flag=0; 
  clrscr(); 
  printf ("Prime Numbers between 10 and 100: "); 
  
  for (n=10; n<= 100; ++n) { 
    flag = 0;       /* Assume number is prime */ 
    
    /* Checking number is prime or Not */ 
    for (i=2; i<= 9; ++i) {
      r=n%i; 
      
      if (r == 0) {
        flag = 1;     /* Concluded that number is not prime */
        break;        /* Terminate the loop */
      } 
    } 
      
      if (flag == 0) { /* No. is prime */
        printf("%d \t", n); 
      } 
    }
    
  getch(); 
}

Here, the outer loop, each time will pass the new number to the inner loop to check whether the number is prime or not.

Output:

Prime Numbers between 10 and 100: 11    13      17      19      23      29      31      37      41      43      47  53       59      61      67      71      73      79      83      89      97

11. Examples

  • Program to print multiplication table of a number
#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int n, r, i; 
  //clrscr(); 
  
  printf(" Enter a number :- "); 
  scanf("%d",&n);
  
  for(i=1;i<=10; ++i) { 
    r = n * i; 
    printf("\n %d * %d = %d",n,i,r); 
  } 
  
  getch();
}

Output:

 Enter a number :- 17

 17 * 1 = 17
 17 * 2 = 34
 17 * 3 = 51
 17 * 4 = 68
 17 * 5 = 85
 17 * 6 = 102
 17 * 7 = 119
 17 * 8 = 136
 17 * 9 = 153
 17 * 10 = 170
  • A program to print numbers, squares, and cubes of the first 10 natural numbers
#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int n, r, s, c; 
  clrscr(); 
  
  printf("number\t|square\t|cube\t|");
  for(n=1; n<=10; ++n) {
    s = n * n;
    c = s * n;
    printf("\n%d\t|%d\t|%d\t|",n,s,c); 
  } 
  
  getch();
}

Output:

number  |square |cube   |
1       |1      |1      |
2       |4      |8      |
3       |9      |27     |
4       |16     |64     |
5       |25     |125    |
6       |36     |216    |
7       |49     |343    |
8       |64     |512    |
9       |81     |729    |
10      |100    |1000   |
  • To find the product of two numbers without using the * symbol
#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int a,b,i; 
  long unsigned int sum=0;
  clrscr();
  
  printf("Enter 2 numbers :- " );
  scanf( "%d%d", &a, &b );
  
  for(i=1; i<=b; ++i) {
    sum = sum + a;
  }
  
  printf("\nMultiplication of %d * %d = %lu", a, b, sum);
  
  getch();
}

Output:

Enter 2 numbers :- 5 7

Multiplication of 5 * 7 = 35
  • To find a maximum out of 5 numbers
#include<stdio.h> 
#include<conio.h> 

void main(void) {
  int p,q,r,s,t; 
  int i,max,sum; 
  clrscr(); 
  
  printf("Enter 5 numbers :- "); 
  scanf("%d %d %d %d %d",&p,&q,&r,&s,&t);
  sum = p + q + r + s + t; 
  
  for(i = sum ; i <= sum ; --i) {  
    if(i == p || i == q || i == r || i == s || i == t) {
      max = i;
      break; 
    } 
  }
  
  printf("\nMax. number is = %d",max); 
  
  getch();
}

Output:

Enter 5 numbers :- 54 65 32 4 13

Max. number is = 65

Share:

Leave a Reply