Learn C - C for






The simple scenario that illustrates iteration scenario is to show list of number.

The general pattern for the for loop is:

for(init_condition; control_condition ; action_per_iteration){
   loop_statement;
}
next_statement;

The statement to be repeated is represented by loop_statement.

The init_condition usually sets an initial value to a loop control variable.

The loop control variable tracks how many time the loop have been done.

You can declare and initialize several variables of the same type here separated by commas. All the variables defined in init_condition are local to the loop and will not exist once the loop ends.

The control_condition is a logical expression evaluating to true or false.

This determines whether the loop should continue to be executed.

As long as this condition has the value true, the loop continues.

It typically checks the value of the loop control variable.

The control_condition is tested at the beginning of the loop rather than at the end.

The loop_statement will not be executed at all if the control_condition starts out as false.

The action_per_iteration is executed at the end of each loop iteration. It is usually an increment or decrement of one or more loop control variables.

At each loop iteration, loop_statement is executed.

The loop is terminated, and execution continues with next_statement as soon as the control_condition is false.

The following code shows how to Sum the integers from 1 to a user-specified number.


    #include <stdio.h>
//from   w w w  .  j  a v a  2  s .c o  m
    int main(void)
    {
      unsigned  long long sum = 0LL;            // Stores the sum of the integers
      unsigned int count = 0;                   // The number of integers to be summed

      // Read the number of integers to be summed
      printf("\nEnter the number of integers you want to sum: ");
      scanf(" %u", &count);

      // Sum integers from 1 to count
      for(unsigned int i = 1 ; i <= count ; ++i)
        sum += i;

      printf("\nTotal of the first %u numbers is %llu\n", count, sum);
      return 0;
    }

We do not need to put any parameters in the for loop statement. The minimal for loop looks like this:

for( ;; ){
  /* statements */
}

The code above generates the following result.





Example

The following code is to do iteration until the number value less than 10.


  #include <stdio.h> 
// w  ww  .  j  av a2s  .c o m
  int main() { 
      
     int i; 
     for(i=0;i<10;i++){ 
             printf("data %d\n",i); 
     } 
     return 0; 
  } 

The code above generates the following result.





Example 2

You use the for loop to execute statements for a number of times.

To display the numbers from 1 to 10, you could write this:


#include <stdio.h>
//  www  .  jav  a  2  s .  co  m
int main(void)
{
    
    int count = 0;
    for(count = 1 ; count <= 10 ; ++count)
    {
        printf("  %d", count);
    }
    printf("\nAfter the loop count has the value %d.\n", count);
    return 0;
}

The code above generates the following result.

Example 3

You don't need to specify the first control expression at all, and the for loop could look like this:


#include <stdio.h>
//from   w ww .j  a v a 2  s. c o  m
int main(void)
{
  int count = 1;
  for( ; count <= 10 ; ++count) {
    printf("  %d", count);
  }
  printf("\nAfter the loop count has the value %d.\n", count);
  return 0;
}

The code above generates the following result.

Example 4

The following code uses for loop to draw a box.


    #include <stdio.h>
//  w w  w  . j a  va  2s. co  m
    int main(void)
    {
      printf("\n**************");         // Draw the top of the box

      for(int count = 1 ; count <= 8 ; ++count)
        printf("\n*            *");       // Draw the sides of the box

      printf("\n**************\n");       // Draw the bottom of the box
      return 0;
    }

The code above generates the following result.

Example 5

This example demonstrates how do calculation within the third control expression in a for loop:


    #include <stdio.h>
/*  w  ww.j  av a2 s. c om*/
    int main(void)
    {
      unsigned  long long sum = 0LL;            // Stores the sum of the integers
      unsigned int count = 0;                   // The number of integers to be summed

      // Read the number of integers to be summed
      printf("\nEnter the number of integers you want to sum: ");
      scanf(" %u", &count);

      // Sum integers from 1 to count
      for(unsigned int i = 1 ; i <= count ; sum += i++);

      printf("\nTotal of the first %u numbers is %llu\n", count, sum);
      return 0;
    }

The code above generates the following result.

Modifying the for Loop Control Variable

The following code show to incrementing the loop control variable by a certain number and sum the first n integers backward.


#include <stdio.h>
int main(void)
{//  w ww  .  j  av  a 2s .  c o m
  unsigned  long long sum = 0LL;            // Stores the sum of the integers
  unsigned int count = 0;                   // The number of integers to be summed

  // Read the number of integers to be summed
  printf("\nEnter the number of integers you want to sum: ");
  scanf(" %u", &count);

  // Sum integers from count to 1
  for(unsigned int i = count ; i >= 1 ; sum += i--);

  printf("\nTotal of the first %u numbers is %llu\n", count, sum);
  return 0;
}

The code above generates the following result.

Limiting Input Using a for Loop

You can use a for loop to limit the amount of input from the user.


#include <stdio.h>
//from w  w  w. j  a v  a2  s . c o  m
int main(void)
{
  int chosen = 5;                     // The lucky number
  int guess = 0;                      // Stores a guess
  int count = 3;                      // The maximum number of tries

  printf("\nGuessing game.");
  for( ; count > 0 ; --count)
  {
    printf("\nYou have %d tr%s left.", count, count == 1 ? "y" : "ies");
    printf("\nEnter a guess: ");      // Prompt for a guess
    scanf("%d", &guess);              // Read in a guess

    // Check for a correct guess
    if(guess == chosen)
    {
      printf("\nCorrect!\n");
      return 0;                       // End the program
    }
    else if(guess < 1 || guess > 10)  // Check for an invalid guess
      printf("between 1 and 10.\n ");
    else
      printf("Sorry, %d is wrong. My number is %s than that.\n",
                            guess, chosen > guess ? "greater" : "less");
  }
  printf("\nYou have had three tries and failed. The number was %d\n", chosen);
  return 0;
}

The code above generates the following result.

Nested Loops

You may place one loop inside another.

The following code shows how to Output a box with given width and height.


#include <stdio.h>
/*w ww  .  j a  va2  s.co  m*/
int main(void) {
      int width = 10;
      int height = 30;

      // Output the top of the box with width asterisks
      for(unsigned int i = 0 ; i < width ; ++i)
         printf("*");

      // Output height-2 rows of width characters with * at each end and spaces inside
      for(unsigned int j = 0 ; j < height - 2 ; ++j)   {
         printf("\n*");                               // First asterisk

        // Next draw the spaces
        for(unsigned int i = 0 ; i < width - 2 ; ++i)
          printf(" ");
        printf("*");                                 // Last asterisk
      }
      // Output the bottom of the box
      printf("\n");                                  // Start on newline
      for(unsigned int i = 0 ; i < width ; ++i)
         printf("*");

      printf("\n");                                  // Newline at end of last line
      return 0;
}

The code above generates the following result.

Example 7

The following code uses nested loop to get Sums of successive integer sequences.


    #include <stdio.h>
/*from ww  w . j av a 2s. c om*/
    int main(void)
    {
      unsigned long sum = 0UL;             // Stores the sum of integers
      unsigned int count = 5;              // Number of sums to be calculated

      for(unsigned int i = 1 ; i <= count ; ++i)
      {
        sum = 0UL;                         // Initialize sum for the inner loop

        // Calculate sum of integers from 1 to i
        for(unsigned int j = 1 ; j <= i ; ++j)
          sum += j;

        printf("\n%u\t%5lu", i, sum);      // Output sum of 1 to i
      }
      printf("\n");
      return 0;
    }

The code above generates the following result.