if Structure

C Language

Overview

In this lesson, we will discuss using if structure in C language, and learning to control the flow of the program and let it do different things in different situations. if structures allow the computer to do different things in different situations, for example, if the user's input is an add sign, then the computer will add the two numbers, and in other situations, it will allow the computer to do different things.


Control Flow and if

Control flow is controlling the program to do different things in different situations and also controlling the program. This include if statements and loops. In this lesson, we will focus on if statements. if structure gives the computer different situations, and tells the computer what to do in each of those situations. For example, in a simple calculator program, the program will give the computer four basic situations: when the user input is '+', '-', '*', or '/'. The program will also tell the computer to add the two numbers when it is '+', to subtract when '-', to multiply when '*', and divide when '/'. There are many examples of if structures used by us in our day to day life, for instance, when you wake up each morning, you will think: if today is Monday-Friday, I will need to go to work/school; else if today is Saturday or Sunday, I can stay at home.

A Basic if Structure

A basic if structure is like this:
if(condition)
{
then do this
}
First, put if at the beginning, followed by a set of parenthesis, and inside them is your condition, or situation that you want the computer to do something. And then in a new line (so the structure of your program is clear), do a set of brackets like you would for the main function, and inside the brackets, indented, is what you want to computer to do in that situation.

#include <stdio.h>

int main()
{
  int num;
  printf("Enter a number:");
  scanf("%d",&num);
  if(num>0)
   {
     printf("The number is positive!\n");
   }
}

Enter a number:5
The number is positive!

In the condition part of the if statement, you will put a statement that the computer will evaluate as either TRUE, or 1, or FALSE, or 0. When the condition is TRUE, the computer will execute the part inside of the brackets; but when the condition is FALSE, the computer will just skip over the brackets and continue on to the next line of code after the brackets end. The condition statement is usually a comparison, like in this program. Here are some of the comparisons you can use:

Comparison Meaning Examples
< Less than 5<7 TRUE, -3<0 TRUE, 7<-1 FALSE
> Greater than 7>5 TRUE, 0>-3 TRUE, -1>7 FALSE
== Equal to 5==5 TRUE, -4==-4 TRUE, -4==4 FALSE
!= Not equal to 5!=3 TRUE, 4!=-2 TRUE, 0!=0 FALSE
<= Less than or equal to 5<=7 TRUE, 5<=5 TRUE, 5<=-4 FALSE
>= Greater than or equal to 5>=-4 TRUE, 5>=5 TRUE, 5>=7 FALSE

As you can see, those are the major types of operations you can do in the condition part of an if structure. The computer will see if the condition is TRUE, and based on the result, decide whether or not execute the body of the structure. Note that the operation sign that checks if two numbers are equal to each other consists of two equal signs: "==". This is because one equal sign assigns the second value to the first value, which is what we discussed in the previous lesson. Make sure you know the difference. The comparison can include both variables and constants, with two variables, one of each, and two constants (which would give you the same result every time since the constants cannot change).

Now you can see, the example program above just simply means:
If the number is greater than 0,
Then print out:"The number is positive!"

Here is a diagram of how an if statement works:

if Statement Diagram

Examples

Here are some examples that uses simple if statements:

#include <stdio.h>

int main()
{
  int a,b;
  printf("Enter two numbers separated by a comma:");
  scanf("%d,%d",&a,&b);
  if(a>b)
   {
     printf("The first number is greater than the second number!\n");
   }
  printf("Thank you!\n");
}

Enter two numbers separated by a comma:5,3
The first number is greater than the second number!
Thank you!

Enter two numbers separated by a comma:-4,5
Thank you!

#include <stdio.h>

int main()
{
  char operation_sign;
  printf("Enter an operation sign:");
  scanf("%c",&operation_sign);
  if(operation_sign=='+')
   {
     printf("You entered the plus sign!\n");
   }
}

Notice that you still have to enclose value with single quotation when comparing or assigning to a character variable!

Enter an operation sign:+
You entered the plus sign!

Enter an operation sign:*

else if Statements

Now you know how to create simple if structures, but most of the times, you will want the computer to do different things is many different situations, not just one. For example, the calculator program, you would want the computer to do addition when the sign is the add sign, subtraction when the sign is minus sign, etc. To do this, you will need to add else if statements.
else if statements works the same way as if statements. Let's look at an example:

#include <stdio.h>

int main()
{
  int num;
  printf("Enter a number:");
  scanf("%d",&num);
  if(num>0)
   {
     printf("The number is positive!\n");
   }
  else if(num==0)
   {
     printf("The number is 0!\n");
   }
  else if(num<0)
   {
     printf("The number is negative!\n");
   }
}
	

Enter a number:-4
The number is negative!

else if statements work like this: The computer will follow the order you put them. The computer first sees the if statement, test the condition (in this case, -4 is not greater than 0, so FALSE), if it is TRUE, it will execute the body of the if statement, and skip the else if statements and continue on the program; but if it is FALSE, the computer will skip the body and go to the following else if statement. The same process is done again: checks if the condition is TRUE, if it is, the body of this else if statement is executed, and the computer skip the rest of the else ifs and continue on; but if it is FALSE, the computer go to the next one, etc.

Here is a diagram of how else if statements work:

else if Diagram

else Statement

There can also be an else statement at the end of an if structure to handle any other situations that you haven't covered yet. For example, in our calculator program, if the user enters something other than '+', '-', '*', or '/', you can use the else statement to cover all the possibilities and print out an error message.

With else statement, the example program above can be changed to this:

#include <stdio.h>

int main()
{
  int num;
  printf("Enter a number:");
  scanf("%d",&num);
  if(num>0)
   {
     printf("The number is positive!\n");
   }
  else if(num<0)
   {
     printf("The number is negative!\n");
   }
  else
   {
     printf("The number is 0!\n");
   }
}
	

Enter a number:0
The number is 0!

As you can see, the 0 situation is handled by the else statement, which don't require the condition part since it will cover any other situations. So if both of the conditions in the ifs and else ifs before the else statement are tested FALSE, then the else statement is executed no matter what. But if any of them is TRUE, then the whole rest of the structure will be skipped over, including the else, and the computer will continue on with the rest of the program.

Here is the diagram for else statements:

else Diagram

Logic Operators

There are three basic logic operators that the computer base on to do all the computations. They are useful too when you use if structures. They are AND "&&", OR "||", and NOT "!". Sometimes, for your condition, you want the computer to add the numbers together when the first number is greater than 0 AND the second number is greater than 0. Or you want the computer to print out something when either the first number is greater than 0 OR the second number is greater than 0. You even sometimes need to let the computer do something when the OPPOSITE (NOT) of an expression. In these cases, you will need to use logic operators.

AND: &&

The AND operator, &&, is used when you want two or more conditions to be TRUE when the computer do something. The computer will evaluate each of the conditions, and when they are all TRUE, execute the body of that if statement; but if any of them is FALSE, then the computer will see the whole condition as FALSE and skip to the next else if/else. The AND operator is used like this:
if(num_1>0 && num_2>0)
{
printf("Both numbers are positive!\n");
}
This condition is saying that print out "Both numbers are positive!" when num_1>0 AND num_2>0. It is good practice to put space between the operator and each condition to make it clear, and when you mix multiple logic operators in one single condition, it would also be a good idea to put parenthesis to make sure the computer will do it the way you want it to.

OR: ||

The second operator is the OR operator, ||. This operator allows the body to be executed as long as one of the subjects in the operation is TRUE. For example:
if(num_1>0 || num_2>0)
{
printf("At least on of the numbers is positive!\n");
}
This will return TRUE as long as one of the subjects in the operation is tested TRUE (when both are TRUE, it will still return TRUE).

NOT: !

The final basic logic operator is the NOT, or !, operator. It only involves one subject, instead of two. It simply flips the result of that subject. If the subject originally is tested TRUE, it will change it to FALSE, and when it is originally FALSE, it turns it TRUE. But it would be a good idea to put parenthesis around what you want to apply the NOT operator, since it is higher up in the order of operations than most other operations in C.
!(subject)

Mix of Operators

You can use multiple operators in a single condition, just be careful of the order of operations so put parenthesis.

When num_1=-5, num_2=-3: ((num_1>0)&&(num_2>0)) || ((num_1<0)&&(num_2<0)) would evaluate to TRUE; when num_1=-5, num_2=3, it would evaluate to FALSE.

Switch Case

Switch case is also a feature in the control flow and is very similar to if structure, but is useful when there is a large amount of cases or situations that you need to handle.

Basic structure of switch case:

#include <stdio.h>

int main()
{
  int day;
  printf("Enter a number 1-7:");
  scanf("%d",&day);
  switch(day)
   {
     case 1:
      {
        printf("Monday\n");
        break;
      }
     case 2:
      {
        printf("Tuesday\n");
        break;
      }
     case 3:
      {
        printf("Wednesday\n");
        break;
      }
     case 4:
      {
        printf("Thursday\n");
        break;
      }
     case 5:
      {
        printf("Friday\n");
        break;
      }
     case 6:
      {
        printf("Saturday\n");
        break;
      }
     case 7:
      {
        printf("Sunday\n");
        break;
      }
     default:
      {
        printf("Not 1-7!\n");
      }
   }
}

Enter a number 1-7:2
Tuesday

In this example, the computer will print out a day of the week based on your input. This is the basic format of a switch case structure. After switch, you would put a variable or value inside the parenthesis instead of a condition of the if structure. The computer will see which of the cases match with this value, and execute that case. Notice that the value of each case must be a constant, so this limits the tasks you can do with switch case structure. Also notice that each case begin with a colon, not a semicolon, and that marks the beginning of that case. There are also break statement in each of the cases. By default, the computer will execute the bodies of every case that follows if a case matches the value after executing the body of that case. So the break statements prevent that and exit the switch case structure. We will discuss the break statement more in Loops. In conclusion, the switch case structure is very similar with the if statement and you can pretty much understand it just by reading the code. But it is not that often used since you can pretty much use if structure in its place.


Practice

Find the mistakes in the following program:

#include <stdio.h>

int main()
{
  float score;
  printf("Enter your score on the test:");
  scanf("%f",&score);
  if(score=100):
   {
     printf("Very good! You got a hundred!\n");
   }
  else(score>=89.5):
   {
     printf("Pretty good! You got an A!\n");
   }
  else:
   {
     printf("Try harder next time!\n");
   }
}

Write a calculator program! The program should be able to do decimal addition, subtraction, multiplication, and division. Print out "Sorry, operation not developed!" when the user enters something other than '+', '-', '*', or '/'. The user inputs an expression like this: -5.2+67 or 6.783*98.3. The program prints out the result.

Fill in the blanks:

#include <stdio.h>

int main()
{
  char punctuation;
  printf("Enter a punctuation mark:");
  if(punctuation__'.')
   {
     printf("This is a period.\n");
   }
  _______(punctuation__',')
   {
     printf("This is a comma.\n");
   }
  else if(punctuation__'?')
   {
     printf("This is a question mark.\n");
   }
  ____
   {
     printf("Sorry, we couldn't identify that yet.\n");
   }
}
	

Write a program, the user inputs three decimals; the computer orders them and prints them back out from least to greatest.

Additional practices on if structure:

Activity 4.2

<< Previous TOC Next >>