C - Doing something x number of times using for statement

Description

Doing something x number of times using for statement

Demo

#include <stdio.h> 

int main() /*from   www .  j  a  v  a  2 s.c o m*/
{ 
      int x; 

      for(x=0; x<10; x=x+1) 
      { 
          puts("Sore shoulder surgery"); 
      } 
      return(0); 
}

Result

for loop does everything required of a loop in a single statement:

for(initialization; exit_condition; repeat_each) 

initialization is a C language statement that's evaluated at the start of the loop.

It's where the variable that's used to count the loop's iterations is initialized.

exit_condition is the test upon which the loop stops.

In a for loop, the statements continue to repeat as long as the exit condition is true.

exit_condition is most often a comparison.

repeat_each is a statement that's executed once every iteration.

It's normally an operation affecting the variable that's initialized in the first part of the for statement.

The for statement is followed by a group of statements held in curly brackets:

for(x=0; x<10; x=x+1) 
{ 
      puts("Sore shoulder surgery"); 
} 

You can omit the brackets when only one statement is specified:

for(x=0; x<10; x=x+1) 
      puts("Sore shoulder surgery"); 

In this for statement, the first expression is initialization: x=0

The value of the int variable x is set to 0.

In C, you start counting with 0, not with 1.

The second expression sets the loop's exit condition: x<10

As long as the value of variable x is less than 10, the loop repeats.

Once that condition is false, the loop stops.

The following code shows another example of a simple for loop. It displays values from -5 through 5.

Demo

#include <stdio.h> 

int main() // w  ww . j  av  a  2s.c  om
{ 
   int count; 

   for(count=-5; count<6; count=count+1) 
   { 
       printf("%d\n",count); 
   } 
   return(0); 
}

Result

Related Example