Midterm Exam: Discussion Examples
C++ FUNDAMENTALS (Given these code segments) 1) Are these syntactically OK (will compile)? a) int it = 100; b) int is, not //; c) const int BIG; d) const int BIGGER = 10; e) const int BIGGEST = it; f) it = BIGGER; g) BIGGER = it; 2) What gets printed? int i = 3, j = 3, k; k = ++i + ++j + 2 ; cout << i << " " << j << " " << k << endl; i = j = 3; k = i++ + j++ + 2 ; cout << i << " " << j << " " << k << endl; LOOPS 3) 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 = 1; i < 3; ++i ) for ( j = 0; j < 3; ++j ) cout << i << " " << j << endl; DECISIONS 5) Write a switch to compute same as if else statement. int i = 1; if ( i == 1 || i == 2 ) ++i; else if ( i == 3 ) { cout << i << endl; i--; } else i--; FUNCTIONS 6) What is missing? a) What gets printed now? b) Is "i" in fn() same as in main()? c) Write fn() to be an overloaded function accepting a formal parameter type float. d) Write int fn(int); to be an inline function. e) Write int fn(int); to be assigned a default initializer of 1. f) What makes an overloaded function? g) What is printed if line 3 omitted the assignment? "fn(i);" 1) #include 2) int main(void) 3) { 4) int i = 1 ; 5) i = fn (i ); 6) cout << i << endl; 7) cout << fn(i) << endl; 8) return 0; 9) } 10) int fn ( int i ) { return(i + 2); } 7) Are these legal? a) int fn (int i = 0, j = 1, int k); b) fn (1, 2, int k = 3); REFERENCE TYPES 8) What gets printed? #include void fn ( int & rj ); int main(void) { int i = 1, j = 3, &ri = i; ++i; cout << i << " " << ri << endl; fn (j); cout << j << endl; return 0; } void fn ( int & rj ) { rj = 4; }