I have to write this program that gives a certain amount of cubes that the user requests. I've got the program all set up so that it allows the user to put in how many cubes they want, and it shows the cubes all proper and whatnot; however, the numbers themselves are displayed in descending order rather than ascending order (i.e. if I say I want 3 cubes displayed, it'll print out as
"3 cubed is 9
2 cubed is 4
1 cubed is 1")
We are not very far into our textbook, and I've tried to scour all my notes and slides and stuff, but I've yet to really find anything that'll help. I don't want anyone to just say "put this in" (apologies if it sounds like that!). I would like for someone to explain where I need to look for my answer, as it is entirely possible that I've been looking in the completely wrong area.
#include <iostream>
usingnamespace std;
int main ( )
{
int x, cube;
cout<<"How many cubes do you want displayed? ";
cin>>x;
while (x > 0)
{
cube = x * x * x;
cout<<x<<" cubed is "<<cube<<endl;
x = x - 1;
}
cout<<endl;
return 0;
}
How about in your loop, instead of starting at x and counting down to 1, you start at 1 and count up to x? Try using a 'for' loop instead of a 'while' loop.
I took a look at the link, threw in a "y", and changed
while ( x > 0 )
to
for (int y = 1; x > 0; y++)
but it still doesn't work. I also tried putting y = 0, x = 1, x++, etc. but they still didn't do what I wanted to do. Is there anything else I could try?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x{ 0 };
int cube{ 0 };
cout << "How many cubes do you want displayed? : ";
cin >> x; // Set the limit for the for loop.
// Use the for loop with a counter to begin 1.
// You can begin with zero if you want to, as well.
// The second parameter of the loop will loop
// from 1 up to equal to the value you set up
// as the limit of the for loop.
// The third parameter will increment the count
// until it reaches the limit of the loop.
for (int y = 1; y <= x; y++)
{
cube = y * y * y;
cout << y << " cubed is " << cube << endl;
}
cout << endl;
return 0;
}
FurryGuy beat me to it :-) I hope you get the concept, though.