Search code examples
cwhile-loopintegerscanf

Creating a while loop in C


I've just started learning C and I've decided to create a while loop to make sure I get the hang of things. This is my code:

#include <stdio.h>

void main(){
    int num, guess, turns;
    num = 13;
    guess = getchar();
    turns = 0;
    
    while(guess != num){
        printf("%d", guess);
        ++turns;
        printf("Turns:\n");
        printf("%d", turns);
        guess;
    }      
}

It gives me an infinite loop. Can someone please tell me where I went wrong? Also, if you have any suggestions or tips, please feel free to leave them.


Solution

  • getchar() does not read from terminal, you have to use:

    scanf(" %d", &guess);
    

    In the while loop you have to read a value from terminal again (if the guess is wrong)

    while(guess != num){
       printf("Turns:\n");
       printf("%d", guess);
       ++Turns;
       scanf(" %d", &guess);
    }
    printf("%d is the correct guess", guess);