Search code examples
do-whilecs50cc

Loop runs ad infinitum, regardless of int entered


I've take a break since I posted this and have read through half of the C programming book I'm studying (Harvard cs50 book). I should be able to solve this by now, yet am unable.

The program runs in a continuous loop, no matter what integer is entered; prints "Good for you..." ad infinitum.

Example code:

//example 3 version2 from chapter 11, beginner programming in c
#include <cs50.h>
#include <stdio.h>

int main ()
{

        int prefer;

        printf("On a scale from 1 to 10, how happy are you?\n");
        scanf(" %d", &prefer);

        while(prefer >= 1  || prefer <= 10)
                //goal is for program to run while entered int "prefer" is between 1 - 10
                if (prefer > 10)
                {
                        printf("Oh really, now?  Can't follow simple directions, can you?\n");
                        printf("want to try that again?  1 through 10...?\n");
                        scanf(" %d", &prefer);
                }
                else if (prefer >= 8)
                {
                        printf("Good for you!\n");
                }
                else if (prefer <= 5)
                {
                        printf("Cheer up : )\n");
                }
                else if (prefer <= 3)
                {
                        printf("Cheer up, Buttercup!\n");
                }
                else
                {
                        printf("Get in the RIVER with that attitude!\n");
                }
        return 0;
}

Solution

  • Operator < and && are binary operators. When we use them, it compares the left and right side values. The above while would look like this.

    while(prefer <= 10 && prefer > 0);