ZeePedia

Flow Charting, if/else structure, Logical Operators

<< C++: Examples of Expressions, Use of Operators
Repetition Structure (Loop), Overflow Condition, Infinite Loop, Properties of While loop, Flow Chart >>
img
CS201 ­ Introduction to Programming
Lecture Handout
Introduction to programming
Lecture No. 5
Reading Material
Deitel & Deitel ­ C++ How to Program
chapter 2
2.4, 2.5, 2.6, 2.19,
2.20
Summary
Conditional Statements
o
Flow Charting
o
·  Sample Program 1
if/else structure
o
Logical Operators
o
·  Sample Program 2
o
Tips
Conditional Statements (Decision Making)
In every day life, we are often making decisions. We perform different tasks while taking
decisions. For example, the statement `if the milk shop is open, bring one liter of milk
while returning home from college', involves this phenomenon.
In this statement, there is an element of decision making. We bring one litre of milk if the
shop is open. And if the shop is closed, we come back to home without milk.
Thus we are making a decision on the condition that the shop is open. The decision-
making process is everywhere in our daily life. We see that the college gives admission to
a student if he has the required percentage in his previous examination and/or in the entry
test. Similarly administration of a basketball team of the college decides that the students
having height more than six feet can be members of the team.
In the previous lectures, we have written simple elementary programs. For writing
interesting and useful programs, we have to introduce the decision making power in
them. Now we will see what kind of decisions are there in programming and how these
can be used.
Every programming language provides a structure for decision making.
'C' also provides this structure. The statement used for decisions in 'C' language is known
as the 'if statement'. The if statement has a simple structure. That is
Page 32
img
CS201 ­ Introduction to Programming
if ( condition )
Statement (or group of statements)
The above statements mean, If condition is true, then execute the statement or a group of
statements. Here the condition is a statement which explains the condition on which a
decision will be made. We can understand it from the example that Ali can become the
member of the basket ball team if he has a height more than six feet .In this case, the
condition will be
if (Ali's height is greater than six feet)
Ali can be a member of team
We have written the condition in English language. Now let's see how we can implement
this in terms of variables, operators and C statements. In the program, we will write the
condition in parentheses, followed by a statement or group of statements to be executed.
Now here is the concept of block of statements. We use braces { } to make a group
(block) of a number of statements. We put `{' before first statement and `}' after the last
statement. Thus if we have to do many things after the if statement. The structure of if
statement becomes as under
if (condition)
{
statement;
statement;
.
.
statement;
}
Note the indentation of the lines and semi-colon after each statement. Semi-colons are
necessary after every C statement. The indentation is only a matter of style. It makes the
code easy to read and understand from where a block starts, ends and what kind of block
it is. It does not affect the logic of the program. But the braces can affect the logic. We
can also write a comment line to state the purpose of code block.
Let's consider a simple example to explain the if statement. Suppose, we have ages of two
students (say for the time being we have got these ages in variables). These variables are-
age1 and age2. Now we say that if the age1 is greater than age2, then display the
statement `Student 1 is older than student 2'.
The coding for this program will be as below
#include <iostream.h>
main()
{
int age1, age2;
age1 = 12;
age2 = 10;
Page 33
img
CS201 ­ Introduction to Programming
if (age1 > age2)
cout << "Student 1 is older than student 2";
}
Here, in our code we see a new operator i.e. ` > ` (greater than) in the if statement. We
need such operators (like greater than, less than, equal to etc) while making decisions.
These operators are called 'relational operators'. These are almost the same relational
operators we use in algebra. Following table summarizes the relational operators.
Algebraic
In C
Example
Meaning
language
Greater than
>
>
x>y
x is greater than y
Equal to
=
==
x == y
x is equal to y
Less than
<
<
x<y
x is less than y
Greater than or
>
>=
x >= y
x is greater than or
equal to
equal to y
Less than or
<
<=
x <= y
x is less than or equal
equal to
to y
Not equal to
!=
x != y
x is not equal to y
Note that there is no space between ==, >=, <= and !=.
These are considered as single operators.
The operator == (equal to) is different from the operator =. We know that operator = is
the assignment operator which is used in assignment statement to assign a value to a
variable.
Don't confuse the assignment operator (=) with equal to operator (==). If we write single
= in condition of if statement. For example, if we write if ( x = 2 ), the compiler will not
give error. This means that it is not a syntax error. The conditional expression in if
statement returns a value. In this case, x = 2 will also have some value but it will not in
the form of true or false. So it will create a logical error. So be careful while using equal
to condition in if statement.
Flow Charting
There are different techniques that are used to analyze and design a program. We will use
the flow chart technique. A flow chart is a pictorial representation of a program. There
are labeled geometrical symbols, together with the arrows connecting one symbol with
other.
A flow chart helps in correctly designing the program by visually showing the sequence
of instructions to be executed. A programmer can trace and rectify the logical errors by
first drawing a flow chart and then simulating it.
The flow chart for the if structure is shown in the figure below.
Page 34
img
CS201 ­ Introduction to Programming
Sample Program 1
Now let's see the usage of relational operators by an example. There are two students
Amer and Amara. We take their ages from the user, compare them and tell who is older?
As there are two students to be compared in terms of age, we need to declare two
variables to store their ages. We declare two variables AmerAge and AmaraAge of type
int. The variable names are one continuous word as we can't use spaces in a variable
name.
Here is an important point about variables declaration. We should assign an initial value
(preferably 0 for integers) to variables when we declare them. This is called initialization
of variables.
We can do this in one line while declaring a variable like int x = 0; This statement will
declare a variable of name x with data type int and will assign a value 0 to this variable.
Initializing a variable in this way is just a matter of style. You can initialize a variable on
a separate line after declaring it. It is a good programming practice to initialize a variable.
Now we prompt the user to enter Amer's age and store it into variable AmerAge. Then
similarly we get Amara's age from the user in the variable AmaraAge.
While comparing the ages, we will use the if statement to see whether Amer's age is
greater than Amara's. We will use > (greater than) operator to compare the ages. This can
be written as if ( AmerAge > AmaraAge) .
With this if statement, we write the statement cout << "Amer is greater than Amara" ;
It's a simple one line test i.e. `if Amer's age is greater than Amara's', then display the
message `Amer is older than Amara'.
The flow chart for the above problem is as under.
Page 35
img
CS201 ­ Introduction to Programming
The complete code of the program is given below.
/* This program test that if the age of Amer is greater
than Amara's age and displays the result. */
# include <iostream.h>
main ( )
{
int AmerAge, AmaraAge;
//prompt the user to enter Amer's age
cout << "Please enter Amer's age  " ;
cin >> AmerAge;
//prompt the user to enter Amara's age
cout << "Please enter Amara's age  " ;
cin >> AmaraAge;
//perform the test
if (AmerAge > AmaraAge )
cout << " Amer is older than Amara";
}
In our program, we write a single statement with the if condition. This statement executes
if the condition is true. If we want to execute more than one statements, then we have to
enclose all these statements in curly brackets { }. This comprises a block of statements
which will execute depending upon the condition. This block may contain a single
statement just like in our problem. So we can write the if statement as follow.
Page 36
img
CS201 ­ Introduction to Programming
if (AmerAge > AmaraAge )
{
cout << " Amer is older than Amara";
}
A sample execution of the program provides the following output.
Please enter Amer's age
16
Please enter Amara's age
14
Amer is older than Amara
Now think what happens if the condition in the if statement is not true i.e. Amer's age is
not greater than Amara's. In this case, if the user enters Amer's age less than Amara's,
then our program does nothing. So to check this condition, another if statement after the
first if statement is required. Then our program will be as:
/* This program checks the age of Amer and Amara's and
displays the appropriate the message. The program is using
two if statements.*/
# include <iostream.h>
main ( )
{
int AmerAge, AmaraAge;
//prompt the user to enter Amer's age
cout << "Please enter Amer's age  " ;
cin >> AmerAge;
//prompt the user to enter Amara's age
cout << "Please enter Amara's age  " ;
cin >> AmaraAge;
//perform the test
if (AmerAge > AmaraAge )
{
cout << " Amer is older than Amara";
}
if (AmerAge < AmaraAge )
{
cout << " Amer is younger than Amara";
}
}
Now our program decides properly about the ages entered by the user.
After getting ages from the user, the if statements are tested and if statement will be
executed if the condition evaluates to true.
Page 37
img
CS201 ­ Introduction to Programming
If/else Structure
We have seen that the if structure executes its block of statement(s) only when the
condition is true, otherwise the statements are skipped. The if/else structure allows the
programmer to specify that a different block of statement(s) is to be executed when the
condition is false. The structure of if/else selection is as follows.
if ( condition)
{
statement(s);
}
else
{
statement(s);
}
Thus using this structure we can write the construct of our program as
if (AmerAge > AmaraAge )
{
cout << " Amer is older than Amara";
}
else
{
cout << " Amer is younger than Amara";
}
In this construct, the program checks the condition in if statement .If the condition is true,
then the line "Amer is greater than Amara" is printed. Otherwise (if condition is not true),
the statement related to else is executed and the message "Amer is younger than Amara"
is printed. Here in if/else structure an important thing is that the else part is executed for
all the cases (conditions) other than the case which is stated in the if condition.
And in the comparison, we know that there are three conditions i.e. first value is greater
than the second value, first value is less than the second value and first value is equal to
the second value. Here in the above program construct the else part competes the greater
than conditions and covers both less than and equal to conditions.
Thus in the above program construct, the message "Amer is younger than Amara" is
displayed even if Amer's age is the same as Amara's age. This is logically incorrect and
so to make this correct, we should display the message "Amer is younger than or is of the
same age as Amara". Now this statement describes both the cases other than the one
`Amer is greater than Amara'.
The use of else saves us from writing different if statements to compare different
conditions, in this way it cover the range of checks to complete the comparison.
If we want to state the condition "Amer is greater than or is of the same age as Amara's"
then we use the greater than or equal to operator (i.e. >=) in the if statement and less than
operator ( < ) in the else statement to complete the comparison.
Page 38
img
CS201 ­ Introduction to Programming
It is very important to check all the conditions while making decisions for good, complete
and logical results. Make sure that all cases are covered and there is no such case in
which the program does not respond.
Logical Operators
There are many occasions when we face complex conditions to make a decision. This
means that a decision depends upon more than one condition in different ways. Here we
combine the conditions with AND or OR. For example, a boy can be selected in basket
ball team only if he is more than 18 years old and has a height of 6 feet. In this statement
a boy who wants to be selected in the basket ball team must have both the conditions
fulfilled. This means that AND forces both the conditions to be true. Similarly we say
that a person can be admitted to the university if he has a BCS degree OR BSC degree. In
this statement, it is clear that a person will be admitted to the university if he has any one
of the two degrees.
Page 39
img
CS201 ­ Introduction to Programming
In programming we use logical operators ( && and || ) for AND and OR respectively
with relational operators. These are binary operators and take two operands. These
operators use logical expressions as operands, which return TRUE or FALSE.
The following table (called truth table) can be used to get the result of the && operator
and || operator with possible values of their operands. It is used to explain the result
obtained by the && and || operators.
Expression 1
Expression 2
Expression 1 &&
Expression 1 ||
Expression 2
Expression 2
True
False
false
True
True
True
true
True
False
False
false
False
False
True
false
True
The && operator has a higher precedence than the || operator. Both operators associate
from left to right. An expressions containing && or || is evaluated only until truth or
falsehood is known. Thus evaluation of the expression (age > 18) && (height > 6) will
stop immediately if age > 18 is false (i.e. the entire expression is false) and continue if
age > 18 is true (i.e. the entire expression could still be true if the condition height > 6 is
true ).
There is another logical operator that is called logical negation. The sign ! is used for this
operator. This operand enables a programmer to `reverse' the meaning of a condition.
This is a unary operator that has only a single condition as an operand. The operator ! is
placed before a condition. If the original condition (without the ! operator) is false then
the ! operator before it converts it to true and the statements attached to this are executed.
Look at the following expression
if ( ! (age > 18 ))
cout << " The age is less than 18";
Here the cout statement will be executed if the original condition (age > 18) is false
because the ! operator before it reverses this false to true.
The truth table for the logical negation operator ( ! ) is given below.
Expression
! Expression
True
False
False
True
Page 40
img
CS201 ­ Introduction to Programming
Sample Program 2
Problem statement
A shopkeeper announces a package for customers that he will give 10 % discount on all
bills and if a bill amount is greater than 5000 then a discount of 15 %. Write a C program
which takes amount of the bill from user and calculates the payable amount by applying
the above discount criteria and display it on the screen.
Solution
In this problem we are going to make decision on the basis of the bill amount, so we will
be using if statement. We declare three variables amount, discount and netPayable and
initialize them. Next we prompt the user to enter the amount of the bill. After this we
implement the if statement to test the amount entered by the user. As we see in the
problem statement that if the amount is greater than 5000 then the discount rate is 15 %
otherwise (i.e. the amount is less than or equal to 5000) the discount rate is 10 %. So we
check the amount in if statement. If it is greater than 5000 then the condition is true then
the if block is executed otherwise if amount is not greater than 5000 then the else block is
executed.
The analysis and the flow of the program is shown by the following flow chart.
Page 41
img
CS201 ­ Introduction to Programming
The complete program code is given below :
/* This program calculates the discount amount for a customer. As different discount
percentage applies on different amount so program is using if statement for deciding
which discount is applicable and display the result. */
# include <iostream.h>
main ( )
{
double amount, discount, netPayable ;
amount = 0 ;
netPayable = 0 ;
discount = 0 ;
// prompt the user to enter the bill amount
cout << "Please enter the amount of the bill  " ;
cin >> amount ;
//test the conditions and calculate net payable
if ( amount > 5000 )
{
Page 42
img
CS201 ­ Introduction to Programming
//calculate amount at 15 % discount
discount = amount * (15.0 / 100);
netPayable = amount - discount;
cout << "The discount at the rate 15 % is Rupees  " << discount << endl;
cout << "The payable amount is Rupees  " << netPayable ;
}
else
{
// calculate amount at 10 % discount
discount = amount * (10.0 / 100);
netPayable = amount - discount;
cout << "The discount at the rate 10 % is Rupees  " << discount << endl ;
cout << "The payable amount is Rupees " << netPayable ;
}
}
In the program we declared the variables as double. We do this to get the correct results
(results may be in decimal points) of the calculations. Look at the statement which
calculates the discount. The statement is
discount = amount * (15.0 / 100) ;
Here in the above statement we write 15.0 instead of 15. If we write here 15 then the
division 15 / 100 will be evaluated as integer division and the result of division (0.15)
will be truncated and we get 0 and this will result the whole calculation to zero. So it is
necessary to write at least one operand in decimal form to get the correct result by
division and we should also declare the variables as float or double. We do the same in
the line discount = amount * (10.0 / 100);
A sample execution of the program is given below
Please enter the amount of the bill
6500
The discount at the rate 15 % is Rupees
975
The payable amount is Rupees
5525
Tips
·
Always put the braces in an if/else structure
·
Type the beginning and ending braces before typing inside them
·
Indent both body statements of an if and else structure
·
Be careful while combining the conditions with logical operators
·
Use if/else structure instead of a number of single selection if statements
Page 43
Table of Contents:
  1. What is programming
  2. System Software, Application Software, C language
  3. C language: Variables, Data Types, Arithmetic Operators, Precedence of Operators
  4. C++: Examples of Expressions, Use of Operators
  5. Flow Charting, if/else structure, Logical Operators
  6. Repetition Structure (Loop), Overflow Condition, Infinite Loop, Properties of While loop, Flow Chart
  7. Do-While Statement, for Statement, Increment/decrement Operators
  8. Switch Statement, Break Statement, Continue Statement, Rules for structured Programming/Flow Charting
  9. Functions in C: Structure of a Function, Declaration and Definition of a Function
  10. Header Files, Scope of Identifiers, Functions, Call by Value, Call by Reference
  11. Arrays: Initialization of Arrays, Copying Arrays, Linear Search
  12. Character Arrays: Arrays Comparisonm, Sorting Arrays Searching arrays, Functions arrays, Multidimensional Arrays
  13. Array Manipulation, Real World Problem and Design Recipe
  14. Pointers: Declaration of Pointers, Bubble Sort Example, Pointers and Call By Reference
  15. Introduction, Relationship between Pointers and Arrays, Pointer Expressions and Arithmetic, Pointers Comparison, Pointer, String and Arrays
  16. Multi-dimensional Arrays, Pointers to Pointers, Command-line Arguments
  17. String Handling, String Manipulation Functions, Character Handling Functions, String Conversion Functions
  18. Files: Text File Handling, Output File Handling
  19. Sequential Access Files, Random Access Files, Setting the Position in a File, seekg() and tellg() Functions
  20. Structures, Declaration of a Structure, Initializing Structures, Functions and structures, Arrays of structures, sizeof operator
  21. Bit Manipulation Operators, AND Operator, OR Operator, Exclusive OR Operator, NOT Operator Bit Flags Masking Unsigned Integers
  22. Bitwise Manipulation and Assignment Operator, Programming Constructs
  23. Pre-processor, include directive, define directive, Other Preprocessor Directives, Macros
  24. Dynamic Memory Allocation, calloc, malloc, realloc Function, Dangling Pointers
  25. History of C/C++, Structured Programming, Default Function Arguments
  26. Classes and Objects, Structure of a class, Constructor
  27. Classes And Objects, Types of Constructors, Utility Functions, Destructors
  28. Memory Allocation in C++, Operator and Classes, Structures, Function in C++,
  29. Declaration of Friend Functions, Friend Classes
  30. Difference Between References and Pointers, Dangling References
  31. Operator Overloading, Non-member Operator Functions
  32. Overloading Minus Operator, Operators with Date Class, Unary Operators
  33. Assignment Operator, Self Assignmentm, Pointer, Conversions
  34. Dynamic Arrays of Objects, Overloading new and delete Operators
  35. Source and Destination of streams, Formatted Input and Output, Buffered Input/Output
  36. Stream Manipulations, Manipulators, Non Parameterized Manipulators, Formatting Manipulation
  37. Overloading Insertion and Extraction Operators
  38. User Defined Manipulator, Static keyword, Static Objects
  39. Pointers, References, Call by Value, Call by Reference, Dynamic Memory Allocation
  40. Advantages of Objects as Class Members, Structures as Class Members
  41. Overloading Template Functions, Template Functions and Objects
  42. Class Templates and Nontype Parameters, Templates and Static Members
  43. Matrices, Design Recipe, Problem Analysis, Design Issues and Class Interface
  44. Matrix Constructor, Matrix Class, Utility Functions of Matrix, Input, Transpose Function
  45. Operator Functions: Assignment, Addition, Plus-equal, Overloaded Plus, Minus, Multiplication, Insertion and Extraction