#include <iostream>
using namespace std;

int main()
{
    int num;
    const int MAX = 8;
    int output[8];
    
    cout << "Enter a number [0 - 255]: ";
    cin >> num;
    
    cout << num << "converts to";
    for (int i = 0; i < MAX; i++)
        {
             output[i] = num % 2;
             num = num/2;
        }
    
    for (int i = MAX - 1; i >= 0; i--)
        cout << output[i] << endl; //Compiling error
        if (i % 8 == 0)
        
           cout << "   " << endl;
           
    
    system("pause");
    return 0;

}

Hi, I'm fairly new to programming and I am stuck on one part. The part that I have noted gets a compiling error. When it is removed, the program compiles, but does not make the calculation. Any ideas?

Comments
Thanks for using code tags correctly on your very first post :)

One problem with your program is that the value of MAX may or may not be big enough. If I enter the value 10 then MAX is too large because 10 in binary is only 4 digits (1010). But if I enter the value of 123456 the binary value is 11110001001000000, which is clearly larger than 8 digits.

Instead of using an array of ints to hold the 1's and 0's just put them in a large character array, then keep track of the number of digits actually used in an integer.

So the calculation in the first loop you posted stops when the value of num is 0.

What Ancient Dragon has suggested is a wonderful suggestion try to implement it but it is completely inconsiderate with the problem in your code...

In your code :

for (int i = MAX - 1; i >= 0; i--)
        cout << output[i] << endl; //Compiling error
        if (i % 8 == 0)
            cout << "   " << endl;

This for loop is the one which is causing the error.Here even though

if (i % 8 == 0)
            cout << "   " << endl;

part should be inside the for loop according to indentation,it wont be considered inside the for loop and would be considered as this:

for (int i = MAX - 1; i >= 0; i--)
        cout << output[i] << endl; //Compiling error

 if (i % 8 == 0)
        cout << "   " << endl;

But when treated like this variable "i" is not at all declared in the function as the scope of "i" ends as soon as the for loop is over.

Therefore correct your code as this :

for (int i = MAX - 1; i >= 0; i--)
{
        cout << output[i] << endl; //Compiling error
        if (i % 8 == 0)
            cout << "   " << endl;
}

and it will work in the way you want it to work.

Edited 7 Years Ago by csurfer: n/a

Edit: Problem solved Thanks to you guys!

Edited 7 Years Ago by kn336a: n/a

This question has already been answered. Start a new discussion instead.