Pages

Wednesday, July 5, 2017

for loop in C++

C++ for Loop: Syntax and Example 


The for loop in C++ is used to repeat a block of code a fixed number of times. It is especially useful when the number of iterations is known in advance. 

Syntax 

for (initialization; condition; increment/decrement)
{
    // statements to be executed repeatedly
}

Key points 
  • Initialization: Declares and initializes the loop control variable (runs once). 
  • Condition: Checked before each iteration. If true, the loop continues. 
  • Increment/Decrement: Updates the loop variable after each iteration. 
  • All three parts of the for loop are optional, but the semicolons (;) are required.

Program 1: C++ program to print 1 to 10 numbers using for loop.

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

// Output of the program

1 2 3 4 5 6 7 8 9 10


Program 2: Print even numbers from 1 to 20

#include <iostream>
using namespace std;

int main() {
    for(int i=2; i<=20; i=i+2) {
        cout << i << " ";
    }
    return 0;
}

// Output of the program

2 4 6 8 10 12 14 16 18 20

Program 3: Find sum of first N natural numbers

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;
    cout << "Enter a number: ";
    cin >> n;

    for(int i = 1; i <= n; i++) {
        sum += i;
    }

    cout << "Sum = " << sum;
    return 0;
}

/* Output
Enter a number: 5
Sum = 15
*/


* * * * *

No comments:

Post a Comment