What is the output of the following C code:Code#include <stdio.h>double hack_func(int *arr, int size) { int i, sum = 0; int res; for (i = 0; i < size; ++i) { sum += arr[i]; } res = (int)sum / size; return res;}int main () { int a[5] = {20, 21, 22, 23, 24}; double res; res = hack_func(a, 5 ); printf("%f", res ); return 0;}
Question
What is the output of the following C code:Code#include <stdio.h>double hack_func(int *arr, int size) { int i, sum = 0; int res; for (i = 0; i < size; ++i) { sum += arr[i]; } res = (int)sum / size; return res;}int main () { int a[5] = {20, 21, 22, 23, 24}; double res; res = hack_func(a, 5 ); printf("%f", res ); return 0;}
Solution
The output of the given C code will be "22.000000".
Here's the step-by-step explanation:
-
The main function starts execution. It declares an integer array 'a' with 5 elements (20, 21, 22, 23, 24) and a double variable 'res'.
-
The function 'hack_func' is called with the array 'a' and its size (5) as arguments.
-
Inside 'hack_func', a for loop runs from 0 to size-1 (0 to 4 in this case). For each iteration, the corresponding element of the array 'arr' is added to the variable 'sum'. So, after the loop, 'sum' will be the total of all elements in the array (20+21+22+23+24 = 110).
-
The variable 'res' is assigned the value of 'sum' divided by 'size'. Since 'sum' and 'size' are both integers, this division will be integer division, and the result will be the integer part of the average of the array elements. So, 'res' will be 110 / 5 = 22.
-
The function 'hack_func' returns 'res' as a double. So, the returned value is 22.0.
-
Back in the main function, 'res' is assigned the returned value from 'hack_func', which is 22.0.
-
The printf statement prints the value of 'res', which is 22.0. Since the format specifier used is "%f", the output will be "22.000000".
-
The main function returns 0 and the program ends.
Similar Questions
What is the output of the following C Program?
What is the output for the following code?
What will be the output of the following C++ code?
What will be the output of the following C code?#include <stdio.h>int main() { int i; for (i = 0; i < 5; i++); printf("%d\n", i); return 0;}
what will be the output of the c program?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.