Friday, July 29, 2016

C Basics - The for Loop in C

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop is,

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

The for allows us to specify three things about a loop in a single line:
  • Setting a loop counter to an initial value.
  • Testing the loop counter to determine whether its value has reached the number of repetitions desired.
  • Increasing the value of loop counter each time the program segment within the loop has been executed.
The general form of for statement is,

for ( initialize counter; test counter; increment counter)
{
  do this;
  and this;
  and this;
}

The initialization expression of the for loop can contain more than one statement separated by a comma.

#include <stdio.h>
 
int main () {

   int i;
 
   for( i = 0; i < 5; i++ ){
      printf("value of i is: %d\n", i);
   }
 
   return 0;
}
Output of above program,

value of i is: 0
value of i is: 1
value of i is: 2
value of i is: 3
value of i is: 4



Related topics:
Loops in C   |   The while Loop in C   |   The do-while Loop in C   |   Nested Loop in C   |   Infinite Loop in C   |   Loop Control Statements in C   |   The break Statement in C   |   The continue Statement in C   |   The goto Statement in C   |   The return Statement in C

List of topics: C Programming

No comments:

Post a Comment