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

CH 2

This document contains examples and explanations of different control statements in C++ including if/else statements, while loops, do-while loops, and for loops. It provides 14 examples of using these control statements to write C++ programs that perform tasks like comparing numbers, calculating averages, printing patterns, and converting between number bases. The document is from the Department of Electricity at the University of Misan's College of Engineering.

Uploaded by

Huthaifah Salman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

CH 2

This document contains examples and explanations of different control statements in C++ including if/else statements, while loops, do-while loops, and for loops. It provides 14 examples of using these control statements to write C++ programs that perform tasks like comparing numbers, calculating averages, printing patterns, and converting between number bases. The document is from the Department of Electricity at the University of Misan's College of Engineering.

Uploaded by

Huthaifah Salman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

University of Misan

College of Engineering
Dept. of Electricity

Chapter Two
Control Statements

2-1 if Selection Statement


Equality and Relational Operators:

For example: (2 = = 3) false , (5 >= 4) true

Ex 2-1: Write a C++ program to find the greater of two integer numbers.

11
University of Misan
College of Engineering
Dept. of Electricity

Note:
1. The if statemen:t

compares the values of variables a and b. If the value of a is greater or equal than b, the
cout statement displays a line of text indicating that the greater is a.

2. You can add more than one statement inside if statement, for example:

Logical AND (&&) Operator:

Logical OR (||) Operator:

Logical Negation (!) Operator:

12
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-2: Write a C++ program to arrange three integer numbers in a descending order.

2-2 if…else Double-Selection Statement


The if single-selection statement performs an indicated action only when the condition is true;
otherwise the action is skipped. The if…else double-selection statement allows you to specify an
action to perform when the condition is true and a different action to perform when the condition is
false.

13
University of Misan
College of Engineering
Dept. of Electricity

Note: To include several statements in the body of an if or in either part of an if…else, enclose the
statements in braces ({ and }). A set of statements contained within a pair of braces is called
a compound statement or a block, for example:

Nested if…else Statements:


Nested if…else statements test for multiple cases by placing if…else selection statements inside
other if…else selection statements.

14
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-3: Write a C++ program read a student grade and print:


A 90 – 100
B 80 – 89
C 70 – 79
D 50 – 69
F < 50

Note: Programmer can use more than one condition within if statement by using logical operators,
as shown below:

15
University of Misan
College of Engineering
Dept. of Electricity

2-3 while Repetition Statement


A repetition statement specifies that a program should repeat an action while some condition
remains true. The code statement:
While there are more items on my shopping list
Purchase next item and cross it off my list
describes the repetition that occurs during a shopping trip. The condition, “there are more items on
my shopping list” is either true or false. If it’s true, then the action, “Purchase next item and cross it
off my list” is performed. This action will be performed repeatedly while the condition remains true.
The statement contained in the While repetition statement constitutes the body of the While, which
can be a single statement or a block.

As an example of C++’s while repetition statement, consider a program segment designed to find
the first power of 3 larger than 100. Suppose the integer variable product has been initialized to 3.
When the following while repetition statement finishes executing, product contains the result:

When the while statement begins execution, product’s value is 3. Each repetition multiplies product
by 3, so product takes on the values 9, 27, 81 and 243 successively. When product becomes 243,
the while statement condition (product <= 100) becomes false. This terminates the repetition, so the
final value of product is 243. At this point, program execution continues with the next statement
after the while statement.

Ex 2-4: A class of ten students toke a quiz, write a C++ program read these ten grades to
calculate the average.

16
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-5: Re-change the above program’s code to calculate the average of quiz grades. Program
terminated when -1 entered.

17
University of Misan
College of Engineering
Dept. of Electricity

2-4 do…while Repetition Statement


The do…while repetition statement is similar to the while statement. In the while statement, the
loop-continuation condition test occurs at the beginning of the loop before the body of the loop
executes. The do…while statement tests the loop-continuation condition after the loop body
executes; therefore, the loop body always executes at least once.

Ex 2-6: Write a C++ program to print integer numbers from 1 to 10.

Ex 2-7: Use do…while repetition statement to write a C++ program printing the following table:

N 10*N 100*N 1000*N


-- ------ -------- ----------
1 10 100 1000
2 20 300 3000
3 30 300 3000
4 40 400 4000
5 50 500 5000

18
University of Misan
College of Engineering
Dept. of Electricity

2-5 for Repetition Statement


C++ provides the for repetition statement, which specifies the counter-controlled repetition details
in a single line of code as follow:

Increment of control variable


Initial value of control variable
Control variable Final value of control variable

When the for statement begins executing, the control variable counter is declared and initialized to
1. Then, the loop-continuation condition counter <= 10 is checked. The initial value of counter is
1, so the condition is satisfied and the body statements (cout << counter; and cout << endl;) prints
the value of counter, namely 1. Then, the expression ++counter increments control variable
counter and the loop begins again with the loop-continuation test. The control variable is now equal
to 2, so the final value is not exceeded and the program performs the body statement again. This
process continues until the loop body has executed 10 times and the control variable counter is
incremented to 11, this causes the loop-continuation test to fail and repetition to terminate.

The general form of the for statement is


for ( initialization; loop Continuation Condition; increment )
statement

19
University of Misan
College of Engineering
Dept. of Electricity

Note: if the control variable is declared at the initialization part of for statement, then it will be
used only inside the body of for statement.

Ex 2-8:
a) Vary the control variable from 1 to 100 in increments of 1.
for ( int i = 1; i <= 100; i++ )

b) Vary the control variable from 100 down to 1 in decrements of 1.


for ( int j = 100; j >= 1; j -- )

c) Vary the control variable from 7 to 77 in steps of 7.


for ( int k = 7; k <= 77; k = k+ 7 )

d) Vary the control variable from 20 down to 2 in steps of -2.


for ( int m = 20; m >= 2; m = m-2 ).

e) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.
for ( int n = 2; n <= 17; n += 3 )

f) Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55.
for ( int r = 99; r >= 55; r -= 11 )

Ex 2-9: Write a C++ program to print the even integers from 2 to 100 with their sum.

20
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-10: A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that
all interest is left on deposit in the account, calculate and print the amount of money in the
account at the end of each year for 10 years. Use the following formula for determining
these amounts:
amount = principle ( 1 + rate )year

where principle is the original amount invested , rate is the annual interest rate, year is the number
of years and amount is the amount on deposit at the end of the nth year.
Use the standard library function pow, the function pow(x, y) calculates the value of x raised to the
yth power.

Ex 2-11: Write a C++ program to draw the following shape:

21
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-12: Write a C++ program to find the largest number from ten integer numbers.

Ex 2-13: Write a C++ program to read a square length and then draw the square using *.

22
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-14: Write a C++ program to convert a decimal number to a binary number.

Decimal to Binary Conversion


( 18 )10 = ( 10010 )2 0 18
1 9
0 4
0 2
1 1
0

( 6 )10 = ( 110 )2 0 6
1 3
1 1
0

Q1: Write a C++ program to convert a binary number to a decimal number.


Q2: Write a C++ program to find the smallest two numbers of 20 float numbers.

2.6 switch Multiple-Selection Statement


C++ provides the switch multiple-selection statement to perform many different actions based on
the possible values of a variable or expression. Each action is associated with the value of a
constant integral expression.
The switch statement consists of a series of case labels and an optional default case. When the flow
of control reaches the switch, the program evaluates the expression in the parentheses following
keyword switch. This is called the controlling expression. The switch statement compares the value
of the controlling expression with each case label. If a match occurs, the program executes the
statements for that case. The break statement causes program control to proceed with the first
statement after the switch.

23
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-15: Write a C++ program read a student grade (-1 to end) and print:

i/p grade o/p


90 - 100 A
80 - 89 B
70 - 79 C
50 - 69 D
0 - 49 F
> 100 Out of range

24
University of Misan
College of Engineering
Dept. of Electricity

Note:
1. Forgetting a break statement when one is needed in a switch statement is a logic error.
2. If no match occurs between the controlling expression’s value and a case label, the default
case executes.
3. The last case in a switch statement (default) does not require a break statement

25
University of Misan
College of Engineering
Dept. of Electricity

Ex 2-16: A mail order house sells five different products whose retail prices are: product 1- $2.98,
product 2- $4.50, product 3- $9.98, product 4- $4.49 and product 5- $6.87. Write a C++
program that reads a series of pairs of numbers as follows:
a) product number
b) quantity sold
The program should use a switch statement to determine the retail price for each product, the
program stop when -1 entered.

26
University of Misan
College of Engineering
Dept. of Electricity

2.7 break and continue Statements


break Statement:
The break statement, when executed in a while, for, do…while or switch statement, causes
immediate exit from that statement. Program execution continues with the next statement. Common
uses of the break statement are to escape early from a loop or to skip the remainder of a switch
statement.
The example below demonstrates the break statement exiting a for repetition statement.

When the if statement detects that count is 5, the break statement executes. This terminates the for
statement, and the program proceeds to the first statement after the for statement, which displays a
message indicating the control variable value that terminated the loop. The for statement fully
executes its body only four times instead of 10. The control variable count is defined outside the for
statement header, so that we can use the control variable both in the loop’s body and after the loop
completes its execution.

27
University of Misan
College of Engineering
Dept. of Electricity

continue Statement:
The continue statement, when executed in a while, for or do…while statement, skips the remaining
statements in the body of that statement and proceeds with the next iteration of the loop. In while
and do…while statements, the loop-continuation test evaluates immediately after the continue
statement executes. In the for statement, the increment expression executes, then the loop-
continuation test evaluates.
The example below uses the continue statement in a for statement to skip the output statement
when the nested if determines that the value of count is 5. When the continue statement executes,
program control continues with the increment of the control variable in the for header and loops
five more times.

28

You might also like