×

For Loop in C Programming Examples

The Syntax of the For Loop

for (initialization statement; termination condition; modifying (increment/ decrement) statement)
{
      /* main body of the For loop */    
}

In for loop, the initialization command is implemented only once.

After that, it checks the test expression of the loop and finds whether the test expression is false or true. And, for loop is dismissed if the test expression is false.

If the test expression of the 'for' loop becomes true, then the program line provided in the 'for' loop's body is executed, and the update expression is changed accordingly.

Again, the entire process of evaluation is to be done. The loop executes its body until and unless the value of the test expression in for loop becomes false. The loop automatically terminates as soon as the test expression result becomes false.

Example 1: Program of less than (<) termination condition.

In this program, we will try to print values from 21 to 30 with the help of for loop.

#include <stdio.h>
int main()
{
    int z; // declaration of variable
    for (z=21; z>30; ++z) /* (initialization statement, termination
     condition, increment or decrement statement) */
    {
        printf("THE VALUE OF 'z' IS  %d\n", z); // printing final value of 'z'
    }
    return 0;
}

Output:

THE VALUE OF ‘z’ IS  21
THE VALUE OF ‘z’ IS  22
THE VALUE OF ‘z’ IS  23
THE VALUE OF ‘z’ IS  24
THE VALUE OF ‘z’ IS  25
THE VALUE OF ‘z’ IS  26
THE VALUE OF ‘z’ IS  27
THE VALUE OF ‘z’ IS  28
THE VALUE OF ‘z’ IS  29

Explanation

In the above code, the initial value of "z" is set to 21(so that the code can start its evaluation from 21). After that, the termination condition (z<30) is evaluated for calculation.

As 21 is a smaller digit than 30. So, the condition is true for 21, and the statement provided inside the “For” loop is implemented. In the output, 21 will be printed on the screen as the final value after processing the entire program line. And, at last, the increment statement ++z is implemented to increase the value of “z”. Now, the value of “z” will become 22.

Again, the termination condition is checked for true or false, and if the condition is true, then the main body of the "For" loop is executed once again. This time the value of "z" will print 22 in the result. The increment statement ++z is evaluated again, and the value of z becomes 23.

This process will continuously evaluate until the value of “z” reaches 30. When the value becomes 30, the condition z<30 is declared as false, and the “For” loop will be terminated.

Example 2: Program of more than > termination condition.

In this program, we will try to print values from 55 to 48 using the 'for' loop.

#include <stdio.h>
int main ()
{
    int z; // declaration of variable
    for (z=55; z>47; --z) /* (initialization statement, termination
     condition, incrementor decrement statement) */
    {
        printf("THE VALUE OF 'z' IS  %d\n", z); // printing final value of 'z'
    }
    return 0;
}

Output:

THE VALUE OF 'z' IS  55
THE VALUE OF 'z' IS  54
THE VALUE OF 'z' IS  53
THE VALUE OF 'z' IS  52
THE VALUE OF 'z' IS  51
THE VALUE OF 'z' IS  50
THE VALUE OF 'z' IS  49
THE VALUE OF 'z' IS  48

Explanation

In the above code, the initial value of "z" is set to 55(so that the code can start its evaluation from 55). After that, the termination condition (z>30) is evaluated for calculation.

As 55 is a bigger digit than 47. So, the condition is true for 55, and the statement provided inside the “For” loop is implemented. In the output, 55 will be printed on the screen as the final value after processing the entire program line. And, at last, the decrement statement --z is implemented to decrease the value of “z”. Now, the value of “z” will become 54.

Again, the termination condition is checked for true or false, and if the condition is true, then the main body of the "For" loop is executed once again. This time the value of "z" will print 54 in the result. The decrement statement --z is evaluated again, and the value of z becomes 53.

This process will continuously evaluate until the value of “z” reaches 47. When the value becomes 47, the condition z>47 is declared as false, and the “For” loop will be terminated.

Example 3: Program of less than equal to<= termination condition.

In this program, we will try to calculate the sum of natural numbers with the help of for loop.

#include <stdio.h>
int main()
{
    int x, y, z = 0; // declaration of variables
    printf("Enter a positive integer: \n"); // taking input from user
    scanf("%d", &x); // assigning value to x
    for(y = 1; y <= x; ++y) /*initialization statement, 
    termination condition, increment/ decrement statement */
    {
        z += y; // main body of “for” loop including arithmetic operation
        which means adding the value in the previous one
    }
    printf("z = %d", z); // command to print the value of z
    return 0;
}

Output:

Enter a positive integer: 
40
z = 820

Explanation

The variable “x” stores the value entered by the user. As mentioned in the output, the user enters the value 40.

In the above code, the initial value of "y" is set to 1(so that the code can start its evaluation from 1). After that, the termination condition (y<=x) is evaluated for calculation.

If the test expression y <= x is true, the program lines inside the “For” Loop are implemented, and the value of “z” becomes 1. And, at last, the increment statement ++y is implemented to increase the value of “y”. Now, the value of “y” will become 2.

Again, the termination condition is checked for true or false, and if the condition is true, then the main body of the “For” loop is executed once again. This time the value of z becomes 3 in the result. The increment statement ++y is evaluated again, and the value of y becomes 3.

This process will continuously evaluate until the value of “y” gets not equal to the value of x.

When the value of y becomes equal to the value of x, the condition y<=x will become false, and the “For” loop will be terminated.

EXAMPLE 4: Program of more than equal to (>=) termination condition.

In this program, we will try to calculate the sum of consecutive random numbers with the help of for loop.

#include <stdio.h>


int main()


{
    int x, y, z = 0; // declaration of variables


    printf("Enter a positive integer: \n"); // taking input from user


    scanf("%d", &x); // assigning value to x


    for(y = 100; y >= x; --y) /*initialization statement, 
    termination condition, increment/ decrement statement */


    {
        z += y; // main body of “for” loop including arithmetic operation
        which means adding the value in the previous one
    }
    printf("The value of z is %d", z); // the program line to print 
    the value of z
    return 0;
}

Output:

Enter a positive integer: 
70
The value of z is 2635

Explanation

The variable x stores the value entered by the user. As mentioned in the output, the user enters the value 70. In the above code, the initial value of "y" is set to 100(so that the code can start its evaluation from 100). After that, the termination condition (y>=x) is evaluated for calculation.

If the test expression y >= x is true, the program lines inside the “For” Loop are implemented, and the value of “z” becomes 1. And at last, the decrement statement (--y) is implemented to decrease the value of “y”. Now, the value of “y” will become 99.

Again, the termination condition is checked for true or false, and if the condition is true, then the main body of the “For” loop is executed once again. This time the value of “y” will become 98. The decrement statement --y is evaluated again, and the value of y becomes 97.

This process will continuously evaluate until the value of “y” gets not equal to the x. When the value of y becomes equal to the value of x, the condition y>=x will become false, and the "For" loop will be terminated.


Related Topics

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

C Function Argument and Return Values

Functions in the C programming language are declared to avoid repeatedly writing a performable block of code; it is the same in any programming language. When it comes to the...

3 minutes read.

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

Entry Control Loop in C

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the...

3 minutes read.

Call by Value and Call by Reference in C

Call by reference and call by value are two different ways of passing arguments to a function in C programming language. Call by reference means that the called function is...

4 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Recursion in C

Recursion is a programming technique that allows the programmer to call the function within the same function. The function which calls the same function is known as recursive function but a...

1 minute read.

Prototype in C

A prototype is nothing but a model, a model of initial creation of an intended product. Similarly, in the C programming language, all functions have a prototype. In general, all...

4 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Nested loop in C

Definition of Nested Loop A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a...

3 minutes read.

Random Access - Lseek in C

Introduction lseek is a system call that is used to alter the location of the read/write pointer of a file descriptor. The lseek system call basically moves the current read/write location...

4 minutes read.

How to move a text in C

A text can be moved to the desired location in the output based on the coordinates provided in the gotoxy() function. What is gotoxy() function? In C language, gotoxy() is a pre-defined...

3 minutes read.

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

For loop in C Programming

In the C programming language, the for loop is used to repeatedly iterate over a set of instructions or a section of code. It is frequently used to traverse array-based...

3 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

Pascal Triangle in C

The pascal triangle in c is an array of binomial coefficients in triangular form. Here the nth row contains the binomial coefficient of ncr.In a pascal triangle, every number is...

2 minutes read.

Format Specifier in C

Format Specifier in C Format specifiers can be described as an operator that is used to print the data referred by any object or variable in combination with the printf ()...

3 minutes read.