Home > front end >  Why does this c program not end when entered 0?
Why does this c program not end when entered 0?

Time:09-22

It keeps on asking for integers whether I put 0 or not. I don't know the way to end it. I appreciate it if you do help me. Thanks. I edited the code due to some basic mistakes.

#include <stdio.h>

int main() {
  int a=1, integers[100];
  while (integers[a] != 0) {
    for (integers[a]; integers[100];   a) {
      printf("Enter the integer: \n");
      scanf("%d", & integers[a]);
    }
  }
  
  return 0;
}

CodePudding user response:

You have some problems with your loops.

  1. The for loop has weird things in the head: The initializer part integers[a] does not have any effect. You can skip it.

  2. The loop condition integers[100] is wrong. There is no element integers[100] as the allowed range for array index is 0..99. You do not assign any value to integers[100]. Your array is uninitialized. You probably want to check if the entered value was 0.

  3. If you fix the inner loop, it will basically do the same as the outer loop, making it redundant.

  4. You do not check if you read more than 100 values into your array.

Try this instead:

#include <stdio.h>

int main(void) {
  int integers[100];
  int a;
  for (a = 0; a < 100; a  ) {
      printf("Enter the integer: \n");
      scanf("%d", &integers[a]);
      // TODO: Check result of scanf!

      if (integers[a] == 0)
          break;
  }
  // Now a holds the number of valid values in the array
  // Elements 0..a-1 are filled with input values.
  
  return 0;
}

CodePudding user response:

Without a critique of your code, here is an example of why many languages offer a do/while loop.

int main() {
    int index = 0, integers[ 100 ] = { 0 }; // initialise everything

    do {
        printf( "Enter integer #%d (0 to quit): ", index   1 );
        scanf( "%d", &integers[ index ] );
    } while( integers[ index ] != 0 &&   index < 100 );

    printf( "Collected %d integers from you.\n", index );

    /* todo: do something with the values */

    return 0;
}
  • Related