94
Lecture 3 Agenda • Text book “absolute C++” • Chapter1:C++ basics cont. – Variable types • Char, string, float, const, boolean. – Type conversion – Math operations

Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Embed Size (px)

Citation preview

Page 1: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Lecture 3Agenda

• Text book “absolute C++”

• Chapter1:C++ basics cont. – Variable types

• Char, string, float, const, boolean.

– Type conversion– Math operations

Page 2: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Character variable// charvars.cpp// demonstrates character variables• #include <iostream> //for cout, etc.

• using namespace std;

• int main()

• {

• char charvar1='A'; //define char variable as character

• char charvar2='\t'; //define char variable as tab

• cout << charvar1; //display character

• cout << charvar2; //display character

• cout << charvar1; //display character

• cout << "\n"; //display newline character

• return 0;

• }

Page 3: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Character variable : Escape Sequences

• \ xdd Hexadecimal notation• Sometimes you need to represent a character

constant that doesn’t appear on the keyboard, such as the graphics characters above ASCII code 127.

• To do this, you can use the “\xdd” “\xdd” representation,• where each dd stands for a hexadecimal digithexadecimal digit.

• cout << “\xE0”; //display α cout << “\xB2”; //display solid rectangle

Page 4: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

ASCII Table

Page 5: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

String variable

• In order to use string variable type, we have to use special library called “String”.

Page 6: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Cin>> with string variable type

Page 7: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

String variable

• #include <iostream>• #include <String> //using string variable• using namespace std;• int main()• {• string strname; // identify a string variable• cout<<" enter your name"<< endl;• cin>>strname;• cout<<"you typed the name"<<strname<<endl;• return 0;• }

Page 8: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Floating Point Types• represent numbers with a decimal place—like 3.1415927,

0.0000625, and –10.2.• There are three kinds of floating-point variables in C++:

– type float, – type double, – and type long double

• float PI = 3.14159F; //the F specifies that it’s type float• You can also write floating-point constants using exponential exponential

notationnotation. • Exponential notation is a way of writing large numbers without

having to write out a lot of zeros. • For example:

– 1,000,000,000 can be written as 1.0E9 in exponential notation.– 6.35239E–5 is equivalent to 0.0000635239 in decimal notation

Page 9: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The const Qualifier9

• The keyword const (for constant) precedes the data type of a variable.

• It specifies that the value of a variable will not change throughout the program.

• Any attempt to alter the value of a variable defined with this qualifier will elicit an error message from the compiler.

• const float PI = 3.14159F; //type const float

Page 10: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example: circarea.cpp10

// circarea.cpp// demonstrates floating point variables#include <iostream> //for cout, etc.using namespace std;int main(){float rad; //variable of type floatconst float PI = 3.14159F; //type const floatcout << "Enter radius of circle: "; //promptcin >> rad; //get radiusfloat area = PI * rad * rad; //find areacout << "Area is " << area << endl; //display answerreturn 0;}

Page 11: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type bool11

• Variables of type bool can have only two possible values: true and false.

• type bool is most commonly used to hold the results of comparisons.

Page 12: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Basic C++ Variable Types12

Page 13: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type Conversion13

• C++ treats expressions involving several different data types.

int main(){int count = 7;float avgWeight = 155.5F;double totalWeight = count * avgWeight;cout << “totalWeight=” << totalWeight << endl;return 0;}

Page 14: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type Conversion, cont.14

• When two operands of different types are encountered in the same expression, the lower-type variable is converted to the type of the higher-type variable.

Page 15: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type Conversion, cont.15

int count = 7;

float avgWeight = 155.5F;

double totalWeight = count * avgWeight;

• the int value of count is converted to type float and stored in a temporary variable before being multiplied by the float variable avgWeight.

• The result (still of type float) is then converted to double so that it can be assigned to the double variable totalWeight.

Page 16: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type Conversion, cont.16

Page 17: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Type Conversion, cont.

Casts17

• Cast convert a value from one type to another.

• CharVar = static_cast<char>(nIntVar);

• Example:

cout<< static_cast<int>('A'); // print ‘A’ as integer , 65

cout<< static_cast<char>(65); // print 65 as ‘A’

Page 18: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Increment and Decrement Operators, cont.

Page 19: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Increment and Decrement Operators, cont.

• When you increment (++) or decrement (--) a variable in a statement by itself, the pre-increment and post-increment forms have the same effect, and the pre-decrement and post-decrement forms have the same effect.

X++;++X;

• It’s only when a variable appears in the context of a larger expression that pre-incrementing the variable and post-incrementing the variable have different effects (and similarly for pre-decrementing and post-decrementing).

• The Next slide shows the precedence and associatively of the operators introduced to this point.

Page 20: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Increment and Decrement Operators, cont.

The precedence of the operators

Page 21: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Increment and Decrement Operators, cont.21

• totalWeight = avgWeight * ++count;

count is incremented first and then multiply with avgWeight

• totalWeight = avgWeight * count ++;

the multiplication would have been performed first, then count would have been incremented.

Page 22: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Increment and Decrement Operators, cont.22

Page 23: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Math Library Function23

// sqrt.cpp // demonstrates sqrt() library function#include <iostream> //for cout, etc.#include <math.h> <math.h> //for sqrt()using namespace std;int main(){double number, answer; //sqrt() requires type doublecout << “Enter a number: “;cin >> number; //get the numberanswer = sqrt(number); //find square rootcout << “Square root is “ << answer << endl; //display itreturn 0;}Enter a number: 1000Square root is 31.622777

Page 24: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Math Library Function, cont. 24

Page 25: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Math Library Function, cont.25

Page 26: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn26

• 18. True or false: It’s perfectly all right to use variables of different data types in the same arithmetic expression.

• 22. The increment operator increases the value of a variable by how much?

• 23. Assuming var1 starts with the value 20, what will the following code fragment print out?

cout << var1--;cout << ++var1;

Page 27: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn, cont.27

*1. Assuming there are 7.481 gallons in a cubic foot, write a program that asks the user to enter a number of gallons, and then displays the equivalent in cubic feet.

Page 28: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn, cont.28

*2. Write a program that generates the following table:

1990 135

1991 7290

1992 11300

1993 16200

Use a single cout statement for all output.

Page 29: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn, cont.29

*3. Write a program that generates the following output:

10

20

19

Use an integer constant for the 10, an arithmetic assignment operator to generate the 20, and a decrement operator to generate the 19.

Page 30: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Answers• 18. true• 22. one• 23. 20 and 20• *1. #include <iostream>

using namespace std;int main(){float gallons, cufeet;cout << “\nEnter quantity in gallons: “;cin >> gallons;cufeet = gallons / 7.481;cout << “Equivalent in cublic feet is “ << cufeet << endl;return 0;}

• *3. #include <iostream>using namespace std;int main(){int var = 10;cout << var << endl; // var is 10var *= 2; // var becomes 20cout << var- - << endl; // displays var, then decrements itcout << var << endl; // var is 19return 0;}

Page 31: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Lecture 4

• Chapter 2 – flow of controlChapter 2 – flow of control– Boolean expressions– Branching mechanisms– Loops– Decisions

31

Page 32: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Control Structures32

• Normally, statements in a program execute one after the other in the order in which they’re written.– Called sequential execution.

• Various C++ statements enable you to specify that the next statement to execute may be other than the next one in sequence.– Called transfer of control.

• All programs could be written in terms of only three control structures– the sequence structure– the selection structure and – the repetition structure

Page 33: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Boolean expressions33• Most branching statements are controlled by Boolean expressions.

• A Boolean expression is any expression that is either true or false. • The simplest form for a Boolean expression consists of two

expressions, such as numbers or variables, which are compared with one of the comparison operators as shown.

Page 34: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Relational Operators34

• A relational operator compares two values.• Our first program demonstrates relational operators in a

comparison of integer variables and constants.int main(){int numb;cout << “Enter a number: “;cin >> numb;cout << “numb<10 is “ << (numb < 10) << endl;cout << “numb>10 is “ << (numb > 10) << endl;cout << “numb==10 is “ << (numb == 10) << endl;return 0; }

Page 35: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Relational Operators, cont.35

• Here’s the output when the user enters 20:Enter a number: 20numb<10 is 0numb>10 is 1numb==10 is 0

• C++ compiler considers that a true expression true expression has the value 1value 1, while a false expression false expression has the value 0value 0.

Page 36: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Some expressions that use relational operators36

• int x= 44; //assignment statement• int y = 12; //assignment statement• bool b1= (x== y); //false• bool b2=(y <= 12); //true• bool b3=(x> y); //true• bool b4=(x>= 44); //true• bool b5=(y != 12); // false• bool b6=(7 < y); //true• bool b7=(0); //false (by definition)• bool b8=(44); //true (since it’s not 0)

• Although C++ generates a 1 to indicate true, it assumes that any value any value other than 0 (such as other than 0 (such as –7–7 or 44) is true or 44) is true; only 0 is falseonly 0 is false.

Page 37: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Building Boolean Expressions

• One can combine two comparisons in order to build a Boolean expression. – Ex. (2 < x) && (x < 7).– It means that the expression is true if x is greater than

2 and x is less than 7.• When two comparisons are connected using an && , the

entire expression is true, if both of the comparisons are true; otherwise, the entire expression is false.– Ex. (y < 0)||(y < 12)

• When two comparisons are connected using a || , the entire expression is true provided that one or both of the comparisons are true; otherwise, the entire expression is false.

Page 38: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Evaluating Boolean Expressions38

• #include <iostream> //for cout, etc.• using namespace std;

int main(){ int y;

bool Opor, Opand;

cout<<"enter number";

cin>>y;

Opor=(y<7)||(y>2);

cout<<"the result of the or operator is\n"<<Opor<<endl;

Opand=Opor=(y<7)&&(y>2);

cout<<"the result of the and operator is \n"<<Opand;

return 0;}

• C++ compiler considers that a true expression true expression has the value 1value 1, while a false expression false expression has the value 0value 0.

Page 39: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Evaluating Boolean Expressions cont.39

Page 40: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Precedence Rules40

• Boolean expressions (and arithmetic expressions) need not be fully parenthesized.

• If you omit parentheses, the default precedence will be used.

High precedence

low precedence

Page 41: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Precedence examples

• Arithmetic before logical – x + 1 > 2 || x + 1 < -3 means: – (x + 1) > 2 || (x + 1) < -3

• Short-circuit evaluation – (x >= 0) && (y > 1)

• Be careful with increment operators! – (x > 1) && (y++)

• Integers as boolean values – All non-zero values →true – Zero value → false

Page 42: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Flow of Control Statements

Three kinds of control structures

1. Sequential Structure

2. Selection structure (also known as Decisions or Branches )

– if– if-else– Switch

3. Repetition structure (also known as Iterative or Loops )– For– While– do-while

42

Page 43: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Selection Structure43

• C++ provides three types of selection statements:1. The if selection statement either

• performs (selects) an action if a condition (predicate) is true or

• skips the action if the condition is false.2. The if…else selection statement

• performs an action if a condition is true or • performs a different action if the condition is false.

3. The switch selection statement performs one of many different actions, depending on the value of an integer expression.

Page 44: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

if-statement

The if selection statement is a single-selection statement because it selects or ignores a single action (or, as we’ll soon see, a single group of actions).

if (expression)statement;

expressionexpression is any expression that can be evaluated as an integerinteger

a non-zero value is taken as “true”, a 0 value is taken as “false”

44

Page 45: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Multiple Statements in the if Body#include <iostream>using namespace std;int main(){

int x;cout << “Enter a number: “;cin >> x;if( x > 100 ){

cout << “The number “ << x;cout << “ is greater than 100\n”;

}return 0;}

Page 46: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example

#include <iostream>using namespace std;int main(){

int x;cout << “Enter a number: “;cin >> x;if( x > 100 )

cout << “That number is greater than 100\n”;return 0;

}

Page 47: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The syntax of if-statement

Page 48: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Multiple Statements in the if Body#include <iostream>using namespace std;int main(){

int x;cout << “Enter a number: “;cin >> x;if( x > 100 ){

cout << “The number “ << x;cout << “ is greater than 100\n”;

}return 0;}

Page 49: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

IF-THEN-ELSE

Page 50: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Control Structures: if…else statements

The if…else statement is called a double-selection statement because it selects between two different actions (or groups of actions).

if (expression)

statement1

else

statement2 statement1 is a statement or group of statements executed

if expression evaluates to a non-zero value. statement2 is a statement or group of statements executed

if expression evaluates to a zero value. statement2 is needed only if the optional else

keyword is present.

50

Page 51: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

syntax

Page 52: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example 1

int main(){

int x;cout << “\nEnter a number: “;cin >> x;if( x > 100 )

cout << “That number is greater than 100\n”;else

cout << “That number is not greater than 100\n”;return 0;}

Page 53: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Compare and branch

• A program can instruct a computer to compare two items and do something based on a match or mismatch which, in turn, redirect the sequence of programming instructions.

• There are two forms: – IF-THEN – IF-THEN-ELSE

Page 54: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example

• Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.

• Hint: – the max grade is 100. – The student is considered pass if the average

>= 50%

Page 55: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example

• Write an algorithm to determine a student’s final grade and indicate whether it is A, B, C, D or F .

• Hint: – the max grade is 100.– 90 and above gets "A“.– 80-89 gets "B“.– 70-79 gets "C“.– 60-69 gets "D" .– less than 60 gets "F"

Page 56: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example 4

if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A";else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F";

Page 57: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Matching the else -- Be careful with if/else

• You can inadvertently match an else with the wrong ifif (fuelGaugeReading < 0.75) if (fuelGaugeReading < 0.25) cout << “Fuel is very low. << endl;else cout << “Fuel over 3/4, don’t stop!” << endl; If the reading is between 0.25 and 0.74, what is displayed?

This does not produce the desired effect.• elseelse is matched with the wrong ifif. The indentation would lead you

to believe that the elseelse is matched with the first iffirst if, but in fact it goes with the second ifsecond if.

• RuleRule: An An elseelse is matched with the is matched with the last if last if that doesn’t have its that doesn’t have its own else.own else.

• This is why scope delimitersscope delimiters can be very important

Page 58: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Matching the else -- Be careful with if/else, cont.

• If you really want to pair an else with an earlier if, you can use braces around the inner if, the right way:

if (fuelGaugeReading < 0.75)

{{ if (fuelGaugeReading < 0.25) cout << “Fuel is very low. << endl;

}}else cout << “Fuel over 3/4, don’t stop!” << endl;

Now, we’ll get the desired results. You might want to always use scope delimiters to avoid confusion

and mistakes down the road.

Page 59: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Matching the else -- Be careful with if/else, cont.

59

Page 60: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The else...if Construction, cont.

if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A";

else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B";

else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C";

else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D";

else // less than 60 gets "F" cout << "F";

Here we only have a single line of code to be executed when the if statement is true. No braces ({,}) are used.

Page 61: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Be careful with the assignment expression

if (x = 0)

cout << “It’s zero” << endl;

else

cout << “No, it’s not zero!” << endl;

WARNING!!!!!WARNING!!!!! While the “if” statement above may look perfectly fine it contains a

very common flaw. The assignment operator (=) is not used to test for equality. “x=0” is an expression which having the side effect of storing the

value 0 in the variable “x”. As an expression which evaluates to “0” it will always cause the

“else” branch to be executed.

61

Page 62: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Be careful with the assignment expression , cont.

if (x == 0)

cout << “It’s zero” << endl;

else

cout << “No, it’s not zero!” << endl;

This is the correct way, use the equality operator (==)

62

Page 63: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Switch Statement The switch selection statement is called a

multiple-selection statement because it selects among many different actions (or groups of actions).

63

Page 64: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Switch Statement

int x;

cin >> x;

if (x = = 0)

cout << “x is zero” << endl;

else if (x = = 1)

cout << “x is one” << endl;

else if (x = = 2)

cout << “x is two” << endl;

else

cout << “x is not 0,1 or 2” << endl; There is nothing wrong nothing wrong with this code, but it is inefficientinefficient.

Consider the code using nested “else … if”64

Page 65: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Switch Statement, cont.

int x;

cin >> x; // read in number from console

switch(x)

{

case 0:

cout << “x is zero” << endl;

break;

case 1:

cout << “x is one” << endl;

break;

case 2:

cout << “x is two” << endl;

break;

default:

cout << “x is not 0,1 or 2” << endl;

}

A better way:65

Page 66: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Syntax of the switch statement

Page 67: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

What happens if break is omitted in a given case statement?

• The break keyword causes the entire switch statement to exit.

• Don’t forget the break; without it, control passes down to the statements for the next case.

Page 68: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Case

• You can’t say

case a<3:

• The case constant must be an integer or character constant, like 3 or ‘a’, or an expression that evaluates to a constant, like ‘a’+32.

Page 69: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Flow of Control Statements

Three kinds of control structures

1. Sequential Structure

2. Selection structure (also known as Decisions or Branches )

– if– if-else– Switch

3. Repetition structure (also known as Iterative or Loops )– For– While– do-while

69

Page 70: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

For

While

Do..while

Repetition Structure70

Page 71: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Repetition Structure (or called Loops)71

• Loops cause a section of your program to be repeated a certain number of times.

• The repetition continues while a condition is true. When the condition becomes false, the loop ends and control passes to the statements following the loop.

• These are the while, do…while and for statements.• The while and for statements perform the action (or group of

actions) in their bodies zero or more times.• The do…while statement performs the action (or group of

actions) in its body at least once.

Page 72: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The for loopfor (cntr = init; cntr <=final; cntr += incr)

A for loop contains three distinct parts: an initialization a test for completion an increment operation

Initialization The “counter” variable is often declared right in the for statement. You have a chance here to set an initial value

Test When this expression evaluates to false (0), the for loop

terminates. Increment

An operation which is performed at the “end” of the for loop. Let’s see an example...

72

Page 73: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The for loop, cont.73

Page 74: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The syntax of the for loop74

Page 75: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

The for loop, cont.

int i; //define a loop variablefor(i=0; i<15; i++) //loop from 0 to 14,

cout << i * i << “ “; //displaying the square of i

Initialize -- i = 0 Test -- i < 15 Increment -- i++

Here’s the output:0 1 4 9 16 25 36 49 64 81 100 121 144 169 196

Example 1:Example 1: Displays the squares of the numbers from 0 to 14:75

Page 76: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Multiple Statements in the Loop Body76• Multiple statements are delimited by braces.• Example 2:Example 2: prints out the cubes of the numbers from 1 to 10, using a two-

column format.

// cubelist.cpp // lists cubes from 1 to 10#include <iostream>#include <iomanip> //for setwusing namespace std;int main(){int numb; //define loop variablefor(numb=1; numb<=10; numb++) //loop from 1 to 10{

cout << setw(4) << numb; //display 1st columnint cube = numb*numb*numb; //calculate cubecout << setw(6) << cube << endl; //display 2nd column

}return 0; }

Page 77: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Multiple Statements in the Loop Body, cont.77

• Here’s the output from the program:1 12 83 274 645 1256 2167 3438 5129 72910 1000

Page 78: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Blocks and Variable Visibility78

• The loop body, which consists of braces delimiting several statements, is called a blockblock of code.

• One important aspect of a block is that a variable defined inside the block is not visible outside it.

• VisibleVisible means that program statements can access or “see” the variable.

• In CUBELIST we define the variable cube inside the block, in the statement

int cube = numb*numb*numb;

You can’t access this variable outside the block; it’s only visible within the braces.

• One advantage of restricting the visibility of variables is that the same variable name can be used within different blocks in the same program.

Page 79: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Decrements the loop variable79

• The “increment” of a for statement can be negative, in which case the loop actually counts downward.

• Example 3:Example 3: FACTOR program asks the user to type in a number, and then calculates the factorial of this number.– The factorial is calculated by multiplying the original

number by all the positive integers smaller than itself.– Thus the factorial of 5 is 5*4*3*2*1, or 120.

Page 80: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Decrements the loop variable, cont.80// factor.cpp// calculates factorials, demonstrates FOR loop#include <iostream>using namespace std;int main(){unsigned int numb;unsigned long fact=1; //long for larger

numberscout << “Enter a number: “;cin >> numb; //get numberfor(int j=numb; j>0 ; j--) //multiply 1 by

fact *= j; //numb, numb-1, ..., 2, 1cout << “Factorial is “ << fact << endl;return 0;}

Page 81: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Decrements the loop variable, cont.81

• The following output shows how large factorials can be, even for small input numbers:

Enter a number: 10Factorial is 3628800

• The largest number you can use for input is 12. You won’t get an error message for larger inputs, but the results will be wrong, as the capacity of type long will be exceeded.

Page 82: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Variables Defined in “for Statements’82

for (int j=numb; j>0; j--)

• If the initialization expression declares (or called defined) the control variable, the control variable can be used only in the body of the for statement—the control variable will be unknown outside the for statement.

• The control variables are visible in the loop body only.• This restricted use of the control variable name is known as

the variable’s scope.• The scope of a variable specifies where it can be used in a

program.

Page 83: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Multiple Initialization and Test Expressions83

• You can put more than one expression in the initialization part and increment part of the for statement, separating the different expressions by commas.

for (int i = 0, j = 0; j < 5 ; i += 2, j++)cout<< i << “ “ << j <<endl;

Page 84: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Empty Initialization

int i=0;for ( ; i < 10; i++)

cout<< i ;

• One might omit the initialization expression if the control variable is initialized earlier in the program.

84

Page 85: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Empty increment

One might omit the increment expression if the increment is calculated by statements in the body of the for or if no increment is needed.

for (int i=0 ; i < 10; ){

cout<< i ;i++;

}

• The increment expression in the for statement acts as a stand-alone statement at the end of the body of the for.

85

Page 86: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Empty statements

for (int i = 1000; i >= 0 ; i--) ; /* empty statement */ /* null-statement */

86

Page 87: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

infinite loop

for (;;)

{

// Loop forever!

}

The three expressions in the for statement header are optional (but the two semicolon separators are required).

If the loop Continuation Condition is omitted, C++ assumes that the condition is true, thus creating an infinite loopinfinite loop.

same as using while(true);

Any (or all) of the three statements in a for loop may be omitted:87

Page 88: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Examples Using the for Statement

• Vary the control variable from 1 to 100 in increments of 1.• for ( int i = 1; i <= 100; i++ )

• Vary the control variable from 100 down to 1 in decrements of 1.• for ( int i = 100; i >= 1; i-- )

• Vary the control variable from 7 to 77 in steps of 7.• for ( int i = 7; i <= 77; i += 7 )

• Vary the control variable from 20 down to 2 in steps of -2.• for ( int i = 20; i >= 2; i -= 2 )

• Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.

• for ( int i = 2; i <= 17; i += 3 )• Vary the control variable over the following sequence of values: 99, 88,

77, 66, 55.• for ( int i = 99; i >= 55; i -= 11 )

Page 89: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Example 4Example 4

• Uses a for statement to sum the even integers from 2 to 20.

89

Page 90: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn (1/3)90

• 1. A relational operatora. assigns one operand to another.b. yields a Boolean result.c. compares two operands.d. logically combines two operands.

• 2. Write an expression that uses a relational operator to return true if the variable X is not equal to Y.

• 3. Is –1 true or false?

Page 91: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn (2/3)91

• 5. In a for loop with a multistatement loop body, semicolons should appear following

a. the for statement itself.b. the closing brace in a multistatement loop body.c. each statement within the loop body.d. the test expression.

• 7. Write a for loop that displays the numbers from 100 to 110.

Page 92: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Your Turn (3/3)92

• 8. A block of code is delimited by ________________.

• 9. A variable defined within a block is visiblea. from the point of definition onward in the program.b. from the point of definition onward in the function.c. from the point of definition onward in the block.d. throughout the function.

• Write a switch statement that prints Yes if a variable ch is ‘y’, prints No if ch is ‘n’, and prints Unknown response otherwise.

Page 93: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

H.W.93

• Write a program that uses for statement to ask the user to enter a series of 10 numbers. Then the program should compute and print the average of them.

Page 94: Lecture 3 Agenda Text book “absolute C++” Chapter1:C++ basics cont. –Variable types Char, string, float, const, boolean. –Type conversion –Math operations

Answers • 1- b,c.• 2- X!=Y.• 3-True.• 5- c,d.• 7- for(int j=100; j<=110; j++)

cout << endl << j;

• 8- braces (curly brackets).• 9- c.21. switch(ch)

{case ‘y’:cout << “Yes”;break;case ‘n’:cout << “No”;break;default:cout << “Unknown response”;}