Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One time execution of "do" in a do-while loop

my goal is to make triangles with #. it does not print the code "Height(a number from 1 to 8):" when a value not between 1-8 is entered in the code below.

#include <stdio.h>

int main(void)
{
    int h;
    do{
        printf("Height(a number from 1 to 8): ");
        h = get_int("");

    }while((h<1)||(h>8));{
       for(int i=0; i<h;i++){
           for(int j=0; j<=i; j++){
               printf("#");
           }
           printf("\n");
       }
    
    }
}

how can I print "Height(a number from 1 to 8):" repeatedly until I enter a number 1-8?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

it does not print the code "Height(a number from 1 to 8):" when a value not between 1-8 is entered in the code below

Yes it does, though you might have to "flush" the stdout buffer. This can likely be done by adding a new line character to printf:

printf("Height(a number from 1 to 8): \n");

Or in case you are using some exotic system, fflush(stdout); will always work.

Also the logic is wrong:
"while h is less than 1 and h is larger than 8, loop" – should be
"while h is less than 1 OR h is larger than 8".


Also, the sloppy code formatting with braces all over isn’t doing you any favors when it comes to understanding your own code. Rewrite it to something readable:

#include <stdio.h>

int main(void)
{
    int h;
    do{
        printf("Height(a number from 1 to 8): \n");
        h = get_int("");
    } while( (h<1) || (h>8) );

    for(int i=0; i<h; i++){
        for(int j=0; j<=i; j++){
            printf("#");
        }
        printf("\n");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading