Looping Statements:
If any process has to be repeated for finite or infinite number of times until the condition evaluates to false is considered as looping or iteration
Loop Type | Description |
while loop | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
do…while loop | Like a while statement, except that it tests the condition at the end of the loop body |
for loop | Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
nested loops | You can use one or more loop inside any another while, for or do..while loop. |
While Loop:
It is a pre-tested loop construct.
The condition is evaluated before the body of the loop gets executed
while(condition)
{
statement(s);
}
- Body of the loop can have more than one statement
- {} braces should be provided for multi-statement
- Including braces for individual statements increases readability
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/*Program to find sum of First N Numbers */ #include <stdio.h> int main() { int sum=0; int current=1; int max; printf("Enter the last number: "); scanf("%d",&max); while(current <= max) { sum += current; current++; } printf("Sum of all numbers till %d is: %d",max,sum); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/*Program to find the factorial of a number*/ #include<stdio.h> void main() { int x,n,fact; printf("\n Enter the value of n ;"); scanf("%d",&n); x=1;fact=1; while(x<=n) { fact*=x; x++; } printf("\n the factorial of a number is :",fact); } |
Mr. Sandeep Soni
Founder, Trainer & CEO, Deccansoft Software Services.
Sandeep has 21 yrs of experience working in various Microsoft Technologies/Platforms incl. VB6.0, ASP, VC++, VB.NET, C#. He is involved in managing and architecting projects at Deccansoft. He will be your liaison to Deccansoft, for any kind of communication and project updates. He knows what works and what doesn’t, and what practices are most suitable for design and programming with the ultimate goal of producing a quality system.