For loop in C++

C++ For Loop :

On this page we will discuss about for loop in c++ language.In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly as long as it satisfies the given condition.

for loop in c++

Looping in C++

Whenever, we need to do some repetitive task over and over again. We use looping, by using logical statements we tell our program how many times we want repetitive statements to be executed over and over.

Example –

  • Printing hello world 100 times
  • Printing first 100 natural numbers

Basic Syntax of a for Loop

for(statement1 ; statement2; statement3)
{
    // execute this code
}
  • Statement 1:  Called initialization part. Executed once, before execution of code block.
  • Statement 2: Called condition part of the loop. Executed every time before execution of code block to check if the condition is satisfied
  • Statement 3: Called incrementation part. Executing every time after code block inside is executed
For Loop in C++

Example 1:

Run
#include<iostream>  
using namespace std;
int main()
{
    int n = 10;
    for(int i = 1; i <= n; i++){
        cout << i << " ";
    }
    return 0;
}

output:

1 2 3 4 5 6 7 8 9 10

Example 2:

Run
#include<iostream>
using namespace std;
int main()
{
    int n = 20;
    for(int i = 0; i <= n; i = i + 2){
        cout << i << " ";
    }
    return 0;
}

Output:

0 2 4 6 8 10 12 14 16 18 20

Example 3:

Run
#include<iostram>
using namespace std;
int main()
{
    string s1 = "PrepInsta";
    // string ends when you encounter \0 character at the end
    // if this new do not worry its a little too advanced
    // we will learn this in strings part of C++
    for(int i = 0; s1[i] != '\0' ; i++){
        cout << s1[i] << " ";
    }
    return 0;
}

Output:

P r e p I n s t a

Example:

Run
#include<iostream>
using namespace std;
int main()
{
    int i = 1;
    // we can keep all 3 parts : initialization, condition, increment
    // empty and the for loop will still run
    // but will run infinitely
    for( ; ; ){
        cout << i << " ";
    }
    return 0;
}

Output:

1 1 1 1 1 1 ... printed infinitely ...

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription