How to control the flow when an invalid value is entered?

2

If I want a condition to be repeated over and over again, how can I use the return command for a specific line? I'll put the program to better explain:

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

int main()
{
    int aprovados, auxa=0, reprovados, auxr=0, notas=0, cont=0;

    while(cont<10)
    {
        printf("digite o resultado: ");
        scanf("%i", &notas);

        if(notas==1)
            auxa++;
        if(notas==2)
            auxr++;
        if(notas!=1 && notas!=2)
        {
            cont--;
            printf("esse valor nao eh valido digite 1 ou 2: ");
            scanf("%i", &notas);
            cont++;
            if(notas==1)
                auxa++;
            if(notas==2)
                auxr++;
        }

        cont++;
    }

    printf("aprovados:%i\n", auxa);
    printf("reprovados:%i\n", auxr);

    if(auxa>=8)
        printf("bonus ao instrutor\n");
    if(auxr>=7)
        printf("algo esta errado com o instrutor\n");

return 0;
}

I want to do the following: in the 3rd if if I type for example 3 it asks to enter another number (I know that I specified in printf that is to type 1 or 2) but if I type 3 then the counter counts 1 increment and if I repeat numbers other than 1 or 2 (in this case 20 times half of those times will be incremented in the counter), how can I give return to a specific line every time some number other than 1 or 2 to be typed?

    
asked by anonymous 26.06.2014 / 17:52

2 answers

3

If I understand, I think this is what you want:

#include <stdio.h>
int main() {
    int auxa = 0, auxr = 0, notas = 0, cont = 0;
    while (cont < 10) {
        printf("digite o resultado: ");
        scanf("%i", &notas);
        if (notas == 1)
            auxa++;
        if (notas == 2)
            auxr++;
        if (notas != 1 && notas != 2)
            continue;
        cont++;
    }
    printf("aprovados:%i\n", auxa);
    printf("reprovados:%i\n", auxr);
    if (auxa >= 8)
        printf("bonus ao instrutor\n");
    if (auxr >= 7)
        printf("algo esta errado com o instrutor\n");
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

The program has other problems but I think it answers your question. Besides this you have better ways to do the same, but I think it's best not to try to teach you the best code style until you understand what the code does.

    
26.06.2014 / 18:26
2

The Return command does not do what you're looking for, which would "skip" / "return" to a line, similar to jmp in assembly. You can not do this in C. The Return ends a certain function and returns its value to the output of the function.

If I understood your question, you're looking for what bigdown responded by using Continue

    
23.07.2014 / 20:30