Beginner · C PROGRAMMING

For loops

What you will learn

Repeat a task a known number of times.

Understand the concept

A for loop has initialization, a continuation condition and an update expression. The condition is checked before each iteration. Here the accumulator begins at zero and adds each integer from one through five.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Total: 15

Practise

Change the limit to 10. Then add only even numbers by increasing the counter by two.

Common mistake

An incorrect < or <= condition causes off-by-one errors. Keep counter bounds within the range of int.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    int total = 0;
    for (int i = 1; i <= 5; ++i) {
        total += i;
    }
    printf("Total: %d\n", total);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Total: 15
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA