Keshav Tiwari
Keshav Tiwari

Reputation: 3

C program to write a GUESS game with certain constraints. Problems occuring - error in code, logic of code, suggesstions

Question :

Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.

My code :

#include<stdio.h>
#include<stdlib.h>
int compare(int m) {
    int b;
    b=73-m; ///I chose my number as 73 here.

    if (b=0) printf("Congrats, you won.");
    else {
        if (-5 < b < 5) printf("Very Close\n"); ///always gives me this output two times.
        else {
            if (-15 < b < 15) printf("Close");
            else {
                printf("You are far");
            }
        }
    }
    return b;
}

int main() {
    int arr[100],guess,count=0,i,m; ///I have 99 tries.
    arr[0]=0;
    for(i=1 ; i<=100 ; i++) {
        printf("Enter your guess\n");
        scanf("%d",&guess);
        if(guess==arr[i-1]) {
            arr[i]=guess;
            printf("Guess is same as the previous input.\n");
        } else {
            arr[i]=guess;
            compare(guess);
            if (m = compare(guess)) {
                count=count+1; /// can i create a separate function to keep the count?
                printf("%d is the number of tries.\n",count);
                break;
            } else {
                printf("\n");
            }
        }
    }
    return 0;
}

This is always giving me the same output two times i.e "Very close Very close". This is either faulty code (syntax) or wrong logic, I think. Also I want to know a better algorithm/logic with the code to solve this question (possibly shorter). Lastly I am new to programming with C as my first language.

Upvotes: 0

Views: 355

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

The condition -5 < b< 5 is equal to (-5 < b) < 5, which means you compare the boolean (0 or 1) result of -5 < b with 5.

If you need to compare b to a range you need to do -5 < b && b < 5. I.e. compare b explicitly against both ends of the range.

Also, b = 0 is assignment not comparison, you need to use == for comparison.

Upvotes: 3

Related Questions