0% found this document useful (0 votes)
2 views

Lecture 6 - Control Statements

The document covers control statements and repetition structures in programming, focusing on conditional statements such as if, if-else, and switch statements, as well as the ternary conditional operator. It provides examples and practical exercises to illustrate the concepts, including nested conditional statements and their applications. Additionally, it highlights the differences between various control structures and their use cases.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 6 - Control Statements

The document covers control statements and repetition structures in programming, focusing on conditional statements such as if, if-else, and switch statements, as well as the ternary conditional operator. It provides examples and practical exercises to illustrate the concepts, including nested conditional statements and their applications. Additionally, it highlights the differences between various control structures and their use cases.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

SCHOOL OF ELECTRICL ENGINEERING &

COMPUTER SCIENCE (SEECS)

Control Statements & Repetition


Structures
Sara Tariq Sheikh
Week’s Agenda

• Control Statements

• Nested Conditional Statements

• Switch Statement

• Ternary Conditional Operator

• Repetition Structures

• Loops

• Practical Application

Conditional Statements 2
Control Structures
• Sequential
• All statements are executed
• No statement is executed more than once
• Conditional
• Executes a statement if the given statement is true
• Decision making/selection structure
• Iterative
• Executes a statement/set of statements repeatedly for a specific number
of times
• Repetition/loops

Conditional Statements 3
Conditional Statements

Operators, Algorithms, and Conditional Statements 4


Conditional Statement

• Perform different computations or


actions depending on whether a specified
condition evaluates to true or false

• It uses comparison \ relational


operators to determine the direction of
execution of the statements in a program

Operators, Algorithms, and Conditional Statements 5


Conditional Statement

• Supported constructs in C++


• If Statement
• If-Else Statement
• Else-If Statement
• Switch Statement

Operators, Algorithms, and Conditional Statements 6


If Statement
• Most common type of flow control statement
• If statement’s clause executes when the condition is true
• The clause is skipped if the condition is false

Flowchart C++ Syntax

true if (condition) {
Condition Execute statement(s)
/* block of code to
false
be executed if the
condition is true */
}
Remainder of the
program

Operators, Algorithms, and Conditional Statements 7


If Statement – Example
Code Output
x is greater than y
int x = 20, y = 18;
if (x > y)
{
cout << "x is greater than y";
}
Code
Output
int x = 20, y = 18;
if (x % y < 2)
cout << "The remainder of x/y is less than 2";

Operators, Algorithms, and Conditional Statements 8


Practice 1
• Write a program that inputs two numbers and finds if second
number is square of the first.
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout << “Enter a number:”;
cin >> a;
cout << “Enter a number:”;
cin >> b;
if (b == a *a)
cout <<“The second number is square of the first”<<endl;
return 0;
}
Operators, Algorithms, and Conditional Statements 9
Limitation

• If the condition is false, nothing happens


• A user may want to:
• Execute one statement or set of statements if the condition is true
• Execute other statement or set of statements if the condition is false
• In this situation, simple if statement cannot be used effectively
• Example ?

Operators, Algorithms, and Conditional Statements 10


If-Else Statement
• Separate clauses executes for true and false conditions
Flowchart C++ Syntax

false true if (condition) {


Execute Execute
statement(s)
Condition
statement(s)
/* block of code to
be executed if the
condition is true */
}
else {
Remainder of the /* block of code to
program
be executed if the
condition is false */
}

Operators, Algorithms, and Conditional Statements 11


If-Else Statement – Example
Code Output
int age; Enter your age: 24
cout << "Enter your age: "; You can vote!
cin >> age;
Thank you for using the system
if (age >= 18) {
cout << "You can vote!";
}
else {
cout << "you cannot vote yet!";
}

cout << "\n\nThank you for using the system";

Operators, Algorithms, and Conditional Statements 12


Important!

• Both blocks of statement can never be executed


• Both blocks of statements can never be skipped

Operators, Algorithms, and Conditional Statements 13


Practice 2

• Write a program that inputs salary and grade. It adds 50% bonus
if the grade is greater than 15. It adds 25% bonus if the grade is
15 or less and then displays the total salary.

Operators, Algorithms, and Conditional Statements 14


Practice 2
#include <iostream>
using namespace std;
int main() {
double salary, bonus, totalSalary;
int grade;
cout << "Enter your salary: ";
cin >> salary;
cout << "Enter your grade: ";
cin >> grade;
if (grade > 15)
{ bonus = salary * 0.50; }
else
{ bonus = salary * 0.25; }
totalSalary = salary + bonus;
cout << "Your total salary after bonus is: " << totalSalary << endl;
return 0;
}

Operators, Algorithms, and Conditional Statements 15


if…else….if Statement
• Execute one of many possible clauses
• Else if statement always follows an if or another else if statement
• Else if condition is checked only if previous conditions were false
if (condition1) {
true /* Code to be executed if
Execute
Condition 1 condition1 is true */
statement(s)
}
false else if (condition2) {
true /* Code to be executed if
Execute the condition1 is false
Condition 2
statement(s) and condition2 is true */
false }
else {
Execute Remainder of /* block of code to be
statement(s) Program executed if all conditions
are false */
Operators, Algorithms, and Conditional Statements } 16
Else-If Statement – Example
Code Output
char alphabet; Enter an alphabet: C
cout << "Enter an alphabet: "; C: Cat
cin >> alphabet;

if (alphabet == 'A') { Enter an alphabet: a


cout << "A: Alligator"; Enter an alphabet between A and C
}
else if (alphabet == 'B') {
cout << "B: Baboon";
}
else if (alphabet == 'C')
cout << "C: Cat";
else
cout << "Enter an alphabet between A and C";
Operators, Algorithms, and Conditional Statements 17
Practice 3
• Write a program that calculates the electricity bill with the
following rates per unit:
• If the units consumed are <=300, then the cost is Rs. 2 per unit.
• If the units consumed are >300 and <=500, then the cost is Rs. 5 per unit.
• If the units consumed exceed 500 then the cost per unit is Rs. 7.
• A line rent Rs. 150 is also added to the total bill and a surcharge of 5%
extra if the bill exceeds Rs 2000.
• Calculate the total bill with all the conditions given.

Operators, Algorithms, and Conditional Statements 18


#include <iostream>
using namespace std;
int main() {
int units;
double costPerUnit, billAmount, totalBill;
const double LINE_RENT = 150;
const double SURCHARGE_RATE = 0.05;

cout << "Enter the number of units consumed: ";


cin >> units;
if (units <= 300) {
costPerUnit = 2.0;
} else if (units > 300 && units <= 500) {
costPerUnit = 5.0;
} else {
costPerUnit = 7.0;
}
billAmount = units * costPerUnit;
totalBill = billAmount + LINE_RENT;
if (totalBill > 2000) {
totalBill += totalBill * SURCHARGE_RATE; }
cout << "Total electricity bill: Rs. " << totalBill << endl;
return 0; }
Operators, Algorithms, and Conditional Statements 19
Nested Conditional Statements
• Decision making is dependent on previous decisions

• Outer decisions must be evaluated to true before inner decisions


are evaluated

true true
Execute
Question 1? Question 2?
statement(s)
false false

Remainder of the
program

Conditional Statements 20
Example

• Write a program that takes an integer number as input and checks:


• If the number is positive, negative, or zero
• If the number is even or odd (only if it is positive)

Conditional Statements 22
Conditional Statements 23
Practice 4

• Write a program that inputs three numbers and displays whether


all numbers are equal or not by using nested if condition.

Conditional Statements 24
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

if (num1 == num2) {
if (num2 == num3) {
cout << "All numbers are equal." << endl;
} else {
cout << "Numbers are not equal." << endl;
}
} else {
cout << "Numbers are not equal." << endl;
}

return 0;
}
Conditional Statements 25
Switch Statement
• Alternative to the If-Else-If ladder
• Switch block consists of cases to be executed based on the value of
the switch variable
Switch (variable)
switch (variable) {
case 1:
true //code for case 1
Statements
Case 1 break;
break;
case 2:
false //code for case 1
true break;
Statements
Case 2
break; default:
//code when no case is valid
false };
Default Remainder of the
Statements program

Conditional Statements 26
Conditional Statements 27
Conditional Statements 28
A Question….

• What do you think will happen if ‘break’ is not used?

• If it is not used then all case blocks that come after the matching
case will be executed.

Conditional Statements 29
Example

• Using switch- case, write a program that takes two numbers and an
operator from the user and performs the corresponding
mathematical operation.

Conditional Statements 30
Conditional Statements 31
Conditional Statements 32
Difference between Nested if and
switch

If…..else….if switch
Can test for equality and for logical Can only test for equality
expressions
Uses multiple expressions for multiple Uses a single expression for multiple choices
choices
Can check for a range of values Cannot check for a range of values
Less compact than switch More compact vs nested if
Can evaluate int, float and other data types Can evaluate only characters and integers

Conditional Statements 33
Ternary Conditional Operator (? : )
• Concise, inline method of writing conditional statements
• Shorthand for if – else condition

C++ Syntax
Example Code condition ? expression1 : expression2;
int marks;
cout << "Enter your marks: ";
cin >> marks;

string result = (marks >= 40) ? "passed" : "failed";

cout << "You " << result << " the exam.";

Conditional Statements 34
Example
• Write a program that takes two numbers as input and finds the
largest using a ternary operator.
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

int max = (a > b) ? a : b;


cout << "The larger number is: " << max << endl;

return 0;
} Conditional Statements 35
Example
• Write a program that takes three numbers as input and finds the
largest using a ternary operator.
#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter the first number:";
cin >> a;
cout << "Enter the second number:";
cin >> b;
cout << "Enter the third number:";
cin >> c;
int maxNum = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
cout << "The max. number is:" << maxNum << endl;
return 0;
}
Conditional Statements 36
Example
• Write a C++ program that checks if given point inside of triangle or outside.

Hint:
• Let the coordinates of the three corners be (x1, y1), (x2, y2), and (x3, y3) and
coordinates of the given point Q be (x, y)
• Calculate the area of the given triangle, i.e., the area of the triangle ABC using:
Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2
• Calculate the area of the triangle QAB. We can use the same formula for this.
Let this area be A1.
• Calculate the area of the triangle QBC. Let this area be A2.
• Calculate the area of the triangle QAC. Let this area be A3.
• If Q lies inside the triangle, then A1 + A2 + A3 must be equal to A
Conditional Statements 37
Solution
#include <iostream> int main()
using namespace std; {
float area(int x1, int y1, int x2, int y2, int x3, int y3) if (Q_Inside(0, 0, 20, 0, 10, 30, 10, 15))
{ cout <<"Inside";
return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0); else
} cout <<"Not Inside";
bool Q_Inside(int x1, int y1, int x2, int y2, int x3, int y3, return 0;
int x, int y)
}
{
float A = area (x1, y1, x2, y2, x3, y3);
float A1 = area (x, y, x2, y2, x3, y3);
float A2 = area (x1, y1, x, y, x3, y3);
float A3 = area (x1, y1, x2, y2, x, y);
return (A == A1 + A2 + A3);
}
Conditional Statements 38

You might also like