Date: January 9th, 2008
Time: 13:10-15:00
Open book; turn off computer & mobile phone
#include <iostream>
using std::cout;
using std::endl;
void to_upper(char* str)
{
int i = 0, j = 0;
while (*(str + j) != '\0')
{
if (*(str + j) == ' ')
j++;
else
*(str + i++) = (*(str + j++) & 0xDF );
}
*(str + i) = *(str + j);
return;
}
int main(void)
{
char message[] = "Time and tide wait for no man";
to_upper(message);
cout << message << endl;
}
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int i, sum;
for (i=10, sum=0; i>5; sum+= --i)
cout << "i = " << i << endl;
cout << "sum = " << sum << endl;
}
#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 = 5555;
int i = (s >> 5) & ~(~0 << 4);
std::cout << i;
}
#include <iostream>
int sum = 0;
void print_sum()
{
std::cout << sum << std::endl;
}
int main(void)
{
for (int i=1; i<=100; i++)
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;
*pvector = *pvector + 1;
*pvector + 1 = *pvector + 2;
*pvector + 2 = *pvector + 3;
for (int i=0; i<5; i++)
cout << vector[i] << endl;
}
#include <iostream>
int main()
{
for (int i = 1; i < 6; i++)
{
if (i==3)
break;
std::cout << i << std::endl;
}
}
// Ex3_13.cpp
// Demonstrating nested loops to compute factorials
#include <iostream>
using std::cout;
using std::endl;
int main(void)
{
char value = 11, factorial = 1;
for (int i = 2; i<=value; i++)
{
factorial *= i;
cout << "Factorial " << i << " is " << static_cast<int>(factorial);
cout << endl;
}
}
#include <iostream>
using std::endl;
using std::cout;
#define WIDTH 15
int main()
{
const int n = 10; //表n!
int x[WIDTH] = { 0 } ; //使用array儲存n!的數值
int i,j; //迴圈用
int k = 0; //儲存第幾個數開始不為0
cout << n << "! = ";
x[WIDTH-1]=1; //1!=1
for(j=2;j<=n;j++)
{
for (i=WIDTH-1; i>=0; i--)
x[i]=x[i]*j;
for (i=WIDTH-1; i>=0; i--)
if(x[i] >= 10)
{
x[i-1]+=x[i]/10;
x[i] %= 10;
}
}
for(i=k;i<WIDTH;i++)
cout << x[i];
cout << endl;
}