21
Lab 3: Control Flow / Conditional Statements Based on the presentation made by Graham Northup

Lab 3: Control Flow / Conditional Statementsweb2.clarkson.edu/class/cs141/webresources/cs141lab3.pdf · Lab 3: Control Flow / Conditional Statements Based on the presentation made

  • Upload
    ngoliem

  • View
    229

  • Download
    0

Embed Size (px)

Citation preview

Lab 3:

Control Flow / Conditional Statements

Based on the presentation made by Graham Northup

Control Flow

#include <iostream>

using namespace std;

int main() { int a, b, c;

a = 3; cout << "Enter factor: "; cin >> b;

c = a * b;

cout << c << "\n"; return 0;}

Normally, a programs code will execute line after line, in the order it appears in the source.(1)

(1)In modern optimizing compilers, this is often an illusion.

PC

“PC” is the program counter—a piece of data on every processor core that indicates what the core is “running” or “looking at”.

Naturally, as a program runs, the PC usually goes from one statement to the next. This change is the most basic form of control flow.

Showing Control Flow(start)

a = 3;

cout << "Enter factor: ";

cin >> b;

(end)

“Control flow” is most easily demonstrated with a graphical aid—the flowchart. In this example, it’s clear that these three statements are always executed in sequence.

Modifying Control Flow

There are exceptions to the general “in-sequence” rule; in C and C++, these are called the control structures, and they change control flow—what the processor executes next—in various useful ways. The most obvious one is only doing the next statement “if” a condition is true.

#include <iostream>

using namespace std;

int main() { int a, b, c;

a = 3; cout << "Enter factor: "; cin >> b;

if(b < 0) { cout << "Factor cannot be negative!\n"; return 1; }

c = a * b;

cout << c << "\n"; return 0;}

PCPC

PC

If Statement

(start)

b < 0

cout << "Factor cannot be negative!;"

(end)

return 1;

All of the control structures we will study today have decision points in them where a condition is checked. I will occasionally also call them branches, because—like a tree’s branch from its trunk—the flowchart (pictures here) splits in two.

True

False

“Relational” Operators

These can be used as a condition wherever a “truth” is expected.

A == B /* True when A is equal to B */A != B /* True when A is not equal to B */A < B /* True when A is less than B */A > B /* True when A is greater than B */A <= B /* True when A is less than or equal to B */A >= B /* True when A is greater than or equal to B */

Activity: Try an If Statement

#include <iostream>

using namespace std;

int main() { int number;

cout << "Enter an integer: "; cin >> number;

if(number > 0) { cout << number << " is positive\n"; }

return 0;}

If/Else Statement#include <iostream>

using namespace std;

int main() { int foobar;

cout << "What is your foobar? "; cin >> foobar;

if(foobar == 7) { cout << "Your foobar is a 7? Mine too!\n"; } if(foobar != 7) { cout << "Aww, my foobar is a 7.\n"; }

return 0;}

With our knowledge of these relations and their inverses, it is easy to construct branches that are always mutually exclusive. However, this is quite a bit of typing...

If/Else Statement#include <iostream>

using namespace std;

int main() { int foobar;

cout << "What is your foobar? "; cin >> foobar;

if(foobar == 7) { cout << "Your foobar is a 7? Mine too!\n"; } else { cout << "Aww, my foobar is a 7.\n"; }

return 0;}

...so one can also just use “else” for this purpose. Control flows to the statement(s) following the “else” when the “if” would be skipped. Exactly one block is always executed—never both. Note that an “else” must always directly follow an “if”.

If/Else Statement(start)

(end)

cout << "Your foobar is a 7? Mine too!\n";

foobar == 7

cout << "Aww, my foobar is a 7.\n";

TrueFalse

In terms of a flowchart...

Activity: Try an If/Else Statement#include <iostream>

using namespace std;

int main() { int number;

cout << "Enter an integer: "; cin >> number;

if(number > 0) { cout << number << " is positive\n"; } else { cout << number << " is non-positive\n"; /* NB: Why not "negative"? */ }

return 0;}

Nesting and LaddersThe simplified flowchart for the “main()” function of the previous program looks approximately like this. Note that there is only one branch.

Nesting and LaddersThe simplified flowchart for the “main()” function of the previous program looks approximately like this. Note that there is only one branch.

It is worth repeating that the control structures are, themselves, statements, which means they can be “nested” inside of other control structures.

Nesting and LaddersThe simplified flowchart for the “main()” function of the previous program looks approximately like this. Note that there is only one branch.

It is worth repeating that the control structures are, themselves, statements, which means they can be “nested” inside of other control structures.

This ability to create arbitrary structure is the hallmark of any non-trivial computer program; if you peruse C++ source, you will likely find some deeply-nested and very long structures!

Nesting and Ladders#include <iostream>

using namespace std;

int main() { int number;

cout << "Enter an integer: "; cin >> number;

if(number > 0) { cout << number << " is positive\n"; } else { if(number == 0) { cout << number << " is zero\n"; /* "0 is zero"! */ } else { cout << number << " is non-positive\n"; } }

return 0;}

What this code does, then, should be no surprise.

(Although this is based on the activities, you don’t need to type this.)

However, while nesting can be used, note the growing indent for each nested “if”...

Nesting and Ladders#include <iostream>

using namespace std;

int main() { int number;

cout << "Enter an integer: "; cin >> number;

if(number > 0) { cout << number << " is positive\n"; } else if(number == 0) { cout << number << " is zero\n"; /* "0 is zero"! */ } else { cout << number << " is non-positive\n"; }

return 0;}

...most programmers prefer this version, so as to avoid the code running off the right side of their editor :) . This version is frequently called a “ladder of ifs”.

Both of them have the same flowchart and same behavior. Choose whichever you prefer.

Switch/Case#include <iostream>

using namespace std;

int main() { int number;

cout << "Magic Eight Ball\n"; /* TODO: Generate random numbers */ cout << "Provide an integer (1-6): "; cin >> number;

if(number == 1) { cout << "MAYBE LATER\n"; } else if(number == 2) { cout << "ASK AGAIN\n"; } else if(number == 3) { cout << "YES\n"; } else if(number == 4) { cout << "UNCERTAIN\n";

} else if(number == 5) { cout << "NO\n"; } else if(number == 6) { cout << "VERY LIKELY\n"; } else { cout << "I said 1-6!\n"; return 1; }

return 0;}

There’s one more, mostly-historical caveat to talk about; another statement less general than “if/else”, and can help when you’re finding yourself testing if something is equal to plenty of other values, as here...

Switch/Case

#include <iostream>

using namespace std;

int main() { int number;

cout << "Magic Eight Ball\n"; /* TODO: Generate random numbers */ cout << "Provide an integer (1-6): "; cin >> number;

switch(number) { case 1: cout << "MAYBE LATER\n"; break;

case 2: cout << "ASK AGAIN\n"; break;

case 3: cout << "YES\n"; break;

case 4: cout << "UNCERTAIN\n"; break;

case 5: cout << "NO\n"; break;

case 6: cout << "VERY LIKELY\n"; break;

        default: cout << "I said 1-6!\n"; return 1; break; }

return 0;}

This is the switch/case statement. The “switch” part takes something that evaluates to an integer value, and the “cases” are labeled with possible values. You can provide a “default” case, which is like the last “else” of an “if ladder”.

The strange syntax is mostly a remnant from the past.

You can use an “if ladder” wherever you would use a switch/case. Although switch/case can sometimes be a little faster, I don’t recommend using it while you’re learning, as its syntax is not obvious. You should at least note its existence for the sake of future exams (hint).

Task 1

You need to submit Grade.cpp file into your directory /afs/ad.clarkson.edu/class/cs141/students/username/lab3/

Task 2

You need to submit Arithmetic.cpp file into your directory /afs/ad.clarkson.edu/class/cs141/students/username/lab3/

Please no other files in lab3 directory except

Grade.cpp and Arithmetic.cpp