The For Statement in C programming



The For Statement

The for repetition statement handles all the details of counter-controlled repetition. The general format of the for statement:


    for ( exp1; exp2; exp3  ) {   
          statement
    }

Often, exp1 and exp3 are comma-separated lists of expressions. The commas as used here are actually comma operators that guarantee that lists of expressions evaluate from left to right.

The value and type of a comma-separated list of expressions are the value and type of the rightmost expression in the list.

The following code demonstrates the for statement:

   
    // Summation with for (odd numbers from 2 to 100)  
    #include <stdio.h>
    
    // function main begins program execution
    int main( void )
    {
     unsigned int sum = 0; // initialize sum
     unsigned int number;  // number to be added to sum
     for ( number = 2; number <= 100; number += 2 ) {
     sum += number; // add number to sum          
     } // end for
     printf( "Sum is %u\n", sum ); // output sum
    } // end function main

    Output:
    Sum is : 2550

Another example using the For Statement

The c program below demonstrates the use of for statement to calculate the compound interest.

   
    // Calculating compound interest
    #include <stdio.h>
    #include <math.h>  
    
    // function main begins program execution
    int main( void )
    {
     double amount; // amount on deposit
     double principal = 1000.0; // starting principal
     double rate = .05; // annual interest rate
     unsigned int year; // year counter
    
    // output table column heads
     printf( "%4s%21s\n", "Year", "Amount on deposit" );
    
    // calculate amount on deposit for each of ten years
     for ( year = 1; year <= 10; ++year ) {
    
    // calculate new amount for specified year
      amount = principal * pow( 1.0 + rate, year );
    
    // output one table row
      printf( "%4u%21.2f\n", year, amount );   
      } // end for
    } // end function main

   Output:
   Year  Amount on deposit
    1		1050.00
    2		1102.50	
    3		1157.63
    4		1215.51
    5		1276.28
    6		1340.10
    7		1407.10
    8		1477.46
    9		1551.33
    10		1628.89

Note: This example made use of the <math.h> library, which we will discuss in C Math tutorial.


Ads Right