Lecture 1 -- 1Computer Science I - Martin Hardwick Odds And Ends – Switch Statement rIt is often necessary in programs to set up a set of cases, where.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick How do Calculators Computer Square Roots? rWhen you enter 29 into your calculator and push the square.
Advertisements

Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Lecture Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient.
Lecture Computer Science I - Martin Hardwick Recursion rA recursive function must have at least two parts l A part that solves a simple case of the.
Lecture Computer Science I - Martin Hardwick Streams In C++ rA stream is a sequence that you either read from or write to. l example – cin is a stream.
Lecture Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays.
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Control Structures.
The if-else Statements
More on Algorithms and Problem Solving
Chapter 16 Exception Handling. What is Exception Handling? A method of handling errors that informs the user of the problem and prevents the program from.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Computer Science 1620 Loops.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
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.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Computer Science 1620 Programming & Problem Solving.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++ (5) 10 September.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
The If/Else Statement, Boolean Flags, and Menus Page 180
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
Switch Statements. Switch Statement Often you want to do a series of tests –if i==0 … else if i==1 …. else if i==2 … else if i==3 …. C++ provides the.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
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.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
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.
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.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
CPS120: Introduction to Computer Science Lecture 14 Functions.
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
1 CS161 Introduction to Computer Science Topic #8.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
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.
FUNCTIONS - What Is A Function? - Advantages Function Declaration
Calvin College Controlling Behavior The if, switch and for Statements.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Computer Programming -1-
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Computer Programming
Review 1.
C++ Programming: CS150 For.
Intro to Programming Week # 6 Repetition Structure Lecture # 10
Chapter 4 Loops Case Studies
Chapter 4: Control Structures I (Selection)
Control Structures Part 3
Control Structures Part 1
Looping III (do … while statement)
Let’s all Repeat Together
Program Flow.
Presentation transcript:

Lecture Computer Science I - Martin Hardwick Odds And Ends – Switch Statement rIt is often necessary in programs to set up a set of cases, where at most one of the cases is executed. l we have done this with nested IF-ELSE statements rThere is a special statement in C++ that makes is easier to set up cases in some situations. l it is called the switch statement switch (score/10) { case 0: case 1: case 2: case 3: case 4: case 5: F = F + 1; break; case 6: D = D + 1; break; case 7: C = C + 1; break; case 8: B = B + 1; break; case 9: case 10: A = A + 1; } if (score < 60) { F = F + 1; } else if (score < 70) { D = D + 1; } else if (score < 80) { C = C + 1; }... Example Counting letter grades for exam scores.

Lecture Computer Science I - Martin Hardwick Switch Statement rSyntax: switch ( ) { case : case :... statement1; statement 2;... break; case : case :... statement10; statement20;... break;... default: statement100; statement200;... } Meaning: == ||... == || yes no statement 1 statement 2... statement 10 statement statement 100 statement

Lecture Computer Science I - Martin Hardwick Break rBreak is used to break out of a For, While and Switch rIn a Switch if there is no break then the code will continue into the next case l This can be a good thing for some programs l However it is a frequent cause of errors for beginners rMake sure that your Cases end in a break or a return.

Lecture Computer Science I - Martin Hardwick Putting it all together rThis program uses everything l A while loop to get data until the user is finished l A for loop to iterate over the array until the end l An if to decide what to do with each value l A break to handle an exception rNow we need to start thinking about writing programs that contain many functions l When main gets too complicated, debugging gets very hard. l Smaller functions are easier to reuse. l The best programmers are always reusing code #include using namespace std; int main() { int grades[100]; int i = 0; double val; cin >> val; while (val != 0) { val >> grades[i++]; cin >> val; } int count = i; double sum; cout << count << " grades" << endl; for (i=0; i<count; i++) { if (grades[i] > 1000) break; sum += grades[i]; } // more code here return 0; }

Lecture Computer Science I - Martin Hardwick Parameterization Old MacDonald had a farm, Ee-igh, Ee-igh, oh! And on this farm he had a, Ee-igh, Ee-igh, oh! With a here And a there Here a, there a, Everywhere a. Old MacDonald had a farm, Ee-igh, Ee-igh, oh! ANIMAL SOUND cow moo pig oink cow moo

Lecture Computer Science I - Martin Hardwick HadA ( Animal ) { And on that farm he had a Animal, } Parameters And C++ Functions HadA ( cow); WithA ( moo); rA function in C++ can be parameterized. rWhen the function is called, values (arguments) for the parameters are supplied as part of the call. rParameters are placed between the parentheses in the function header. rThe arguments and parameters must be listed in the same order. WithA ( Sound ) { With a Sound Sound here And a Sound Sound there Here a Sound, there a Sound Everywhere a Sound Sound. } argument parameter

Lecture Computer Science I - Martin Hardwick Old MacDonald Program // Program to generate the words for // Old MacDonald had a farm. #include using namespace std; void EiEio() { cout << "Ee-igh, Ee-igh, oh!" << endl; } void Refrain() { cout << "Old MacDonald had a farm, "; EiEio(); } rSince we will be using string parameters, we need to include. rThe functions EiEio() and Refrain() dont need parameters. rNote that the parentheses with nothing between them indicate that these functions require no parameters.

Lecture Computer Science I - Martin Hardwick New Version Of Old MacDonald (continued) void HadA(string ANIMAL) { cout << "And on his farm he had a " << ANIMAL << ", "; EiEio(); } void WithA(string SOUND) { cout << "With a " << SOUND << " " << SOUND << " here" << endl; cout << "And a " << SOUND << " " << SOUND << " there" << endl; cout << "Here a " << SOUND << ", " << "there a " << SOUND << ", " << "everywhere a " << SOUND << " " << SOUND << "." << endl; } rThe syntax for a parameter declaration in a function is: type name rThe parameter name can be any valid identifier. rAny place where the parameter name appears in the function, the value of the parameter is substituted.

Lecture Computer Science I - Martin Hardwick Old MacDonald (continued) int main () { // Verse for a cow Refrain(); HadA("cow"); WithA("mow"); Refrain(); cout << endl; // Verse for a pig Refrain(); HadA("pig"); WithA("oink"); Refrain(); cout << endl; // Verse for a duck Refrain(); HadA("duck"); WithA("quack"); Refrain(); cout << endl; return 0; } rWhen a function with parameters is called, the call must specify a value (argument) for each parameter. l place the arguments between the parentheses in the function call l if a function requires no parameters, then nothing is placed between the parentheses in the function call rIf a function requires more than one parameter, the order of the arguments in the call must match the order of the parameters in the function header.

Lecture Computer Science I - Martin Hardwick Functions With Multiple Parameters rRather than the main function calling all the other functions, we can create a function Verse to do this. l displays one complete verse of the song l requires two parameters, the name of an animal and its sound rThe new main function now calls function Verse for each verse of the song to generate l it passes both the animal name and sound for the verse as arguments // Display one verse of the song void verse(string name, string sound) { Refrain(); HadA( name ); WithA( sound ); Refrain(); cout << endl; } // Generate the song with three verses int main () { Verse( cow, moo); Verse( pig, oink); Verse( duck, quack); return 0; }

Lecture Computer Science I - Martin Hardwick Functions that return a value rA functions that returns a value l Says what type of value it is going to return in its header l Returns that type of value using a return l The compiler will complain if the type returned by the return is not compatible with the type defined for the function. // Compute a sum int sum (int a, int b) { return a + b; } // Compute two sums int two_sum (int a, int b, int c, int d) { int sum1 = sum (a, b); int sum2 = sum (b, c); return sum (sum1, sum2); } // double version double sum_d (double a, double b) { return a + b; }