The for Loop in C

the syntax and programming examples on the use of for loop

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

A for statement is used to repeatedly run a set of one or more statements. It's one of the options for running a loop, in addition to the while statement that we have already seen. The looping continues till a condition continues to be true or until a jump, like a break, or goto statement causes the control to transfer out of the loop. A return statement also terminates a for loop.

The Syntax

The following code shows a simple for loop that prints a line exactly five times.


int main()
{
    for(int i = 0; i < 5; i++)
    {
        cout << "Hoven Trainings" << endl;
    }
 
    return 0;
}
 

A for statement is made up of three expressions, each of which is separated by a semi-colon. The first expression is called the initialization expression. It is used to give initial values to the loop variables. It also serves as a convenient place to define the for loop variables. In the above example, this is the initialization expression.

int i = 0;

The second expression is called the condition expression, that evaluates to a boolean true or false value. If this expression evaluates to true, the looping can continue, provided of course, that other things such as a break statement donot cause an exit. In the above for loop, the following is the condition expression.

i < 5;

The third expression is called the loop expression. Typically, it is a postfix increment or decrement expression. The loop expression is used to bring the loop variable closer and closer to the exit condition. In the loop above, following is the loop expression.

i++

Each of the above three expressions is optional. Following rules may be taken note of -

  1. If the initialization expression is present, then it is always evaluated.
  2. If the condition expression is present, then it is evaluated as a boolean value. So it is either true or false. If the condition expression is not present, then it is treated as evaluate to true.
  3. If the loop expression is present, then it is evaluated only if the condition expression evaluates to true.

A for loop can be run as an infinite loop by omitting the condition expression. In that case the condition is always treated as true. Such a loop should be exited by using either a break, or a goto or a return statement. The following is the common method of running a for loop in infinite mode.

int main()
{
    for(; ; )
    {
        // must have an exit possibility by using 
        // the break, goto or return statement
    }
 
    return 0;
}

It is also possible to specify multiple statements in the intialization and loop expressions. Such statements must be separated by commas. They can be used to define two or more variables if the variables are required in the body of the loop. Another use case is when the condition expression has to depend on multiple factors. In the following code, the loop continues for a maximum of 10 times, but terminates immediately when the user enters a number greater than 10.

int main()
{
    for(int x = 0, y = 0; x < 10; y++)
    {
        cout << "Enter a number(less than 10):";
 
        cin >> y;
 
        if(y >= 10)
        {
            break;
        }
 
        cout << "Square = " << (y * y) << endl;
    }
 
    return 0;
}

The condition expression can contain one or more logical expressions, and can also be constructed with one or more variables as shown below. Please note that this code is not equivalent to the above code. I have written it only to demonstrate the use of multiple logic expressions involving more than one variable.

int main()
{
    for(int x = 0, y = 0; x < 10 || (y < 10); y++)
    {
        cout << "Enter a number(less than 10):";
 
        cin >> y;
 
        cout << "Square = " << (y * y) << endl;
    }
 
    return 0;
}

The following code uses two variables in each of the three expressions. The looping continues till the sum of x and y is less than 10.

int main()
{
    for(int x = 0, y = 9; (x + y) < 10; y--, x++)
    {
        cout << "Enter a number:";
 
        cin >> y;
 
        cout << "Square = " << (y * y) << endl;
    }
 
    return 0;
}

Print a String in Reverse Order

The following code can be used to print the characters of a string in reverse order. The strlen function is used to calculate the number of characters in the string. If you are not yet familiar with char arrays then you can skip this program.

int main()
{
    char cName[] = "http://www.hoventrainings.com";
 
    for(int x = strlen(cName); x > 0;)
    {
        cout << cName[--x];
    }
 
    return 0;
}
 

Count the Number of Characters

Following is a program to count the number of "t" in the string - http://www.hoventrainings.com. This for loop uses a complicated loop expression that is written using the ternary operator. There are no hard and fast rules for constructing the three expressions, but you must write expressions which make your code readable, and brief, and of course, efficient. The code below is not necessarily ideal, but it does push the idea of using the loop expression in imaginative and artistic ways.

#include <iostream>
#include <cstring>
 
using namespace std;
 
int main()
{
    char cName[] = "http://www.hoventrainings.com";
 
    int counter = 0;
 
    for(
        int x = strlen(cName);
        x > 0;
        (cName[--x] == 't' ? counter++ : counter)
     )
    {
    }
 
    cout << "Count of lowercase \"t\": ";
 
    cout << counter << endl;
 
    return 0;
}
 

The choice of the three expressions and distribution of code in them can make a huge difference in the efficiency of your program. The above code looks a bit round about way of doing things, but it is efficient because the call to strlen takes place only once - just at the time of initialization. But if a developer chooses to write a code like the one below, then the calls to strlen occur as many times as is the length of the string because the call[to strlen] has been moved to the condition expression, which is evaluated before each run of the loop.

int main()
{
    char cName[] = "http://www.hoventrainings.com";
 
    int counter = 0;
 
    for(
        int x = 0;
        x < strlen(cName);
        (cName[x++] == 't' ? counter++ : counter)
     )
    {
    }
 
    cout << "Count of lowercase \"t\": ";
 
    cout << counter << endl;
 
    return 0;
}

A good developer always has his eye on the minute details, and the above code is one example that is a fit case that demonstrates such a need.

Complex for Loop

The three expressions of a for loop are not restricted to one-liners. They can be as complex as you want. For example you could call a function, and execute as much code as you want. In the following example, two functions are being called. One function returns a boolean, and is used for testing the loop condition. The loop condition is now determined by a value entered by the user. Another function is called as a part of the loop expression. You can also see a one-liner statement appear in the loop expression. This is also possible. You can have as many one liners, but they must be comma separated.

#include <iostream>
#include <string>
 
using namespace std;
 
bool fx()
{
    cout << "Continue?[Y/N]:";
 
    string str;
 
    getline(cin, str);
 
    switch(str[0])
    {
    case 'y':
    case 'Y':
        
        return true;
    
    default:
 
        cout << "Terminating ..." << endl;
    
        return false;
    }
}
 
void gx()
{
    cout << "gx() called !" << endl;
}
 
int main()
{
    for ( ; fx(); gx(), cout << "Hello Hoven" << endl )
    {
        ; // null statement
    }
 
    return 0;
}

Variable Scope and the for Loop

The variables declared inside a for loop are not available outside the body of the for loop. In the code below, accessing the variable x will give an error. Please note that some compilers do not implement this requirement of the C++ Standard.

int main()
{
    for(int x = 0; x < 10; x++)
    {
        cout << x << endl;
    }
 
    // ERROR, x is not available 
    // outside the for loop
    cout << x << endl;
 
    return 0;
}

for loop - Series

Write a program to print the following series by using a 'for loop' 50, 48 ,46........................2...0.
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
 
int main() 
{    
    for(int i = 50 ; i >= 0; i = i - 2 )
    {
        
        printf("%d \n",i);
    
    }
    
    return 0;
      
}

for loop - Sum

Write a program to find the sum of 'n' natural numbers. Obtain the value of n from the user.
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main() 
{
    
    int i, n, sum;
    
    sum = 0;
    
    cin >> n;
    
    for( i = 1; i <= n; i++ )
    {
     
        sum = sum + i;
     
    }
     
    printf("%d",sum);
     
    return 0;
      
}

for loop - Factorial

Write a program to find the factorial of number entered through keyboard. Factorial is a product of numbers till 1. For example, factorial of 5 is 5 X 4 X 3 X 2 X 1.
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main()
{
    cout << "Enter no.: ";
 
    int n;
 
    cin >> n;
 
    int facto = 1;
 
    for(int i = 1; i <= n; i ++ )
    {
 
        facto *= i;
 
    }
 
    cout << facto << endl;
 
    return 0;
} 

for loop - Multiplication Table

Write a program to print the multiplication table of a number obtained from a user.
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main() 
{
      
    int n, m, i;
     
    printf("Enter any no.: ");
    
    cin >> n;
     
    for(i=1; i<=10; i++)
    {
        
        m = n*i;
    
        printf("%d * %d = %d\n",n , i ,m);
    
    }
    
    return 0;
      
}

Alternate Solution

This is an alternate solution using cout, instead of printf.
int main()
{
    cout << "Enter a positive number:";
    
    int n;
 
     cin >> n;
 
    for(int i = 1; i <= 10; i++)
    {
        cout << n << " X " << i << " = " << (n * i) << endl;
    }
 
    return 0;
}

Another Shorter Solution

What is the trick in this one? Find out !
int main()
{
    cout << "Enter a positive number:";
    
    int n;
 
     cin >> n;
 
    for(
        int i = 1; 
        i <= 10; 
        cout << n << " X " << i << " = " << (n * i) << endl, 
        i++
     ) ;
 
    return 0;
}

for loop - Number Pattern

Write a program to print the following pattern.

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5 
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main() 
{
    
    int i, j;
 
    for( i = 1 ; i<= 5; i++ )
    {
        
        for( j = 5; j>= i; j--)
        {
            
            printf("%d", j);
        
        }
        
        printf( "\n" );
 
    }
    
    return 0;
      
}

for loop - Number Pattern

Write a program to print the following pattern.

 1
 2 2
 3 3 3
 4 4 4 4
 5 5 5 5 5 
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main() 
{
    
    int i, j;
 
    for( i = 1; i <=5 ; i++ )
    {
        
        for( j = 1; j <= i; j++ )
        {
            
            printf("%d",i);
        
        }
    
     printf("\n");
    
    }
         
    return 0;
      
}

for loop - Floyd's Triangle

Write a program to print Floyd's triangle.


1
2 3
4 5 6
7 8 9 10
#include<iostream> 
#include<cstdio> 
 
using namespace std ;
 
int main() 
{
    
    int n, i, c, a = 1;
     
    printf("Enter the number of rows = ");
     
    cin >> n;
     
    for(i = 1; i <= n; i++)
    {
        
        for(c = 1; c <= i; c++)
        {
            
            printf("%d ",a);
        
            a++;
        
        }
        
        printf("\n");
    
    }
 
    return 0;
      
}

Classroom Training

Classroom training in C/C++ is available at our training institute. Click here for details. You can also register yourself here.

Video Tutorial

We have created a video tutorial that can be downloaded and watched offline on your windows based computer. It is in the form of an exe file. No installation is required, it runs by double clicking the file. Since the exe file is hosted on the Google Drive, it should be very safe because Google itself checks for any virus or malware. The video can be watched offline, no internet is required.

Pricing

This single video will cost you USD $5. When you download the video, you will be able to watch the first few minutes for free, as a sample. The video app will prompt you for payment through PayPal and other payment options. If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials The entire set is priced at USD $50.

Screenshots

This is a screenshot of the software that should give you a good idea of the available functionality. Click on the image to see a larger view.screenshot of the video being played in the software

Installation

This software doesn't require any installation. Just download and double-click to run it. It doesn't require administrative priviliges to run. It runs in limited access mode, so should be very safe.

supports windows xp and later Supported Operating Systems

These videos can be run on 32-bit as well as 64-bit versions of the Microsoft Windows Operating Systems. Windows XP and all later OS are supported. If you want to run it on Windows XP and Windows Vista, then you must also have the .NET Framework Version 3.5 installed on your machines. Those users who have Windows 7 and later donot have to worry because these operating systems already have the .NET Framework installed on them.

Download Links

IMPORTANT NOTE: This download contains ONLY ONE video. The video is about the topic of this tutorial.

Want ALL Videos? If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials. TIP: If you plan to buy these videos, then it would be more economical to buy the entire set.

DISCLAIMER: Even though every care has been taken in making this software bug-free, but still please take a proper backup of your PC data before you use it. We shall not be responsible for any damages or consequential damages arising out of the use of this software. Please use it solely at your own risk.

Please download the software here.
download the video for Loop in C



Creative Commons License
This Blog Post/Article "The for Loop in C" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-10-05