My program asks a user to put in a number between 10 and 20. Then create a progression of the first number 10 multiples of that number (ie: 3, 6, 9, stopping at 30). We are using a generic form of C++. here is what i have so far. I know the total is 0; but for now that is fine. I cannot get the number to add up ten times. Please help this class is killing me.
int main() {
int counter = 0;
int number;
int total = 0;
cout << "Enter a number";
cin >> number;
cout << endl;
while (counter < 20) {
counter = (counter + number);
cout << counter;
cout << endl;
cout << ",";
}
cout << endl;
cout << "The total is";
cout << total;
return 0;
}
That's because you are comparing counter to 20 which is the max value a user can enter. So if you enter a number between 10 and 20, so for values from 10 to 19 you could get through the loop twice. But since any number between those values number+number < 20 it would stop after that. If you enter 20 to begin with it wouldn't even make it through that loop once. If you want it to loop 10 times a better way would be to have a separate variable that you increment every time through the loop and compare that to 10, which is the number of multiples you want to create. For this kind of loop a for loop would work just as well since you could declare and initialize the loop variable and increment it all in the for loop's initialization and test expression. Like:
1 2 3 4 5 6 7
for (int i = 0; i < 10, i++)
{
counter = (counter + number);
cout << counter;
cout << endl;
cout << ",";
}
If you wanted to calculate total of all those multiples that's easy enough to add into the for loop to, or the while loop, whichever one you fancy.
1 2 3 4 5 6 7 8
for (int i = 0; i < 10, i++)
{
counter = (counter + number);
cout << counter;
cout << endl;
cout << ",";
total += number;
}
If you want to do that in a while look it might loop like:
1 2 3 4 5 6 7 8 9 10
while (i < 10)
{
int i = 0;
counter = (counter + number);
cout << counter;
cout << endl;
cout << ",";
total += number;
i++;
}