- 2074 Asoj · 4 marks
Correct program: case array and average
Short answer
Correct: #include <stdio.h>, #define MAX 5, rename array to arr, fix for‑loop semicolons, sum+=arr[i], declare float average, return 0. Array sum = 24; integer division 24/5 = 4, printed as 004.00. Output shows each Case line and final 004.00.
Rewrite the following program by correcting any errors, if present and also write down the output of the corrected code.
Define MAX '5'
int main ( )
{
int case[MAX]={2,3,5,4,10},i,sum=0;
for(i=0,i<MAX,i+=1)
{
printf("Case %d = %3.2d\n",i,case[i]);
sum +=* case+i;
};
average = sum/MAX;
printf("%06.2f",average);
return 1;
}
Errors found
Define MAX '5'should be#define MAX 5; also'5'is a character constant (value 53), not 5.#include <stdio.h>is missing, needed forprintf.caseis a keyword, so it cannot be an array name; rename itarr.- The
forheader uses commas; it needs semicolons:for(i=0; i<MAX; i+=1). sum +=* case+iis invalid; it should besum += arr[i].averageis not declared; declare it asfloat.- The
;after the closing brace of the loop is unnecessary.
Corrected code
#include <stdio.h>
#define MAX 5
int main(void)
{
int arr[MAX] = {2, 3, 5, 4, 10}, i, sum = 0;
float average;
for (i = 0; i < MAX; i += 1)
{
printf("Case %d = %3.2d\n", i, arr[i]);
sum += arr[i];
}
average = sum / MAX;
printf("%06.2f", average);
return 0;
}
Output
Case 0 = 02
Case 1 = 03
Case 2 = 05
Case 3 = 04
Case 4 = 10
004.00
Explanation
%3.2dprints each integer with at least 2 digits (a leading zero is added) inside a width of 3, so 2 prints as02.sum = 2+3+5+4+10 = 24. SincesumandMAXare bothint,sum/MAXis integer division: 24/5 = 4. It is stored in the floataverageas 4.0.%06.2fprints it in width 6, 2 decimals, padded with zeros:004.00.- If
(float)sum/MAXis used instead, the average is 4.8 and the output becomes004.80.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Correct program: do-while and pow · Computer Programming, chapter 3
- Correct program: Celsius to Fahrenheit · Computer Programming, chapter 3
- Output of printf statements · Computer Programming, chapter 4
- Correct program: character arrays · Computer Programming, chapter 7
- Output of arithmetic expression program · Computer Programming, chapter 3
- Pass 2D array; largest and smallest · Computer Programming, chapter 7
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- Trellis decoding of 1/2 rate conv. code (3-bit errors) · Data Communication, chapter 8 · asked 2×
- Trellis decoding of 1/2 rate conv. code (2-bit errors) · Data Communication, chapter 8 · asked 2×
- Step-down chopper with 1 V drop: average and rms · Power Electronics, chapter 4 · asked 2×