Excercise Solutions
Walkthroughs
Walkthrough 1:
What is the output of the following program?
#include <stdio.h>
int main(void){
int x=1;
int y=1;
printf("whole thing: %d\n", x = y += 3 / 4 + 5 * 2 % 3 - 6);
printf("x = %d, y = %d\n", x , y);
x = 2;
y = 2;
printf("x++ = %d\n", x++);
printf("++y = %d\n", y++);
printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
Solution:
whole thing: -4
x = -4, y = -4
x++ = 2
++y = 2
x = 3
y = 3
Walkthrough 2:
What is the output of the following program?
#include <stdio.h>
int main(void){
int x=1;
float y=1;
printf("whole thing: %d\n", x = y = (9 * 2.0 - 2 % 3 * 5) / 3);
printf("x = %d, y = %f\n", x , y);
return 0;
}
Solution:
whole thing: 2
x = 2, y = 2.666667
Debugging
Here is the original code:
#include <stdio.h>
int main(void)}
integer x=0;
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
return 0
}
Here are the syntax errors:
- } instead of { on the
int main(void)}line - integer should be int in the
integer x = 0;line - missing ; on the
return 0line
Logical errors:
x is initially 0, the first line of output outputs x++. since x++ results in the original value of x, the first output would be 0. This program prints:
0
1
2
3
4
To fix this, we can do one of two things. Either we initialize x with 1 (int x = 1) or we use prefix increment instead printf("%d\n", ++x); on each line
Thus, the solution is either:
#include <stdio.h>
int main(void)
{
int x=1;
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
printf("%d\n",x++);
return 0;
}
or:
#include <stdio.h>
int main(void)
{
int x=0;
printf("%d\n",++x);
printf("%d\n",++x);
printf("%d\n",++x);
printf("%d\n",++x);
printf("%d\n",++x);
return 0;
}