Loops in C


INTRODUCTION

 Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save  time, reduce errors, and they make code more readable.

TYPES OF LOOPS

1.WHILE LOOP :Repeats a statement or group of statements until a given condition is true. It  testes the condition before executing the loop body. 

3 Steps to write while loop: 

1)Initialization, 2)Condition check, 3)Increment/Decrement

Syntax :

while (condition)

{

statements

}

                                                   



 Flowchart

Example
Question : Print 1 to 10 numbers
code :
#include<stdio.h>
int i=1;
int main()
{
while(i<=10)
{
printf("%d",i);
i++;
}
}

output: 1 2 3 4 5 6 7 8 9 10


2.FOR LOOP :Execute a sequence of statements multiple times and reduce the code that manages the loop variable.

3 Steps to write for loop: 

1)Initialization, 2)Condition check, 3)Increment/Decrement

Syntax :

for(initialization; condition check; increment/decrement )

{

statements

}



                                                                      Flowchart

Example

Question : Print 1 to 10 numbers

code :
#include<stdio.h>
int i;
int main()
{
for(i=1; i<=10; i++)                   // (if i want to print 10 to 1 then i=10; i>=1; i-- )
{
printf("% d \n", i);
}
}

output: 1 2 3 4 5 6 7 8 9 10


3.NESTED FOR LOOP :You can use one or more loops inside the main loop.

Syntax :

 for(init; condition check; inc/dec)

         {

             for(init; condition check; inc/dec)

                {

                        for(init; condition check; inc/dec)

                }

         }


                                                                              Flowchart

Example

code :
#include<stdio.h>
int i,j;
int main()
{
  for(i=0; i<=2; i++)                 
    {
        for(j=0; j<=2; j++)
           {
               printf("% d  %d ", i, j);
            }
     }
}

output : 00 01 02 10 11 12 20 21 22
               


No comments:

Post a Comment