Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Similar documents
Unit 7. 'while' Loops

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Increment and the While. Class 15

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

CSCE 206: Structured Programming in C++

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Why Is Repetition Needed?

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Computer Programming : C++

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

REPETITION CONTROL STRUCTURE LOGO

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Computer Science II Lecture 1 Introduction and Background

ENJOY! Problem 2 What does the following code do, in a brief English sentence? int mystery(int k) { int i = 0; if (k < 0) return -1;

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Programming Language. Functions. Eng. Anis Nazer First Semester

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

The following expression causes a divide by zero error:

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Chapter 4 - Notes Control Structures I (Selection)

(Refer Slide Time 01:41 min)

5. Control Statements

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Add Subtract Multiply Divide

COMP322 - Introduction to C++ Lecture 01 - Introduction

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Third Edition

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Getting started with C++ (Part 2)

C++ Programming Lecture 1 Software Engineering Group

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

Chapter 4 Computation

1 Unit 8 'for' Loops

Maciej Sobieraj. Lecture 1

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

Chapter 4. Computation. Bjarne Stroustrup.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Chapter 5: Control Structures II (Repetition)

Introduction to C ++

In this chapter you will learn:

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ Support Classes (Data and Variables)

CS2141 Software Development using C/C++ C++ Basics

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Looping. Arizona State University 1

Intro. Scheme Basics. scm> 5 5. scm>

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Lab 10: Alternate Controls

Lab Instructor : Jean Lai

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Lecture Transcript While and Do While Statements in C++

LECTURE 5 Control Structures Part 2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

These are notes for the third lecture; if statements and loops.

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

377 Student Guide to C++

CSCI 1061U Programming Workshop 2. C++ Basics

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

LOOPS. Repetition using the while statement

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 3. More Flow of Control

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

Chapter 2 Basic Elements of C++

PIC 10A. Review for Midterm I

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

Lecture 7: General Loops (Chapter 7)

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Arrays in C++ Instructor: Andy Abreu

Objectives. In this chapter, you will:

Chapter 2. C++ Basics

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

To become familiar with array manipulation, searching, and sorting.

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

How to approach a computational problem

Transcription:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5; x += 5; The above expressions add 5 to x and store the increased amount back into x. Similarly, you can do: y = y - 10; or y -= 10; z = z * (x + 2); or z *= x + 2; The following is erroneous. Do you see why? x = 10; y /= x - 10; There is yet another shortcut for incrementing/decrementing a value. The following are equivalent:! x = x + 1;!! x += 1;!! x++;!! ++x; // increment by 1! y = y - 1;!! y -= 1;!! y--;!! --y; // decrement by 1 The incremental operator ++ is the reason behind the naming of language C++, as C++ started as the extention of the language C. (Can you guess the name of the predecessor of C?) (Maybe a little tricky) ++ and -- behave slightly differently based on their location. See the following: x = 5;! y = x++;! cout << y << endl;!!! // It prints: This is an assignment, so the first step is to evaluate the right hand side expression and the next step is to assign the evaluated value to the variable on the left hand side. The expression x++ evaluates to the original value of x. On the contrary, when the variable comes after ++, it evaluates to the resulting value. x = 5;! y = ++x;! cout << y << endl;!!! // It prints: Use this kind of increment-assignment combination only if you fully understand what is going on. It is wise to break it into two statements when it is not obvious what you are doing. The Type bool Remember, boolean expressions are expressions that evaluate to either true or false. Just like integers can be stored in int variables and real numbers can be stored in double variables, true and false values can be stored in bool variables. For instance, the following are equivalent: if (x > 5) cout << "x is greater than 5" << endl; and Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 1/10

bool test = x > 5; if (test) cout << "x is greater than 5" << endl; bool s can be handy when you have to evaluate the same condition multiple times. They let you evaluate the expression once and for all, as in: bool test = x > 5;!! // test is true if x is greater than 5 at this moment. if (test && x < 10)! // true if x is greater than 5 and less than 10. // do something if (test x < 0)! // true if x is greater than 5 or less than 0. // do something else Nested If Statements Recall that an if statement takes the following form ( else part omitted): if (condition) // if body This is a single if statement, and both if and else bodies may consist of multiple statements. The following if statement has two statements in the if body. if (x > 5) cin >> x; cout << "x was greater than 5, so we assigned a new value for x: " << x << endl; This means that in an if body (and in an else body), we can have another if statement as well. if (x > 5) cout << "x is greater than 5"; if (x > 10) cout << "... and it is even greater than 10." << endl; else cout << "... but it is less than or equal to 10." << endl; And you can nest your if statements as many times as you want (as long as it doesn t get messy). Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 2/10

Practices Problem 1 Get name and test score of a student, and print a letter grade. The score must be between 0 and 100 (inclusive). If the score is out of range, print error. Assume the class is not curved -- give A for 90-100, B for 80-89, C for 70-79, D for 60-69, and F for below 60. The score cannot have any decimal points. Assume the user always enters some number (as opposed to characters) for score. For example: Name: Brian Score: 92 Brian receives a/an A. Your code: Name: Mr. Lazy Score: 25 Mr. Lazy receives a/an F. Name: Sean Score: -1 error Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 3/10

Problem 2 Get the birthday of a person and today s date, and determine how many days are left before the birthday. If the birthday has passed, say so. For simplicity, assume there are only 30 days in a month, and that the user never provides illogical input. Examples: Birthday (month): 5 Birthday (day): 25 Today (month): 3 Today (day): 2 83 days left Birthday (month): 11 Birthday (day): 4 Today (month): 9 Today (day): 20 44 days left Birthday (month): 3 Birthday (day): 2 Today (month): 5 Today (day): 24 Your birthday has passed I ve written a portion of the code for you below: int birthmonth, birthday; int currentmonth, currentday; int daysleft; // Get the dates. cout << Birthday (month): ; cin >> birthmonth; cout << Birthday (day): ; cin >> birthday; cout << Today (month): ; cin >> currentmonth; cout << Today (day): ; cin >> currentday; // Your code below. return 0; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 4/10

Loops While Loops Here is the syntax for a while loop: while (condition) body; body is repeatedly run while condition holds. Take a look at the following example: #include <iostream> Output: using namespace std; int x = 0, y = 10; while (x < y) x++; // equivalent to x = x + 1 cout << x << endl; cout << endl; return 0; Be careful when you are using while statements, though. what is wrong with the following code? x = 1; y = 0; while (y == 0) x++; Infinite loops will cause your program to crash so you should always make sure that it ends at some point! There is a variation of while statement called do-while. It works just like while, but will execute the loop once no matter what, and then test the condition. This is most useful in a case like the following, where you ask for a valid input from the user: int x = 0; do cout << "Input 5 or 6: "; cin >> x; while (x!= 5 && x!= 6); // Don t forget that semicolon For Loops Often, in your looping structure you will need some kind of counter to keep track of the number of times the loop is executed. (e.g., printing Hello 100 times, adding numbers 1 to 50) While this can be done with a while loop, for your convenience, C++ defines another looping structure that supports it: for ( initialization ; condition ; update ) body which we call for loops. An example should help this make better sense: Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 5/10

#include <iostream> using namespace std; int i, sum = 0; for (i = 1; i <= 100; i++) sum = sum + i; cout << "sum = " << sum << endl; return 0; What does the above program do? The evaluation rule is as follows. Recall that the syntax for a for loop is: for ( initialization ; condition ; update ) body 1. Execute initialization 2. Check the condition If true, 3. run the body 4. do the update go back to 2 If false, exit the for loop. The order of execution is therefore 1-2-3-4-2-3-4-2-3-4-...-2-3-4-2. For to While conversion If you can do something using a while loop, you should be able to write a for loop equivalent, and vice versa. The for-to-while conversion rule is quite straightforward, and is illustrated on the right side. initialization should come before everything, and it must be executed only once. Therefore, it comes before the whole while loop. Then the condition must be checked, thus condition goes inside the while statement. If this is true, we execute the body, and then update. Note that update statement must be inside the while loop. (What happens if it s outside the loop?) This conversion is somewhat straightforward from the evaluation steps of for loops we saw above. For to do-while conversion works in a similar way. Homework 2 should have bugged you enough for this. for (initialization; condition; update) body initialization while (condition) body update Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 6/10

Question: Can you tell how the following for statements will behave? What values does i take on? for (int i = 10; i >= 0; i--) for (int i = 0; i < 100; i += 2) for (int i = 32; i > 1; i /= 2) Question: Write a for loop that finds the sum of numbers 1 to 100. Question: (Nested Loops) How many times does # get printed? for (int i = 0; i < 10; i++) for (int j = i; j < 10; j++) cout << # ; cout << # ; Question: Convert the following for loop into a while loop. for (int i = 0; i < 50; i += 2) cout << Hello << endl; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 7/10

Functions Suppose I want to write a program that computes 3 things: - the sum of integers 1 to 100 - the sum of integers 51 to 150 - the sum of integers 103 to 276 You can create a loop for each one of the sums, but this is cumbersome. If we are allowed to define a method of summing up numbers just once, and then use it three times, it will reduce some burden. In other words, you can teach your computer how to sum, as opposed to what to sum. In C++, functions (or equivalently known as methods, subroutines, or procedures in other contexts) are meant to serve this purpose. An example of a C++ function is shown here ----> Hey, that resembles the main() thing that we used to write. In fact, main() is also a function, which we call main function, and it happens to be the one that gets executed when the program begins. Before we take it apart, let me bring up an analogy: int sum(int begin, int end) int temp = 0; for (int i = begin; i <= end; i++) temp += i; return temp; This is called a function for a reason. Where else do you see functions? In high school algebra, we ve seen functions presented in the following way: f(x) = 2x + 5 This function, called f, takes a value, denoted x, and maps this number in a predetermined way to another number. If the input x is 5, for instance, we do: f(5) = 2(5) + 5 = 15 and it would result in a different number for a different output. Once we have defined this function f, we can simplify other expressions using f. 4x + 10 = 2f(x) 2x 2 + 7x + 5 = (x+1)(2x+5) = (x+1)f(x) This is exactly what we do with our C++ functions. We define it, and then use it to simplify our program. Now let s take the function definition apart. - int indicates that the output is of type integer. We call this return type. - sum is the name, or the identifier, of the function, just like f is for the function above. - begin and end are arguments to the function sum, just like x is for the function f. The arguments must be within parentheses. - The function body within defines the mapping rule. - The function must return the value explicitly, depending on the input it receives. Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 8/10

In general, the syntax goes as follows: return_type function_name(arg1, arg2, arg3,...) function_body and the function body must include return statements such that every execution of the function ends up in a return statement. A function can also have no arguments, in which case the argument list simply becomes empty (i.e., ()). So where in the program should this function go and how do we use it? Here is an example. #include <iostream> using namespace std; int sum(int begin, int end) int temp = 0; for (int i = begin; i <= end; i++) temp += i; return temp; cout << sum(1, 20) << endl; // prints the sum 1 +... + 20 cout << sum(20, 50) << endl; // prints the sum 20 +... + 50 int sum1, sum2; sum1 = sum(4, 8); // stores the sum 4+5+6+7+8 into sum1 sum2 = sum(1, 10) + sum(15, 20); // stores the sum 1+...+10+15+...+20 into sum2 cout << sum1 << << sum2 << endl; return 0; Note that the function must be defined before it can be used. If the definition of sum comes after the main function, the compiler will complain that sum is an undefined identifier. If for a style reason you want to keep the main function on the top and define other functions later, you can let the computer know that there s going to be a function with a certain name first, and define later. For instance, you can do what s on the right. The bolded line is called a function prototype. #include <iostream> // I will define "sum" later. int sum(int begin, int end);... // Define it here. int sum(int begin, int end)... Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 9/10

Now it s time for a little practice: Question: Define a function f that takes in a real number x and returns the result of 2x + 5. Question: Use the function f and sum to find the sum from f(3) to f(72), and store it in a variable called z. Question: How many # s will you see on the screen? int mystery(int len) for (int i = 0; i < len; i++) cout << # ; if (len % 2 == 0) return len + 1; else return len + 3; int y = 5; while (y < 10) y = mystery(y); return 0; Copyright Brian Choi 2011. All Rights Reserved. Week 3, Page 10/10