Docsity

Understanding Loops in C Programming: For, While, and Do While - Prof. lokhande, Exercises of Computer Communication Systems

Toggle sidebar
bg1
Loops
There are three types of loops:
for loop
while loop
do while loop
For Loop:
Syntax:
for (initialization; expression; update)
{
// statements inside the body of loop
}
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the body of
the for loop are executed, and the update expression is updated.
Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop
terminates.
pf3
pf4
pf5

Partial preview of the text

Download Understanding Loops in C Programming: For, While, and Do While - Prof. lokhande and more Exercises Computer Communication Systems in PDF only on Docsity!

Loops

There are three types of loops:  for loop  while loop  do while loop For Loop: Syntax: for (initialization; expression; update) { // statements inside the body of loop }  The initialization statement is executed only once.  Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.  However, if the test expression is evaluated to true, statements inside the body of the for loop are executed, and the update expression is updated.  Again the test expression is evaluated. This process goes on until the test expression is false. When the test expression is false, the loop terminates.

Example: #include <stdio.h> int main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } return 0; } Example: #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }

Do While loop: The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated. Syntax: do { // the body of the loop }while (expression);  The body of do...while loop is executed once. Only then, the expression is evaluated.  If expression is true, the body of the loop is executed again and expression is evaluated once more.  This process goes on until expression becomes false.  If expression is false, the loop ends.

Example: #include <stdio.h> int main() { double number, sum = 0; do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); return 0; }