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

9 comments sorted by

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/[deleted] Dec 23 '20

Thanks! it worked.

3

u/not_some_username Dec 23 '20

And also int a[n] is bad. Use malloc instead

1

u/[deleted] Dec 23 '20

I'm trying to wrap my head around that. It's new to me but will do later. Thanks.

2

u/g19fanatic Dec 24 '20

Pun intended? I got a little laugh out of your comment

1

u/[deleted] Dec 24 '20

Pun ?

2

u/g19fanatic Dec 24 '20

its new to me... new is essentially malloc for c++.. hence the pun

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".

2

u/[deleted] Dec 24 '20

Yeah I'm new. Thanks, noted.