Repeat commands to restrict a valid value

Asked

Viewed 127 times

3

I need a code that reads a number greater than 1, and if a number less than or equal to zero is entered, another number is requested, and therefore can be tested if true.

I wanted help to complete my code.

#include <stdio.h>

int main()


{
int num,primo;
num=1;
do
{
    printf("Informe um numero primo maior que 1:");
    scanf("%d",&primo);

    if((primo%num)==0)
    printf("Numero primo",primo);

    else
    printf("Numero não primo");
}
while(primo>1);
}

1 answer

2


I solved other problems, I formatted better for easier reading. See that even looking silly, the spaces, the score, everything helps.

If the problem is to keep repeating the order until an invalid value is entered then you should only put inside the repetition what needs to be done again and the only thing that should be done again is the typing request. The rest stay out of the loop.

And if you must stay inside the loop while the condition is invalid, you must reverse the operator of what is valid. That is, if you need the value to be > 1, it should get stuck as invalid if the value is <= 1.

And this is another important learning. The opposite of > is <= and not < as many may think. Obviously the opposite of < is >=. If the opposite of > were <, then the equal value would be what? Would be lost in space? The same has to enter on one side.

#include <stdio.h>

int main() {
    int num = 1, primo;
    do {
        printf("Informe um numero primo maior que 1:");
        scanf("%d", &primo);
    } while (primo <= 1);
    if (primo % num == 0) {
        printf("Numero primo %d", primo);
    } else {
        printf("Numero não primo");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

That’s not how you find your cousin, but I’ll let you tidy up 'cause that’s not the point of the question.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.