CS 240: Data Structures Tuesday, June 5 th Programming Semantics, Software Life Cycle.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer Science 1620 Loops.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
Announcements The first graded lab will be posted Sunday 2/15 and due Friday 2/27 at midnight It is brand new, so please don’t hand in last semester’s.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Computer Science 1620 Programming & Problem Solving.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5: Control Structures II (Repetition)
Debugging Logic Errors CPS120 Introduction to Computer Science Lecture 6.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
CPS120 Introduction to Computer Science Iteration (Looping)
Monday, Jan 13, 2003Kate Gregory with material from Deitel and Deitel Week 2 Questions from Last Week Control Structures Functions Lab 1.
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.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
CPS120: Introduction to Computer Science Lecture 14 Functions.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
CPS120 Introduction to Computer Science Iteration (Looping)
1 10/3/05CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Engineering Problem Solving with C++, Etter/Ingber
CS1010 Programming Methodology
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Announcements Final Exam on August 17th Wednesday at 16:00.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Coding Concepts (Basics)
Computing Fundamentals
Looping III (do … while statement)
Let’s all Repeat Together
For Loops (Iteration 1) Programming Guides.
Chapter 5: Control Structures II (Repetition)
Python Basics with Jupyter Notebook
Lecture 3 More on Flow Control, More on Functions,
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

CS 240: Data Structures Tuesday, June 5 th Programming Semantics, Software Life Cycle

Programming Structure To solve a programming problem: To solve a programming problem: Define the problem Define the problem Break it up into manageable parts Break it up into manageable parts Split up the problem into smaller tasks Split up the problem into smaller tasks If a task can be immediately realized, it is small enough If a task can be immediately realized, it is small enough Code the parts Code the parts Integrate parts together Integrate parts together

Converting ideas to code: Sometimes, the ideas are easy. Sometimes, the ideas are easy. Getting the code down – or approaching the problem – becomes the challenge. Getting the code down – or approaching the problem – becomes the challenge. Most code revolves around the following statements: Most code revolves around the following statements:

Common Code Structures Control Structures Control Structures if if else else switch switch while while do { } while; do { } while; for for break break continue continue return return Other manipulators Other manipulators & * = == == && && || || static_cast () static_cast () When do we use these things? When do we use these things?

if Use if when you have a simple decision to make: Use if when you have a simple decision to make: Is a number negative? Is a number negative? if(number < 0) {} If the user inputs “y”: If the user inputs “y”: if(userinput == “y”) {} Remember: Number and userinput must be variables of an appropriate type!

if In the previous two examples, we run additional code if the condition is met. In the previous two examples, we run additional code if the condition is met. Consider this function: Consider this function: If number is 4, what makes this inefficient? If number is 4, what makes this inefficient? bool isPositive(int number) { bool returnvalue = 0; if(number >= 0) { returnvalue = 1; } if(number < 0) { returnvalue = 0; } return returnvalue; }

if Possibility #2 Possibility #2 This is better, but we can do more. This is better, but we can do more. At this point, what can number be? At this point, what can number be? Then, we don’t need the second if statement! Then, we don’t need the second if statement! bool isPositive(int number) { if(number >= 0) { return 1; } if(number < 0) { return 0; } //Compiler may complain if no return is at the //end of this function }

if Possibility #2 - Revised Possibility #2 - Revised This also gets rid of the compiler warning. This also gets rid of the compiler warning. We can do this because of “control flow”. Let’s try this with the first code we had. We can do this because of “control flow”. Let’s try this with the first code we had. bool isPositive(int number) { if(number >= 0) { return 1;//is positive } return 0;//is negative }

if Possibility #2 – Revision: Applied to earlier code. Possibility #2 – Revision: Applied to earlier code. This doesn’t work the way we want! This doesn’t work the way we want! What is wrong with this code? What is wrong with this code? Why isn’t it a problem on the previous slide? Why isn’t it a problem on the previous slide? bool isPositive(int number) { bool returnvalue = 0; if(number >= 0) { returnvalue = 1; } returnvalue = 0; return returnvalue; }

If and else If we examine what number can be we know that number is negative if it failed “if(number>=0)” If we examine what number can be we know that number is negative if it failed “if(number>=0)” Therefore, code after the if is only reached when we fail the first if. Therefore, code after the if is only reached when we fail the first if. This is because “return 1” stops us from progressing further. This is because “return 1” stops us from progressing further. Alternatively, we can use else. Alternatively, we can use else. The compiler won’t complain about a missing return in this case. The compiler won’t complain about a missing return in this case. bool isPositive(int number) { if(number >= 0) { return 1;//is positive }else{ return 0;//is negative }}

Multiple conditions Be careful when testing multiple conditions: Be careful when testing multiple conditions: If we wanted a program to describe the temperature: If we wanted a program to describe the temperature:

int tempinF; tempinF = gettemperature(); if(tempinF<32){ cout << “It is freezing!” <<endl; } else if((tempinF>=32) && (tempinF =32) && (tempinF <60)){ cout << “It is cold!” <<endl; } else if((tempinF>=60) && (tempinF =60) && (tempinF < 80)){ cout << “It is cozy!” <<endl; } else if(tempinF>=80) { cout << “It is hot!” <<endl; } //below 32, or [-,32) //32 -> 60, or [32,60) //60 -> 80, or [60,80) //greater than 80, or [80,-]

Get used to having {} for your if and else and other relevant statements. Get used to having {} for your if and else and other relevant statements. It makes it easier to read and quicker to edit later. It makes it easier to read and quicker to edit later. It will make the code longer; but, you don’t need to worry about that. It will make the code longer; but, you don’t need to worry about that. This is part of the reason we separate code out into separate files. This is part of the reason we separate code out into separate files.

switch Use switch when you have a bunch of equality decisions to make: Use switch when you have a bunch of equality decisions to make: switch replaces a set of if statements. switch replaces a set of if statements.

switch int number; cin >> number; if(number == 5) { cout << “apple” <<endl; } if(number == 7) { cout << “tomato” <<endl; } if(number == 10) { cout << “biscuit” <<endl; } int number; cin >> number; switch(number){ case 5:cout << “apple” <<endl; break; case 7:cout << “tomato” <<endl; break; case 10:cout << “biscuit” <<endl; break;} Becomes

switch Switch isn’t terribly good for a range of values. Switch isn’t terribly good for a range of values. If you had an if condition: If you had an if condition: if((number > 5) && (number 5) && (number < 10)) How would you represent this with a switch? How would you represent this with a switch? However, switch does have an equivalent statement to “else”. However, switch does have an equivalent statement to “else”.

switch int number; cin >> number; if(number == 5) { cout << “apple” <<endl; } else if(number == 7) { cout << “tomato” <<endl; } else if(number == 10) { cout << “biscuit” <<endl; }else{ cout << “Not food!” <<endl; } int number; cin >> number; switch(number){ case 5:cout << “apple” <<endl; break; case 7:cout << “tomato” <<endl; break; case 10:cout << “biscuit” <<endl; break; default:cout << “Not food!” <<endl; break;} Becomes The cases in a switch isolate the conditions from each other. (unless you forget “break;”

while You use a while for the following: You use a while for the following: Repeat code until some condition is met Repeat code until some condition is met Repeat code forever – need control flow to exit Repeat code forever – need control flow to exit

Repeat forever: Repeat forever:while(1){ int number; cin >> number; if(number == 10) break;} Repeat condition: Repeat condition: int counter = 4; while(counter>0){ int number; cin >> number; counter--;}

A “while” is a different form of “for” A “while” is a different form of “for”

for vs while int conditionvariable = initialvalue; while(condition){//stuffchange(conditionvariable);} for(int conditionvariable=initialvalue;condition;change(conditionvariable)) {//stuff}

for “For” is generally used to repeat code a certain number of times (infinite is possible), or iterate over some data. “For” is generally used to repeat code a certain number of times (infinite is possible), or iterate over some data.

for(int i=0;i<10;i++) {//stuff}for(;;){//stuff} string userinput; cin >> userinput; for(int i=0;i<userinput.size();i++) {stuff(userinput[i]);}

Control Flow Statements continue; continue; Ends the current loop. Ends the current loop. break; break; Terminate the current loop. Terminate the current loop. return X; return X; Terminate the current function, return X to the caller. Terminate the current function, return X to the caller.

Using continue: for(int i=0;i<10;i++) { cout << i << endl; cout << “I printed!” <<endl; } for(int i=0;i<10;i++) { cout << i << endl; continue; cout << “I printed!” <<endl; }

Using continue: int i=0; while(i<10){ cout << i << endl; cout << “I printed!” <<endl; i++;} int i=0; while(i<10){ cout << i << endl; continue; cout << “I printed!” <<endl; i++;} This example has problems!

continue, break for(int i=0;i<10;i++) { cout << i << endl; break; cout << “I printed!” <<endl; } break leaves the loop. break leaves the loop. Continue and break are useful, just be careful when you use them. Continue and break are useful, just be careful when you use them.

Return All functions return something (even void functions). All functions return something (even void functions). Return is how we get stuff done! Return is how we get stuff done! A function completes some work and returns to its caller whatever it needs to return. A function completes some work and returns to its caller whatever it needs to return. Return ends the current function, no other code in that function will be executed! Return ends the current function, no other code in that function will be executed!

Some style issues Indentation: Indentation: Provides readability of the code (required by some languages, namely Python) Provides readability of the code (required by some languages, namely Python) Generally, 1 tab for each preceding { without a } Generally, 1 tab for each preceding { without a } For clarity, you can put { and } alone on their own line For clarity, you can put { and } alone on their own line A line with “}” has 1 less tab. A line with “}” has 1 less tab.

int main() { int a; { int b; { int c; { int d; { int e; } int f; { int g; }}} int h; { int I; }}}

Globals Globals aren’t all bad, but they are generally bad. Globals aren’t all bad, but they are generally bad. There are some reasons to use globals that we won’t discuss here. There are some reasons to use globals that we won’t discuss here. So, what is wrong with using a global variable? So, what is wrong with using a global variable? How does it violate information hiding and encapsulation? How does it violate information hiding and encapsulation?

Pointers and reference double *shorty; double jimmy; jimmy = 10; shorty = &jimmy; cout << shorty << endl; What does this code output? What does this code output? What does: What does: “cout << *shorty <<endl;” output? output?

Pointers and reference double *shorty; double jimmy; jimmy = 10; shorty = &jimmy; cout << shorty << endl; cout << *shorty << endl; Name: shorty Value: Uninitialized Location: Topmost! Name: jimmy Value: Uninitialized Location: The bottom Name: jimmy Value: 10 Location: The Bottom Name: shorty Value: The Bottom Location: Topmost! Output: The Bottom Output: 10

Other manipulators Other manipulators = == == && && || || static_cast () static_cast ()