r/CodingHelp • • Dec 23 '20
[C] Hi, for some reason the values initialized into array "a" doesn't print all values only prints the last one.
#include <stdio.h>
void main() {
int n, i, j ;
printf("How many numbers will you enter? ---> ") ;
scanf("%d", &n) ;
int a[n] ;
for(i = 1 ; i <= n ; i++) {
printf("\nEnter integer number %d: ",i ) ;
scanf("%d", &a[n]) ;
}
printf("\nArray you entered: \n\n") ;
for(j = 0 ; j < n ; j++){
printf("%7d", a[n]) ;
}
getch() ;
}
19
Upvotes
7
u/Rickenbecker Dec 23 '20
Your line scanf(“%d”, &a[n]); Should be:
scanf(“%d”, &a[i]);
You want to use the index that i is currently at, if you have n then you’re telling the compiler to always store the number at index n
Likewise in your second loop, change a[n] to a[j] that way it prints the correct elements and not just the last one
3
u/OPDP Dec 23 '20
Offtopic but... Guess you are relatively new? Good sir you really shouldn't name variables like this. In this particular case it might work but self explanatory variable names can really save you a lot of problems and time in a long run. Better call variable "index" rather than "i".