learnprogramming123

LEARN PROGRAMMING 123
your resources to programming and free tutition



Navigation

 
C
 
C++ soon here!
VB - soon here!

Search

 

 

 

 

Next Back

 

The lesson will show you how to:

  • Use the for loop

Q. How do you make a blonde laugh on a Saturday?
A. Tell her a joke on a Wednesday

Iteration, for loops

    The basic format of the for statement is:

for (start condition; continue condition; re-evaluation)
program statement;

    /* Sample program using a for statement */

#include <stdio.h>

int main(void)
{

int count;

for (count = 1; count <=10; count = count + 1)
printf(“%d”, count);

printf(”\n”);

return 0;

}

Sample program output

1 2 3 4 5 6 7 8 9 10

The program declares an integer variable count. The first part of the for statement

    for (count = 1
Initializes the value of count to 1. The for loop continues whilst the condition

    count <=10
Evaluates to TRUE. A s the variable count has just been initialized to 1, this condition is TRUE and so the program statement

    printf(“%d”, count );
Is executed, which prints the value of count to the screen, followed by a space character. Next, the remaining statement of the for is executed

    count = count + 1)
Which adds one to the current value of count. Control now passes back to the conditional test,

    count <= 10
Which evaluates as TRUE, so the program statement

    printf(“%d”, count);
Is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of 11. When this occurs the conditional test

    count <= 10
Evaluates as FALSE, and the for loop terminates, and program control passes to the statement

    printf(“\n”);
Which prints a new line, and then the program terminates, as there are no more statements left to execute.

    // sample program using a for statement

#include <stdio.h>

int main(void)
{

int n, t_number;
t_number = 0;

for (n = 1; n <= 200; n = n + 1)
    t_number = t_number + n;

printf(“The 200th triangular_number is %d\n”, t_number);

return 0;

}

Sample program output

The 200th triangular_number is 20100

The above program uses a for loop to calculate the sum of the numbers from 1 to 200 inclusive (said to be the triangular number).

An example of using a for loop to print out characters

#include <stdio.h>

int main(void)
{

char letter;

for (letter = ‘A’; letter <= ‘E’; letter = letter + 1)
{
    printf(“%c”, letter);
}

return 0;


}

back to top          exercises     lesson 8          lesson 10

 


 






1