MIDTERM EXAM: DISCUSSION EXAMPLES

C++ FUNDAMENTALS (Given code segments)

  1. Are these syntactically OK (will compile)?
    int it = 100;
    const int BIG;
    const int BIGGER = 10;
    const int BIGGEST = it;
    it = BIGGER;
    BIGGER = it;
  2. What gets printed?
    int i = 3, j = 3, k;
    1 + 1 % 4 + 4 / 5
    k = ++i + ++j + 2 ;
    i = j = 3;
    k = i++ + j++ + 2 ;
    k = 6;
    k %= 5 - 1 ;
  3. LOOPS
    Write a for loop to print the same output as while loop below.
    a) Write a do loop to print the same output as while loop below.
    b) What gets printed if it was "while ( i = 5 )" instead ?
    int i = 1;
    while ( i < 5 )
    {
    ++i;
    cout << i << endl;
    }
  4. What gets printed?
    int i, j;
    for ( i = 0; i < 2; ++i )
    for ( j = 0; j < 5; ++j )
    cout << i << " " << j << endl;
  5. DECISIONS
    What gets printed?
    cout << ( !3 + 2 > 1 || 0 ) << endl;
    cout << ( !3 + 2 > 1 && 0 ) << endl;
  6. Write an if else to print same output as switch statement below.
    int i = 3, sum = 0 ;
    switch ( i )
    {
    case 1:
    case 2:
    sum++;
    break;
    case 3:
    sum--;
    default:
    cout << i << endl;
    break;
    }
  7. FUNCTIONS
    What is missing?
    a) What gets printed now?
    b) Is "i" in fn() same as in main()?
    c) Write fn() to be an inline function.
    d) Write fn() to be assigned a default initializer of 1.
    e) Write fn() to be an overloaded function accepting a formal parameter type float.
    f) What makes an overloaded function?
    #include
    int main(void)
    {
    int i = 1;
    i = fn (i );
    cout << i << endl;
    cout << fn(i) << endl;
    }
    int fn ( int i ) { return(i + 2); }
  8. Are these legal?
    int fn (int i = 0, int j, int k = 2);
    fn (1, 2, int k = 3);
  9. REFERENCE TYPES
    What gets printed?
    int i = 3, &r = i;
    ++i;
    cout << i << " " << r << endl;
  10. What gets printed?
    #include
    void fn ( int & r );
    int main(void)
    {
    int i = 1;
    fn (i);
    cout << i << endl;
    return 0;
    }
    void fn ( int & r ) { r = 2; }


HOME || Course Description || Course Outline || Lab Hours || FAQ || Midterm || Final Exam