






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







ents o 1 o e o tors e Program 2 o
eet can be members of the
, we have written simple elementary programs. For writing ograms, we have to introduce the decision making power in ow we will see what kind of decisions are there in programming and how
provides a structure for decision making. is structure. The statement used for decisions in 'C' language is t'. The if statement has a simple structure. That is
Statement (or group of statements)
Deitel & Deitel – C++ How to Program chapter 2 2.4, 2.5, 2.6, 2.19,
o Conditional Statem Flow Charting Sample Program if/else structur Logical Opera Sampl Tips
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 f team. In the previous lectures interesting and useful pr them. N these can be used. Every programming language 'C' also provides th known as the ' if statemen
if ( condition )
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
ecome the member of the basket ball team if he has a height more than six feet .In is case, the condition will be
if (Ali’s height is greater than six Ali can be a member of team
n he conditio English la Now l t this in terms of variables, operators and C statements. In the program, we tion in paren es, followed by a statement cuted. he cept of blo f statement se braces up umb ents. We put ‘{’ before first statem the if statement. The structure
of the lines and semi-colon after each statement. Semi-colons are y C statement. The indentation is only a matter of style. It makes
ain() { int age1, age2; age1 = 12; age2 = 10; if (age1 > age2) cout << “Student 1 is older than student 2”; }
b th
feet)
We have writte implemen
t n in nguage. et's see how we can
will write the con to be exe
di thes or group of statements
Now here is t lock) of a n
con er of statem
ck o s. We u { } to make a gro (b ent and ‘}’ after the last statement. Thus if we have to do many things after of if statement becomes as under
if (condition) { statement; statement; . . statement; }
Note the indentation necessary after ever 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
m
include
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.
docsity.com
ow let’s see the usage of relational operators by an example. There are two students o is er? s there are two students to be compared in terms of age, we need to declare two ges. We declare two variables AmerAge and AmaraAge of pe int. The variable names are one continuous word as we can’t use spaces in a ame. re is an important point about variables declaration. We should assign an initial alue ( to variables when we declare them. This is called
We can ariable like int x = 0 ; This statement e x with data type int and will assign a value 0 to this ariabl st a matter of style. You can initialize a is a good programming practice to
to enter Amer’s age and store it into variable AmerAge. rom the user in the variable AmaraAge. hile compar nt to see whether Amer’s age is eater than Amara’s. We will use > (greater than) operator to compare the ages. This an be written as if ( AmerAge > AmaraAge). ith this if statement, we write the statement cout << "Amer is greater than Amara" ;
Sample Program 1 N Amer and Amara. We take their ages from the user, compare them and tell wh old A variables to store their a ty variable n He v preferably 0 for integers) initialization of variables. do this in one line while declaring a v will declare a variable of nam v e. Initializing a variable in this way is ju variable on a separate line after declaring it. It initialize a variable. Now we prompt the user Then similarly we get Amara’s age f W ing the ages, we will use the if stateme gr c W 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.
The flow chart for the if structure is shown in the figure below.
The flow chart for the if structure is shown in the figure below.
docsity.com
The com is given below.
This p an Amara’s age and displays the result. */
ain (
pt the user to enter Amer’s age
AmerAge; ara’s age < “Please enter Amara’s age “ ; cin >> rm the test if (AmerAge > AmaraAge ) cout << “ Amer is older than Amara”;
plete code of the program
/* rogram test that if the age of Amer is greater th
m ) { int AmerAge, AmaraAge; //prom cout << “Please enter Amer’s age “ ; cin >> //prompt the user to enter Am cout < AmaraAge; //perfo
In our program, we write a single statement with the if condition. This statement ion is true. If we want to execute more than one statements, then
if (AmerAge > AmaraAge )
cout << " Amer is older than Amara"; }
executes if the condit 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.
{
docsity.com
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 ondition. nd in the comparison, we know that there are three conditions i.e. first value is eater 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 than conditions and covers both less than and equal to
c A gr
competes the greater 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. 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.
docsity.com
Logical Operators
face complex conditions to make a decision. This eans 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 if he is more than 18 years old and has a height of 6 feet. In this atement a boy who wants to be selected in the basket ball team must have both the
programming we use logical operators ( && and || ) for AND and OR respectively with relational operators. These are binary operators and take two operands. These logical expressions as operands, which return TRUE or FALSE. he following table (called truth table) can be used to get the result of the &&
There are many occasions when we m
basket ball team only st 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. In
operators use T 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 2
Expression 1 || Expression 2 True False false True
docsity.com
ount in if statement. If it is greater than 000 then the condition is true then the if block is executed otherwise if amount is not
discount rate is 10 %. So we check the am 5 greater than 5000 then the else block is executed. The analysis and the flow of the program is shown by the following flow chart.
docsity.com
amount for a customer. As different discount ercentage applies on different amount so program is using if statement for deciding hich discount is applicable and display the result. */
e
ain ( ) { dou a amo t netPaya discount = 0 ; // pr cout << "Please enter the amount of the bill " ; cin >> amount ; //test the conditions and calculate net payable
if ( amount > 5000 ) { //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 ; }
}
The complete program code is given below:
/* This program calculates the discount p w
m
ble mount, discount, netPayable ; un = 0 ; ble = 0 ;
ompt the user to enter the bill amount
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
docsity.com