Chapter 4 – Conditional Control Structures
Chapter 4 – Conditional Control Structures
PROGRAMMING BASIC
– IN C
MODULE CODE: CS 6224
MODULE NAME: Computer Programming Basic in C
FACILITATOR: Pangahela, R. A
Email: pangriz@gmail.com Phone: +255 742 926 569
COMPUTER
PROGRAMMING BASIC – IN C
CHAPTER 4 - CONDITIONAL CONTROL STRUCTURES
Chapter 4 – Conditional Control Structures
4.1 The if Statement
4.2 The if-else Structure
4.3 The if-else-if Ladder
4.4 Nesting Conditions
4.5 Conditional Operator
4.6 The switch Construct
/* Program-4.1 */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //get marks
if (marks >50) // if marks >50 display message
printf("You have passed the exam!");
return 0;
}
Example 4.1 – Write a program which accepts a
number (an amount of money to be paid by a
customer in Tsh) entered from the keyboard. If the
amount is greater than or equal to 1000 rupees, a
5% discount is given to the customer. Then display
the final amount that the customer has to pay.
First the program needs to check whether the
given amount is greater than or equal to 1000; if
it is the
case a 5% discount should be given. Then the final
amount needs to be displayed. All these are done
only if the condition is TRUE. So instructions
which compute discount and final amount should
be executed as a block. Program 4.2 is an
implementation of this.
/* Program-4.2 */
#include <stdio.h>
int main()
{
float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{
discount = amount* 0.05;
final_amount = amount - discount;
printf ("Discount: %.2f", discount);
printf ("\nTotal: %.2f", final_amount);
}
return 0;
}
Example 4.2 – Modify Program-4.2 so that it
displays the message “No discount…” if the
amount is less than 1000.
Another if clause is required to check whether the
amount is less than 1000. The second if clause can
be used before or after the first (existing) if clause.
Program-4.3 below has been modified from
Program-4.2 to address this.
/* Program-4.3 */
#include <stdio.h>
int main()
{
float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{
discount = amount* 0.05;
final_amount = amount - discount;
printf ("Discount: %.2f", discount);
printf ("\nTotal: %.2f", final_amount);
}
if (amount < 1000) // if amount < 1000 no discount
printf ("No discount...");
return 0;
}
Exercise 4.1 – Modify Program-4.1 so that it
displays the message “You are failed!”, if marks
are less than or equal to 50.
In many programs it is required to perform some
action when a condition is TRUE and another
action
when it is FALSE. In such cases, the if clause can
be used to check the TRUE condition and act upon
it. However it does not act upon the FALSE
condition. Therefore the expression resulting the
FALSE condition needs to be reorganized.
Then the Program-4.3 can be modified as follows:
/* Program-4.4 */
#include <stdio.h>
int main()
{
float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{
discount = amount* 0.05;
final_amount = amount - discount;
printf ("Discount: %.2f", discount);
printf ("\nTotal: %.2f", final_amount);
}
else // else no discount
printf ("No discount...");
return 0;
}
4.3 The if-else-if Ladder
In certain cases multiple conditions are to be detected. In such
cases the conditions and their associated statements can be
arranged in a construct that takes the form:
if ( condition- 1 )
statement-1 ;
else if ( condition- 2)
statement-2 ;
else if ( condition- 3)
statement-3 ;
…
else
statement-n;
The above construct is referred as the if-else-if
ladder. The different conditions are evaluated
starting from the top of the ladder and whenever a
condition is evaluated as TRUE, the corresponding
statement(s) are executed and the rest of the
construct it skipped.
Example 4.3 – Write a program to display the
student’s grade based on the following table:
In this case multiple conditions are to be checked. Marks
obtained by a student can only be in one of the ranges.
Therefore if-else-if ladder can be used to implement
following program
/* Program-4.5 */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //read marks
if(marks > 75) // if over 75
printf("Your grade is: A");
else if(marks >= 50 && marks <75) // if between 50 & 75
printf("Your grade is: B");
else if(marks >= 25 && marks <50) // if between 25 & 50
printf("Your grade is: C");
else
printf ("Your grade is: F"); // if less than 25
return 0;
}
/* Program-4.6 */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //get marks
if(marks > 75)
printf("Your grade is A"); // if over 75
else if(marks >= 50 )
printf("Your grade is B"); // if over 50
else if(marks >= 25 )
printf("Your grade is C"); // if over 25
else
printf ("Your grade is F"); // if not
return 0;
}
In Program-4.6, when the marks are entered from
the keyboard the first expression (marks>75) is
evaluated. If marks is not greater than 75, the
next expression is evaluated to see whether it is
greater than 50. If the second expression is not
satisfied either, the program evaluates the third
expression and so on until it finds a TRUE
condition. If it cannot find a TRUE expression
statement(s) after the else keyword will get
executed.
if (a>=2)
if (b >= 4)
printf("Result 1");
else
printf("Result 2");
An else matches with the last if in the same block.
In this example the else corresponds to the
second if. Therefore if both a>=2 AND b>=4 are
TRUE “Result 1 ” will be displayed; if a>= 2 is
TRUE but if b>=4 is FALSE “Result 2” will be
displayed. If a>=2 is FALSE nothing will be
displayed.
To reduce any confusion braces can be used to
simplify the source code. Therefore the above can
be rewritten as follows:
if (a>=2)
{
if (b >= 4)
printf("Result 1");
else
printf("Result 2");
}
In the above, if else is to be associated with the
first if then we can write as follows:
if (a>=2)
{
if (b >= 4)
printf("Result 1");
}
else
printf("Result 2");
Exercise 4.4 – Rewrite the program in Example 4.3
using nested conditions (i.e. using braces ‘{‘ and
‘}’.
Example 4.4 – A car increases it velocity from u
ms-1
to v ms-1 within t seconds. Write a program to
calculate the acceleration.
The relationship among acceleration (a), u, v and t
can be given as v = u + at . Therefore the
acceleration can be found by the formula
In the program we implement users can input any
values for u, v and t. However, to find the correct
acceleration t has to be non zero and positive
(since we cannot go back in time and a number
should not be divided by zero). So our program
should make sure it accepts only the correct
inputs. The Program-4.7 calculates the
acceleration given u, v and t.
4.5 Conditional Operator
Conditional operator (?:) is one of the special
operators supported by the C language. The
conditional operator evaluates an expression and
returns one of two values based on whether
condition is TRUE or FALSE. It has the form:
condition ? result-1 : result- 2 ;
If the condition is TRUE the expression returns
result- 1 and if not it returns result-2 .
Example 4.5 – Consider the following example
which determines the value of variable “b” based
on the whether the given input is greater than 50
or not.
/* Program-4.7 */
#include <stdio.h>
int main()
{
float u,v,t,a;
printf("Enter u (m/s): ");
scanf("%f", &u); //get starting velocity
printf("Enter v (m/s): ");
scanf("%f", &v); //get current velocity
printf("Enter t (s) : ");
scanf("%f", &t); //get time
if(t >= 0)
{
a = (v-u)/t;
printf("acceleration is: %.2f m/s", a);
}
else
printf ("Incorrect time");
return 0;
}
/* Program-4.8 */
#include <stdio.h>
int main()
{
int a,b;
printf("Enter value of a: ");
scanf("%d", &a); //get starting velocity
b = a > 50 ? 1 : 2;
printf("Value of b: %d", b);
return 0;
}
Executing Program-4.8 display the following:
Enter value of a: 51
Value of b: 1
Enter value of a: 45
Value of b: 2
If the input is greater than 50 variable “b” will be
assigned “1” and if not it will be assigned “2”.
Conditional operator can be used to implement simple
if-else constructs. However use of conditional
operator is not recommended in modern day
programming since it may reduce the readability of
the source code.
4.6 The switch Construct
Instead of using if-else-if ladder, the switch
construct can be used to handle multiple choices,
such as menu options. The syntax of the switch
construct is different from if-else construct. The
objective is to check several possible constant values
for an expression. It has the form:
sw itch ( control variable)
{
case constant-1:
statement(s);
break;
case constant-2:
statement(s);
break;
…
case constant-n:
statement(s);
break;
default:
statement(s);
}
The switch construct starts with the switch
keyword followed by a block which contains the
different cases. Switch evaluates the control
variable and first checks if its value is equal to
constant- 1; if it is the case, then it executes the
statement(s) following that line until it reaches the
break keyword. When the break keyword is found
no more cases will be considered and the control is
transferred out of the switch structure to next part
of the program.
If the value of the expression is not equal to constant-
1 it will check the value of constant-2. If they are
equal it will execute relevant statement(s). This process
continuous until it finds a matching value. If a matching
value is not found among any cases, the statement(s)
given after the default keyword will be executed.
The control variable of the switch must be of the type
int, long or char (any other datatype is not allowed).
Also note that the value we specify after case keyword
must be a constant and cannot be a variable (example:
n*2)
Example 4.6 – Write a program to display the
following menu on the screen and let the user
select a menu item. Based on the user’s selection
display the category of software that the user
selected program belongs to.
Program-4.9 implements a solution to the above problem:
/* Program-4.9 */
#include <stdio.h>
int main()
{
int a;
printf("\t\tMenu");
printf("\n-----------------------------------");
printf("\n1 - Microsoft Word");
printf("\n2 - Yahoo messenger");
printf("\n3 - AutoCAD");
printf("\n4 - Java Games");
printf("\n-----------------------------------");
printf("\nEnter number of your preference: ");
scanf("%d",&a); //read input
switch (a)
{
case 1: //if input is 1
printf("\nPersonal Computer Software");
break;
case 2: //if input is 2
printf("\nWeb based Software");
break;
case 3: //if input is 3
printf("\nScientific Software");
break;
case 4: //if input is 4
printf("\nEmbedded Software");
break;
default:
printf("\nIncorrect input");
}
return 0;
}
Exercise 4.5 – Develop a simple calculator to accept
two floating point numbers from the keyboard.
Then display a menu to the user and let him/her
select a mathematical operation to be performed on
those two numbers. Then display the answer. A
sample run of you program should be similar to the
following:
In certain cases you may need to execute the
same statement(s) for several cases of a switch
block. In such cases several cases can be grouped
together as follows:
END
THANK YOU