Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I dont understand fully how program in c++ is working. Someone will explain?

–1 vote
asked Oct 23, 2018 by Grochu (110 points)
Hello, I have started programming in c++. This program is working correctly but i dont understand what line

 wynik = (znak == '*') ? 1:0;

 is for and how works?

void zamiana(int&, int&);

int main(){
    int g;
    int A,B, wynik;
    char znak;
    
    
    scanf("%d", &g);
    for (int i = 0; i < g; i++){
        scanf("%d %d %c", &A, &B, &znak);
        if (A == B){
            continue;
        }
        else if (A > B){
            zamiana(A, B);
        }
        wynik = (znak == '*') ? 1:0;
        for(int j = A; j <= B; j++){
            if(znak == '+'){
                wynik += j;
                
            } else if(znak == '-') {
                    wynik -= j;
            }   else{
                    wynik *= j;
            }
        }
        cout << wynik;
    }
    return 0;
}
 

void zamiana(int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

1 Answer

0 votes
answered Oct 25, 2018 by ananth222 (140 points)
The statement "(znak == '*') ? 1:0;"  is called a ternary operator.

It has the form "(condition) ? True_value : False_value"

The way it works is it checks the condition, if the condition is true, it returns the True_value, otherwise it returns the False_value.

In your case "wynik = (znak == '*') ? 1:0; " checks if the char znak is "*", and if true, assigns the value 1 to wynik, and if false assigns the value 0 to wynik.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...