The next statements compute in z the maximum number of a and b.
if(a>b)
z=a; /*if statement is TRUE (1)*/
else
z=b;/*if statement is FALSE (0)*/
The conditional expression, written with the ternary operator “?:” provides an alternative way to write this:
z = (a>b) ? a : b;
If a is greater than b, then z=a else z=b. If a and b are of different type, then the type of result is determined by the rules of conversion. For example, if f is a float and n an int then the expression (n>0) ? f : n is of type float regardless of whether n is positive .
for (i = 0; i < n; i++)
printf(“%6d%c”, a[i] , (i%10==9 || i==n-1) ? ‘\n’ : ”);
Example above prints n elements of an array, 10 per line, with each column separated by one blank, and with each line (including the last) terminated by a newline.
Because this expression leads very succinct code, the programmer must be very careful with the brackets that they are in the right place. Next one good example of using this expression:
printf(“You have %d item%s. \n”, n, n==1 ? “” : “s”);
Exercises:
1. Write a program, which asks the user enter 2 numbers and then prints the bigger.
2. Write a program, which asks the user enter 2 numbers and then asks the user, does he/she want that program prints either smaller or bigger number and then prints it.
3. Write a program which checks whether a number entered by user is prime or not.
NOTE! Exercises for that chapter can be found in quizzes Exercises 4 and P3-4 where these skills will also be tested. It is also important that the student does these examples above