Reputation: 11
I'm currently learning C
and wanted to write a program that takes a number ganzeZahl
to determine array length.
Then you have to input the numbers being stored in that array of size n
and after that it's supposed to do a selection sort (which I cut out here, because my program doesn't even reach to that part).
I can't get past the while loop whenever I try to run it. It compiles fine.
It never reaches the printf("!!!--------!!!");
//this part isn't reached for some reason? test5.
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
Upvotes: 0
Views: 63
Reputation: 21
for(int z = 0; z < ganzeZahl; z++){
printf("%d\n", array[z]);
The array is not initialized and so you can't print the array yet.
Actually you messed up with the order of code.The while loop should come first and then the for loop. I have corrected your code below. Happy coding!
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
Upvotes: 1
Reputation: 46
Your program does execute correctly, and eventually reaches the last printf
call.
When, it enters the while
loop, it keeps on calling scanf
, what causes it to stop and wait until you enter a value every iteration. If you provide ganzeZahl
inputs (enter a number and press 'enter'), it will complete the loop and proceed. I guess that if you add a printf
before scanf
within the loop, it should be more intuitive.
Upvotes: 2