Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

Chapter 3

Controls & Decisions

1
So Far…
The C++ programs we have been writing so
far have been executing sequentially

Statement 1 int n, temp, ans;

Statement 2 cout<<“Enter number: “;


. .
. .
. .
Statement n-1 cout<<“The answer is “<<ans;

Statement n return 0;
2
Flow of Control
• A program is usually not limited to a linear sequence of
instructions. During its process it may repeat code
(Looping) or take decisions/select (selection) . For that
purpose, C++ provides control structures that serve to
specify what and how to perform our program.
1.Decisions/ Selection (if, if…else, switch)
• While using decision or selection statement, we select one
block of code based on certain conditions.

3
i ) If statements
• An if statement has two forms: one with an else branch and one
without
A test expression that
i) if statement (single selection) evaluates to a boolean value
Syntax: (either true or false)

If(expression or condition)
{ A single statement or a
//code/statement(s) compound statement, to be
executed if condition
} evaluates to true.

If the condition is true, the statement is executed, otherwise it is


skipped.

4
Example 1
#include<iostream>
using namespace std;
int main()
{
unsigned short age;
cout<<“Enter your age:”;
cin>>age;
if (age < 17)
cout<<“You are too young!\n”;
cout<<“Thank you.”<<endl;
return 0;
}
Note: the if statement in this example, executed only a single statement when
the expression is true 5

Example 2
In order to execute multiple statements, we can use a block e.g.
#include<iostream>
using namespace std;
int main()
{
int val;
cout<<“Enter an integer value: “;
cin>>val;
if (val%2 == 0)
{
int quotient = val/2;
cout<<val<<“ is divisible by 2.”<<endl;
cout<<“The quotient is ”<<quotient<<endl;
cout<<“Thank you.”<<endl;
return 0;
}
6
}
ii) if… else statement (double selection)

• The if else executes the codes inside the body of if statement if


the test expression is true and skips the codes inside the body of
else.
• If the test expression is false, it executes the codes inside the
body of else statement and skips the codes inside the
If condition body of if.
evaluates
to true, this statement
will be executed
Syntax:
If(expression or condition)
{
//code1/statement1
}
else If condition evaluates
{ to false, this statement
will be executed
//code2/statement2
}
7
Example-3
#include<iostream>
using namespace std;
int main()
{
int x;
cout<<"Enter a number:";
cin>>x;
if(x>10)
{
cout<<x<<" is greater than 10"<<endl;
}
else{
cout<<x<<" is less than 10"<<endl;
return 0;
}
}
8
Example 2
In order to execute multiple statements we can use a block code

9
// Program to check whether an integer is positive or negative
// This program considers 0 as positive number
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number >= 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else
{
cout << "You entered a negative integer: " << number << endl;
}
return 0;
10
}
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
11
Flowchart equivalents

12
iii) Nested if …else statements

• The if...else statement executes two different codes


depending upon whether the test expression is true or
false. Sometimes, a choice has to be made from more
than 2 possibilities.
• The nested if...else statement allows you to check for
multiple test expressions and execute different codes for
more than two conditions.
If(expression)
statement1
else
statement2
Note that: statement1 and statement 2 can be any
statement including if… else statement
13
If …else if … else
Convenient form for nested if…else statements
if (testExpression1)
{
// statements to be executed if testExpression1 is true }
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is
true }
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and
testExpression3 is true
}..
else
{
// statements to be executed if all test expressions are false }
14
Nested if …else statements
E.g. when statement 2 itself is again another if…else statement

#include<iostream>
using namespace std;
int main()
{

unsigned short age;


cout<<"Enter your age: ";
cin>>age;
if (age < 17)
cout<<"You are too young!\n";
else if (age < 40)
cout<<"You are still young!\n";
else if (age < 70)
cout<<"Young at heart!\n";
else
cout<<"Are you sure?\n";

cout<<"Thank you."<<endl;
return 0;
15
}
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<“ enter value of a:”;
cin>>a;
cout<<“enter value of b:”;
cin>>b;
if(b>a)
{
cout << "b is greater"<<endl;
}
else if(a>b){
cout << "a is greater"<<endl;
}
else
{
cout << "\n Both are equal"<<endl; 16
}
#include <iostream>
using namespace std;
int main()
{
int testScore; char grade;
cout << "Enter your numeric test score and I will\n tell you the letter grade you
earned: ";
cin >> testScore;
if (testScore < 60)
grade = 'F';
else if (testScore < 70)
grade = 'D';
else if (testScore < 80)
grade = 'C';
else if (testScore < 90)
grade = 'B';
else if (testScore <= 100)
grade = 'A';
cout << "Your grade is " << grade << ".\n";
return 0; 17
}
• Write a C++ program to check the
largest number among two given
integers.

18
ii) The Switch Statement
• It is usually very difficult to express our intended logic
using such deeply nested if...else statements.
• As an alternative method of choosing among a set of
mutually exclusive choices, C++provides the switch
statement.

19
iv) The switch Statement
Syntax: An integer expression, whose value
we want to test
switch (expression)
{ Unique, possible values that we are
case constant1: testing for equality with expression
statements
break;
case constant2:
statements
break;
Statements to be executed when
expression becomes equal to

constant N
case constant N:
statements
break;
Statements to be executed when
default:
expression is not equal to any of
statements
The break statement causes the the N constants
} Program to exit the switch
20
statement
The Switch Statement

• The switch expression is evaluated to produce a


value,
• and each case label is tested against this value for
equality.
• If a case label matches, the statements after the case
label are executed.
• If no case label matches the switch expression, the
code under the default label is executed (if it exists).

21
Example
// This program demonstrates the use of a switch statement.
// The program simply tells the user what character they entered.
#include <iostream>
using namespace std;
int main()
{
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
switch (choice)
{
case 'A': cout << "You entered A.\n";
break;
case 'B': cout << "You entered B.\n";
break;
case 'C': cout << "You entered C.\n";
break;
default: cout << "You did not enter A, B, or C!\n";
}
return 0; }

22
The switch statement

#include<iostream> • Note that the expressions of each case


using namespace std; statement in the block must be unique.
int main()
• That is , you can’t do this
{
Switch(x)
int x;
{
cout<<”Enter a number”;
cin>>x;
case 4:
switch (x) …..
{ case 4://illegal…already used
case 1:cout<<”You Entered 1:”; value 4
break;
……
case 2:cout<<”You Entered 2:”;
break;
default:
case 3:cout<<”You Entered 3:”; }
break;
default: cout<<”Invalid Input:”;
}
return 0; 23
2. Looping
• A loop is a control structure that causes a statement or group of
statements to repeat.
• C++ has three looping control structures: the while loop, the do-
while loop, and the for loop.
• The difference between each of these is how they control the
repetition.

24
i)While Loop
• Syntax :
while (expression/condition )
{
statement;
statement;
// Place as many statements here as necessary
}
and its function is simply to repeat statement while expression is true,
Each repetition is known as an iteration

Principle:
Condition of while loop is first executed (pretest loop)and if
condition is TRUE, statement is executed .Then ,condition is
evaluated again & if TRUE, statement is repeated. It loops until the
condition comes to be FALSE. when it ‘s FALSE, it leaves the loop.

25
While Loop Statement

• (If there is only one statement in the loop body, the braces may
be omitted.)
while (expression)
statement;

26
Example
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”;
This outputs:
0 1 2 3 4 5 6 7 8 9 done! 27
While Loop Statement
 An important characteristic of the while loop is that the
loop will never iterate if the test expression is false to
start with.
• It is possible that a while statement executes 0 times.
int i = 15;
while(i<10)
{
cout<<i<<” “;
i++;
}

28
Example-2
// Loop through every number between 1 and 50
int i= 1;
while (i<= 50)
{
// print the number
cout << i<< " ";

// if the loop variable is divisible by 10, print a newline


if (i% 10 == 0)
cout << endl;

// increment the loop counter


i++;
}
This program produces the result:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
29
41 42 43 44 45 46 47 48 49 50
…cont’

//a program to print even numbers


between 0 and n
#include<iostream>
using namespace std;
int main()
{ int n;
int i=0;
cout<<”enter an integer n:”<<endl;
cin>>n;
while(i<=n)
{
if((i%2)==0)
{
cout<<i<<”is even”<<endl;
}
i++;
}
return 0;
} 30
This version of the loop will stop after it has executed 10 times:

int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”

31
ii)Do While Loop

• The do-while loop looks similar to a while loop turned upside


down
Do
{
statement;
statement;
} while (expression);
• Principle: first Action is executed. Then if the condition in
while is TRUE ,action is repeated and it continues until the
condition gets FALSE

32
//program that displays list of integer
from 0 to number n, as: 0,1,2,3,4,5,
……….,n.(n is inputted from
keyboard)
#include<iostream>
using namespace std;
int main()
{
int n ,i=0;
cout<<”enter n:”<<endl;
cin>>n;
do
{
cout<<i<<”,”<<endl;
i++;
}
while(i<=n);
return 0;
} 33
Do While Loop
• The difference between the do-while loop and the while loop is
that do-while is a post-test loop.
• This means do-while always performs at least one iteration,
even if the test expression is false from the start.
• Ex.

While Do While
int x = 1; int x = 1;
while (x < 0) do
cout << x << cout << x << endl;
endl; while (x < 0);

Never executes Executes once because the


expression x<0 is not
evaluated until the end of
the loop

34
iii)For loop
Syntax
for (Initialization of control var; test; update control var)
{
statement;
statement;
// Place as many statements
// here as necessary.
}

35
For Statements
• The for loop has three expressions inside the parentheses,
separated by semicolons.
• The first expression is the initialization expression.
It is typically used to initialize a counter or other variable that
must have a starting value. This is the first action performed by
the loop and it is only done once.
• The second expression is the test expression.
Like the test expression in the while and do-while loops, it
controls the execution of the loop.

36
For Statements

• As long as this expression is true, the body of the for loop will
repeat.
• The for loop is a pretest loop, so it evaluates the test
expression before each iteration.
• The third expression is the update expression.
It executes at the end of each iteration.
Typically, it increments a counter or other variable that must
be modified in each iteration.

37
Example
for(int i = 0; i< 10; i++)
cout << i << " ";
Consequently, this program prints the result:
0123456789

• Programmers love for loops because they are a very compact way to do
loops of this nature
• The previous program can be un-compacted into its while-statement
equivalent
int i = 0;
while (i < 10)
{
cout << i << " ";
i++;
38
}
• Example-1
int main()
{
for(int x=0;x<10;x++)
{ Out put
0
cout<<x; 1
cout<<endl; 2
3
} 4
5
return 0;
6
} 7
8
9

39
• Example-2
int main()
{
int sum=0;
for (int x=1;x<=5;x++)
{
sum+=x;
}
cout<<sum;
return 0;
}

40
//For looping #include<iostream>
#include<iostream>
int main()
int main() {
{
int i;
int i; for(i=100;i>0;i--)
for(i=0;i<100;i+=2) cout<<i<<endl;
cout<<i<<endl; return 0;
return 0; }
}

41
Sum of Natural Numbers using loop
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
42
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; ++i)
{

cout << i <<;


}
return 0;
}
43
#include <iostream>
using namespace std;
int main()
{
int n=10, sum = 0;
for (int i = 1; i <= n; ++i)
{
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
44
#include <iostream>
using namespace std;
int main()
int i = 0;
while (i < 5)
{
cout << i << " ";
i++;
}

45
find an error line in the following C++ programming and then by correcting error
find the out put

2. #include <iostream>
1. #include <iostream> using namespace std;
using name space std; int main();
int main() {
{ int n, sum = 0,
cout << "Enter a positive integer:
int n
"
cout << "Enter an integer: "; cin >> n;
cin >> n; for (int i = 1; i <= n; ++i) {
if ( n % 2 == 0) sum += i;
cout << n << " is even."; }
else cout << "Sum = " << sum;
cout << n << " is odd."; return 0
}
return 0;
} 46
4. #include <iostream>
3. #include <iostream>
using namespace std;
Using namespace std;
int main()
Int main()
{ {
int a=5,b=20; for (int i = 1, i <= 10, ++i)
if(b>a) {
{
cout << "b is greater"<<endl; cout << i <<;
}
}
else if(a>b){
return 0 ;
Cout << "a is greater"<<endl;
}
else
{
cout << "\n Both are equal"<<endl;
}
Return 0;
47
}
5. include<iostream>
6. include<iostream>
using namespace std; Using namespace std;
int main() int main()
int n; {
int i=0; int n ; i=0;
Cout<<”enter an integer n:”<<endl; Cout<<”enter n:”<<endl;
cin>>n cin>>n;
while(i<=n); do
{ {
if((i%2)==0) cout<<i<<”,”<<endl;
{ i++
cout<<i<<”is even”<<endl; }
} while(i<=n);
i++ return o;
}
return ;
} 48

You might also like