counting iterations of a while loop
Oct 11, 2014 at 9:29pm Oct 11, 2014 at 9:29pm UTC
I am starting with a user input (a whole number). The goal is to us a loop to decrement the input number by 10. What I want to out put is the final number of iterations ONLY.
Here is the code I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
using namespace std;
int main()
{
int ticketsWon;
int num; num = 0;
//ask user to input number of tickets won
cout << "Enter the number of tickets you won: " ;
cin >> ticketsWon;
//if number entered is >= 10 subtract 10
while (ticketsWon >= 10)
{
ticketsWon = ticketsWon - 10;
cout << "Candy Bars = " << ++num << " \n" ;
}
return 0;
}
It's basically doing what I want, except it's printing every iteration. Like this:
flip2 ~/kingmat 81% ./arcade3
Enter the number of tickets you won: 100
Candy Bars = 1
Candy Bars = 2
Candy Bars = 3
Candy Bars = 4
Candy Bars = 5
Candy Bars = 6
Candy Bars = 7
Candy Bars = 8
Candy Bars = 9
Candy Bars = 10
What I want to print is JUST the last line. Thanks!
Oct 11, 2014 at 9:42pm Oct 11, 2014 at 9:42pm UTC
Just take your cout statement and move it to after your while loop has complete. Like so:
1 2 3 4 5 6
while (ticketsWon >= 10)
{
ticketsWon = ticketsWon - 10;
++num;
}
cout << "Candy Bars = " << num << " \n" ;
Last edited on Oct 11, 2014 at 9:43pm Oct 11, 2014 at 9:43pm UTC
Oct 12, 2014 at 12:01am Oct 12, 2014 at 12:01am UTC
Thanks, that helped a lot.
Now I have to add a part that captures the leftover and uses a loop to decrement it by 3. Here's what I've done, and my output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//if number entered is >= 10 subtract 10
while (ticketsWon >= 10)
{
ticketsWon = ticketsWon - 10; //Decrement the number of tickets by 10
++num;
}
cout << "You have enough tickets for " << num << " " ;
cout << " candy bars,\n" ;
leftover = (ticketsWon % 10); //Capture the left over for gum balls
while (leftover >= 3)
{
leftover = leftover - 3; // Decrement the leftover by 3
cout << "and " << num << " " ;
cout << " gum balls.\n" ;
}
Enter the number of tickets you won: 56
You have enough tickets for 5 candy bars,
and 5 gum balls.
and 5 gum balls.
Topic archived. No new replies allowed.