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

Similar documents
CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

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

The C++ Language. Arizona State University 1

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

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

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

CS31 Discussion. Jie(Jay) Wang Week6 Nov.4

2 nd Week Lecture Notes

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

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

Name Section: M/W T/TH Number Definition Matching (6 Points)

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Fundamentals of Programming CS-110. Lecture 2

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

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Chapter 2: Basic Elements of C++

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

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

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

LECTURE 02 INTRODUCTION TO C++

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;

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

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

Introduction to Programming EC-105. Lecture 2

Name Section: M/W T/TH Number Definition Matching (8 Points)

A First Program - Greeting.cpp

Getting started with C++ (Part 2)

Objectives. In this chapter, you will:

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

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

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

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

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

CHAPTER 3 BASIC INSTRUCTION OF C++

Practice test for midterm 1

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

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

Computer Programming : C++

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

Chapter 2: Introduction to C++

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 (!

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

CSCI 1061U Programming Workshop 2. C++ Basics

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

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

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

A SHORT COURSE ON C++

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

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

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Operations. Making Things Happen

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++

CSCE 121 ENGR 112 List of Topics for Exam 1

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

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

C++ Input/Output: Streams

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

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

Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

Programming with C++ as a Second Language

Week 3: File I/O and Formatting 3.7 Formatting Output

BITG 1233: Introduction to C++

Exercise 1.1 Hello world

Engineering Problem Solving with C++, Etter/Ingber

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

6.096 Introduction to C++ January (IAP) 2009

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

LESSON 4. The DATA TYPE char

CS302 - Data Structures using C++

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

C++ Quick Reference. switch Statements

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

VARIABLES & ASSIGNMENTS

EECS 183, Week 5. General. Variables I/O. 0. At which location do you have to take the exam? 1. Source code vs. object code? 2. What s a library?

Chapter 2. C++ Basics

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

Computer Programming

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

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

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

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

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Why Is Repetition Needed?

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

Understanding main() function Input/Output Streams

Introduction to Programming

Chapter 3 - Notes Input/Output

Computer Science II Lecture 1 Introduction and Background

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Chapter 2 C++ Fundamentals

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

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

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Name. CPTR246 Spring '17 (100 total points) Exam 2

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

Transcription:

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

Outline Problems from Project 1 Review of lecture String, char, stream If-else statements Switch statements loops Programming challenge

Problems from Project 1 Q1: Should I write return 0; at the end of the main() function? A: No need to write it in C++ program. Operating System (Windows/Mac OS/Linux) Main function will return integers to the operating system. Zero The program executes w/o errors Non-zero The program executes w/ errors. Operating System (Windows/Mac OS/Linux) #include <iostream> using namespace std; int main(){ cout << "Hello World!" << endl; return 0; -1/0/1/2/

Problems from Project 1 #include <iostream> using namespace std; int main(){ cout << "Hello World" << endl; // return 0; Still works. The compiler will handle the case and add return 0; for you at the end of the main() function. #include <iostream> using namespace std; int main(){ int age; cin >> age; if (age < 0){ cout << "Please input nonnegative number!" << endl; return 1; cout << age << endl; return 0;

Problems from Project 1 Q2: What are these lines in the console? (If you are using Visual Studio) A: The text Press any key to continue is added by IDE, and there is not need to worry about it confounding your answers.

String Strings are objects that represent a sequence of characters. #include <string> Examples: Jie \n A few things you can do with strings. Operation What it does Example string s = hello ; string s =!!! ; Declare strings s and s2 s.length() or s.size() Return the length of s cout << s.size(); // prints 5 s[i] or s.at[i] Return i-th character. (i should be integer between 0 and size-1 (inclusive)) cout << s[1]; // prints e cout << s.at(0); // prints h s + s2 Concatenate two strings cout << s + s2; // prints hello!!!

String Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> using namespace std; Input: Jay Output: Hello! Jay int main(){ string name; getline(cin, name); cout << "Hello! " << name << endl; Compiler is being nice to you. It detects that you are using strings and includes the library <string> for you. It is always the best practice to include <string> when you are using strings. (<iostream> also includes part of definitions in <string>)

String Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> using namespace std; int main (){ string text = "hi", blank = "", space = " ", newline = "\n", result; result = text + blank + space + "!" + newline; cout << result << endl; cout << "---" << endl; Output: hi! ---

String Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> using namespace std; int main () { string test = "hi"; int five = 5; test = test + five; cout << test << endl; Output: This program won t compile. The operands for concatenation operator + should be two strings.

Char Characters are single letters or symbols like a, or, include special characters like the new line character \n. We use single quotes to designate characters. Characters can be represented by a unique integer value. ASCII(American Standard Code for Information Interchange) defines the mapping between characters and integers. #include <iostream> #include <string> using namespace std; int main () { int x = '0'; // Note that x is an integer and '0' is a character! cout << x << endl; Output: 48

Char Here are some functions you can call on characters, after including <cctype> library. Operation char c; isspace(c) isalpha(c) isdigit(c) islower(c) isupper(c) What it does Declare a character c True if c is a whitespace character True if c is a letter True if c is a digit True is c is a lowercase letter True if c is a uppercase letter You can refer to this webpage for more details about <cctype> http://www.cplusplus.com/reference/cctype/?kw=cctype

Char Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> #include <cctype> using namespace std; Output: int main () { string c = 'hi5'; cout << isalnum(c[2]) << endl;

Char Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> #include <cctype> using namespace std; int main () { string c = "hi5"; cout << isupper(c[2]) << endl; Output: 0 isupper(c) returns non-zero value if c is an uppercase alphabetic letter. Zero otherwise.

Stream In C++, I/O performed by using streams. A stream is a stream of data in which character sequences are flow into or flow out off. cout is the standard output stream which by default accesses the screen. cin is the standard input stream which by default accesses the keyboard. A B 1 2 cout #include <iostream> #include <string> using namespace std; int main() { cout << "AB12" << endl; 2 1 B A cin #include <iostream> #include <string> using namespace std; int main() { string c; cin >> c;

Stream cin >> var; command accesses input characters, ignores whitespace, and ignores the newline at the end of the user s input. We use this to get numerical input, and store it in variable var. getline(cin, s); command consumes all characters up to, and including, the newline character. It then throws away the newline, and stores the resulting string in s. We use this to gather string inputs. (requires <string> library) #include <iostream> #include <string> using namespace std; int main () { string inputstring; int inputint; cout << "Enter a number: "; cin >> inputint; cout << "Input was: " << inputint << endl; cout << "Enter a string: "; getline(cin, inputstring); cout << "Input was: " << inputstring << endl; Input: 32 world Output: Enter a number: 32 Input was: 32 Enter a string: Input was:

Stream cin 1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main () { 6 string inputstring; 7 int inputint; 8 cout << "Enter a number: "; 9 cin >> inputint; 10 cout << "Input was: " << inputint << endl; 11 cout << "Enter a string: "; 12 getline(cin, inputstring); 13 cout << "Input was: " << inputstring << endl; 14 At line 9: 3 2 \n Input: 32 world Output: Enter a number: 32 Input was: 32 Enter a string: Input was: inputint 32 The value 32 is stored in the variable inputinput, \n is left in the cin stream. cin \n At line 12: The getline(cin, inputstring) consumes \n, then discards the newline \n, and stores the string left to inputstring. Since there is nothing left, null character is stored to inputstring. cin inputstring

Stream 1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main () { 6 string inputstring; 7 int inputint; 8 cout << "Enter a number: "; 9 cin >> inputint; 10 cout << "Input was: " << inputint << endl; 11 cin.ignore(10000, '\n'); 11 cout << "Enter a string: "; 12 getline(cin, inputstring); 13 cout << "Input was: " << inputstring << endl; 14 Input: 32 world Output: Enter a number: 32 Input was: 32 Enter a string: world Input was: world To fix it, we will need to consume the extra newline. cin.ignore(n, pattern) ignores n characters or until the first encountered instance of pattern from input stream. At line 11: cin \n cin.ignore(10000, \n ); command consumes either 10000 characters, or discards all the characters until the first encountered \n (inclusive). At line 12: cin w o r l d \n Use cin.ignore(n,pattern) when we ve used cin and then directly after use getline. cin inputstring world The getline(cin, inputstring) consumes world\n, then discards the newline \n, and stores the string left to inputstring.

If-else statements In many cases, you want your program to behave differently based on some condition. if-else statements are what you would use in those cases. If takes the following form: if (condition) statement; if (condition){ statement1; statement2; Use curly brackets when there are multiple statements in the if-block if (condition1){ // Execute if condition1 is evaluated as true statement1; statement2; else { // Execute if condition1 is evaluated as false statementn; if (conditional1){ // Execute if conditional1 is evaluated as true else if (conditional2){ // Execute if conditional1 is evaluated as false AND // conditional2 is evaluated as true else { // Execute if conditional1 is evaluated as false AND // conditional2 is evaluated as false

If-else statements Boolean statements The condition in the if statement must be a yes-or-no question. We express this question in the form of a boolean expression, which evaluates to either true or false. symbol Meaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to!= Not equal to && AND OR Equal to symbol consists of two = s, not one. => And =< are invalid.

If-else statements Question: Suppose that x==5,y==6,and z==7. Can you evaluate the following expressions? Boolean statement x >= y x == y x y > 10 x > y && y < z ((x!= y) (x > y)) && (y == z) (x!= y) ((x > y) && (y == z)) Answer False False False False False True

If-else statements Question: Will this program compile? If so, what s the output? #include <iostream> #include <string> using namespace std; int main () { int age; cin >> age; if (age = 30){ cout << "Your age: 30" << endl; else { cout << "You are not 30" << endl; Input: 40 Output: Your age: 30 The result of assignment age = 30 is the value of the age after the assignment. 30 is a non-zero number, the result of the condition is therefore true. If the value assigned is 0, the condition is false.

Switch statements The switch statement is used to check for a value among a number of possible constant expressions. The value of the expression you use should be an integer (int), or something that is equivalent to an integer (char or enum). It is something similar to concatenating if-else statements, but limited to constant expressions. switch (expression) { case constant1: group-of-statements-1; break; case constant2: group-of-statements-2; break;... default: default-group-of-statements; Switch example switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; If-else equivalent if (x == 1) { cout << "x is 1"; else if (x == 2) { cout << "x is 2"; else { cout << "value of x unknown";

Switch statements Question: Will this program compile? If so, what s the output? #include <iostream> using namespace std; int main(){ int x; cin >> x; switch (x) { case 1: cout << "x is 1"; break; case 2: case 3: cout << "x is 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; Input: 1 Output: x is 1 Input: 2 Output: x is 2 or 3 Input: 3 Output: x is 2 or 3 Input: 4 Output: x is not 1, 2 nor 3

Switch vs. if-else https://www.quora.com/what-is-the-differencebetween-switch-and-if-else-statements-which-isbetter-in-different-cases-why

Loops Loops let you repeat the same or similar task multiple times. Three primitive loops in C++: while, do-while, and for. while loop while (condition) 2 body; do-while loop do { 1 body; 2 while (condition); 1 Don t forget the ; here. 1. Evaluate the condition. If true, 2. run the body. Go back to 1, If false, exit the while loop. 1. Execute the body. 2. Evaluate the condition If true, Go back to 1, If false, exit the while loop. Notice: The body in do-while loop will be executed once no matter what.

Loops Question: Will this program compile? If so, what s the output?

Loops Question: Will this program compile? If so, what s the output? #include <iostream> using namespace std; Output: 1 2 3 4 5 6 7 8 9 10 int main() { int x = 0, y = 10; while (x < y) { x++; // equivalent to x = x + 1 cout << x << " "; cout << endl; return 0;

Loops for loop 1 2 for (initialization; condition; update) body; 3 1. Execute initialization. 2. Evaluate the condition. If true, 3. Run the body. 4. Do the update. Go back to 2. If false, exit the for loop. 4

Loops Question: Will this program compile? If so, what s the output? #include <iostream> using namespace std; int main () { int iterations = 10; for (int i = 0; i < iterations; i++) { if (i % 2 == 0) { cout << i << endl; Output: 0 2 4 6 8 %: modulus operator -> compute the remainder that results from preforming integer division

Loops 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. for (initialization; condition; update) { body; initialization; while (condition) { body; update;

Loops Question: Convert the following for loop into a while loop. for (int i = 0; i < 50; i += 2) { cout << "Hello" << endl; int i = 0; while(i < 50){ cout << "Hello" << endl; i += 2;

Programming challenge 0 1 2 3 4 i Design a program that writes a 5 by 5 capital letter N made up of the character N. Output should be: 01234 N N NN N N N N N NN N N Hints: j j =?, print N j =?, print N j =?, print N 0 i < 5

Programming challenge N N NN N N N N N NN N N #include <iostream> #include <string> using namespace std; int main () { // Assume SIZE must be odd const int SIZE = 5; // For loop that goes through // SIZE rows... for (int i = 0; i < SIZE; i++) { // And loop that goes through // SIZE columns for (int j = 0; j < SIZE; j++) { // [!] Condition for printing 'N' // HINT: 3 cases for printing one! if (??? ) { cout << "N"; // Otherwise, print a space else { cout << " "; cout << endl; #include <iostream> #include <string> using namespace std; int main () { // Assume SIZE must be odd const int SIZE = 5; // For loop that goes through // SIZE rows... for (int i = 0; i < SIZE; i++) { // And loop that goes through // SIZE columns for (int j = 0; j < SIZE; j++) { // [!] Condition for printing 'N' // HINT: 3 cases for printing one! if (j == 0 j == 4 j == i) { cout << "N"; // Otherwise, print a space else { cout << " "; cout << endl;

Advice When encountering new problems in C++, Google www.cplusplus.com www.stackoverflow.com

Credit to 2 previous CS31 TAs This slide is finished with reference from: Andrew Forney http://web.cs.ucla.edu/~forns/ Brian Choi http://netlab.cs.ucla.edu/~schoi/cs31/

Thanks!