简体   繁体   中英

C: why does my program not continue after while loop? (scanf)

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;
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM