Skip to main content

Control Statements: Loops in C programming

Loops are used when we want to execute a part of program or block of statement several times. So, a loop may be defined as a block of statements which are repeatedly executed for a certain number of times or until a particular condition is satisfied. There are three types of loop statements in C:

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

Each loop consists of two segments, one is k/a the control statement and the other is the body of the loop. The control statement in loop decides whether the body is to be executed or not. Depending on the position of control statement in the loop, loops may be classified either entry_controlled loop or exit_controlled loop. While and For are entry_controlled loops where as do...while is exit_controlled loop.

For Loop:

For loops is useful to execute a statement for a number of times. When the number of repetitions is known in advance, the use of this loop will be more efficient. Thus, this loop is also known as determinate or definite loop.
The general syntax

for (counter initialization ; test condition ; increment or decrement)
{
| * body of loop * |
}



 
  (Fig : Flowchart of For Loop)


For example:

|* Calculate the factorial of a number *|
    #include<stdio.h>
    main()
    {
    int num, i
    long fact = 1
    printf (“ln Enter a number whose factorial is to be calculated : “) ;
    scanf (“%d”, &num) ;
    for (i=1 ; i<=num ; i++)
    fact * = i ; |* fact = fact*i *|
    printf (“\n The factorial is : %d”, fact ) ;
    }

    Output:
      Enter a number whose factorial is to be calculated: 5
      The factorial is: 120

 



While Loop:
The while statement can be written as
while(condition)                                  while(condition)
statement ;                                           {
statement ; | * bed of the loop *|
statement ;
- - - - - - -
}
First the condition is evaluated; if it is true then the statements in the body of loop are executed. After the execution, again the condition is checked and if it is found to be true then again the statements in the body of loop are executed. This means that these statements are executed continuously till the condition is true and when it becomes false, the loop terminates and the control comes out of the loop. Each execution of the loop body is called iteration.
             |* Program to print the sum of digits of any num *|
            #include<stdio.h>
            main()
            {
            int n, sum = 0, rem ;
            printf (“Enter the number :”) ;
            scanf (%d”, &n) ;
            while (n>0)
            {
            rem = n%10 ; |* taking last digit of number *|
            sum+ = rem ; |* sum = sum + rem * |
            n/ = 10 ; |* skipping last digit *|
            } |*n = n/10 *|
            printf (“Sum of digits = %d \n”, sum) ;
            }
            Output:
            Enter the number : 1452
            Sum of digits = 12

 
 




















do...while loop:
The do...while statement is also used for looping. The body of this loop may contain a single statement or a block of statements. The general syntax is :
do                                                        do
statement ;                                           {
while(condition) ;                               Statement 1 ;
Statement 2 ;
- - - - - - - -
Statement n ;}
while(condition) ;

Here firstly the segments inside the loop body are executed and then the condition is evaluated. If the condition is true, then again the loop body is executed and this process continues until the condition becomes false. Unlike while loop, here a semicolon is placed after the condition. In a ‘while’ loop, first the condition is evaluated and then the statements are executed whereas in do while loop, first the statements are executed and then the condition is evaluated. So, if initially the condition is false the while loop will not execute at all, whereas the do while loop will always execute at least once.
                   |* program to print the number from 1 to 10 using do while *|
                 #include <stdio.h>
                 main()
                 {
                  int i = 1 ;
                  do
                  {
                  printf (“%dlt”, i) ;
                  itt ;
                  } while (i<=10) ;
                  printf(“ln”) ;
                  }
                Output : 1 2 3 4 5 6 7 8 9 10

 
 















Differences between while loop and do while loop:
while                                                                                                        
  1. while loop is entry controlled loop i.e. test condition is evaluated first and body of loop  is executed only if this test is true.
  2. The body of the loop may not be executed  at all if the condition is not satisfied at the  very first attempt.
  3. syntax :
   while (condition)
{    body of the loop }
      4. Draw flowchart
do...while
1. do...while loop is exit controlled loop i.e. the body of the loop is executed first without checking condition and at the end of body of loop, the condition is evaluated.
2. The body of the loop is always executed at least once.
3. syntax :
do
{
body of the loop
} while (condition)
4. Draw flowchart


Nesting of loops:
When a loop is written inside the body of another loop, then it is k/a nesting of loops. Any type of loop can be nested inside any other type of loop. For example, a for loop may be nested inside another for loop or inside a while or do...while loop. Similarly, while and do while loops can be nested.
| * program to understand nesting in for loop * |
#include<stdio.h>
main()
{
int i,j ;
for (i = 1 ; i<=3 ; itt) |* Outer loop *|
{
printf (“i=%d|n”, i)
for (j=1 ; j<=4 ; j++) |* inner loop *|
printf (“j=%d\t”,j) ;
printf (“\n”) ;
}
}

Output:
i = 1
j = 1 j = 2 j = 3 j = 4
i = 2
j = 1 j = 2 j = 3 j = 4
i = 3

j = 1 j = 2 j = 3 j = 4

Comments

Popular posts from this blog

Object Oriented Programming

Object Oriented Programming Programming paradigm that represents the concept of "objects" that have data fields (attributes that describe the object) and associated procedures known as methods Programming methodology based on objects, instead of just functions and procedures Focuses on data rather than process As individual objects can be modified without affecting other aspects of the program, it is easier for programmers to structure and organize software programs Easier to update and change programs written in object-oriented languages Simula was the first object oriented programming language Eg: C++, Java, etc. Features of OOPS Objects Referred as instance of class Basic run-time entities in an object-oriented system a person, a place, a bank account, a table of data, etc can be an object They occupy space in memory that keeps its state  Each object contains data and code to manipulate the data  Classes Blue print or prototype  which ...

Passing arrays to functions in C programming

Like any other variables, we can also pass entire array to a function. An array name can be named as an argument for the prototype declaration and in function header. When we call the function no need to subscript or square brackets. When we pass array that pass as a call by reference because the array name is address for that array. /* Program to illustrate passing array to function */ #include<stdio.h> void display(int) ; /* function prototype */ main( ) { int num[5] = {100, 20, 40, 15, 33, i ; clrscr( ) ; printf (“\n The content of array is \n”) ; for (i=0; i<5; i++) display (num[i]) ; /*Pass array element fo fun */ getch{ } ; } void display(int n) { printf (“\t%d”, n ) ; } Output:     The content of array is 100      20       40       15 3 /* Program to read 10 numbers from keyboard to store these num into array and then c...

Software Development Life Cycle

Software Crisis In earlier days, same codes needed to be written time and again increasing the complexity and time required for development This resulted in software not being completed on time and the cost increased than expected Solution: Object Oriented Programming Software Evolution Investigation Feasibility Study Analysis Design Implementation Maintenance Investigation First step in preparation of the IS includes the preliminary study of proposed information system investigates the information needs of the users and determines the resource requirement, costs, benefits and feasibility of a proposed project 2. Feasibility Study feasibility study is an analysis of the practicality of an idea focuses on helping answer the essential question of “should we proceed with the proposed project idea?” The feasibility study is conducted in four different areas: 1. Organizational feasibility 2. Economic feasibility 3. Technical feasibility 4. Operation...