Search code examples
cdo-whilecs50logical-orlogical-and

Non-function do while loop in C


I'm new to programming and was hoping I could get some help. I'm attempting to create a 'do while' loop in C as part of my CS50 problem sets. I'm attempting to use two different conditions under 'while', but for some reason they are not being recognised. Here's my code

#include <stdio.h>
#include <cs50.h>

int get_height(void);

int main(void)

{
    int height = get_height();
    printf("you picked %i\n", height);
}

int get_height(void)
{
    int height;
    do
    {
        height = get_int("enter height\n");
    }
    while (height > 8 && height < 1);
    return height;
}

I'm trying to force the user to type an integer under 8, but above 0. If I take out either one of the two conditions, that single condition works. If I try to use both conditions however, the code compiles and runs but it doesn't force me to enter a number within the parameters specified. I can just enter any number and it will be accepted. Can anyone help?

EDIT: I'm embarrassed. I misunderstood how AND operators work.


Solution

  • I think that mathematics have not yet found an integer number that can be at the same time less than 1 and greater than 8.

    while (height > 8 && height < 1);
    

    It is evident you mean

    while (height > 8 || height < 1);
    

    But to make such a condition more clear for yourself it is useful sometimes to write at first the condition for which a number is being searched.

    You need a number that lies in the range [1, 8] that is the target number shall satisfy the condition

    1 <= height && height <= 8
    

    In this case the condition in the do-while statement will be a negation of the condition above.

    while ( !( 1 <= height && height <= 8 ) );
    

    Now if to remove the negation you will have

    while ( !( 1 <= height ) || !( height <= 8 ) );
    

    that is equivalent to

    while ( 1 > height || height > 8 );
    

    So either use

    while ( !( 1 <= height && height <= 8 ) );
    

    pr

    while ( 1 > height || height > 8 );