Skip to main content

Correct program: character arrays

Short answer

Errors: ar1 size 11 with 12 initializers, missing null terminator; similar issue for ar3; return 0 missing ';'; extra '{'. Correct by increasing ar1 and ar3 sizes to at least 13. Output: Array 1 = IoE PULCHOWK, Array 2 = IoE, Pulchowk, Array 3 = IOE PULCHOWK.

Rewrite program correctly and write output of the given program written in C programming language below:

# include<stdio.h>
# include<conio.h>
# include<string.h>
void main( )
{
  char ar1[11] = {'I','o','E',' ','P','U','L','C','H','O','W','K'};
  char ar2[15] = "IoE, Pulchowk";
  char ar3[11] = {{'I'},{'O'},{'E'},
  {' '},{'P'},{'U'},{'L'},{'C'},{'H'},{'O'},{'W'},{'K'}};
  clrscr( );
  {printf ("\nArray 1 = %s\n", ar1);
  printf ("\nArray 2 = %s\n", ar2);
  printf ("\nArray 1 = %s\n", ar3);
  return 0
}

Errors in the given program

  1. char ar1[11] is given 12 initialisers (IoE PULCHOWK has 12 characters). Excess initialisers are an error, and even a size of 12 would leave no space for the null character '\0', so %s could run past the array (undefined behaviour). The size must be at least 13.
  2. ar3 has the same size problem. Also, the braces around every single character ({'I'}) are unnecessary; they are allowed only with a warning ("braces around scalar initializer").
  3. return 0 has no semicolon, and void main() cannot return a value. Use int main() or remove the return.
  4. The extra { before the first printf is never closed, so the closing } of main is missing.
  5. conio.h and clrscr() are Turbo C only (not standard C). They may be kept in Turbo C, but are removed here.
  6. The third printf prints the label "Array 1" for ar3; it should be "Array 3".

(gcc -Wall -std=c99 on the original reports the excess elements, the braces warnings and the missing ;.)

Corrected program

#include <stdio.h>

int main(void)
{
    char ar1[13] = {'I','o','E',' ','P','U','L','C','H','O','W','K'};
    char ar2[15] = "IoE, Pulchowk";
    char ar3[13] = {'I','O','E',' ','P','U','L','C','H','O','W','K'};

    printf("\nArray 1 = %s\n", ar1);
    printf("\nArray 2 = %s\n", ar2);
    printf("\nArray 3 = %s\n", ar3);
    return 0;
}

Output


Array 1 = IoE PULCHOWK

Array 2 = IoE, Pulchowk

Array 3 = IOE PULCHOWK

ar2 is "IoE, Pulchowk" (13 characters plus '\0' in a 15-element array, so the last element is also '\0'). ar1 keeps the small o, while ar3 has capital O in "IOE".

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →