How to get input from user in a for loop in C++

In this tutorial, we will learn about for loop, and how to get user input in for loop in C++.

What is a for iteration statement?

for iteration statement specifies counter-controlled-iteration details in a single line of code. A for loop is used when we know the number of times our loop has to run. The syntax of a for loop is as follows:

for(i=0//initialization;i<n//condition;i++//increment or decrement)
{
//statements;
}

All the three expressions in a for statement header are optional. If the loop continuation condition is omitted, it is assumed that the condition is never false. Initialization expression can be omitted if the looping variable is initialized before the loop. Similarly, increment condition can be omitted if no increment is needed, or if the incremented value is calculated inside the loop’s body.

Taking only integer input in C++

How to take user input in a for-loop:

We can take input from the user using the console input(cin) statement:

//program to take marks of five subjects of a student as input and display avg as output.
#include<iostream>
using namespace std;
int main()
{
    int i,sum=0,marks[10];
    float avg;
    for(i=0;i<5;i++)
    {
        cout<<"\n enter the marks of student in subject "<<i+1<<": ";
        cin>>marks[i];
        sum+=marks[i];
    }
    avg=sum/5;
    cout<<"the average marks are: "<<avg<<endl;
    return 0;
}

The output of the above program is given below:

 enter the marks of student in subject 1: 56

 enter the marks of student in subject 2: 65

 enter the marks of student in subject 3: 73

 enter the marks of student in subject 4: 45

 enter the marks of student in subject 5: 90
the average marks are: 65

The for loop can be used to take inputs in the form of strings, characters and floating-point numbers as well.

With this, we come to the end of this tutorial.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *