Search code examples
cloopsgoto

Goto and Code Repetition - Are they avoidable in this case?


I've recently faced a programming problem, and it seems to me that the most optimized way of solving it is by using goto, even though it's not a good practice. The problem is: tell the user to enter a positive natural number ( > 0) and read the input. If this number is valid, tell the user the square of that number. Do this while the input is correct. I came up with a few solutions, but all of them seem to have problems. Here are two of them:
Solution 1 - Problem: Uses goto

#include <stdio.h>

int main()
{
    int num;

_LOOP:
    printf("Enter a positive natural number: ");
    scanf("%i", &num);

    if (num > 0) {
        printf("Square: %i\n", num * num);
        goto _LOOP;
    }

    printf("Invalid number\n");

    return 0;
}

Solution 2 - Problem: Double-checks if num > 0 (code repetition)

#include <stdio.h>

int main()
{
    int num;

    do {
        printf("Enter a positive natural number: ");
        scanf("%i", &num);

        if (num > 0)
            printf("Square: %i\n", num * num);
    } while (num > 0);
    
    printf("Invalid number\n");

    return 0;
}

Obviously, there are more ways to solve the problem, but all the other ones I came up with that do not use goto encouter the same code repetition problem. So, is there a solution where both goto and code repetitions are avoided? If not, which one should I go for?


Solution

  • Here's half the answer; try to fill in what's missing. Remember that sometimes it's better to structure your loop as "do something until..." rather than "do something while..."

        for (;;) {
            printf("Enter a positive natural number: ");
            scanf("%i", &num);
            if (num <= 0)
                break;
            printf("Square: %i\n", num * num);
        }
        printf("Invalid number\n");
    

    [updated with @rdbo's answer]