生查子 ~ 歐陽修 去年元夜時,花市燈如晝, 月上柳梢頭,人約黃昏後; 今年元夜時,月與燈依舊, 不見去年人,淚濕春衫袖。

Slides:



Advertisements
Similar presentations
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
Advertisements

1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Do/while Structure (L15) * do/while structure * break Statement * continue Statement * Loop Programming Techniques - Interactive input within a loop -
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 4 Program Control Statements
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Chapter 4 Selection Structures: Making Decisions.
Chapter 02 (Part III) Introduction to C++ Programming.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else.
Chapter 05 (Part III) Control Statements: Part II.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Decision Making in Programs.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
The Ohio State University
ㅎㅎ Fifth step for Learning C++ Programming Homework 1 Homework 2
Introduction to Computer Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 3 Selection Statements
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
Control Structures Sequential execution Transfer of control
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
The setw Manipulator The setw manipulator causes the number (or string) that follows it in the stream to be printed within a field n characters wide, where.
Selection (also known as Branching) Jumail Bin Taliba by
Bill Tucker Austin Community College COSC 1315
Chapter 4 Loops DDC 2133 Programming II.
Engineering Problem Solving with C++, Etter/Ingber
Chapter 2.1 Control Structures (Selection)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 2.2 Control Structures (Iteration)
Control Statements Kingdom of Saudi Arabia
Looping.
Chapter 8 Repetition Statements
Conditinoal Constructs Review
- Additional C Statements
CS1100 Computational Engineering
Additional Control Structures
Arrays Kingdom of Saudi Arabia
Chapter 7 Additional Control Structures
Conditinoal Constructs Review
Chapter 6 Decision Making and Looping
Chapter 4 - Program Control
Chapter 7 Conditional Statements
Chapter 2.2 Control Structures (Iteration)
Computing Fundamentals
2.6 The if/else Selection Structure
Decisions, decisions, decisions
Control Statements Paritosh Srivastava.
生查子 ~ 歐陽修 去年元夜時,花市燈如晝, 月上柳梢頭,人約黃昏後; 今年元夜時,月與燈依舊, 不見去年人,淚濕春衫袖。
ㅎㅎ Fifth step for Learning C++ Programming Homework 1 Homework 2
Presentation transcript:

生查子 ~ 歐陽修 去年元夜時,花市燈如晝, 月上柳梢頭,人約黃昏後; 今年元夜時,月與燈依舊, 不見去年人,淚濕春衫袖。

Chapter 3 Decisions and Loops

Relational Operators Compare the values of two operands, and return < Less than > Greater than == Equal to <= Less than or equal to >= Greater than or equal to != Not equal to Compare the values of two operands, and return true false

Example of Logical Expressions Suppose two integer variables i = 10, j = -5 The following expressions are all true: i > j i != j j > -8 i <= j + 15 cout << (i < j) Displays “0” (implicit type conversion, P.63) cout << (i > j) Displays “1” (implicit type conversion)

True or False #include <iostream> int main() { int a = 0; int b = 10; if (a = b) std::cout << "True \n"; else std::cout << "False \n"; return 0; }

True or False #include <iostream> int main() { int a = 10; int b = 0; if (a = b) std::cout << "True \n"; else std::cout << "False \n"; return 0; }

Flowcharts for three constructs

The if Statement The condition to be tested appears in parenthesis if (letter == 'A') cout << "Apple"; A block of statements between braces could replace the single statement. if (letter == 'A') { cout << "Apple"; letter = 'a'; } Nested if Statement (P.94)

The if … else … Statement if (number % 2) cout << "Odd" << endl; else cout << "Even" The condition express (number % 2) is equivalent to (number %2 != 0) A non-zero value is interpreted as true (implicit cast). A zero value result casts to false.

Logical Operators if ((letter >= 'A') && (letter <= 'Z')) cout << "This is a capital letter."; if ( !(i > 5) ) cout << "i is not greater than 5\n"; && Logical AND || Logical OR ! Logical negation (NOT)

The Conditional Operator (P.103) c = a>b ? a : b ; // set c to the maximum of // a and b Sometimes called the ternary operator. condition ? expression1 : expression2 if (a > b) c = a; else c = b;

Output Control cout << endl << "We have " << nCakes << ((nCakes > 1) ? "s." : ".") << endl; nCakes = 1 We have 1 cake. nCakes = 2 We have 2 cakes.

HSR Ticket Machine

Its Code cin >> nTicket; cout << "The transaction will issue " << nTicket << " ticket(s)." << endl; Try to modify it using the “conditional operator” of C language.

The switch Statement if (option >= 'a' && option <= 'z') switch (option) { case 'a': cout << "Append" << endl; break; case 'd': cout << "Delete" << endl; case 'q': cout << "Quit" << endl; default: cout << "You entered a wrong option."; }

Saves the Trouble of Multiple-if if (option == 'a') cout << "Append" << endl; else if (option == 'd') cout << "Delete" << endl; if (option == 'q') cout << "Quit" << endl; cout << "You entered a" << " wrong option." << endl;

Ex3_06.cpp (P.107) An elegant example to demonstrate the power of C language. switch (letter * (letter >= 'a' && letter <= 'z')) { case 'a': case 'e': case 'i': case 'o': case 'u': cout << "You entered a vowel."; break; case 0: cout << "That is not a small letter."; default: cout << "You entered a consonant."; }

Unconditional Branching myLabel: cout << "myLabel is here"; . goto myLabel; Whenever possible, you should avoid using gotos in your program.

Loop (Ex3_07 in P.110)

Loop (Ex3_07 in P.110) int i = 1, sum = 0; const int max = 5; KevinLabel: sum +=i; if (++i <= max) goto KevinLabel; cout << "sum=" << sum << endl << "i = " << i << endl; i = 5, sum = 15 i = 4, sum = 10 i = 2, sum = 3 i = 1, sum = 1 i = 3, sum = 6

The for Loop for (i=1; i<=6; i++) cout << i << endl;

The for Loop (2) for (i=1; i<=6; i+=2) cout << i << endl; 2

Using the for Loop for Summation int i = 0, sum = 0; const int max = 5; for (i=1; i<=max; i++) sum += i; General form of the for loop: for (initializing_expression; test_expression; increment_expression) loop_statement; i = 4, sum = 10 i = 5, sum = 15 i = 2, sum = 3 i = 1, sum = 1 i = 3, sum = 6

Exercises: Fibonacci Sequence Sum of Numbers Write a program that computes the nth Fibonacci number where n is a value input by the user. Sum of Numbers Write a program to find the sum of the first N natural numbers, where the value of N is provided by the user.

Nested for Loop const int N = 5; int i, j; for (i=1; i<=N; i++) { for (j=1; j<=i; j++) cout << '*'; cout << endl; } A block of statements between braces could replace the single loop_statement. * ** *** **** *****

Increment/Decrement of the Counter for (i=1; i<=N; i++) { for (j=1; j<=i; j++) cout << '*'; cout << endl; } for (i=N; i>=1; i--) * ** *** **** *****

ASCII Table #include <iostream> using std::cout; using std::endl; int main() { unsigned char c; for (c=32; c<=126; c++) if (c % 8 == 0) cout << endl; cout << c << '\t'; } cout << endl; return 0;

ASCII Table (2) #include <iostream> #include <iomanip> using std::cout; using std::endl; using std::setw; // P.49 int main() { unsigned char c; for (c=32; c<=126; c++) if (c % 8 == 0) cout << endl; cout << setw(3) << static_cast<int>(c) << ' '; cout << c << '\t'; } cout << endl; return 0;

Supplementary: Flowchart

START Summing Up Odd Numbers sum0 i 1 #include <iostream> using std::cout; using std::endl; int main() { int i; int sum=0; for (i=1; i<=9; i+=2) sum += i; cout << sum << endl; return 0; } NO i9 YES sumsum+i ii+2 sum END

Variation on the for Loop Declare the counter i within the loop scope. The loop statement can be empty. for (int i = 1; i<=max; sum+= i++) ; You can omit the initialization expression int i = 1; for (; i <= max; i++) sum += i; Use the comma operator (P.60) to specify several expressions: for (i=0, power=1; i<=max; i++, power *=2)

break vs. continue The keyword continue allows you to skip the remainder of the current iteration in a loop and go straight to the next iteration. The keyword break provides an immediate exit from a loop. (See P.116 and P.117)

Other Types of Loop The while loop The do-while Loop while (condition) loop_statement; Ex3_12.cpp on P.121 The do-while Loop do { loop_statements; } while (condition); Always executed at least once. You may see infinite loops like while (true) { … } while (1) { … } for (;;) { … }

Greatest Common Divisor (1) START Greatest Common Divisor (1) A, B Imin(A,B) #include <iostream> using std::cout; using std::cin; int main() { int a, b, i; cin >> a >> b; for (i=(a>b?b:a); i>1; i--) if (a % i == 0 && b % i == 0) cout << i << " is the gcd of " << a << " and " << b << std::endl; break; } return 0; A % I == 0 AND B % I == 0 NO II-1 YES I is the gcd of A and B END

Greatest Common Divisor (2) START Greatest Common Divisor (2) A, B I2 C 1 #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int a, b; int i =2, c = 1; cin >> a >> b; while (i<=a && i<=b) if (a % i == 0 && b % i == 0) a = a / i; b = b / i; c = c * i; } else i = i + 1; cout << "GCD is " << c << endl; return 0; I > A OR I > B YES NO A % I == 0 AND B % I == 0 NO YES AA/I B B/I CC*I II+1 C is the gcd of A and B END

Greatest Common Divisor (3) #include <iostream>    using std::cin; using std::cout; using std::endl; int main() {     int a, b, temp;     cout << "a=? ";     cin >> a;     cout << "b=? ";     cin >> b;     if (a==0 && b==0)     {         cout << "I don't know how to calculate their gcd.\n";         return 1;     }     cout << "The greatest common divisor of " << a << " and " << b << " is ";     while (b != 0)     {         a %= b;         temp = b; b = a; a = temp;    // swap a,b     }     cout << a << endl;     return 0; }

Homework Prime number <= N Extend the “Prime Number Test” program to list all prime numbers less than or equal to N, where N is input from the user.

Homework (bonus) Perfect Number For example, In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors; that is, the sum of its positive divisors excluding the number itself. For example, 6 = 1 + 2 + 3 28 = 1 + 2 + 4 + 7 + 14 Write a program to list all perfect numbers less than or equal to N, where N is input from the user.