13 December 2013
You can assume that every program here begins with the usual iostream
and namespace
declarations.
1. Describe the error in the following code fragment.
char message[8] = "Nice job.";
cout << message << "\n";
2. The following program contains two void
functions. What does it output?
void cron();
void yen();
int main()
{
yen(); cron();
cout << "\n";
cron(); yen();
cout << "\n";
return 0;
}
void cron()
{
cout << "X";
yen();
cout << "Z";
}
void yen()
{
cout << "Y";
}
3. The following program uses nested function calls with return values. What is its output?
int zig(int x)
{
if(x > 5) {
return x - 2;
}
else {
return x + 3;
}
}
int zag(int y)
{
return y*2;
}
int main()
{
cout << zig(3) << "\n";
cout << zag(4) << "\n";
cout << zig(zag(5)) << "\n";
cout << zag(zig(zag(6))) << "\n";
return 0;
}
4. The following program uses an array. What does it output?
int main()
{
const int SZ = 5;
int g[SZ];
int x = 5;
for(int i = 0; i < SZ; i++)
{
x += i;
g[i] = x;
}
for(int i = SZ-1; i >= 0; i--)
{
cout << g[i] << "\n";
}
return 0;
}
5. The following program contains a function with a reference parameter. What is the output?
void groon(int & x)
{
cout << x << "\n";
x--;
}
void preen(int y)
{
cout << y << "\n";
y++;
}
int main()
{
int a = 3;
int b = 4;
groon(a);
preen(b);
preen(a);
groon(b);
cout << a << "\n";
cout << b << "\n";
return 0;
}
6. The following program contains a function with an array parameter. What does it output?
void stomp(int x[], int stop)
{
for(int i = 0; i < stop; i++)
{
x[i]--;
}
}
int main()
{
const int SIZE = 5;
int z[SIZE] = { 9, 7, 8, 7, 8 };
stomp(z, 3);
stomp(z, 2);
stomp(z, SIZE);
for(int i = 0; i < SIZE; i++)
{
cout << z[i] << " ";
}
cout << "\n";
return 0;
}
7. The following program manipulates a string. What does it output?
int main()
{
const int MAX = 40;
char mesg[MAX] = "Thor";
cout << mesg << "\n";
mesg[6] = '\0';
mesg[5] = 'n';
mesg[4] = 'i';
cout << mesg << "\n";
return 0;
}
8. The following program manipulates a string. What does it output?
int main()
{
char name[] = "Ada Lovelace";
int i = 0;
while(name[i] != '\0')
{
switch(name[i])
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
name[i] = 'o';
}
i++;
}
cout << name << "\n";
return 0;
}