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:

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

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

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Introduction to Programming Using Java (98-388)

Introduction to C ++

Absolute C++ Walter Savitch

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

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

A SHORT COURSE ON C++

CSCE 110 PROGRAMMING FUNDAMENTALS

Scientific Computing

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

UNIT- 3 Introduction to C++

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

Lab Instructor : Jean Lai

Computer Science II Lecture 1 Introduction and Background

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

CSCE 206: Structured Programming in C++

a data type is Types

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

C++ Quick Guide. Advertisements

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

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

Chapter 14 Sequential Access Files

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Types, Values, Variables & Assignment. EECS 211 Winter 2018

G52CPP C++ Programming Lecture 17

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

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

Short Notes of CS201

C++ Support Classes (Data and Variables)

Fundamentals of Programming CS-110. Lecture 2

COMP322 - Introduction to C++ Lecture 01 - Introduction

Ch. 12: Operator Overloading

CS201 - Introduction to Programming Glossary By

CS2255 HOMEWORK #1 Fall 2012

Programming Language. Functions. Eng. Anis Nazer First Semester

CSI33 Data Structures

Understanding main() function Input/Output Streams

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

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

Computer Programming : C++

Summary of basic C++-commands

Introduction to C++ Systems Programming

Bruce Merry. IOI Training Dec 2013

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Introduction to Programming using C++

The C++ Language. Arizona State University 1

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

PIC 10A Objects/Classes

Chapter 2 Basic Elements of C++

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Chapter 3 - Functions

CSCI 1061U Programming Workshop 2. C++ Basics

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Motivation was to facilitate development of systems software, especially OS development.

Chapter 2: Basic Elements of C++

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

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

CHAPTER 3 Expressions, Functions, Output

AN OVERVIEW OF C++ 1

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

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 2. Procedural Programming

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

Chapter 2 C++ Fundamentals

Objectives. In this chapter, you will:

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

Variables. Data Types.

Input And Output of C++

Chapter 15 - C++ As A "Better C"

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Cpt S 122 Data Structures. Introduction to C++ Part II

CS242 COMPUTER PROGRAMMING

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

CS3157: Advanced Programming. Outline

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

Interview Questions of C++

CPSC 427: Object-Oriented Programming

A First Program - Greeting.cpp

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Basics of Java Programming

C++ basics Getting started with, and Data Types.

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

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

Motivation was to facilitate development of systems software, especially OS development.

Outline. 1 About the course

WARM UP LESSONS BARE BASICS

Function Overloading

Highlights. - Making threads. - Waiting for threads. - Review (classes, pointers, inheritance)

Transcription:

Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams Vectors Strings You remember all of this, right? 2 Hello, Let s Review Here s a simple C++ program: #include <iostream> using namespace std; string hello = "Hello, world!"; cout << hello << endl; 3 A function, specifically the required function Return type Hello, Let s Review #include <iostream> using namespace std; Function name (Empty) parameter list Assignment operator Variable Literal string hello = "Hello, world!"; cout << hello << endl; Type Return Operator value This tells the compiler that it should include symbols and types from the standard library iostream. This is boilerplate that lets you use standard library symbols without extra ugly syntax. Don t worry about it for now, just put it in whenever you #include something. 4 How to Review Reing slides: Some new material e.g., function overloading Mostly review Your responsibility: Go through all the slides that follow Note any questions on old or new concepts Try to learn concept from textbook Ask instructor if you still have questions! Starts with fun! FUNDAMENTALS 5 6 1

Declaration: int x; Use in expressions: x + 10 Set via assignment operator: x = 4; Declare and initialize: int x = 42; Variables Types Basic types Integer types: int : 42, -99, 103482039 unsigned: like int, but non-negative values only char : 'k' Floating point types: double : 3.14159, 4.5e3, -0.0001 Boolean type: bool : true, false Pointers Arrays Class/struct types 7 8 Expressions Working definition: anything with a value is an expression: Variables x Indexed array variables arr[10] Literals 42 "Hello" true Function calls returning a value sqrt(17) Arithmetic/logical expressions using operators (next page) Operators Operators are like functions, but expressed in a more mathematical format: The addition operator. It is a binary infix operator, i.e., it acts on the two operands on either side. x + 4 The two operands must be expressions. Here, one is a variable, and one is a literal. The logical negation operator. It is a unary prefix operator.!a 9 10 Operators & Expressions Arithmetic expressions 4 + 7 / 3.0 (x * sqrt(2) + 1) % y Mixed type expressions allowed due to numeric type conversions Logical expressions: count == 0 // true if count = 0 a b &&!c // a or b and not c Which operators act first? Use parentheses or know precedence rules. Expressions and Types Anything with a value also has a type! Literal types are inferred from their formats: 42 -> int "Hello" -> char[] (not string more soon) true -> bool Variables/indexed array variables get the type of the variable: int x; x -> int Function definitions specify return type double sqrt(double n) { sqrt(42) -> double Operator expressions: type depends on operator and operands int x = 1; x + 17 -> int x + 17.0 -> double string a = "Hello", b = "world"; a + b -> string 11 12 2

Loops What if we want to print Hello, world! three times? Initial value for i for (int i = 1; i <= 3; i++) { cout << i << " Hello, world!" << endl; Output: 1 Hello, world! 2 Hello, world! 3 Hello, world! Loop condition Loop update int i = 3; Another Loop while (i > 0) { cout << i << " Hello, world!" << endl; i--; Output: 3 Hello, world! 2 Hello, world! 1 Hello, world! Also should know use of: break continue 13 14 Conditionals if (true-false-expression) { true-block else { false-block Hello, if? Let s modify Hello to respond to an input: char answer; cout << "Say (H)ello or (G)oodbye?" << endl; cin >> answer; if (answer == 'H') { cout << "Hello, world!" << endl; else { cout << "Goodbye, world!" << endl; What happens if the user enters h instead of H? 15 16 Arrays Arrays int numbers[3]; numbers[1] = 14; numbers[2] = -3; numbers[3] = 7093; Oops! What s wrong here? int numbers[3]; numbers[0] = 14; numbers[1] = -3; numbers[2] = 7093; Let s print out the numbers in the array. What about in reverse order? 17 18 3

Loops on Arrays int numbers[] = {14, -3, 7093; Array initialization only when array is declared! for (int i = 0; i < 3; i++) { cout << numbers[i] << endl; for (int i = 2; i >= 0; i--) { cout << numbers[i] << endl; Even more fun! FUNCTIONS 19 20 Functions Hello Functions! We ve seen one function: Here s another: return type name parameter list int print_it(string msg) { cout << msg << endl; return msg.length(); body (statements) A silly program. #include <iostream> #include <string> #include <cmath> using namespace std; int print_it(string); int n; double nroot; Note, we have to declare a function before we use it. Here we used a function prototype declaration; alternately we could have just defined the entire function here. n = print_it("hello, world!"); nroot = sqrt(n); cout << "The square root of the number of characters printed is "; cout << nroot << endl; 21 int print_it(string msg) { cout << msg << endl; return msg.length(); 22 Recursion Functions can call themselves. void print_n_times(string s, int n) { if (n == 0) return; cout << s << endl; print_n_times(s, n 1); Base case. Very important! Recursive call. Note that the parameter n moves towards the base case condition. Function Overloading C++ allows multiple functions of the same name: void print_it(int x) { cout << "an integer: " << x << endl; void print_it(string s) { cout << "a string: " << s << endl; What to call based on the parameter list So parameter lists must be different for each overload Can get confusing when mixed with type promotion: print_it(3.1415); // what does this do? 23 24 4

Default Parameters Pass by Value or Reference Alternative when one overload is just a specialized version of another: // prints n times, or just once if n omitted void print_n_times(string s, int n = 1) { for (int j = 0; j < n; j++) { cout << s << endl; With the above, we can do: print_n_times("hello", 10); or print_n_times("goodbye"); // prints Hello 10 times // prints Goodbye once Rules: Cannot omit earlier parameters, supply later ones Cannot overload if parameter list is interpretable as call to function with default params omitted, e.g., cannot also define void print_n_times(string s) { What does this program print? void set_to_zero(int x) { x = 0; int n = 42; set_to_zero(n); cout << n << endl; Answer: 42 Parameter passed by value 25 Passing Parameters by Reference The void set_to_zero(int &x) { x = 0; int n = 42; set_to_zero(n); cout << n << endl; This prints: 0 Holds stack frames aka activation records Each function call results in a new stack frame Each stack frame contains memory for: Local variables declared in the function Arguments passed into function Return address for function When the function is exited, all of this memory is returned to the stack automatically. Function Call void quotient(double num, double den) { double q = num / den; cout << num << '/' << den << " is " << q << endl; void (int x, int y) { quotient(x, y); quotient(y, x); int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); At start of () One stack frame int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); int a =? int b =? Top of By custom, the function call stack is visualized as growing down. 5

After getting input: int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); Top of At beginning of call to : void (int x, int y) { quotient(x, y); quotient(y, x); Top of At beginning of first call to quotient: At end of call to quotient: void quotient(double num, double den) { double q = num / den; cout << num << '/' << den << " is " << q << endl; quotient double num = 7 double den = 2 double q =? void quotient(double num, double den) { double q = num / den; cout << num << '/' << den << " is " << q << endl; quotient double num = 7 double den = 2 double q = 3.5 Top of Top of After return from call to quotient: At beginning of second call to quotient: void (int x, int y) { quotient(x, y); quotient(y, x); Top of void quotient(double num, double den) { double q = num / den; cout << num << '/' << den << " is " << q << endl; quotient double num = 2 double den = 7 double q =? Top of 6

At end of second call to quotient: After return from second call to quotient: > 2/7 is 0.285714 > 2/7 is 0.285714 void quotient(double num, double den) { double q = num / den; cout << num << '/' << den << " is " << q << endl; quotient double num = 2 double den = 7 double q = 0.285714 void (int x, int y) { quotient(x, y); quotient(y, x); Top of Top of After call to : > 2/7 is 0.285714 Top of CLASSES AND OBJECTS 40 Objects C++ is an object-oriented (OO) language. What s an object? A working definition: An object is a package of data with associated behavior. More specifically, we say that an object has properties (fields, attributes, data, state), and that it has associated methods (functions). Classes Objects also have type. Objects of the same type: Have a common set of properties and methods Used in a similar manner to primitive types. Types are (usually) modeled by classes. Classes formally define the properties and methods. Essentially, defining classes is a way to add new types to C++. (Classes do some other neat things, too, but we ll get to that later.) 41 7

Classes in C++ Defining Member Functions Classes are created via a class declaration: visibility modifier class student { public: string name; string year; double gpa; bool is_hungry; ; class name student(); void eat(); void sleep(); void program(int); Don t forget this semi-colon! member variable declarations (properties) (C++98 didn t allow initializers here, but C++11 does.) A constructor function. member function declarations (methods) The declaration only gave the member function signatures (prototypes); we still have to write the functions themselves: Etc. void student::eat() { is_hungry = false; void student::program(int assignment) { if (grade(this, assignment) == 'A') gpa++; this is a special keyword that references the object itself. More on this later. Scope resolution operator defines what class the method belongs to. Using Objects in C++ Objects can be created just like chars, ints, etc.: student s; Properties are referenced by the. operator: s.name = "April"; s.gpa = 4.0; double d = s.gpa; Methods are invoked on objects also using. : s.sleep(); Some Notes on Visibility Many philosophies around visibility All data should be private Partly a matter of style Rule of thumb: If it is specific to the implementation, it is private Else, it is public Not all OO languages have visibility modifiers. (But they all have commenting systems!) Streams Console I/O: #include <iostream> cin >> some_var; cout << expression << endl; string s; getline(cin, s); // must #include <string> Input/Output STREAMS File I/O: #include <fstream> ifstream fin("words.txt"); fin >> some_var; getline(fin, s); ofstream fout("output.txt"); fout << expression << endl; We ll also learn about stringstream objects (later). 47 48 8

Arrays and Vectors Arrays: int foo[10]; for (int j = 0; j < 10; j++) foo[j] = j; VECTORS Vectors: #include <vector> Declares that this vector will hold int values. Gives an initial size to the Vector. vector<int> foo(10); for (int j = 0; j < 10; j++) foo[j] = j; // foo.at(j) = j 49 50 Do More with Vectors E.g. you can append to a vector it automatically resizes: vector<int> foo; for (int j = 0; j < 10; j++) { foo.push_back(j); foo contains: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Initially size 0 without optional argument. And so much more: see Help page of course website for C++ documentation websites. Something New-ish C++ 11 added a new type of for loop: vector<int> numbers = {14, -3, 7093; for (int x: numbers) { cout << x << endl; Note vector initializer list can be used almost like a literal in certain contexts. This denotes that x is a variable of type int which will take on each value in numbers in turn. 51 52 About Strings In C/C++, the literal "Hello" is called a string. It is of type char[] (a char array). Confusingly, C++ defines a new type, string. A string is mostly interchangeable with a string (which in C++ is called a C-string ). But, you can do more with string objects: STRINGS #include <string> string foo = "Hello"; // note assignment of string to string string bar = "World"; // actually implicit constructor call string hello = foo + ", " + bar + "!"; if (foo == bar) { // test for equality works with string 53 54 9

More About Strings Know/learn the string interface! See Help page of course website for C++ documentation websites Some string methods you should know: length operator[] size operator+ find operator+= substr relational operators Up Next Please continue to review chapters 1 6, 8, 9 in your textbook Friday, August 24 Lab 1 - Compile APT 1 assigned Monday, August 27 Abstraction Lab 1 due 55 56 10