Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
int main()
{
	int x(5),a[7],i(0);

	for(i=0;i<8;i++)
	{
        a[i] = 0;
        cout << "i=" << i <<endl;
        cout << "a[" <<i <<"]=" <<a[i]<<endl;
	}
	for(i=7;i>=0;i++)
	{
		a[i]=x%2;
		cout << "a[" <<i <<"]=" <<a[i]<<endl;
		x=x/2;
		if(x<2)
		{
			i--;
			a[i]=x;
			break;
		}
	}

}
Posted
Updated 18-Aug-15 20:09pm
v2
Comments
Sergey Alexandrovich Kryukov 19-Aug-15 2:11am    
To start with, always declare loop variables inside "for". Never use your externally defined "i" as a loop variable. Use the debugger.
—SA
CPallini 19-Aug-15 2:27am    
You should also check
for(i=7;i>=0;i++)
it doesn't look correct.

1 solution

Look at your code:
int x(5),a[7],i(0);

for(i=0;i<8;i++)
{
a[i] = 0;
...
}

So your array a has 7 elements, and you write 0 into the first 8.
When you write the 8th element, it overruns the array, and writes into the next memory location - which contains the variable i. So after the 8th time round the loop, it looks at i and sees it is zero, so it goes round again... And again...
 
Share this answer
 
Comments
the_beginner 19-Aug-15 2:19am    
Thanks
OriginalGriff 19-Aug-15 2:32am    
You're welcome!
CPallini 19-Aug-15 2:24am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900