Hassen Fatima
Hassen Fatima

Reputation: 423

How to create a loop without knowing when the loop will stop?

I am trying to create a program which takes a number and we match that number with a variable which has a specific number stored. We need to keep doing that until the user enters the correct number that matches the number we have stored in our variable:

#include <stdio.h>
int main(void) {

        int i;
        int j;
        int num1;
        int num2 = 2;

        printf("Enter number");
        scanf("%d", &num1);

        while (num1 == 0) {

                printf("Enter number");
                scanf("%d", &num1);
        }

        while (num1 != num2) {

                for(j=1;j
                printf("This is not the correct number! \n");
                printf("Enter number again: ");
                scanf("%d", &num1);
        }

        if (num1 == num2) {

                printf("The numbers have matched! \n");
        }
}

I am confused with how do we create a loop where we don't know how many times the user will enter an incorrect number. What I want with the loop is to display is how many times the user enters an incorrect number. Let say if they enter 3 times.

    This is not the correct number 1!
    This is not the correct number 2!
    This is not the correct number 3!

But we don't know how many times the user will enter an incorrect number, so what condition do I put in a loop, so it counts.

Upvotes: 0

Views: 272

Answers (1)

dbush
dbush

Reputation: 223917

You want to create a separate counter variable that keeps track of how many times you've gone through the loop. Set it to 0 before the loop, then increment on each iteration.

   int count = 0;
   ...
   while (num1 != num2) {
            count++;
            printf("This is not the correct number %d! \n", count);
            printf("Enter number again: ");
            scanf("%d", &num1);
    }

Also, I'm presuming this is a typo:

for(j=1;j

Upvotes: 2

Related Questions