0

I need help making my code work. I want it so the user inputs a number less than 50, if this is true it will print hello world. Otherwise the terminal will ask for another input.

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

int main(void)
{
// Asking user for a number less or equal to 50
int i = get_int("Choose a number less or equal to 50\n");

// If i is less or equal to 50 print "hello world"
if ((int) i <= 50)
{
    printf("hello, world\n");
    i++;

}


}
Beaner21
  • 15
  • 4
  • Note that casting `int` to `int` is meaningless. (not harmful, but just meaningless) – MikeCAT Jul 21 '21 at 22:37
  • 1
    Your questions says "inputs a number less than 50", but your comment says "If i is less or equal to 50". Which is what you really want to do? – MikeCAT Jul 21 '21 at 22:39

2 Answers2

0

You should use a loop to repeatedly do something.

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

int main(void)
{
    int i;
    for (;;)
    {
        // Asking user for a number less than 50
        i = get_int("Choose a number less than 50\n");

        // If i is less than 50, print "hello world"
        if (i < 50)
        {
            printf("hello, world\n");
            i++;
            break; // exit from the loop
        }
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

You can use goto instead of a loop. I've created the function like in the next case:

#include <stdio.h>
#define PRINT_N  int n = 10;for(;n--;printf("Hello World\n")) 

int main(void)
{   
    int input_number;
    start:
    printf("\nChoose a number less or equal to 50\n");
    scanf("%d",&input_number);
    if(input_number <= 50 ) 
        {
            PRINT_N;
        }
    else
        goto start;
    
    return 0;

}

I hope this gonna be helpful.

  • This is a efficent solution but how do you print hello world 10 times, IF a number is less than equal to 50. Please send the code with print hello world 10 times aswell! – Beaner21 Jul 24 '21 at 22:11
  • Please add `#define PRINT_N int n = 10;for(;n--;printf("Hello World\n"))` at the beginning of the code, and `PRINT_N;` instead of `printf("\nHello World\n");`. I hope this is what you want to do @Beaner21. I've updated the code. Best regards. – Felipe Gomez Jul 25 '21 at 03:02