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

Similar documents
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;

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

REVIEW. The C++ Programming Language. CS 151 Review #2

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

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

The C++ Language. Arizona State University 1

Fundamentals of Programming CS-110. Lecture 2

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Announcements. Lab 1 this week! Homework posted Wednesday (late)

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

A First Program - Greeting.cpp

Chapter 2: Introduction to C++

CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Lab # 02. Basic Elements of C++ _ Part1

Announcements. Homework 0 out! Coming soon: 1. remote access 2. programming instructions 3. lab 1 (graded!) this week

LECTURE 02 INTRODUCTION TO C++

Ex: If you use a program to record sales, you will want to remember data:

printf( Please enter another number: ); scanf( %d, &num2);

CHAPTER 3 BASIC INSTRUCTION OF C++

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Getting started with Java

Introduction to Programming EC-105. Lecture 2

Getting started with C++ (Part 2)

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

BITG 1233: Introduction to C++

CS102: Variables and Expressions

Text Input and Conditionals

Lesson 2 Variables and I/O

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

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

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

PIC 10A. Review for Midterm I

This watermark does not appear in the registered version - Slide 1

Lecture 1. Types, Expressions, & Variables

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

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

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

The Java Language Rules And Tools 3

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Information Science 1

Maciej Sobieraj. Lecture 1

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

int x = 5; double y = 3; // Integer division rounds the result down to the nearest whole number. cout << "1a: " << x / 3 << endl; //1

COMP Primitive and Class Types. Yi Hong May 14, 2015

download instant at Introduction to C++

A variable is a name for a location in memory A variable must be declared

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

CS31 Discussion 1E Spring 17 : week 08

(I m not printing out these notes! Take your own.)

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

Introduction to the C++ Programming Language

Chapter 2. C++ Basics

Lecture 2 Tao Wang 1

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

Chapter 2: Data and Expressions

CS31: Introduction to Computer Science I Spring 2011

CMSC 201 Computer Science I for Majors

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Full file at

Review of Important Topics in CS1600. Functions Arrays C-strings

Basics of Java Programming

Lecture 3. Input, Output and Data Types

Reserved Words and Identifiers

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Programming with C++ as a Second Language

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Objectives. In this chapter, you will:

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

VARIABLES & ASSIGNMENTS

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Computer Programming : C++

Variables, expressions and statements

Creating a C++ Program

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

CPE Summer 2015 Exam I (150 pts) June 18, 2015

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;

Transcription:

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Variables You have to instruct your computer every little thing it needs to do even what it needs to remember. We create data storages for the computer and explicitly tells it what to store in which storage. We call these storages variables. /* */ A simple program demonstrating the usage of variables. int x; // create an integer variable x int y; // create an integer variable y x = 5; // store 5 in x y = 6; // store 6 in y cout << "x = " << x << ", y = " << y << endl; // print them out Output: (Note: We use /*... */ and // for making notes in the code for ourselves. Text within /* and */ (which can span over multiple lines), and everything after // and before the end of the line are not considered to be part of the code. We call such text a comment and say that part of the code is commented out. It is an important practice to get your codes properly commented.) int x; This is how you declare a variable. int indicates this variable must store an integer (called data type), and labels it x (called identifier). You can think of it as the process of creating an integer box for later use. See the textbook for other data types. Among these data types, we mainly use the following types in this course: int : integer, 4 bytes long, ranging from -2,147,483,647 to 2,147,483,647 double : real numbers, 8 bytes long, ranging from 1.7 10 308 to 1.7 10 308 bool : boolean, 1 byte long, either true or false (IGNORE FOR NOW) char : character, 1 byte long, holds an ASCII character (IGNORE FOR NOW) string : string, let s talk about this later today Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 1/8

Identifiers There are variable naming rules. An identifier must begin with an alphabetic character (a-z or A-Z) or an underscore ( _ ), which may be followed by alphabetic/numeric (0-9) characters and underscores. Violating any of these rules will result in a compile error. Question: Can you tell which ones of these are valid identifiers? los angeles computer_science engineering bruin@ucla.edu C++ 5272BH cs31 A commonly used convention is that you use lowercase letters except for the first letter of the second word (e.g. moneypaid, milesperhour). Later you ll see some special variables called constants (actually, constants are constants because they are not variables, but we will explain this later), which we name using uppercase letters (e.g. GRAVITY). Be descriptive with the varible names -- countapple is better than ca. Question: (case sensitivity) Do engineering and Engineering refer to the same variable? Variable Declaration You ve seen examples already. Here are more examples of variable declarations: int x; // integer x double milesperhour; // double milesperhour int countapple, countorange; // multiple declarations (same type) at once You can use these variables only after you declare them. Otherwise, the compiler will throw an unknown variable error. Also note that these variables initially store some random values (that is, you cannot assume x is initialized to 0). Assignments You created some variables. Now it s time to store data in there. We saw in page 1: x = 5; y = 6; = is called the assignment operator. Note that an assignment is different from equal to. Important! Evaluation order for the assignment: 1. Evaluate the expression on the right-hand side of the assignment operator. 2. Store the value into the variable on the left-hand side of the assignment operator. The original value gets overwritten. You may assign initial values as you declare the variable: int x = 5; // create an integer variable x, assign 5 int y = 6; // create an integer variable y, assign 6 You are allowed to do the following as well: int x = 5, y = 6; // multiple declarations/assignments at once The value you put into a variable must be compatible. For example, x = "Hello" won t work because "Hello" cannot be converted into an integer. However, x = 5.23 is a valid statement, as a decimal number on the right can be made into an integer simply by cutting off the fractional part. Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 2/8

Now something fun: let s make the user decide what to store in the variables. int x, y; cout << "Enter x: "; cin >> x; // get a number for x cout << "Enter y: "; cin >> y; // get a number for y cout << "x = " << x << ", y = " << y << endl; // print them out Output: Enter x: 7 Enter y: 2 Try diffrent inputs. In particular, try inputs other than integers and see how they change the outcome. Expressions Just inputting and outputting stuff is not fun or useful. Now let s play with the data. double initpos, finalpos; // initial and final position double time; // time traveled double distance, velocity; // distance traveled and velocity - to be computed cout << "What is the ball s initial position (at t=0)? "; cin >> initpos; cout << "What is the ball s final position? "; cin >> finalpos; cout << "For how long did the ball travel (in sec)? "; cin >> time; distance = finalpos - initpos; velocity = (finalpos - initpos) / time; cout << "The ball traveled the distance of " << distance << "m at " << velocity << "m/s on average." << endl; Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 3/8

We are particularly interested in the following lines: distance = finalpos - initpos; velocity = (finalpos - initpos) / time; The arithmetic operations on the right hand side of = s are called expressions. It can take the form of an arithmetic expression like this, or can be more complex C++ operations. In any case, the expression is expected to return us the data that we can store into the variable on the left hand side of =. Here are some of the possible operators we can use: + - * / ( ) ++ -- If you try inputting 2 for initpos, 5 for finalpos, and 7 for time, you will see the following output: The ball traveled the distance of 3m at 0.428571m/s on average. Well, that may be too many decimal points for us to handle. We can restrict the number of decimal points to show using the following magic code: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); // vary this number as you need to Try including this into the code before outputting anything and see what happens. Don t try to understand or remember these 3 lines of code (but I know some of you nerds will do regardless). Just copy-and-paste it whenever you need it. Strings We left out the explanation for the type string, so let s talk about it now. We have already seen the use of double quotes in Hello! program last week. A string is an ordered sequence of 0 or more characters. #include <string> // this enables us to use cin and cout // this enables us to use strings string str = "Hello!"; // create a string str with // "Hello, World!" as the initial value string answer; // create a string variable called answer cout << str << endl; cout << "Please answer my greeting!" << endl; getline(cin, answer); // get a user input for answer cout << "You said, " << answer << endl; Output: Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 4/8

Note the two bold-faced lines #include <string> and getline(cin, str). #include <string> allows you to use string data type. You can store values in string variables using the usual assignment, with the value in double quotes. However, when getting input from the user, use getline (cin, str) instead of cin >> str. The former lets let the user to type in a string, and stores the whole line he typed in into str. Can you guess when cin >> str fails to work as intended? If Statements There are times when you want your program to behave differently based on some condition. if-statement is what we use to achieve this. It takes the following form: if ( condition ) then_body else // else part is optional else_body When your computer reaches this part of the program, then_body is executed if condition evaluates to true. Otherwise, else_body is executed. Take a look at the following example: int x, y; cout << "Input x and y: "; cin >> x >> y; if (x > y) // is x greater than y? cout << "x is greater" << endl; // yes else cout << "y is greater" << endl; // no This program receives two values, x and y, from the user. Then it compares the two values to see if x is greater than y, and prints different statements on screen based on the comparison. A quick question: Do you see any logic error in the above code? Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 5/8

Boolean Expressions A boolean expression is an expression that evaluates to either true or false (e.g. x > y). What are other things you can do with conditionals? See the table below for some binary operators you can use. symbol meaning > greater than >= greater than or equal to < less than <= less than or equal to == equal to!= not equal to && AND OR Note that equal to symbol consists of two = s not just one. (Ask yourself now: how are = and == different?) As in arithmetic expressions you saw last week, you can use parentheses in boolean expressions. and and or operations apply to boolean expressions only. Let s do some exercises. Assume x, y, z are all integers. Try reading the following expressions in English. x >= y x == y (x - y) > 10 x > y && y < z ((x!= y) (x > 3)) && (y == z) Don t really try the last one, but you should know what it means. Question: The following expressions are all invalid. Do you see why? x = y x!= y x x < 10 && > 5 5 < x < 10 Question: Now suppose x == 5, y == 6, z == 7. Can you evaluate the following expressions? x >= y x == y (x - y) > 10 x < y && y < z ((x!= y) (x > y)) && (y == z) (x!= y) ((x > y) && (y == z)) Question: Now let s write a couple of expressions! appleprice is less than 50 appleprice times numapples is greater than 10 or numpeaches is greater than 5 Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 6/8

Back to If Statements Now, can you predict the output of the following program? double gasprice = 1.00; // $1 per gallon (we all hope) double tank = 10; // how many gallons to fill the whole tank? double remaining = 1; // 1 gallons left in our tank... double inpocket = 35; // 35 dollars in my pocket... if (gasprice * (tank - remaining) <= inpocket) cout << "Enough money, let's fill it up." << endl; else cout << remaining << " gallons of gas might be enough to get me home." << endl; // Wait, but I m too hungry -- let s get some food inpocket = inpocket - 10; if (gasprice * (tank - remaining) <= inpocket) cout << "Enough money, let's fill it up." << endl; remaining = tank; inpocket = inpocket - (gasprice * (tank - remaining)); else cout << "Not enough money to fill the whole tank, but enough for " << gasprice * inpocket << " gallons." << endl; remaining = remaining + inpocket / gasprice; inpocket = 0; cout << "I have " << remaining << " gallons in the tank." << endl; Output: Try this in Visual C++. Was your prediction correct? Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 7/8

Additional Notes on Number Types int and double are both types that represent numbers, and thus are compatible. The following lines are valid: double x = 5; int y = 7.0; When you assign a non-integer into an integer, it takes the floor of the number (i.e. decimal points are dropped -- the number is NOT rounded): int z = 10.999; // z becomes 10 If an arithmetic expression consists only of integers, it evaluates to an integer. And this holds even for divisions. int q = 5 / 2; // q becomes 2 Note that 5 / 2 is an integer 2 not because you are assigning it into an integer q, but because it is a division that involves only integers. This means, quite confusingly to many at first: double q2 = 5 / 2; // q2 becomes 2.0! Damn! How do I make it such that q2 correctly gets 2.5? Simply make sure your expression contains an non-integer! That is: double q2 = 5.0 / 2; // q2 will be 2.5 You can t apply this.0 trick to integer variables. If your expression involves an integer variable, then you should do: int d = 5; double q3 = (double) d / 2; or equivalently double q3 = static_cast<double>(d) / 2; This is a technique called casting, but you probably won t use it much in this class, so the above use is the only thing you need to know about casting. Copyright Brian Choi 2011. All Rights Reserved. Week 2, Page 8/8