Midterm d200 Sol Spring2023
Midterm d200 Sol Spring2023
Name_________________________
Problem 1
Problem 2
Problem 3
TOTAL
Instructions:
Good luck!
1
Problem 1 [40 points]
a) [10 points] What will be the output of the following program? Explain your answer.
#include <stdio.h>
const int RED = 0;
const int GREEN = 1;
const int BLUE = 2;
const int YELLOW = 3;
printf("%s\n", str+5);
return 0;
}
Answer: the while loop will stop at ind=0 because str[0]=0. Str+5 the points to 5. The program will print
567
2
c) [10 points] Will the code below compile?
If yes, what will be the result of the execution?If not, explain errors/warnings/potential issues.
#include <stdio.h>
#include <stdlib.h>
3
Problem 2 [30 points]
a) [15 points] Write a function that gets an int n>=0 and returns a string containing this int.
Make sure the returned string is allocated on the heap.
For example,
● int2str(10) returns "10".
● int2str(4) returns "4".
● int2str(0) returns "0".
● int2str(625) returns "625".
● int2str(88088) returns "88088".
4
b) [15 points] Write a function that gets an array of non-negative ints of length n>0,
and returns a string representing this array in the following format:
● array_to_string([2,123,103], n=3) returns "[2,123,103]".
● array_to_string([22,3,40,100], n=4) returns "[22,3,40,100]".
● array_to_string([41], n=1) returns "[41]".
5
Problem 3 [30 points]
a) [15 points] Write a function that gets an int n and returns a string of length n, of the form
"01234567890123...".
That is, the i’th character in the string (counting from zero) is the unit digit of i.
For example,
● get_string(4) returns "0123".
● get_string(0) returns "".
● get_string(10) returns "0123456789".
● get_string(12) returns "012345678901".
● get_string(25) returns "0123456789012345678901234".
char* get_string(int n) {
6
b) [15 points] Write a function that gets an int n>0 and returns an array of strings of length n,
where the i’th string is get_string(i) from the previous item. You may assume n>0.
For example,
● get_n_strings(1) returns [""] .
● get_n_strings(4) returns ["","0","01","012"] .
● get_n_strings(7) returns ["","0","01","012","0123","01234","012345"] .
char** get_n_strings(int n) {
return ret;
7
Extra page
8
Empty page