0% found this document useful (0 votes)
8 views8 pages

Chapter 3

Chapter 3 discusses the flow of control in computer programming, focusing on sequential statements, decision-making with if, if-else, and switch statements, as well as looping mechanisms like for, while, and do-while loops. It explains how these constructs allow for conditional execution and repetition of code, enhancing the program's ability to make decisions and perform tasks efficiently. Additionally, it includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

tigist hidru
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Chapter 3

Chapter 3 discusses the flow of control in computer programming, focusing on sequential statements, decision-making with if, if-else, and switch statements, as well as looping mechanisms like for, while, and do-while loops. It explains how these constructs allow for conditional execution and repetition of code, enhancing the program's ability to make decisions and perform tasks efficiently. Additionally, it includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

tigist hidru
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer programming Chapter 3 Flow of control

Chapter 3
3. Flow of control
Sequence
Sequential statements are statements that are executed one after the other in the order they are written
in the source code. In these kinds of statements the flow of control is said to be sequential.
Eg. int main ()
{
float number1, number2, number3;
cin>>number1;
number2=number1*10;
number3=number2*number2;
cout<<number2<<number3;
}
Decision
Programming helps to make a computer a little intelligent or enable to make decisions. The basis of decision in
computing lies ultimately in testing whether an expression is true or false. The tools available in C++ for
making decision are if, if-else and switch statements.

The Nature of Truth


In C++, zero is considered false, and all other values are considered true, although true is usually represented by
1. Thus, if an expression is false, it is equal to zero, and if an expression is equal to 1, it is true. If a statement is
true, all you know is that it is nonzero, and any nonzero statement is true.
3.1 If statement
Normally, your program flows along line by line in the order in which it appears in your source code. The if
statement enables you to test for a condition (such as whether two variables are equal) and branch to different
parts of your code, depending on the result.
The simplest form of an if statement is this:
if (expression)
statement;
The expression in the parentheses can be any expression at all, but it usually contains one of the relational
expressions.
Consider the following example:
if (bigNumber > smallNumber)
bigNumber = smallNumber;
This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the
value of smallNumber.
Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following
type of branch can be quite large and powerful:

Page 1 of 8 DMU
Computer programming Chapter 3 Flow of control

if (expression)
{
statement1;
statement2;
statement3;
}
Here's a simple example of this usage:
if (bigNumber > smallNumber)
{
bigNumber = smallNumber;
cout << "bigNumber: " << bigNumber << "\n";
cout << "smallNumber: " << smallNumber << "\n";
}
This time, if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an
informational message is printed.
if- else
Often your program will want to take one branch if your condition is true, another if it is false. In the above
example using several ifs for testing first one condition and then the other, works fine but is a bit cumbersome
and every if statement has to be tested. The keyword else can make far more readable code:
if (expression1)
statement;
else if (expression2)
statement;
else
statement;
Eg.
#include <iostream.h>
int main()
{
float number;
cout<<”Enter a number: “;
cin>>number;
if (number>0)
cout<<number<<” is greater than zero”;
else if (number<0)
cout<<number<<” is less than zero”;
else
cout<<number<<” is equal to zero”;
}
Advanced if Statements(nested if)
It is worth noting that any statement can be used in an if or else clause, even another if or else statement. Thus,
you might see complex if statements in the following form:
if (expression1)
{
if (expression2)
statement1;

Page 2 of 8 DMU
Computer programming Chapter 3 Flow of control

else
{
if (expression3)
statement2;
else
statement3;
}
}
else
statement4;
This cumbersome if statement says, "If expression1 is true and expression2 is true, execute statement1. If
expression1 is true but expression2 is not true, then if expression3 is true execute statement2. If expression1 is
true but expression2 and expression3 are false, execute statement3. Finally, if expression1 is not true, execute
statement4." As you can see, complex if statements can be confusing!
If using logical operators
if ( (x == 5) && (y == 5) ) Logical and
if ( (x == 5) || (y == 5) ) Logical Or
if ( !(x == 5) ) Logical not

Example write a program which print wether the number is positive ,negative or equal to zero
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int num;
cout<<"enter the number:";
cin>>num;
if(num==0)
cout<<"number is Zero";
else
{
if(num>0)
cout<<"number is positive";
else
cout<<"number is negative";
}
getch();
}
3.1 Switch Statement
The if and if/else statements become quite confusing when nested too deeply, and C++ offers an alternative.
The general form of the switch statement is:
switch (expression)
{
case valueOne: statement;
break;

Page 3 of 8 DMU
Computer programming Chapter 3 Flow of control

case valueTwo: statement;


break;
....
case valueN: statement;
break;
default: statement;
}
expression is any legal C++ expression, and the statements are any legal C++ statements or block of statements.
switch evaluates expression and compares the result to each of the case values. Note, however, that the
evaluation is only for equality; relational operators may not be used here.
If one of the case values matches the expression, execution jumps to those statements and continues to the end
of the switch block, unless a break statement is encountered. If nothing matches, execution branches to the
optional default statement. If there is no default and there is no matching value, execution falls through the
switch statement and the statement ends.
NOTE: It is almost always a good idea to have a default case in switch statements. If you have no other
need for the default, use it to test for the supposedly impossible case, and print out an error message;
this can be a tremendous aid in debugging.
It is important to note that if there is no break statement at the end of a case statement, execution will fall
through to the next case statement. This usually is an error. If you decide to let execution fall through, be sure to
put a comment, indicating that you didn't just forget the break.

The list below illustrates use of the switch statement.

// Demonstrates switch statement

#include <iostream.h>

int main()
{
int number;
cout << "Enter a number between 1 and 5: ";
cin >> number;
switch (number)
{
case 0: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!\n"; // will display Good job
break;
case 4: cout << "Nice Pick!\n"; // will display Nice Pick
break;
case 3: cout << "Excellent!\n"; // will display Excellent
break;

case 2: cout << "Masterful!\n"; // will display Masterful

Page 4 of 8 DMU
Computer programming Chapter 3 Flow of control

break;
case 1: cout << "Incredible!\n";// will display Incredible
break;
default: cout << "Too large!\n";// will display Too large!
break;
}
}

Output: Enter a number between 1 and 5: 3


Excellent!

Enter a number between 1 and 5: 8


Too large!

3.2 Looping: for, while, do while

Repetition
The great power of computers is their ability to perform a task over and over again with a
phenomenal speed, accuracy and reliability. Three facilities offered by C++ for performing
repetition are: the while loop, the do-while loop, and the for loop,.

Looping
Many programming problems are solved by repeatedly acting on the same data. There are two ways to do this:
recursion, and iteration. Iteration means doing the same thing again and again. The principal method of iteration
is the loop.
The while loop
The syntax for the while statement is as follows:
while ( condition )
statement;
condition is any C++ expression, and statement is any valid C++ statement or block of statements. When
condition evaluates to TRUE (1), statement is executed, and then condition is tested again. This continues until
condition tests FALSE, at which time the while loop terminates and execution continues on the first line below
statement.

Example
// count to 10
int x = 0;
while (x < 10)
cout << x++;
do-while Loops
It is possible that the body of a while loop will never execute. The while statement checks its condition before
executing any of its statements, if the condition evaluates false, the entire body of the while loop is skipped.

Page 5 of 8 DMU
Computer programming Chapter 3 Flow of control

The do...while loop executes the body of the loop before its condition is tested and ensures that the body always
executes at least one time. The syntax for the do...while statement is as follows:
do
statement
while (condition);
statement is executed, and then condition is evaluated. If condition is TRUE, the loop is repeated; otherwise, the
loop ends. The statements and conditions are otherwise identical to the while loop.
// count to 10
int x = 0;
do
cout << x++;
while (x < 10)

DO use do...while when you want to ensure the loop is executed at least once.

for Loops
The syntax for the for statement is as follows:
for (initialization; test; action )
statement;
The initialization statement is used to initialize the state of a counter, or to otherwise prepare for the loop. test is
any C++ expression and is evaluated each time through the loop. If test is TRUE, the action in the header is
executed (typically the counter is incremented) and then the body of the for loop is executed.
Example 1
// print Hello ten times
for (int i = 0; i<10; i++)
cout << "Hello! ";
Example 2
for (int i = 0; i < 10; i++)
{
cout << "Hello!" << endl;
cout << "the value of i is: " << i << endl;
}
A for loop works in the following sequence:
1. Performs the operations in the initialization.

2. Evaluates the condition.

3. If the condition is TRUE, executes the action statement and the loop.
After each time through, the loop repeats steps 2 and 3.

Nested Loops
Loops may be nested, with one loop sitting in the body of another. The inner loop will be executed in full for
every execution of the outer loop.

Page 6 of 8 DMU
Computer programming Chapter 3 Flow of control

Exercise 1
1. Write a single if statement that examines two integer variables and changes the larger to the
smaller, using only one else clause.

2. Examine the following program. Imagine entering three numbers, and write what output you
expect.
1 #include <iostream.h>
int main()
{
int a, b, c;
cout << "Please enter three numbers\n";
cout << "a: ";
cin >> a;
cout << "\nb: ";
cin >> b;
cout << "\nc: ";
cin >> c;
if (c == (a-b))
{cout << "a: ";
cout << a;
cout << "minus b: ";
cout << b;
cout << "equals c: ";
cout << c << endl;}
else
cout << "a-b does not equal c: " << endl;
}
3. Enter the program from Exercise 2; compile, link, and run it. Enter the numbers 20, 10, and 50. Did you
get the output you expected? Why not?

4. Examine this program and anticipate the output:


1: #include <iostream.h>
2: int main()
3: {
4: int a = 1, b = 1, c=2;
5: if (c = (a-b))
6: cout << "The value of c is: " << c;
8: }
5. Enter, compile, link, and run the program from Exercise 4. What was the output? Why?

Page 7 of 8 DMU
Computer programming Chapter 3 Flow of control

Exercises 2
1. What is the value of x when the for loop completes?
for (int x = 0; x < 100; x++)
2. Write a for statement to count from 100 to 200 by 2s.

3. Write a while loop to count from 100 to 200 by 2s.

4. Write a do...while loop to count from 100 to 200 by 2s.

5. What is wrong with this code?


int counter = 0
while (counter < 10)
{
cout << "counter: " << counter;
}
6. What is wrong with this code?
for (int counter = 0; counter < 10; counter++);
cout << counter << " ";
7. What is wrong with this code?
int counter = 100;
while (counter < 10)
{
cout << "counter now: " << counter;
counter--;
}
8. What is wrong with this code?
cout << "Enter a number between 0 and 5: ";
cin >> theNumber;
switch (theNumber)
{
case 0:
doZero();
case 1: // fall through
case 2: // fall through
case 3: // fall through
case 4: // fall through
case 5:
doOneToFive();
break;
default:
doDefault();
break;
}

Page 8 of 8 DMU

You might also like