Module-1Lesson3
Module-1Lesson3
In this lesson, we will continue our journey into the world of C++
Language from the previous lesson. At this point, you will learn to
convert a flowchart into a functioning C++ program by translating
each symbol to its respective statement.
Along this line, we will focus to write the C++ program implementing
the decision-making and looping concept. Our goals are to develop a
flowchart, convert that flowchart into computer codes, encode the
codes and execute.
Learning Outcomes
This lesson introduces conditional processing. In previous lessons, all the code
in the examples executed, that is, from the first line of the program to the last,
every statement was executed in the order it appeared in the source code. This
may be correct for some programs, but others need a way to choose which
statements will be executed or run. Conditional processing extends the
usefulness of programs by allowing the use of simple logic or tests to determine
which blocks of code are executed. In this lesson, a simple guessing game will
be developed to illustrate the use of conditional execution.
#include <iostream>
using namespace std;
int main()
{
int number = 5;
int guess;
cout << "I am thinking of a number between 1 and 10" << endl;
cout << "Enter your guess, please " << endl;
cin >> guess;
if (guess == number)
{
cout << "Incredible, you are correct" << endl;
}
return 0;
}
The "==" is called a relational operator. Relational operators, ==, !=, >, >=, <,
and <=, are used to compare two operands. If the user enters 5 as a choice, he
gets back a nice message, "Incredible, you are correct". But what happens if the
user puts in an incorrect choice? Nothing. No message, no suggestions,
nothing. Luckily, for our program user, C++ has a solution.
The else statement provides a way to execute one block of code if a condition
is true, another if it is false.
#include <iostream>
using namespace std;
int main()
{
int number = 5;
int guess;
cout << "I am thinking of a number between 1 and 10" << endl;
cout << "Enter your guess, please ";
cin >> guess;
if (guess == number)
{
cout << "Incredible, you are correct" << endl;
}
else
{
cout << "Sorry, try again" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int number = 5;
int guess;
cout << "I am thinking of a number between 1 and 10" << endl;
cout << "Enter your guess, please ";
cin >> guess;
if (guess == number)
{
cout << "Incredible, you are correct" << endl;
}
else if (guess < number)
{
cout << "Higher, try again" << endl;
}
else // guess must be too high
{
cout << "Lower, try again" << endl;
}
return 0;
}
It is interesting to note that there is no C++ keyword "else if", as may exist in
other languages. For instance, Perl has a keyword "elsif". The if/else if
construct is created out of if and else statements. To see this, the above code
can be rewritten as follows:
if (guess == number)
{
cout << "Incredible, you are correct" << endl;
}
else
if (guess < number)
{
cout << "Higher, try again" << endl;
}
else // guess must be too high
{
cout << "Lower, try again" << endl;
}
This code is identical to the code in the program. Only the spacing has been
changed to illustrate how if/else if statements are constructed.
Table 4-1. Summary of Relational Operators
Here's an example. Suppose that an ice cream store has asked us to write a
program that will automate the taking of orders. We will need to present a
menu and then based on the customer's choice take an appropriate action.
#include <iostream>
using namespace std;
int main()
{
int choice;
return 0;
}
This program will work fine, but the if/else block is cumbersome. It would be
easy, particularly if there were more choices and maybe sub choices involving
more if/else's to end up with program that doesn't perform the actions
intended. Here's the same program with a switch.
#include <iostream>
using namespace std;
int main()
{
int choice;
switch (choice) {
case 1:
cout << "Chocolate, good choice" << endl;
break;
case 2:
cout << "Vanillarific" << endl;
break;
case 3:
cout << "Berry Good" << endl;
break;
case 4:
cout << "Big Mistake" << endl;
break;
default:
cout << "We don't have any" << endl;
cout << "Make another selection" << endl;
}
return 0;
}
switch (variable) {
case expression1:
do something 1;
break;
case expression2:
do something 2;
break;
....
default:
do default processing;
}
switch (myLetter) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowelCnt++; // increments vowel count
// same as, vowelCnt = vowelCnt + 1;
break;
default:
consonantCnt = consonantCnt + 1;
}
If any vowels are found execution drops through each case until the count is
incremented and the "break" is encountered. For some coding practice, how
could the same logic be implemented using if and else's?
ANSWER
As can be seen in this table, && will return true only if both expressions are
true, while || will be true if either expression is true. The operator "!" provides
logical negation. One very important consideration when forming expressions is
the order of precedence of the relational and logical operators. Relational
operators are of higher precedence than the logical and the order of evaluation
is from left to right. Here are some examples that illustrate what this means.
if (myChoice == 'A' and myAge < 25) is evaluated as
if ((myChoice == 'A') and (myAge < 25))
Suppose x = 8, y = 49, z = 1.
if (x < 7 && y > 50 || z < 2) is evaluated as
if (((x < 7) && (y > 50)) || (z < 2)) which is TRUE, not as
if ((x < 7) && ((y > 50) || (z < 2)) which is FALSE.
Now, here are a few final points to wrap up this lesson. First, even if you are
sure about the order of precedence of an expression, use explicit parenthesis.
This serves to increase readability and will help avoid errors. Second, there is
such a thing as green tea ice cream and I recommend that you not buy it.
LOOPING
Do, While and For Constructs
This lesson covers three constructs that are used to create loops in C++
programs. Loops can be created to execute a block of code for a fixed number of
times. Alternatively, loops can be created to repetitively execute a block of code
until a boolean condition changes state. For instance, the loop may continue
until a condition changes from false to true, or from true to false. In this case,
the block of code being executed must update the condition being tested in
order for the loop to terminate at some point. If the test condition is not
modified somehow within the loop, the loop will never terminate. This creates a
programming bug known as an infinite loop.
While
The while loop is used to execute a block of code as long as some condition is
true. If the condition is false from the start the block of code is not executed at
all. Its syntax is as follows.
Here is a simple example of the use of while. This program counts from 1 to
100.
#include <iostream>
using namespace std;
int main()
{
int count = 1;
return 0;
}
Here is a more realistic use of while. This program determines the minimum
number of bits needed to store a positive integer. The largest unsigned number
that can be stored in N bits is (2N - 1).
#include <iostream>
using namespace std;
int main()
{
int bitsRequired = 1; //the power of 2
int largest = 1; //largest number that can be stored
int powerOf2 = 2;
int number;
cout << "To store " << number << " requires ";
cout << bitsRequired << " bits" << endl;
return 0;
}
Do
do {
block of code
} while (condition is satisfied)
Here is an example of the use of a do loop. The following program is a game
that allows a user to guess a number between 1 and 100. A "do" loop is
appropriate since we know that winning the game always requires at least one
guess.
#include <iostream>
using namespace std;
int main()
{
cout << "You win. The answer is " << number << endl;
return 0;
}
For
The third looping construct in C++ is the for loop. The for loop can execute a
block of code for a fixed number of repetitions. Its syntax is as follows.
The test conditions may be unrelated to the variables being initialized and
updated (assigned). Here is a loop that counts until a user response terminates
the loop.
More complicated test conditions are also allowed. Suppose the user of the last
example never enters "N", but the loop should terminate when 100 is reached,
regardless.
Initializations are optional. For instance, suppose we need to count from a user
specified number to 100. The first semicolon is still required as a place keeper.
The actions are also optional. Here is a silly example that will repeatedly echo a
single number until a user terminates the loop;