Upload
andra-mccarthy
View
217
Download
2
Tags:
Embed Size (px)
Citation preview
Lecture 3Agenda
• 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;
• }
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
ASCII Table
String variable
• In order to use string variable type, we have to use special library called “String”.
Cin>> with string variable type
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;• }
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
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
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;}
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.
Basic C++ Variable Types12
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;}
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.
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.
Type Conversion, cont.16
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’
Increment and Decrement Operators, cont.
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.
Increment and Decrement Operators, cont.
The precedence of the operators
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.
Increment and Decrement Operators, cont.22
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
Math Library Function, cont. 24
Math Library Function, cont.25
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;
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.
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.
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.
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;}
Lecture 4
• Chapter 2 – flow of controlChapter 2 – flow of control– Boolean expressions– Branching mechanisms– Loops– Decisions
31
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
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.
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; }
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.
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.
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.
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.
Evaluating Boolean Expressions cont.39
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
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
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
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.
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
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;}
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;
}
The syntax of if-statement
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;}
IF-THEN-ELSE
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
syntax
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;}
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
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%
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"
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";
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
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.
Matching the else -- Be careful with if/else, cont.
59
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.
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
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
Switch Statement The switch selection statement is called a
multiple-selection statement because it selects among many different actions (or groups of actions).
63
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
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
Syntax of the switch statement
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.
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.
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
For
While
Do..while
Repetition Structure70
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.
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
The for loop, cont.73
The syntax of the for loop74
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
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; }
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
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.
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.
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;}
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.
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.
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;
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
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
Empty statements
for (int i = 1000; i >= 0 ; i--) ; /* empty statement */ /* null-statement */
86
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
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 )
Example 4Example 4
• Uses a for statement to sum the even integers from 2 to 20.
89
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?
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.
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.
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.
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”;}