Week 4 Computer Laboratory II
Week 4 Computer Laboratory II
There is a whole other class of operators known as the logical operators. C++ programs have
to make decisions. A program that can’t make decisions is of limited use. The temperature
conversion program is about as complex you can get without some type of decision-making.
Invariably a computer program gets to the point where it has to figure out situations such as
“Do this if the a variable is less than some value, do that other thing if it’s not.” That’s what
makes a computer appear to be intelligent — that it can make decisions.
Simple Logical Operator
Computer programs are all about making decisions. If the user presses a key, the computer
responds to the command. This section focuses on controlling program flow. Flow-control
commands allow the program to decide what action to take based on the results of the C++
logical operations performed. There are basically three types of flow-control statements: the
branch, the loop, and the switch.
Branch Statement
Branch statements allow you to control the flow of a program’s execution from one path of a
program or another. This is a big improvement, but still not enough to write full-strength
programs. Executing the same command multiple times requires some type of looping
statements.
While Loop: The simplest form of looping statement is the while loop. Here’s what the while
loop looks like:
while(condition)
{
// ... repeatedly executed as long as condition is true
}
The condition is tested. This condition could be if var > 10 or if var1 == var2 or anything else
you might think of. If it is true, the statements within the braces are executed. Upon
encountering the closed brace, C++ returns control to the beginning, and the process starts
over. The effect is that the C++ code within the braces (i.e. code block) is executed repeatedly
as long as the condition is true. If the condition were true the first time, what would make it
be false in the future?
for loop
The most common form of loop is the for loop. The for loop is preferred over the more basic while loop because it’s
generally easier to read. The for loop has the following format:
for (initialization; conditional; increment)
{
// ...body of the loop
}
Execution of the for loop begins with the initialization clause, which got its name because it’s normally where
counting variables are initialized. The initialization clause is only executed once when the for loop is first
encountered. Execution continues with the conditional clause. This clause works a lot like the while loop: as long as
the conditional clause is true, the for loop continues to execute.
Assignment