CSC231 Powers of 2 in C++

From dftwiki3
Revision as of 08:45, 13 November 2014 by Thiebaut (talk | contribs) (The C++ Program)
Jump to: navigation, search

--D. Thiebaut 13:43, 8 October 2010 (UTC)


This exercise is a companion of the same exercise dealing with a Python implementation of the program.


Exercise

  • Below is a C++ program, and its complete output
Question 1
Do the numbers output by the program look correct?
Question 2
Remove the comment sign (//) in front of the last printf. Compile and run the program again.
Explain the new output!
Question 3
Remove the word unsigned from the program. This changes the integer variable from an unsigned variable to a signed one.
Change the %u printing format command by %d to indicate that you want to print the contents of a signed variable.
  • Predict the output of the program.
  • Verify whether you were correct in your prediction!


The C++ Program



// mulby2.cpp
// D. Thiebaut
// To compile and run:
// 
//   g++ -o mulby2 mulby2.cpp
//   ./mulby2
//
#include <stdio.h>

int main() {
  unsigned int x = 1;

    for ( int i=0; i<32; i++ ) {
       printf ( "%u\n", x );
       x = x * 2;
    }

  //printf( "final x = %u\n\n", x );
  return 0;
}


The Output


g++  -o  mulby2  mulby2.cpp

./mulby2 

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648