Midterm Review 3
Questions covering chapters 2- 12
Run the code for answers
Problem 1 What gets printed ? #include < stdio.h> const int n = 4; int main(void) { int i, sum = 0, a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; i = 0; while (i <= n){ sum += a[i]; printf("%d is sum\n", sum); ++i; }; return 0; }
Problem 2 typedef struct pair{ double x, y;} pair; pair w = {0.5, 2.5}; pair *p = &w; What is the value of w.y? --------- What is the value of p -> x? --------- Write a routine void print_pair(pair w); /* nicely output pair */
Problem 3
Fill in the integer value of each expression assuming the following
declarations:
int i = 1, j = 3, k = 4;
Expression Value
i <= j
j % k
k / j
2 * i + 1 < = j
!i <= 2
Problem 4
What gets printed?
#include < stdio.h>
int f (int a) {return (2* a + 1); }
int g (int *y) { *y += 1; return (*y + *y); }
int main(void)
{
int i = 11, j = -2;
printf(" f = %d\n", f(i + j));
printf(" g = %d\n", g(&i));
i = i + 3;
printf(" g = %d\n", g(&i));
printf(" g = %d\n", g(&j));
printf(" i = %d j = %d\n", i, j);
return 0;
}
Problem 5
What gets printed?
#include < stdio.h>
int rec (int i)
{
int j = 0;
printf ("%d\n",i);
if (i > 2)
j = rec(i - 2) + 1;
else
j = i;
printf("%d\n", j);
return j;
}
int main(void)
{
rec(5);
return 0;
}
Problem 6
What gets printed?
#include < stdio.h>
void swap (int *m, int *n)
{
int temp = *m;
*m = *n;
*n = temp;
}
int main (void)
{
int a[4] = {2,7,4,8};
int i, j;
for (i = 3; i > 0; --i) {
for (j = 0; j < i; ++j)
if (a[j] < a[j+1])
swap (&a[j], &a[j+1]);
for (j = 0; j < 4; ++j)
printf ("%d ",a[j]);
printf ("\n");
}
return 0;
}
Problem 7
What gets printed?
#include < stdio.h>
void func1(int a, int b)
{
static int count = 0;
count += a + b;
a += b;
printf ("%d %d %d\n", a, b, count);
}
void func2(int *a, int *b)
{
int count = 0;
count += *a + *b;
*a += *b;
printf ("%d %d %d\n", *a, *b, count);
}
int main(void)
{
int i=2, j=3;
func1 (i,j);
printf("%d %d\n", i, j);
func2 (&i,&j);
printf("%d %d\n", i, j);
func1 (i,j);
return 0;
}
Problem 8
What gets printed?
#include < stdio.h>
#include < string.h>
int main(void)
{
char *s1, *s2, *s3;
char s4[20] = "bedroom";
s1 = "bedroom tray fire";
s2 = "bedroom tray ashes";
s3 = "bedroom tray";
printf("%d is length of s1\n", strlen(s1));
printf("%d is length of s4\n", strlen(s4));
printf("%d is length of s3 offset\n", strlen(s3 + 2));
printf("%d is s1 == s2\n", (strcmp(s1, s2) == 0));
printf("%c %c \n", s4[3], s3[4]);
return 0;
}
Problem 9
What gets printed?
#include < stdio.h>
int main(void)
{
int i, j = 5;
for (i = 0; i < 6; ++i)
switch (i % 4) {
case 0:
printf("%d\n", ++j);
break;
case 1:
printf("%d\n", j++);
break;
case 2:
printf("%d\n", j);
break;
case 3:
printf("%d\n", --j);
case 4:
printf("%d\n", j);
break;
default:
printf("error\n");
break;
}
return 0;
}
Feel free to report any site problems to the current Webmaster, Debra Dolsberry.