int digits, y=0, b=0;
cout << "Enter numbers or -1 to stop: " << endl;
for (int x=0; x<10; x++)
cin >> y;
for ( x = 10-b, b = 0; x < 10; b++, x++)
cout << digits[b] << " ";//and print out all the values in the array
cout << endl;
You can make it even fancier by using the isdigits(int) function to check that a valid digit is entered, then print a message to the user if the value entered is not a number.
I would have done it that way, but in his code, he had b incrementing at the same time as x was. So if I used while(b < x) that would not have worked. I understand what you mean by letting b = 0 until it was needed, but I was trying to stick to his format.
Thank you guys, that helped a lot.
@Smac89 I haven't heard of isdigits(int) function, I'm barely in a intro to programming class. Or you mean creating my own predefined function? As we just covered that on Tuesday as our last lecture.
@maeriden I prefer your code, as it is easier to understand and does what I need but I still have a problem.
Here is what I am using:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int digits, x, input;
cout << "Enter digits or -1 to stop: ";
for(x = 0; x < 10; x++)
cin >> input;
if(input != -1)
digits[x] = input;
for(int i = 0; i < x; i++)
cout << "Digits: " << digits[i] << endl;
And my output is:
1 2 3 4
Enter digits or -1 to stop: 9 1 1 -1
How can I make it so it outputs like this:
And can you help me understand what is going on in the second for loop. Why exactly is the "i < x"?
Using for loops for these types of problems always seems a little disingenuous to me. We're looping until x is 10.. except we're not. Why not use a while loop and get the actual loop condition in the loop condition?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
using std::cin ;
using std::cout ;
int digits ;
constunsigned max_digits = sizeof(digits)/sizeof(digits) ;
unsigned digits_entered = 0;
int input ;
while ( digits_entered < max_digits && (cin >> input) && input != -1 )
digits[digits_entered++] = input ;
cout << "Digits: " ;
for ( unsigned i=0; i<digits_entered; ++i )
cout << digits[i] ;
cout << '\n' ;
Every time the loop executes it prints "Digits: " and the newline again. You want to move "Digits: " outside the loop so that it's printed only once and remove the 'endl'
And can you help me understand what is going on in the second for loop
In the first for, every time a valid number is inserted the loop reaches the end, 'x' is incremented and it restarts. This means that the array has x valid numbers that you want to print. In your example x == 3
The second for uses the variable 'i' to select which element to print. It will stop when 'i' becomes equal or greater than the number of valid elements in 'digits'. In your example the condition translates to i < 3.
first iteration i = 0. i < 3? Yes -> print digits
second i = 1. i < 3? Yes -> print digits
third i = 2. i < 3? Yes -> print digits
fourth i = 3. i < 3? No -> exit the loop. Perfectly executed since we only had 3 numbers in the array