Question 6: Show the output (arrays) [6]
Show the precise output from the following C++ program:
#include <cstdio> const int ArrSize = 3; const float Data1[] = { 16, 8, 4 }; const float Data2[] = { 1.1, 2.2, 3.3 }; void fill(float arr[], int size); void print(const float arr[], int size); int main() { const int dataSize = 2 * ArrSize; float myData[dataSize]; fill(myData, dataSize); print(myData, dataSize); } void fill(float arr[], int size) { printf("Filling array of size %d\n", size); for (int i = 0; i < size; i++) { int p = i / 2; if ((i % 2) == 0) { arr[i] = Data1[p]; } else { arr[i] = Data2[p]; } } } void print(const float arr[], int size) { printf("Printing array of size %d\n", size); for (int i = 0; i < size; i++) { if (i > 0) { printf(", "); } printf("%g", arr[i]); } printf("\n"); } |
Sample solution: Filling array of size 6 Printing array of size 6 16, 1.1, 8, 2.2, 4, 3.3 Explanation: fill goes through positions i=0..5 of arr, pos = i/2, but this is integer division so rounds down, if i is even then takes from Data1[p] otherwise from Data2[p] i p arr[i] 0 0 16 1 0 1.1 2 1 8 3 1 2.2 4 2 4 5 2 3.3 |