It is used to execute group of statement repeatedly till the condition is satisfy.
C support three types of looping statement.Syntax: Initialization ; While(condition) { Block of statement// }Flowchart
#include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); while(i<=5) { printf("\n Hello world"); i++; } getch(); }o/p
Hello world Hello world Hello world Hello world Hello world
The main difference here is the condition is tested after the body of the loop and the statement in the body will be executed at least once whether the condition is true or false. This is not the case with the other two loops where if the condition is false at the beginning, then the body of the loop is not executed at all. Notice the semicolon at the end of the while line of code.
Syntax: initialization; do { Block of statement// }while(condition);Flowchart
#include<stdio.h> #include<conio.h> main() { int n, num, factorial = 1; printf ("Enter the number:"); scanf ("%d", &n); num = n; if (n < 0) printf ("\n factorial of negative number not possible:"); else if (n = = 0) printf ("Factorial of 0 is 1 \n"); else do { factorial * = n; n - -; } while (n > 1); printf ("factorial of % d = % d", no, fact); }o/p
if the value entered is 5, the program outputs 120 (i.e., 5 * 4 * 3 * 2 * 1).
A for loop allows execution of a statement (or a block of statements) repeatedly a number of times. When the number of times a statement is to be executed is known in advance, for loop is particularly useful. The syntax of for loop in C language is as follows
Syntax: for(<initialization>; <condition>; <modification>) { statement-1; }Flowchart
#include<stdio.h> #include<conio.h> main( ) { int i; clrscr(); for (i = 1; i <= 5; i ++) printf ("%d \n", i); getch(); }o/p
1 2 3 4 5