if (condition)
{
statement;
}
else if (condition2)
{
statement2;
}
else
{
statement3;
}
nextStatement;
if (randNum < 0.2) x = 1; else if (randNum < 0.5) x = 2; else x = 3;
Note that you can omit { } if there is only 1 statement for a condition. But if you need to do a couple things if a codition is met, you need { } to make a ``block'' of statements.
if (randNum < 0.2)
{
x = 1;
y = -2;
}
else
x = 3;
if (randNum < 0.2) x = 1; y = -2;
| a > b | greater than |
| a >= b | greater than or equal to |
| a < b | less than |
| a <= b | less than or equal to |
| a == b | equal |
| a != b | not equal |
Let's say x = 3, and y = 1 now.
| Expression | what it evaluates to | |
| x == y | 0 (false) | |
| x > y | 1 (true) | |
| x != y | 1 (true) | |
| x + 2 == y * 5 | 1 (true) |
if (x) y = 1 / x ;
Guess the behavior of the following code?
if (a-b) a = -1; else a = 3;
Copy /home/progClass/src/immig-emig/ifProb.c, compile it, and run it.
Find out what is wrong with the code.
#include <stdio.h>
int
main (void) {
int x, y;
x = 3;
if (x = 1)
printf("x is 1\n");
else
printf("x is NOT 1\n");
y = 0;
if (y = 0)
printf("y is 0\n");
else
printf("y is NOT 0\n");
return(0);
}
y = a + (b - c) * d / e
I think these arithmetic operators needs no explanation except %.
% is called modulus, and it is very handy.
x % y
retuns the remainder when x is divided by y.
| 0 % 3 | = 0 |
| 1 % 3 | = 1 |
| 2 % 3 | = 2 |
| 3 % 3 | = 0 |
| 4 % 3 | = 1 |
| 5 % 3 | = 2 |
| 6 % 3 | = 0 |
| Expression | equivalent to | |
| x += 3; | x = x + 3; | |
| x -= 5; | x = x - 5; | |
| x *= 2; | x = x * 2; | |
| x /= 4; | x = x / 4; | |
| x %= 6; | x = x % 6; | |
| x++ or ++x | x = x + 1; | |
x-- or --x |
x = x - 1; |