CS 1400 Pick ups from chapters 4 and 5. if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
CS Sept 2006 Pick ups from chapters 4 and 5.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
CS 1400 Pick ups from chapters 4 and 5. if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver.
CS 1400 Chapter 5, section 2. Loops! while (rel-expression)while (rel-expression) {statements statement } if the relational-expression is true, execute.
1 10/9/06CS150 Introduction to Computer Science 1 for Loops.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Chapter 05 (Part III) Control Statements: Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Overview Go over parts of quiz? Another iteration structure for loop.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
April 11, 2005 More about Functions. 1.Is the following a function call or a function header? calcTotal(); 2.Is the following a function call or a function.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II (Repetition)
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Let’s all Repeat Together
Chapter 5: Control Structures II (Repetition)
Presentation transcript:

CS 1400 Pick ups from chapters 4 and 5

if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver rate (C) preferred rate (D) special rate

Example Menu char choice; cin >> choice; if (choice == ‘A’) rate = 2.15; else if (choice == ‘B’) rate = 3.25; else if (choice == ‘C’) rate = 4.86; else rate = 5.22;

The switch statement General form: switch (ordinal variable) { case constant value 1 : statements break; case constant value 2 : statements break; case constant value 3 : statements break; … default: statements }

Example Menu (bis) char choice; cin >> choice; switch (choice) {case ‘A’:rate = 2.15; break; case ‘B’:rate = 3.25; break; case ‘C’:rate = 4.86; break; default:rate = 5.22; }

The break is optional… char choice; cin >> choice; switch (choice) {case ‘A’: case ‘a’:rate = 2.15; break; case ‘B’: case ‘b’: rate = 3.25; break; case ‘C’: case ‘c’:rate = 4.86; break; default:rate = 5.22; }

Compound boolean expressions Two relational (or Boolean) expressions can be combined using && (and) || (or) examples: if ((age > 21) && (age < 35)) cout << “You could be drafted!”; if ((age 120)) cout << “Incorrect age!”; (Don’t confuse with & and |)

Precedence && has precedence over || relational operators have precedence over && if (a d || e==f)same as if (((a d)) || (e==f))

Caution!! Be sure &&, || are between relational expressions or Boolean variables… if (a < b||c)?? if (b&&a == c)??

Comparing two strings… The following will have unexpected results: char name1[20], name2[20]; cin >> name1 >> name2; if (name1 == name2) cout << “these names are the same!”; The reasons will become clear later on… This is correct: if (strcmp (name1, name2) == 0) cout << “these names are the same!”; *FYI

Testing for file errors… A file variable may be tested for the failure of the most recent file operation using the member function.fail() Example: ifstream fin; fin.open(“f:myfile.txt”); if (fin.fail()) cout << “this file could not be opened!”; Alternate example: if (!fin) cout << “this file could not be opened!”;

Other loop statements… The do-while loop do {statements; } while ( expr ) ; This is a post-test loop: The expression is tested at the bottom of the loop and always performs at least one iteration

Example; Input validation – a program must prompt for an age and only accept a value greater than 0 and less than 120. do { cout << “Enter a valid age: “; cin >> age; } while ((age 120));

Other loop statements. The for loop for ( initialization ; test expr ; update ) { statements; } This is a pre-test loop: The test expression is tested at the top of the loop. The initialization, test expression and update segments can be any valid C++ expression

Explanation of segments… initialization –This segment is executed once prior to beginning the loop test expr –This segment is executed prior to each iteration. If this segment is false, the loop terminates update –This segment is executed at the bottom of each iteration.

Example; Add 20 numbers input by the user; float num, sum = 0.0; int n; for (n=0; n<20; n++) { cout << “Enter a number: “; cin >> num; sum += num; }

Example variation… The test variable can actually be declared within the loop float num, sum = 0.0; for (int n=0; n<20; n++) { cout << “Enter a number: “; cin >> num; sum += num; }

A programmer has a choice… Convert the following while loop to a for loop int count = 0; while (count < 50) { cout << “count is: “ << count << endl; count ++; } Convert the following for loop to a while for (int x = 50; x > 0; x-- ) { cout << x << “ seconds to launch.\n”; }

Example – loan amoritization A case study (5.14, pg 295) Write a loan amoritization program –inputs: principle, interest_rate, num_years –outputs: monthly payment for each month: month number, interest, principle, remaining_balance

Formulas payment = (principle * interest_rate/12 * term) / (term-1) where term = (1 + interest_rate/12) num_years * 12 monthly_interest = (annual_rate / 12) * balance principle = payment – monthly_interest

Example execution: Enter loan amount: $ 2500 Enter annual Interest rate: 0.08 Enter number of years: 2 Monthly payment: $ month interest principle balance … (a total of 24 month lines)

Pseudocode… 1.Prompt and input loan amount, annual interest rate, and number of years 2.Calculate and display monthly payment 3.Print report header 4.For each month in the loan period: a)calculate the monthly interest on the current balance b)calculate the principle for this month’s payment c)display the month number, interest, principle, and balance d)calculate the new balance

1 2 3 for ( int month = 1 ; month <= num_years * 12 ; month++) // 4. {}{} d) c) b) a) First refinement…

Example – loops within loops table of grades file Students: 64 John 9 scores: Fred 13 scores: Emily 8 scores: …

Pseudocode – rough outline 1. Input number_of_students 2. Repeat for number_of_students iterations; a-f) process a student and output the name and average

Pseudocode – more detail 1. Input number_of_students 2. Repeat for number_of_students iterations; a-b) Input student_name and count_of_grades c-d) sum grades for this student e) Calculate average f) Output student_name and average

Pseudocode -- final detail 1. Input number_of_students 2. Repeat for number_of_students iterations; a) Input student_name b) Input count_of_grades c) initialize sum to 0. d) Repeat for count_of_grades iterations; i– Input grade ii– sum grade e) Calculate average f) Output student_name and average

1 for ( int student = 0 ; student < num_of_students ; student++) //2 {}{} c) b) a) First refinement… e) f) d)

c) Second refinement… e) f) … for (int count=0; count<num_of_grades; count++) // d) { } … ii-- i--

Examples – loops within loops for (int n=0; n<4; n++) {for (int k=0; k<3; k++) { cout << “n: “ << n << “ k: “ << k << endl; } for (int n=0; n<4; n++) {for (int k=n; k<3; k++) { cout << “n: “ << n << “ k: “ << k << endl; }