Date: December 16th, 2009
Time: 14:10-16:00
Open book; turn off computer & mobile phone
#include <iostream>
int main() // Understanding bitwise operators.
{
unsigned s = 2009;
int i = (s >> 5) & ~(~0 << 4);
std::cout << i << std::endl;
}
using std::cout;
using std::endl;
int main()
{
int value = 10;
int& rvalue = &value;
value += 5;
cout << value + rvalue << endl;
}
// Checksum
#include <iostream>
using std::cout;
using std::endl;
int main()
{ int cksum;
char *p;
char buf[8192] = "DECEMBER";
/*
* Draft 8 POSIX 1003.2:
*
* s = sum of all bytes
* r = s % 2^16 + (s % 2^32) / 2^16
* cksum = (r % 2^16) + r / 2^16
*/
cksum = 0;
for (p = buf; *p; ++p)
cksum += *p;
cksum = (cksum & 0xffff) + (cksum >> 16);
cksum = (cksum & 0xffff) + (cksum >> 16);
cout << cksum << endl;
return (0);
}
// String pointers vs. string arrays.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char str[10] = "Discovery";
char* p = str;
cout << str << endl;
cout << p++ << endl;
for ( ; *p != '\0'; p++)
*p ^= 0x20;
cout << p << endl;
cout << str << endl;
}
Show the output of the following program.
// Convert lowercase characters to uppercase
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
// Compare the statement with string "QUIT"
char pStatement[] = "question";
char pstr1[] = "QUIT";
char* p1=pStatement;
char* p2=pstr1;
bool flag = true;
while (flag && *p1 != '\0')
{
if (*p1>=97 && *p1<=122)
*p1 -= 32; // Convert to uppercase
if (*p1 != *p2)
flag = false;
p1++; p2++;
}
if (flag && *p2 != '\0')
flag = false;
if (flag || *pStatement == '\0')
cout << "This command is QUIT." << endl;
else
cout << "The command " << pStatement << " is not QUIT." << endl;
}
// Increment operator & for-loop
#include<iostream>
using std::cout;
using std::endl;
main()
{ int a,x;
for(a=0,x=0; a<=2 && !x++; a++)
{
a++;
}
cout << a << x << endl;
}
#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==3)
break;
std::cout << i << std::endl;
}
}
// dec2bin.c
#include <iostream>
using std::cout;
using std::endl;
void binary(int n, char *s)
{
int i = 0;
if (n>1)
{
binary(n/2, s);
s[i++] = '0' + n % 2;
}
else
s[i++] = '0' + 1;
}
int main()
{
char binary_string[16] = { 0 };
short a = 2009;
binary(a, binary_string);
cout << binary_string << endl;
return 0;
}
// dec2bin.c
// Hint: This program slightly differs from the previous one.
#include <iostream>
using std::cout;
using std::endl;
void binary(int n, char *s)
{
static int i = 0;
if (n>1)
{
binary(n/2, s);
s[i++] = '0' + n % 2;
}
else
s[i++] = '0' + 1;
}
int main()
{
char binary_string[16] = { 0 };
short a = 2009;
binary(a, binary_string);
cout << binary_string << endl;
return 0;
}