Display the largest and smallest value between two integers when they are different from each other

I am not able to display the values of minor and major.

Make an algorithm that reads two numbers and indicates whether they are the same or, if different, shows the largest and smallest in this sequence.

int V1,V2;

printf("Valor 1 :"); scanf("%d",&V1);
printf("Valor 2 :"); scanf("%d",&V2);

if (V1==V2){
    printf("O valor é igual \n\n ");
}
else{
    printf("O valor é diferente \n\n");
}
if (V1>V2){
    printf("O valor maior é %d",V1);
}
if (V1<V2){
    printf("O valor menor é %d", V2);
}
return(0);
system("pause");
 3
Author: Maniero, 2018-09-14

2 answers

#include <stdio.h>

int main()
{
    int v1, v2;
    printf("Valor 1:");
    scanf("%d", &v1);
    printf("Valor 2:");
    scanf("%d", &v2);

    if(v1 == v2){
        printf("Os valores %d e %d são iguais.", v1, v2);
    }   
    else {
        printf("Os valores %d e %d são diferentes.", v1, v2);
        if(v1 > v2){
            printf("\nO maior valor é: %d e o menor é: %d.", v1, v2);
        }
        else{
            printf("\nO maior valor é: %d e o menor é: %d.", v2, v1);
        }
    }
}

You only need to know if a value is higher or lower if they are different, so I used a chained decision Structure , that is, the program will only enter if or else if the values are different.

 3
Author: Alicia Tairini, 2018-09-19 12:40:42

You started well using else in the first if, it should have continued like this. So when v1 is greater than v2 you already have reason to write which is the largest and which is the smallest at the same time. And if not, then write the same, but this time with the inverted variables.

#include <stdio.h>

int main(void) {
    int v1, v2;
    printf("Valor 1 :"); scanf("%d", &v1);
    printf("Valor 2 :"); scanf("%d", &v2);
    if (v1 == v2) printf("O valor é igual\n");
    else printf("O valor é diferente\n");
    if (v1 > v2) printf("O valor maior é %d\nO valor menor é %d", v1, v2);
    else printf("O valor maior é %d\nO valor menor é %d", v2, v1);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

Or maybe I didn't even want to have two ifs, then you should use one if, one else if and one else. It remains to do it, but I think a worse solution.

 5
Author: Maniero, 2020-08-06 14:38:39