code only works with 3 digits

• 11-12-2005
bejiz
code only works with 3 digits
This code for finding the binary representation of a number works if I type a number of 3 digits but if i type a number like 3427 , it doesn't ...
I use Dev-++ , I have tried to debug and apparently the problem is on the line after while , perhaps the ze[u] .

Code:

```#include <iostream> using namespace std; int main() {  long x,z,n,y=0,u;  long ze[y];   cout<<"write an integer : "; cin>>x;     for(n=x;n>0;n/=2){     z=n%2;      cout<<z<<',';ze[y]={z}; y++;                    }     cout<<"  The last digit  is the first digit\n of the binary representation of "<<x<<endl<<endl;     cout<<" Now , the right order : "<<endl;     u=y-1;     while (u>=0){           cout<<ze[u]<<",";u--;           }     char zs;cin>>zs; }```
• 11-12-2005
SlyMaelstrom
Knock out that array declaration with a variable as the size.

This works:
Code:

```#include <iostream> using namespace std; int main() {  long x,z,n,y,u;  y = 0;  long ze[100];   cout<<"Write an integer : "; cin>>x;     for(n = x; n > 0; n /= 2){     z = n % 2;      cout << z;     ze[y]=z;     y++;                    }     cout<<"  The last digit  is the first digit\n of the binary representation of "<<x<<endl<<endl;     cout<<" Now , the right order : "<<endl;     u=y-1;     while (u>=0){           cout<<ze[u];           u--;           if ((u+1) % 4 == 0)             cout << " ";           }           }     char zs;     cin>>zs; }```
You're going out of bounds on your index, the program is trying to access memory that doesn't belong to it, and windows is giving it a spanking.
• 11-12-2005
bejiz
Thanks , it is more pleasant like that .
• 11-12-2005
SlyMaelstrom
As a critique on the output, I don't understand why you even bother showing it backwards, it's much nicer looking like this.

Code:

```#include <iostream> using namespace std; int main() {  long x,z,n,y,u;  y = 0;  long ze[100];   cout << "Write an integer: "; cin >> x; cin.ignore();     for(n = x; n > 0; n /= 2){     z = n % 2;     ze[y] = z;     y++;                    }     cout<<"Binary Representation: "<<endl;     u = y - 1;     while (u >= 0){           cout << ze[u];           u--;           if ((u+1) % 4 == 0)             cout << " ";           }     cin.get(); }```
Sample Output:
Code:

```Write an integer: 364365 Binary Representation: 101 1000 1111 0100 1101```
• 11-12-2005
bejiz
The simple reason was that i didnt know how to dispay it rightward on the screen .
The spaces between every 4 digits also make the result easier to read .