Week 6 July 2023 Solution
Week 6 July 2023 Solution
1. What is an array in C?
a) A collection of similar data elements with the same data type.
b) A built-in function that performs mathematical calculations.
c) A keyword used for declaring variables.
d) A data type used to store characters only.
Solution: a) A collection of similar data elements with the same data type.
Solution: a) 0
Explanation: In C, array indices start from 0. Therefore, the index of the first element in an
array is 0, the second element's index is 1, and so on.
Explanation: The "for" loop is commonly used to iterate through all elements of an array in C.
It allows precise control over the loop variable and is well-suited for iterating over a
range of elements, as required in array traversal.
5. How can you find the sum of all elements in a 1D array "arr" with 5 elements using
loop in C?
a) sum = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
Week 6 Assignment Solution
b) sum = arr[5];
c) for (int i = 0; i <= 5; i++) { sum += arr[i]; }
d) for (int i = 0; i < 5; i++) { sum += arr[i]; }
Explanation: To find the sum of all elements in a 1D array "arr" with 5 elements, you can use
a "for" loop to iterate through the array and add each element to the "sum" variable. The
code provided correctly calculates the sum of all elements.
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int i = 0;
while (i < 5) {
printf("%d ", arr[i]);
i += 2;}
return 0;
}
a) 135
b) 12345
c) 123
d) 14
Solution: a) 1 3 5
Explanation: The provided code uses a "while" loop to print elements of the array "arr" with
an increment of 2 for the loop counter "i." The loop starts at index 0 and prints elements
at indices 0, 2, and 4. The output will be "1 3 5."
Solution: (a) k=arr[1]++ due to post increment operation, assignment is done first. so it actually
becomes k=arr[1]=2. j=++arr[2]=++3=4. i=arr[j++]=arr[4++]=arr[4]=5 (as its post
increment hence assignment is done first). Due to post increment in i=arr[j++], value of
j is also incremented and finally becomes 5. So, finally i=5, j=5, k=2.
a) 1
b) 2
c) 3
d) 4
Solution: (d) The program finds the maximum element of an array. Hence, the output is 4.
}
printf("%d", sum);
return 0;
}
Week 6 Assignment Solution
a) 5, 4
b) 5, 5
c) 4, 4
d) 3, 4
Solution: (c)
The execution steps are as follows:
1. arr[1] = ++arr[1]; arr[1]=++2=3 so, arr={1, 3, 3, 4, 5}
2. a = arr[1]++; a=arr[1]=3 (due to post increment). arr remains the same as step 1.
3. arr[1] = arr[a++]; arr[1]=arr[a]=arr[3]=4. arr={1, 4, 3, 4, 5}. a is incremented to 3+1=4
after the assignment is done.
4. Finally, a=4 and arr[1]=4 are printed