How to add multiple parameters in DO-WHILE loop in C

1.6k views Asked by At
#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n;
    do
    {
        n = get_int("height: ");
    }
    while(n<1&&n>8);
    for (int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            printf("#");
        }
        printf("\n");
    }
}

im writing a program to print a square with hashes,but my while in the Do loop wont work. i want it to accept values only between 1 and 8 inclusive,but it wont work and wouldnt prompt again if i enter values out of the parameter.but it works if I only put a single parameter in the while loop e.g. n<1. please help me,im a beginner.

3

There are 3 answers

0
0___________ On

The answer is very easy and it is not related to the programming only simple math and logic

while(n<1&&n>8)

If n is lower than 1 it cannot be larger than 8 at the same time.

3
Krishna Kanth Yenumula On

Reason for not working : while( n<1 && n>8); See the image for clarity. There is no value in the intersection. I mean there is no number, less than one and greater than 8.

enter image description here

Solution : Use while(n < 1 || n > 8); for n values between 1 and 8 inclusive.

0
Vlad from Moscow On

There is no such a number that would be simultaneously less than 1 and greater than 8.:)

n<1&&n>8

A simple way to write correctly the condition of the loop is to write at first the condition that a number shall satisfy. That is

1 <= n && n <= 8

and then to apply negation to the condition

do { /*...*/ } while ( !( 1 <= n && n <= 8 ) );

Then using rules for logical operations you can write for example

do { /*...*/ } while ( !( 1 <= n ) || !( n <= 8 ) );

and at last

do { /*...*/ } while ( ( 1 > n ) || ( n > 8 ) );

or

do { /*...*/ } while ( n < 1 || n > 8 );