Continue after incorrect input for loop

120 views Asked by At
#include<stdio.h>
#define M 6
#define N 5


int main(){

  int array[N][M];
  int i, j;

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
        scanf("%d", &array[i][j]);
        if(array[0][1]<1 || array[0][2]<1 || array[0][3]<1){
            // ??
        }

    }
  }
  return 0;
}

How do I make it so that if the input doesn't match my (very likely wrong) if statement, the
user must reinput that array field and it doesnt just skip to the next input field?

2

There are 2 answers

0
dhalik On

To solve this you can simple do the following. If input is wrong, decrement j by 1 to force the user to reinput the same field. It may also make sense to tell the user that their input was wrong, so they know to enter the proper value.

0
nem035 On

How do I make it so that if the input doesn't match my (very likely wrong) if statement, the user must reinput that array field and it doesnt just skip to the next input field?

You can have the condition of your if statement determine how the loop variables (that serve as array indexes) are updated:

for(i=0;i<N;i++){     // dont update i here
    for(j=0;j<M;j++){ // dont update j here

Instead use a while loop that updates i and j if your condition is satisfied as well as if there are any rows and columns left:

while(1) {
    printf("Enter value: ");
    scanf("%d", &array[i][j]);
    printf("array[%d][%d] = %d\n", i, j, array[i][j]);
    if(YOUR_CONDITION) {

        // update i and j inside this statement
        // this means the user can advance to the next array element
        // ONLY if your if statement condition is true

        if(j < M-1) { // if there are columns left, update j
            j++;
        }
        else if(i < N-1) { // otherwise, if there are rows left, reset j and update i
              j = 0; 
              i++; 
        } else {
            break;  // if we reach this point we are out of rows and columns and we break out of the loop
        } 
    } else {
          printf("Please satisfy the condition!\n");
    }
}

Now, as far as YOUR_CONDITION:

if(array[0][1]<1 || array[0][2]<1 || array[0][3]<1)

The problem with this statement is that it is checking values in the array that weren't yet entered by the user.

If you specify what you want to do with this statement, maybe I can be of further help.