Date: March 4th, 2009
Time: 14:10-16:00
Open book; turn off computer & mobile phone
#include <iostream>
using std::cout;
using std::endl;
void echo(char* s)
{
int i = 0;
while (s[i++] != '\0')
cout << s[i];
cout << endl;
}
void main()
{
echo("CAD");
}
#include <iostream>
#define N 10
using std::cout;
void dout(int n)
{
if(n<0)
cout << "(" << n << ")";
else
cout << n;
}
int main()
{
int M[N], D[N], Q[N], R[N], A[N], B[N];
int i = 0;
M[0] = 1610; D[0] = 590;
do
{
Q[i] = M[i] / D[i];
R[i] = M[i] - Q[i]*D[i];
M[i+1] = D[i];
D[i+1] = R[i];
} while (R[i++] > 0);
i-=2; A[i] = 1; B[i] = -Q[i];
cout << R[i];
while (1)
{
cout << "\t=\t"; dout(A[i]);
cout << "*"; dout(M[i]);
cout << "+"; dout(B[i]);
cout << "*"; dout(D[i]);
cout << "\n";
if (i==0) break;
A[i-1] = B[i];
B[i-1] = A[i] - B[i]*Q[i-1];
i--;
}
}
#include <iostream>
void exchange(int& a, int& b)
{ a ^= b;
b ^= a;
a ^= b;
}
int main(void)
{ int x[] = { 1, 3, 5, 7, 2, 4, 6 };
const int K = sizeof x / sizeof x[0] - 1;
int i, j;
for (i=0; i<K-1; i++)
for (j=i+1; j<K; j++)
if (x[i] < x[j])
exchange(x[i], x[j]);
for (i=0; i<K; i++)
std::cout << x[i] << " ";
std::cout << std::endl;
}
Show the output of the following program.
#include <iostream>
int main() // Understanding bitwise operators.
{
unsigned s = 3333;
int i = (s >> 3) & ~(~0 << 3);
std::cout << i;
}
#include <iostream>
int sum = 0;
void print_sum()
{
std::cout << sum << std::endl;
}
int main(void)
{
int i;
for (i=1; ++i<=100; i++)
if (i>90) break;
sum += i;
print_sum();
}
#include <iostream>
using std::cout;
using
std::endl;
int main()
{
int value[5] = { 5 };
int i = 0;
for (i=0; i<5; i += 2)
value[i] += i;
cout << value[0] << "\t" << value[2] << "\t" << value[3] << endl;
}
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int vector[] = {1, 2, 3, 4, 5};
int* pvector = vector;
int* p2 = &vector[2];
cout << static_cast<int>(p2 - pvector) << endl;
cout << sizeof(pvector) << endl;
cout << sizeof(vector) << endl;
}
#include <iostream>
using std::cout;
using std::endl;
int gcd(int a, int b) // Greatest Common Divisor
{
if (b > 0)
return gcd(b, a % b);
else
return a;
}
void main()
{
cout << gcd(12, 8) << endl;
cout << gcd(5, 97) << endl;
}
// Ex3_13.cpp
// Demonstrating nested loops to compute factorials
#include <iostream>
using std::cout;
using std::endl;
int main(void)
{
unsigned char value = 12, factorial = 1;
for (int i = 2; i<=value; i++)
{
factorial *= i;
cout << "Factorial " << i << " is " << static_cast<int>(factorial);
cout << endl;
}
}