Home > front end >  Array prints an unwanted number for no reason
Array prints an unwanted number for no reason

Time:10-15

/*This is a c program that inputs an array of 9 numbers, reverses it and prints it*/

#include <stdio.h>

int main()
{
    int a[9]; 
    
    printf("Enter 9 numbers \n");
    
    int i;
    
    for(i=0;i<9;i  )
    {
        scanf("%d",&a[i]);
    }
    
    int n=10; 
    
    int t;
    
    for(i=0;i<9/2;i  )
    {
        t=a[i];
        a[i]=a[8-i];
        a[8-i]=t;
    }
    
    for(i=0;i<10;i  )
    {
        printf("%d\t",a[i]);
    }
    
}

This is the output:

Enter 9 numbers 1 2 3 4 5 6 7 8

9

9 8 7 6 5 4 3 2 1
32765

I want to understand where the 32765 is coming from and how to fix it.

CodePudding user response:

The last weird number you see there is the value of the next (10st) address from the cell after your array. "a" has been declared with 9 values, and you should remember that arrays in C start from 0. While printing you are trying to access 10 numbers (from 0 to 9)

CodePudding user response:

As other answers point out, you are using a wrong array length at the last loop.

To avoid these kind of mistakes, use macros or const variables to store the fixed length of the array. For example:

#define ARRAYLEN 9
// ...
int a[ARRAYLEN];
// ...
for (int i = 0; i < ARRAYLEN; i  ) {
    // ...
}
  • Related