In C, there is a ternary operator ?:
if...else
).The general syntax of this operator is:
(test) ? expressionTrue : expressionFalse ;
This operator is mainly used when you want to assign different values depending on the test.
// If x not equal to 0, 10 is assigned to n. Otherwise, 20 is assigned to n
n = (x != 0) ? 10 : 20;
The example below assigns the variable a
to max
if a
is greater than b
, otherwise,
the variable b
is assigned to max
. This instruction can be summarized in one sentence:
The variable
max
will contain the largest value betweena
andb
. :
max = (a > b) ? a : b;
This instruction can also be written with an if...else
:
if (a>b)
max = a;
else
max = b;
Write a program that asks the user to enter the number of kids. Then, the program displays : You have 7 kids. The word kid must be in the plural if the number entered is strictly greater than 1.
int nbKids;
// Get number of kids
printf ("How many kids? ");
scanf ("%d", &nbKids);
// Displays the number of kid(s)
printf ("You have %d kid%c.\n", nbKids, /* COMPLETE HERE */ );
Tip: ASCII code zero does not display anything.
Here is the expected output:
How many kids? 1
You have 1 kid.
How many kids? 7
You have 1 kids.
What does the following code display?
int n = (2>3) ? 0 : 1;
putchar ('%d', n);
What does the following code display?
int n=(2<3)?0:1;
putchar ('%d', n);
Which instruction is equivalent to the code below?
if (x%2)
c = 'p';
else
c = 'i';