Conditional Statements

Relational Operators
Relational operators are needed when making comparisons. If we want to see if 2 numbers are equal, one is less than the other, etc. The relational operators return a Boolean value. This means that they either evaluate to “true” or “false”.

int x = 4;
int y = 2;

int a = x < y; //the less than operator
int b = x >= y; //the greater than or equal to
int c = x == y; //the equality operator
int d = x != y; //not equal to operator 

Following the lines above, you can see that if the comparison on the left side evaluates to “true” the integer is assigned to a 1, else it’s 0.
Hence, since 4 is greater than 2. x < y is evaluated false and a is set to 0.
Correspondingly, b is evaluated to true and set to 1. Finaly, since 4 does not equal 2, c gets evaluated false and d is evaluated as true.

The If Statement
A key aspect to any programming language is decision making. We often need to evaluate a condition and check if its true -> do something, else -> do something else
The general form of an if-statement in C is the following:

if(condition) 
     <operation 1>
else
     <operation 2>

Example
Write code that takes an integer from a user, checks if the number is even. If it’s even it prints out “Is Even”, if it’s odd, it prints out “Number is odd”.

int userNum;

printf("Enter a number: ");
scanf("%d", &userNum);

if(userNum % 2 == 0)
     printf("Is evenn");
else
     printf("Number is odd"n);

Note that we are using the relational operator == to check if the input is even.
Observe that == is a relational operator, hence it evaluates to a 1 if true, or a 0 if false. Since we are checking if userNum % 2 is exactly 0 or not, we can also write the condition as

if(!(userNum % 2))        // note that the inversion operator is applied here
     printf("Is evenn");
else
     printf("Number is odd"n);

At first, this may look strange but recall that if our number is even, the modulus operator, %, results in a 0. Hence applying the inversion on it makes it a 1, causing our program to print out “Is Even”. Similarly, if the user input is an odd number, the modulus will result in some, non zero, value. Applying the ! operator on anything non zero, makes it zero, resulting in “Number is odd” being printed.

Example extended
Now, modify this code to print an error message if the input is less than or equal to zero, with a message “Error: must be greater than zero”.

int userNum;

printf("Enter a number: ");
scanf("%d", &userNum);

if(userNum > 0)
{
     if(userNum % 2 == 0)   //this inner if statement is nested inside the upper one
          printf("Is evenn");
     else
          printf("Number is odd"n);
}
else
     printf("Error: must be greater than zero".n");

Here we can see that the first thing you do is check if the input is indeed greater than 0. If the input doesn’t satisfy that condition, there is no meaning in checking if it’s odd or even. Hence, if it does indeed turn out to be greater than 0, we proceed to the inner condition and check if besides being positive if it is also odd or even and print a message accordingly. Otherwise we skip the inner if and immediately print out the error.

The Switch/Case Statement
An alternative to the if-statement is called the case statement, this is useful when you have a single variable that can take multiple different values, and each corresponding value should have it’s own operation.
For example, for a student, say we have a character representing his/her grade. If the grade is an A, print out “Stop trying so hard”. If they have a B or a C print out “Could have been worse”, if it’s a D print out “Great job! you’re going far in life”. Otherwise, print out “Incorrect grade”.

char Grade;

scanf("%c", &Grade);

switch(Grade)
	{
	case 'A': 
		printf("Stop trying so hard.n");
		break;
	case 'B':
	case 'C':
		printf("Could have been worse.n");
		break;
	case 'D': 
		printf("Great job! you're going far in life.n");
		break;
	default : 
		printf("Incorrect grade.n");
	}

printf("Out of switchn");

Note that after each operation you have a “break”. This is done to avoid a fall through like with cases B and C. When a break is encountered we exit the switch and jump down the next line, in this case it will print “Out of switch”.
In the event that Grade doesn’t match any of the cases provided, the default case is triggered and we print “Incorrect grade”.

Try writing this same code in the form of an if-statement.


	char Grade;
	
	scanf("%c", &Grade);
 
    if (Grade == 'A')
		printf("Stop trying so hard");
	else if ((Grade == 'B') || (Grade == 'C'))   // Here we use the or (||) since it can be either B OR C
		printf("Could have been worse.n");
	else if (Grade == 'D')
		printf("Great job! you're going far in life.n");
	else
		printf("Incorrect grade.n");

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s