Can someone help me with this?

+1 Tomas Käldström · February 15, 2015
Hello guys!

I recently had a "pen and paper" c++ test in school, where we got a paper with program code and had to explain what kind of program it is and what it does.

I flunked the test and will probably have to do the same test again.

I memorized some of the code and tried it on my computer, but I still don't get what it does.

Could someone please help me with this?


int main(void)
{
    int nn[8], number = 39, i =0, maxi;

        while (number != 0)
            {
                nn[i++] = number%2;
                number = number/2;
            }

    maxi = i-1 ;

    cout << "The answer is: ";

        for(i = maxi; i >= 0; i--)
            {
                cout << nn;
            }
        
    cout << endl;

}

I get the answer 100111 but I have no idea why...

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · February 16, 2015
First thing, your answer is wrong.  To fit in with the assignment, I have not done actually executed this code b/c that wouldn't really help. What I did was store what happens at each iteration on the side to paint a clearer picture of what is happening. I think that the program is supposed to be printing out the array i times when i is the amount of times a number can divide before becoming 0. Then you print out a newline. 

Looking at the end result, it is easy to see that nn holds very little significance other than its location in memory which like I said before is printing out i times where is the number of times number can divide before becoming 0. I hope this clears up your confusion. 
  • 1

C++

107,170 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator