Conditional statements

Sometimes we only want to do something if a condition is true. This is done in C by using a conditional statement.

In the simplest situation, the statement to be performed conditionally is placed after a test, using the construction

      if (condition) statement
and the statement is only performed if the condition is true. The condition is any integer expression, with zero interpreted as false, all other values as true. An example is
      if (IntVal>4) printf("Greater\n");
In other situations we may wish to have one statement executed if a condition is true and another if it is false. This uses the extended form
      if (condition) statement else statement
and an example is
      if (IntVal>4) printf("Greater"); else printf("Not greater");

An example program

Putting some of these together, we get the following program to test your understanding.
#include <stdio.h>

	/*Reads 2 chars and writes the mean of their integer code*/

void main()
{
	int Val1, Val2, Result;

	Val1 = getchar();
	Val2 = getchar();
	Result = Val1 + Val2;
	Result = Result / 2;
	printf("%d", Result);
	printf(" which is ");
	if (Result>10) printf("not ");
	printf("less than 11");
}
Simple text version to compile

Exercises on this section.


Next.

Back to Contents page.