1

I am just learning C. i am working through this problem trying to predict the output:

#include <stdio.h> int gNumber; int MultiplyIt( int myVar ); int main (int argc, const char * argv[]) { int i; gNumber = 2; for ( i = 1; i <= 2; i++ ) gNumber *= MultiplyIt( gNumber ); printf( "Final value is %d.\n", gNumber ); return 0; } int MultiplyIt( int myVar ) { return( myVar * gNumber ); } 

so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512...

maybe i am missing something easy here, but as i said, i am very new to C and programing in general..

2
  • 0th=2;1st = (0th*0th*0th)=8; 2nd=1st*1st*1st=512; Commented Feb 14, 2016 at 23:45
  • the compiler will raise two warning messages about the unused parameters argc and argv. suggest changing the main function signature to: int main( void ) Commented Feb 16, 2016 at 0:50

2 Answers 2

3

Let's start from here:

gNumber *= MultiplyIt( gNumber ); 

This line contains a call to MultiplyIt with myVar = gNumber. By looking at the return value of that function, we can say that MultiplyIt( gNumber ) is equivalent to gNumber * gNumber. So the line above is equivalent to this:

gNumber *= gNumber * gNumber; 

or also:

gNumber = gNumber * gNumber * gNumber; 

In plain words, the body of the for-loop replaces gNumber with its cube.

The loop runs two times, with i going from 0 to 1 (inclusive). gNumber is 2 initially. Putting everything together, here's what the loop is doing:

gNumber = 2 * 2 * 2 = 8; /* First iteration, i = 1 */ gNumber = 8 * 8 * 8 = 512; /* Second iteration, i = 2 */ 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Like I said i missed something easy
0

given the following instrumented code:

#include <stdio.h> int gNumber; int MultiplyIt( int myVar ); int main ( void ) { int i; gNumber = 2; for ( i = 1; i <= 2; i++ ) { gNumber *= MultiplyIt( gNumber ); printf( "\n%s, gNumber *= MultiplyIt(): %d\n", __func__, gNumber); } printf( "Final value is %d.\n", gNumber ); return 0; } int MultiplyIt( int myVar ) { printf( "\n%s, pasted parameter: %d\n", __func__, myVar); printf( "%s, global gNumber: %d\n", __func__, gNumber); return( myVar * gNumber ); } 

the output is:

MultiplyIt, pasted parameter: 2 MultiplyIt, global gNumber: 2 main, gNumber *= MultiplyIt(): 8 MultiplyIt, pasted parameter: 8 MultiplyIt, global gNumber: 8 main, gNumber *= MultiplyIt(): 512 Final value is 512. 

so the first pass through the for loop is:

2*2*2 = 8 

the second pass through the for loop is:

8*8*8 = 512 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.