last modified 2/12/01

Conditions

Often, you will want to execute certain statements only if a specific condition is met.

Operators are provided to test for equality and relative value (greater than / less than.)

comparison operators
operator meaning
==  equals
!= does not equal
>= is greater than or equal to
<= is less than or equal to
> is greater than
< is less than

The value of a conditional expression is either true or false:

(3 > 2 ) is true.

(3 < 2 ) is false.

(a == b) may be true or false, depending on the values of the variables a and b.


Conditions can be combined into longer expressions with parentheses and AND/OR operators.

So, you can have an expression like:

(((a < b) && (c < d)) || (a == c))

which reads: either a is less than b AND c is less than d OR a is equal to c.


Conditions are used in loops to specify whether the body of the loop should be executed.

Example:

for (i = 0; i < 10; i++)
	sum = sum + i;

The condition in this for loop is "i < 10". As long as that condition is true, the loop will continue to execute. When writing loops, you need to be careful to write conditions that will eventually fail. Otherwise, you will have created an 'infinite' loop.


Conditions are also used in if-else constructs. If you want to execute some code only when some condition is true, you can use an if statement.

if (n < 100)
{
   do something...

}

All the statements between the curly brackets will be executed if n is less than 100. If n is not less than 100, the program will continue executing with the next statement after the closing curly bracket.

If you have only one statement associated with the if expression, you don't need curly brackets, but it's fine if you leave them in.

Optionally, you can write an else clause following the if clause. You can also write else if. Here's an example:

if (n < 10)
	printf("10 is a good number.\n");
else if (n < 100)
	printf("100 is a better number.\n");
else 
	printf("You've got a really big number!\n");
main page