View
218
Download
0
Category
Tags:
Preview:
Citation preview
RECAPWe have learnt: Variables and Data Types
– Declaration and initialization
– int, char, double, float, long, short, strings
– Size and ranges of data types
– Scope of variables, global and local variables
– Limited to the block where they are declared
– Constants using #define and const
Relational Operators – AND, OR, NOT, &&, ||,!
RECAPWe have learnt: Compound assignment
– +=, -=, *=, /=, %=
– Value += increase Value = Value + increase
– Value -= increase Value = Value - increase
Increase / Decrease ++ --– C++;
– C+=1;
– C=C+1
– Can be used both as prefix or suffix
RECAP
We have learnt: Creating functions Calling functions Passing arguments Functions have prototypes (or signatures) that indicate to both the compiler and the programmer how to use the function
RECAPWe have learnt: Decision Making using if and if…else selection statements to choose among alternative actions– Compound statements or blocks
– A block can be placed anywhere a single statement can be placed
– Nested If else
– Dangling else, else is associated with the last if
OBJECTIVES
In this class you will learn: Basic problem-solving techniques. To use the while repetition statement to execute statements in a program repeatedly
To use the for repetition statement To use Do-While statements More functions
Introduction• Before writing a program
– Have a thorough understanding of problem
– Carefully plan your approach for solving it• While writing a program
– Know what “building blocks” are available
– Uptill now we have been focusing on the building blocks
– Use good programming principles
Algorithms
•Any solvable computing problem can be solved by the execution of a series of actions in a specific order
•Algorithms are the procedure for solving a problem in terms of – The actions to execute– The order in which these actions execute
•Program control– Specifies the order in which actions execute in a program
– This is performed in C++ through control statements
Pseudocode•Pseudocode
–Artificial, informal language used to develop algorithms•Used to think out program before coding
–Easy to convert into C++ program
–Similar to everyday English•Only executable statements
–No need to declare variables
–Not executed on computers
1 Prompt the user to enter the first integer
2 Input the first integer
3
4 Prompt the user to enter the second integer
5 Input the second integer
6
7 Add first integer and second integer, store result
8 Display result
Control Structures
• Normal statements in a program – Sequential execution– Statements executed in sequential order
• Transfer of control– some statements allow a programmer to specify that
the next statement executed is not the next one in sequence
• Structured programming– Eliminated goto statements– Clearer, easier to debug
• Only three control structures in C++– Sequence structure
– Programs executed sequentially by default– Selection structures
– if, if…else, switch – Repetition structures
– while, do…while, for
Selection statements
•Three types of selection statements– if
• Single selection statement
– if…else• Double selection statement• Selects between two different actions
– Switch statement• Multiple selection statement • Selects between many different actions
Conditional Operator ?:• Closely related to if…else statements• Three operands• First operand is a condition• Second operand is the value of the entire expression if the condition is true
• Third operand is the value of the entire expression if the condition is false
cout << ( grade >= 60 ? "Passed" : "Failed" ); • Values in the conditional expression can also be actions to execute
grade >= 60 ? cout << "Passed" : cout << "Failed";
Meaning: If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed"
4.6 if…else Double-Selection Statement (Cont.)
•Ternary conditional operator (?:)– Three arguments (condition, value if true, value if false)
•Code could be written:– cout << ( grade >= 60 ? “Passed” : “Failed” );
Condition Value if true Value if false
Repetition statements•Three types of repetition statements in C++•Enable programs to perform an operation repeatedly as long as a condition is true– While Loop
•Performs the actions zero or more times– For Loop
•Performs the actions in the body zero or more times
– Do…While Loop•Performs the actions in the body at least once
Repetition statements
• Counter-controlled repetition requires:– Name of a control variable (loop counter)
– Initial value of the control variable
– Loop-continuation condition that tests for the final value of the control variable
– Increment/decrement of control variable at each iteration
Shopping trip example
While there are more items on my shopping list Purchase next item and cross it off my list
• Condition: While there are more on my list• It can be either true or false
Shopping trip example
While there are more items on my shopping list Purchase next item and cross it off my list
• Condition: While there are more on my list• It can be either true or false• If it is true
– Purchase next item and cross it off my list
Shopping trip example
While there are more items on my shopping list Purchase next item and cross it off my list
• Condition: While there are more on my list• It can be either true or false• If it is true
– Purchase next item and cross it off my list• The action will be performed repeatedly while the condition is true
• This action constitutes the body of the while loop• It can be a single statement or a block {}
Shopping trip example
While there are more items on my shopping list Purchase next item and cross it off my list
• Condition: While there are more on my list• It can be either true or false• If it is true
– Purchase next item and cross it off my list• The action will be performed repeatedly while the condition is true
• This action constitutes the body of the while loop• It can be a single statement or a block {}• Once the condition is false, the loop would no longer be executed and execution will start from the next statement
1 // Fig. 5.1: fig05_01.cpp
2 // Counter-controlled repetition.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int counter = 1; // declare and initialize control variable
10
11 while ( counter <= 10 ) // loop-continuation condition
12 {
13 cout << counter << " ";
14 counter++; // increment control variable by 1
15 } // end while
16
17 cout << endl; // output a newline
18 return 0; // successful termination
19 } // end main 1 2 3 4 5 6 7 8 9 10
Outline
•fig05_01.cpp
•(1 of 1)
Control-variable name is counter with variable initial value 1
Condition tests for counter’s final value
Increment the value in counter
• While the while loop beings execution, counter is 1• Each repetition of the loop, counter is incremented • The loop executes till the counter <= 10• Loop executes 10 times• What if we do not increase the counter by 1?
Common Programming Error
• Floating-point values are approximate, so controlling counting loops with floating-point variables can result in imprecise counter values and inaccurate tests for termination.
While Example code: down-counter.cpp1: int main()2: {3: int counter = 10; // Initialize variable4:5: while ( counter > 0 ) // loop continuation condition6: {7: cout << counter << " ";8: counter = counter - 1; // decrease control counter by 19: }10: return 0;11: }• While the while loop beings execution, counter is 10• Each repetition of the loop, the value of counter is reduced by 1• The loop executes till the counter > 0• Loop executes 10 times
while ( ++counter <= 10 ) cout << counter << " ";
for Repetition Statement
•for repetition statement– Specifies counter-controlled repetition details in a single
line of code
1 // Fig. 5.2: fig05_02.cpp
2 // Counter-controlled repetition with the for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 // for statement header includes initialization,
10 // loop-continuation condition and increment.
11 for ( int counter = 1; counter <= 10; counter++ )
12 cout << counter << " ";
13
14 cout << endl; // output a newline
15 return 0; // indicate successful termination
16 } // end main
1 2 3 4 5 6 7 8 9 10
Outline
Control-variable name is counter with initial value 1
Condition tests for counter’s final value
Increment for counter
• Variable counter is declared and initialized on line 11• The the condition counter <=10 is checked • Condition is true so goes onto line 12• Then counter ++ is executed, incrementing the counter• Loop begins again from line 11• If condition is false, program continues to line 14
Good Programming Practice
Using the final value in the condition of a while or for statement and using the <= relational operator will help avoid off-by-one errors. For a loop used to print the values 1 to 10, for example, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which is an off-by-one error) or counter < 11 (which is nevertheless correct). Many programmers prefer so-called zero-based counting, in which, to count 10 times through the loop, counter would be initialized to zero and the loop-continuation test would be counter < 10.
for Repetition Statement (Cont.)
• General form of the for statement– for ( initialization; loopContinuationCondition; increment )
statement;
• Can usually be rewritten as:– initialization;
while ( loopContinuationCondition )
{ statement; increment; }
• If the control variable is declared in the initialization expression– It will be unknown outside the for statement
Common Programming Error
• When the control variable of a for statement is declared in the initialization section of the for statement header, using the control variable after the body of the statement is a compilation error.
Good Programming Practice
Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they should execute only once, like initialization statements) or in the loop body (if they should execute once per repetition, like incrementing or decrementing statements).
for Repetition Statement (Cont.)
• The initialization and increment expressions can be comma-separated lists of expressions– These commas are comma operators
• Comma operator has the lowest precedence of all operators
– Expressions are evaluated from left to right
– Value and type of entire list are value and type of the rightmost expressions
Common Programming Error
• Using commas instead of the two required semicolons in a for header is a syntax error.
Common Programming Error
Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for statement an empty statement. This is usually a logic error.
Software Engineering Observation
Placing a semicolon immediately after a for header is sometimes used to create a so-called delay loop. Such a for loop with an empty body still loops the indicated number of times, doing nothing other than the counting. For example, you might use a delay loop to slow down a program that is producing outputs on the screen too quickly for you to read them. Be careful though, because such a time delay will vary among systems with different processor speeds.
Error-Prevention Tip
Although the value of the control variable can be changed in the body of a for statement, avoid doing so, because this practice can lead to subtle logic errors.
Examples Using the for Statement
•for statement examples– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in increments of -1• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in steps of 7• for ( int i = 7; i <= 77; i += 7 )
– Vary control variable from 20 to 2 in steps of -2• for ( int i = 20; i >= 2; i -= 2 )
– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20• for ( int i = 2; i <= 20; i += 3 )
– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0• for ( int i = 99; i >= 0; i -= 11 )
Common Programming Error 5.6
Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as incorrectly using i <= 1 instead of i >= 1 in a loop counting down to 1) is usually a logic error that yields incorrect results when the program runs.
1 // Fig. 5.5: fig05_05.cpp
2 // Summing integers with the for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int total = 0; // initialize total
10
11 // total even integers from 2 through 20
12 for ( int number = 2; number <= 20; number += 2 )
13 total += number;
14
15 cout << "Sum is " << total << endl; // display results
16 return 0; // successful termination
17 } // end main Sum is 110
Outline
Vary number from 2 to 20 in steps of 2
Add the current value of number to total
do…while Repetition Statement
•do…while statement– Similar to while statement
– Tests loop-continuation after performing body of loop• Loop body always executes at least once
Good Programming Practice
• Always including braces in a do...while statement helps eliminate ambiguity between the while statement and the do...while statement containing one statement.
1 // Fig. 5.7: fig05_07.cpp
2 // do...while repetition statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int counter = 1; // initialize counter
10
11 do
12 {
13 cout << counter << " "; // display counter
14 counter++; // increment counter
15 } while ( counter <= 10 ); // end do...while
16
17 cout << endl; // output a newline
18 return 0; // indicate successful termination
19 } // end main 1 2 3 4 5 6 7 8 9 10
OutlineDeclare and initialize control variable counter
do…while loop displays counter’s value before testing for counter’s final value
break and continue Statements
•break/continue statements– Alter flow of control
•break statement – Causes immediate exit from control structure
– Used in while, for, do…while or switch statements
•continue statement – Skips remaining statements in loop body
• Proceeds to increment and condition test in for loops
• Proceeds to condition test in while/do…while loops
– Then performs next iteration (if not terminating)
– Used in while, for or do…while statements
1 // Fig. 5.13: fig05_13.cpp
2 // break statement exiting a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int count; // control variable also used after loop terminates
10
11 for ( count = 1; count <= 10; count++ ) // loop 10 times
12 {
13 if ( count == 5 )
14 break; // break loop only if x is 5
15
16 cout << count << " ";
17 } // end for
18
19 cout << "\nBroke out of loop at count = " << count << endl;
20 return 0; // indicate successful termination
21 } // end main 1 2 3 4 Broke out of loop at count = 5
Outline
Loop 10 times
Exit for statement (with a break) when count equals 5
1 // Fig. 5.14: fig05_14.cpp
2 // continue statement terminating an iteration of a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 for ( int count = 1; count <= 10; count++ ) // loop 10 times
10 {
11 if ( count == 5 ) // if count is 5,
12 continue; // skip remaining code in loop
13
14 cout << count << " ";
15 } // end for
16
17 cout << "\nUsed continue to skip printing 5" << endl;
18 return 0; // indicate successful termination
19 } // end main 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5
Outline
Loop 10 times
Skip line 14 and proceed to line 9 when count equals 5
Good Programming Practice
Some programmers feel that break and continue violate structured programming. The effects of these statements can be achieved by structured programming techniques we soon will learn, so these programmers do not use break and continue. Most programmers consider the use of break in switch statements acceptable.
Performance Tip
The break and continue statements, when used properly, perform faster than do the corresponding structured techniques.
Factorial Program#include <iostream>using namespace std;int Factorial (int);
int main(){
int maximum; // Maximum numberint counter = 0; // initialize counter
cout << " Enter max number for factorial "<< endl;cin >> maximum;
while (counter <= maximum){
cout << "Factorial of "<< counter cout << " = " << Factorial(counter)<<endl;counter++;
}return 0;}
Factorial Programint Factorial(int number){
int temp = 1;int count = 0;while (count<number){
count = count + 1;temp = temp * count;
}return temp;
}
Factorial ProgramEnter max number for factorial 18Factorial of 0 = 1Factorial of 1 = 1Factorial of 2 = 2Factorial of 3 = 6Factorial of 4 = 24Factorial of 5 = 120Factorial of 6 = 720Factorial of 7 = 5040Factorial of 8 = 40320Factorial of 9 = 362880Factorial of 10 = 3628800Factorial of 11 = 39916800Factorial of 12 = 479001600Factorial of 13 = 1932053504 6227020800Factorial of 14 = 1278945280 87178291200Factorial of 15 = 2004310016Factorial of 16 = 2004189184Factorial of 17 = -288522240Factorial of 18 = -898433024
Recommended