Date: October 26th, 2011
Time: 14:10-16:00
Open book; turn off computer & mobile phone
#include <iostream>
int main() // Understanding bitwise operators.
{
unsigned s = 1026;
int i = (s >> 3) & ~(~0 << 3);
std::cout << i << std::endl;
return 0;
}
10000001 10000001
(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).
// dec2bin.cpp
#include <iostream>
using std::endl;
using std::cout;
int main()
{
short i;
short b[8] = { 26 } ;
for (i=0; i<7; i++)
{
b[i+1] = b[i] / 2;
b[i] %= 2;
}
for (i=7; i>=0; i--)
switch (i)
{
case 0:
cout << '0';
break;
case 1:
cout << '1';
break;
}
cout << 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).
#include <iostream>
using std::cout;
using std::endl;
int main()
{
const int N = 3;
int a[N][N] = { { 1, 2, 3 }, { 2, 2, 3 }, { 3, 2, 3 } };
int at[N][N];
int c[N][N] = { 0 };
int i, j, k;
for (i=0; i<N; i++)
for (j=0; j<N; j++)
at[i][j] = a[j][i];
for (i=0; i<N; i++)
for (j=0; j<N; j++)
for (k=0; k<N; k++)
c[i][j] += a[i][k] * at[k][j];
for (i=0; i<N; i++)
{
for (j=0; j<N; j++)
cout << c[i][j];
cout << 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).
#include <iostream>
int main() // break in a nested loop
{
for (int i = 1; i < 6; i++)
for (int j = 1; j < 6; j++)
{
if (j==4)
break;
std::cout << i << std::endl;
}
}
// 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] = { 1, 0, 2, 6};
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;
}
}
if (j == 1)
{
cout << endl << "Round " << j+1 << ":\t";
for (i=0; i<MAX; i++)
cout << data[i] << '\t';
}
}
return 0;
}
// break vs. continue
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int sum=0, i = 1;
do {
if (i++ == 6) continue;
sum += i++;
} while (i<10);
cout << i << '\t' << sum << endl;
return 0;
}