For Versus While Loop in C

CProgrammingServer Side Programming

For Loop

The for loop is a repetition control structure. It executes the statements a specific number of times. First, it takes the initial value from where it starts the iterations. Second, it takes the condition, which is checked for true, or false. At the end, it increment/ decrement and update the loop variables.

Here is the syntax of for loop in C language,

for ( init; condition; increment ) {
   statement(s);
}

Here is an example of for loop in C language,

Example

 Live Demo

#include <stdio.h>
int main () {
   int a = 5;
   for(int i=0;i<=5;i++) {
      printf("Value of a: %d\n", a);
      a++;
   }
   return 0;
}

Output

Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
Value of a: 10

While Loop

While loop is used to execute the statements inside the while loop block till the condition is true. It takes only one condition to execute statements inside the block. As the condition becomes false, it stops and execute the statements below the while loop.

Here is the syntax of while loop in C language,

while(condition) {
   statement(s);
}

Here is an example of while loop in C language,

Example

Live Demo

#include <stdio.h>
int main () {
   int a = 5;
   while( a < 10 ) {
      printf("Value of a: %d\n", a);
      a++;
   }
   return 0;
}

Output

Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
raja
Published on 08-Oct-2018 12:18:57
Advertisements