C++ 11: For Loop

In computer programming, loops are used to repeat a block of code.

For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.

Syntax:

    for(initilization;condition;update){

                    -----

                    -----

    }


Working: 

  • Here, frist the condition is checked the initia
    lization of for loop ariable takes place only one line. Then the given condition is checked.
  • The condition is true then the program control either enter the loop and executes the code in the loop.
  • When it reaches to the end of the loop, the program control is move to update the value of the loop variable.
  • After updating the variable value of the loop variable.
  • If the condition is true then the above process repeats otherwise the program control exits from loop.
NOTE:
  • If opening and closing braces { , } are not specified with specified with the loop the for loop then by default executes only one line of code.
  • Try to avoid opening and closing braces if you want to execute only one line of code within the loop.
  • Use the opening and closing braces if you want to execute more than one line of code inside the loop.

Program:
#include <iostream>
using namespace std;
main()
{
    int c = 0;
    for (int i = 1i <= 5i++)
    {
        cout << "Value of i is " << i << endl;
    }
    return 0;
}

Output

Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5

WAP to find sum of all numbers upto entered that number.

#include <iostream>
using namespace std;
main()
{
    int n;
    int sum;

    cout << "Enter a number: ";
    cin >> n;

    for (int i = 1i <= ni++)
    {
        sum = sum + i;
    }
    cout << "Sum of numbers is " << sum;

    return 0;
}

Output

Enter a number: 5
Sum of numbers is 15

WAP to check it is prime or not

#include <iostream>
using namespace std;
main()
{
    cout << "Enter a Nuber: ";
    cin >> n;

    for (int i = 1i <= ni++)
    {
        if (n % i == 0)
        {
            c++;
        }
    }
    if (c == 2)
        cout << "Entered Number is Prime" << endl;
    else
    {
        cout << "Entered NUmber is Composite" << endl;
    }
    return 0;
}

Output:

Enter a Nuber: 19
Entered Number is Prime


Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected