int a[5] = {1, 2, 3, 4, 5};
int sum =0;
for (int i =0; i <5; i++)
if (a[i] %2==0) sum += a[i];
printf("%d\n", sum);
Output:
Answer: 6
Q18string NUL
C string terminator (source form)?
Answer: \\0
Q19string funcs
Standard library names.
// concatenate[1](dst, src);
// lengthsize_t len =[2](s);
// compare (0 if equal)if ([3](a, b) ==0) { }
[1]: γ[2]: γ[3]:
Answer: strcat, strlen, strcmp
Q202D sizeof
int m[3][4]; elements and sizeof (int=4).
elements: γsizeof(m):
Answer: 12, 48
Q21array to function
Prototype of a function that takes an int array and length and returns the sum.
Answer: int sum(int a[], int n);
Q22char array size
For char s[] = "Hello";, give sizeof(s) and strlen(s).
sizeof: γstrlen:
Answer: 6, 5
Functions, recursion, scope
Q23prototype
Prototype for int add(a,b) returning int.
Answer: int add(int a, int b);
Q24return
Keyword for returning a value?
if (a > b) [1] a;
else[1] b;
[1]:
Answer: return
Q25recursion
Complete factorial.
intfact(int n) {
if (n <=1) return[1];
return n *fact([2]);
}
[1]: γ[2]:
Answer: 1, n - 1
Q26Fibonacci
fib(0)=0, fib(1)=1; fib(6)?
fib(6) =
Answer: 8
Q27pass-by-value
Output of a, b after swap()?
voidswap(int x, int y) { int t = x; x = y; y = t; }
int a =3, b =5;
swap(a, b);
printf("%d %d", a, b);
Output:
Answer: 3 5
Q28scope
After the inner block, what's x?
int x =10;
{ int x =20; }
printf("%d", x);
Output:
Answer: 10
Q29global
Output?
int g =0;
voidadd(int x) { g += x; }
intmain(void) {
add(3); add(4);
printf("%d", g);
}
Output:
Answer: 7
Q30static
Output after 3 calls?
voidcount(void) {
staticint n =0;
n++;
printf("%d ", n);
}
Output:
Answer: 1 2 3
Block B result: not graded
C. Pointers & Advanced
pointer, struct, malloc, bitwise, mixed (Q31-45)
Score: 0/15
Pointers, struct, dynamic memory
Q31pointer basics
Pointer to n, then add 10 through pointer.
int n =100;
int[1]p =[2]n;
[3]p +=10;
[1]: γ[2]: γ[3]:
Answer: *, &, *
Q32array vs pointer
Pick all correct.
A: array name is address of first element
B: a[i] == *(a+i)
C: sizeof(a) equals sizeof(&a[0]) always
D: inside a function, sizeof on an array param gives pointer size
Answer:
Answer: A, B, D
Q33struct access
Member access operators.
struct Point { int x, y; };
struct Point p = {3, 4};
printf("%d", p[1]x);
struct Point *pp =&p;
printf("%d", pp[2]y);
[1]: γ[2]:
Answer: ., ->
Q34malloc/free
Allocate n ints, then release.
int*a = (int*)[1](n *sizeof(int));
[2](a);
[1]: γ[2]:
Answer: malloc, free
Q35swap via pointers
Complete swap.
voidswap(int[1]x, int[1]y) {
int t =[2]x;
[2]x =[2]y;
[2]y = t;
}
swap([3]a, [3]b);