what the expression means:

Asked

Viewed 28 times

0

Can anyone tell me what this part of the code means? (sorry for the redundancy, had asked the same question in another post of mine and was not answered). I’m still a layperson at c and normally I would use an if, rather than assign it this way.

int x = a > b ? b : a;
int y = a < b ? b : a;
#include <stdio.h>
int main() {
    
    // Fazemos leitura e cálculo das entradas 30 vezes
    for (int i = 0; i < 30; ++i) {
        int a, b, soma = 0;
        
        // Primeiro, lemos um par de números
        printf("Primeiro número : ");
        scanf("%d", &a);
        printf("Segundo número : ");
        scanf("%d", &b);
        
        // Segundo, armazenamos esses números em variáveis x, y: x para o menor número, y para o maior
        int x = a > b ? b : a;
        int y = a < b ? b : a;
        printf("(x, y) = (%d, %d)\n", x, y);
        
        // Terceiro, fazemos a soma de todos os inteiros de x até y (incluindo x e y)
        while (x <= y) {
            soma += x;
            x++;
        }
        printf("Soma: %d\n", soma);
    }
    return 0;
}
  • 4

    is a ternary operator, which has two results based on a condition (logical operation), means the same as int x; if (a > b) x = b else x = a;

No answers

Browser other questions tagged

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