Date: March 6th, 2008
Time: 08:10-11: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>
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;
}
}