do while loop help

0 Alex Jam · September 11, 2014
After watching video 26 on do while loops I tried to create a simple do while program myself, and I can't get it to work. When the user enters a number less than or equal to 5 the prompt "YAY" should appear on screen, but if the user inputs a number greater than 5 the prompt "NO" should appear and the program terminates.  
The loop does not seem to work properly.

#include <stdio.h>
#include <stdlib.h>

int main()
    int x;
    do {
        printf("Enter a number ");
        scanf(" %d \n", &x);
        printf("YAY \n");
    } while(x <= 5);
    printf("NO \n");
    return 0;

Post a Reply


Oldest  Newest  Rating
0 George Williams · September 12, 2014
Its not working because what you want is the user to input a number less than or greater than 5, which the best thing for that is a if statement. If you want to experiment with do and while, create a simple username application where you set a string to a value such as "John" and read from cmd...If the user input doesn't equal "John" then increment i by 1(I is an integer you must declare).
When i reaches above 5, make cmd print "U failed bro"
+1 Горан Куга · October 14, 2014
Hi here is my way of doing it. Check comments in code for clarification.
#include <stdio.h>
#include <stdlib.h>

int main()
    float x;
    printf("Enter a number that is less then 5: ");
    scanf(" %f", &x);

    if(x <= 5){ // best way is using an if statement. we are saying if our float x is less or equal to 5 do next code.
       printf("Good job your number is less then 5. \n");
    }else{ // if our float x is larger then 5 do next code.
       printf("Your number is larger then 5. \n");

    return 0;
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator