C: More Operators and Arrays
(Page 1 of 5 )
In our last article we left off discussing some of C's Operators and how to use them. We will pick up on the same subject in this article, and cover arrays as well. As always, there is a lot to cover, so let's get to it.
Conditional OR Ternary Operator
Our good buddy the conditional operator is made up of two symbols: the question mark (?) and the colon(:). Consider the following:
mine = 100;
yours = 200;
ours = (mine > yours) ? mine : yours
In this example, the variable ours will be assigned the value of the variable yours, or 200. This occurs because the expression (mine > yours) is false. Had it been true, then the value of ours would have been the value of the variable mine, or 100.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int mine,yours,bigger;
printf ("Input my number and your number : ");
scanf_s("%d %d",&mine, &yours);
bigger = mine > yours ? mine : yours;
printf("The largest of two numbers is %d \n", bigger);
}
This code asks the user for two numbers. It stores the first number in the variable mine, and the second in the variable yours. Next it asks if mine is greater than yours. If so, bigger will get the value of the mine variable. If not, it will get the value of the yours variable. Finally it prints some text and appends the value of the variable bigger.
If the user had entered the numbers 20 and 50, the result would be:
Input my number and your number: 20 50
The largest of the two numbers is 50
Next: Bitwise Operators >>
More BrainDump Articles
More By James Payne