I was wondering if there is a way to increment and terminate a while loop based on the number of user inputs? Like, have the user enter a number, do something to said number, then prompt for a new number, rinse and repeat (x) number of times?
Here is my code, or lack thereof lol.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int num_1, num_2, num_3, num_4, num_5;
//while(user inputs <= 5)
// cout << "Enter a number" << endl;
// print that number
// sum number to total
// print sum
// return to beginning of loop
return 0;
}
Yes, you can do that. You just need a counter which will hold the information regarding the number of loop executions:
#include <iostream>
int main() {
int input = 0;
int sum = 0;
int user_input = 0; // counter for loop executions
while (user_input < 5) { // while the loop executed fewer than 5 times, execute the code...
++user_input; // ... and mark that the loop executed one more time
// code logic:
std::cout << "enter a number: ";
std::cin >> input;
sum += input;
std::cout << "the input: " << input << '\n';
std::cout << "sum so far: " << sum << '\n';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.