Skip to main content

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 for printf.
  • case is a keyword, so it cannot be an array name; rename it arr.
  • The for header uses commas; it needs semicolons: for(i=0; i<MAX; i+=1).
  • sum +=* case+i is invalid; it should be sum += arr[i].
  • average is not declared; declare it as float.
  • 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.2d prints each integer with at least 2 digits (a leading zero is added) inside a width of 3, so 2 prints as 02.
  • sum = 2+3+5+4+10 = 24. Since sum and MAX are both int, sum/MAX is integer division: 24/5 = 4. It is stored in the float average as 4.0.
  • %06.2f prints it in width 6, 2 decimals, padded with zeros: 004.00.
  • If (float)sum/MAX is used instead, the average is 4.8 and the output becomes 004.80.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 3 questions →