Date: October 23rd, 2012
Time: 14:10-16:00
Open book; turn off computer & mobile phone
11000000 11000000
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// increment and decrement
#include <iostream>
using std::endl;
using std::cout;
int main()
{
unsigned short a = 100, b = 200, c = 300;
cout << (a++, b = --c) << endl;
cout << a << ' ' << b << ' ' << c << endl;
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Conditional operator
#include <iostream>
using std::cout;
using std::endl;
int main()
{
unsigned short n = 23;
do {
cout << n << ' ';
if (n == 1)
break;
} while ( n = n % 2 ? 3 * n + 1 : n / 2 );
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// break vs. continue
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int i;
for (i=1; i<10; i++)
{
if (i>2)
if (i==5)
break;
else
continue;
cout << i << endl;
}
cout << i << endl;
return 0;
}
// exchange_sort.cpp
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
int main()
{
const int MAX = 4;
int data[MAX] = { 2, 3, 1, 0};
int i, j, temp;
for (j=0; j<=MAX-2; j++)
{
for (i=j+1; i<=MAX-1; i++)
{
if (data[j] > data[i])
{
temp = data[j]; data[j]=data[i]; data[i]=temp;
}
}
cout << endl << "Round " << j+1 << ":\t";
for (i=0; i<MAX; i++)
cout << data[i] << '\t';
}
return 0;
}
// Array
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int y = 2012;
int day = ( y-1 + y/4 - y/100 + y/400) % 7;
int month_days[13] = { 0,
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
char weekdays[][10] = { "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
int m = 10, d = 23;
int i;
if ( y % 4 == 0 ) month_days[2] = 29; // leap year
if ( y % 100 == 0 && y % 400 != 0 ) month_days[2] = 28;
cout << "day = " << day << endl;
for (i=1; i<m; i++)
day += month_days[i];
day += d -1;
cout << "Today is " << weekdays[ day % 7 ] << endl;
cout << "day = " << day << endl;
return 0;
}