CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

Similar documents
Functions, Arrays & Structs

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

Functions, Arrays & Structs

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

The C++ Language. Arizona State University 1

UNIT- 3 Introduction to C++

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

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

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

Objectives. In this chapter, you will:

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

CHAPTER 3 Expressions, Functions, Output

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

LECTURE 02 INTRODUCTION TO C++

BITG 1233: Introduction to C++

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

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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

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:

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

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

Chapter 2: Introduction to C++

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

CHAPTER 3 BASIC INSTRUCTION OF C++

ARG! Language Reference Manual

CSCI 1061U Programming Workshop 2. C++ Basics

2 nd Week Lecture Notes

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

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Fundamental of Programming (C)

C++ Quick Guide. Advertisements

Programming with C++ as a Second Language

Introduction to C ++

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

I/O Streams and Standard I/O Devices (cont d.)

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

Input And Output of C++

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:

The pixelman Language Reference Manual. Anthony Chan, Teresa Choe, Gabriel Kramer-Garcia, Brian Tsau

Review of the C Programming Language for Principles of Operating Systems

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.

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

Creating a C++ Program

Definition Matching (10 Points)

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

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Introduction to Programming using C++

Chapter 3 - Notes Input/Output

Computer Science II Lecture 1 Introduction and Background

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

Introduction to Programming

Chapter 4 - Notes Control Structures I (Selection)

The SPL Programming Language Reference Manual

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.

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

CS3157: Advanced Programming. Outline

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Chapter 2 Basic Elements of C++

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

Chapter 7. Additional Control Structures

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

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

Fundamentals of Programming CS-110. Lecture 2

Getting started with C++ (Part 2)

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

CS2255 HOMEWORK #1 Fall 2012

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

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

Engineering Problem Solving with C++, Etter/Ingber

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review of the C Programming Language

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

Chapter 3. Numeric Types, Expressions, and Output

Chapter 2. Procedural Programming

From Pseudcode Algorithms directly to C++ programs

CS242 COMPUTER PROGRAMMING

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

Short Notes of CS201

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

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

WARM UP LESSONS BARE BASICS

VARIABLES & ASSIGNMENTS

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)

CS201 Some Important Definitions

CS201 - Introduction to Programming Glossary By

Chapter 2 C++ Fundamentals

A SHORT COURSE ON C++

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

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

Transcription:

CS 1428 Review CS 2308 :: Spring 2016 Molly O Neil

Structure of a C++ Program Hello world // This program prints a greeting to the screen #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; Generalized // This is a comment #include <includefile1> using namespace std; void functionprototypes(argument-types,...); int main() { statements return 0; void functiondefinition(arguments,...) { statements... 2

Variables & Identifiers Variable: a storage location in the computer s memory Identifier: the name of a program element (e.g., a variable). Must conform to some rules: First character must be in a-z or A-Z or _ Other characters must in a-z or A-Z or _ or 0-9 Cannot be a reserved C++ keyword (see Gaddis Table 2-4) Case sensitive: myinteger is not the same as myinteger Check class style guidelines for more info All variables must be declared (and can optionally be initialized in the same statement): < Variable Declaration int number; char letter; // stores a letter grade int number = 42; // life, the universe, and everything char letter = 'Q'; < Variable Initialization 3

Fundamental Data Types Integers short int int long long int unsigned short int unsigned int unsigned long long int usually 2 bytes s: -32,768 to +32,767 u: 0 to +65,535 usually 4 bytes s: -~2b to +~2 billion u: 0 to +~4 billion usually 8 bytes s: -~9q to +~9 quintillion u: 0 to +~18 quintillion Floating-Point (Real) Numbers float double long double usually 4 bytes +/-3.4e-38 to +/-3.4e38 usually 8 bytes +/-1.7e-308 to +/-1.7e308 usually 8-10 bytes. if 10: +/-3.4e-4932 to +/-3.4e4932 Characters char Boolean values (can only hold true or false) bool 4

Strings Not a built-in/fundamental data type, but included in standard C++ Must #include <string> for most operations string firstname, lastname; Operations include: = for assignment.size() member function for character-count ==, <,... relational operators (alphabetical order, within case) [n] for access to single char 5

Literals & Named Constants Literal: a specific value written directly into a program s code 1 75-12 11.42-3.8 6.25e-5 A 2 \n true false "This is my string I want printed to the screen" Named Constants: a variable whose value cannot be changed const datatype identifier = constant; const double TAX_RATE = 0.0825; Use these often in place of literals! Good code has very few magic constants 6

Assignment Modify the value stored in a variable (copy in a new value) variable = expression; count = 10; The left-hand side must be an lvalue (storage location) The right-hand-side is an expression that yields the correct type An expression has a type and evaluates to a value Literal Named constant Variable Arithmetic expression sum = 5; sum = INITIAL_SUM; sum = initcount; sum = 1 + 2; sum = initcount + newcount; 7

Operators Negation (unary) - negation Arithmetic (binary) + addition - subtraction * multiplication / division x + 10 7 - y 2 + 5 * sum 10 / 4 12 % z -2 -x x + 10.2 7.0 - y 2.3 + 0.5 * sum 10 / 4.0 Be careful! Integer division! % modulo < Modulo unsupported for FP Relational (binary) result is always a bool == equals!= not equal to > greater than < less than x == 13 42 < y 2!= z x + y >= 0 >= greater than or equal to <= less than or equal to 8

Operators Logical - result is always a bool! not [unary] && and [binary] or [binary] x < 10 && y > 0 z == 10 z == 20!x!(a == b) Compound Assignment (binary) Increment/Decrement (unary) Conditional (ternary) operator e.g. equivalent to += x += e; x = x + e; -= x -= e; x = x - e; *= x *= e; x = x * e; /= x /= e; x = x / e; operator e.g. equivalent to ++ x++; ++x; x = x + 1; -- x--; --x; x = x - 1; expression? expression : expression; y = x < 0? 10 : 20; 9

Operator Precedence Answers which happens first? ( )! - (unary) * / % + - (binary) < > <= >= ==!= && Parentheses can override operator precedence When in doubt, use parentheses (within reason)!(y == 10) y == 20 && x > 3 * -z + 2!(y == 10) ( y == 20 && x > (3 * -z + 2) )!(y == 10) ( (y == 20) && ( x > ( (3 * (-z)) + 2 ) ) ) parentheses used to override precedence: (!(y == 10) y == 20 ) && x > 3 * (-z + 2) equivalent 10

Type Conversion Type coercion: If you use an operator on two different data types, C++ will implicitly (try to) convert operands to same type char, short always promoted to int Type order: double float long int char When operator works on 2 types, lower rank promoted to higher If expression yields value of one type that is assigned to lvalue of other type, it is converted to the type of the lvalue Caution: this may result in loss of information! int x, y = 2; int x = 10, y = 4; float z = 1.2; double d1 = x / y; // d =?? oops!!! x = y * z; // x =?? double d2 = 10 / 4.0; // d = 2.5 Type casting: You can also manually (explicitly) promote/demote a value int sum, count;... float avg = static_cast<float>(sum) / count; 11

User-Defined Data Types (Structs) A struct (structure) stores a user-defined collection of physically-grouped variables of possibly-different types Define the new struct data type, then declare variables of your new type Each element in the struct is a member Accessed using the. (dot) operator struct Student { int idnumber; string name; float gpa; ; Define a new data type Declare new variables Student student1, student2; Student student3 = {123456, "Alan Turing", 3.57; student1.name = "Ada Lovelace"; student2.idnumber = 987654; 12

Struct Operations Valid operations over entire structs: Assignment: student1 = student2; Function call: myfunc(student1, x); INVALID operations over structs: Comparison: student1 == student2 Output: cout << student1; Input: cin >> student2; All of these must be done member by member 13

I/O #include <iostream> Output (cout and <<) cout << expression; cout << expr1 << expr2; cout << "Hello world!\n"; cout << "Count is: " << count << endl; Input (cin and >>) cin >> variable; cin >> var1 >> var2; RHS must be an lvalue cin >> x; cout << "Enter the height and width: "; cin >> height >> width; (will separate on whitespace) 14

Output Formatting #include <iomanip> setw: sets field width for immediately-following value int value = 23; cout << "(" << setw(5) << value << ")"; ( 23) setprecision: sets the # of significant digits of FP # double value = 28.92786 cout << setprecision(3) << value; fixed: sets fixed-point notation. With fixed, setprecision sets # of digits to right of decimal point double value = 28.92786; cout << setprecision(2) << fixed; cout << value; showpoint: shows trailing zeros for existing setprecision, always shows decimal point for FP double value = 32.0; cout << setprecision(5) << showpoint << value; 28.9 28.92 left / right: left or right justify text inside field width 32.000 15

File I/O #include <fstream> Output (ofstream) ofstream fout; fout.open("filename.txt"); fout << "Hello!\n"; fout << "Count is: " << count << endl; fout.close(); Input (ifstream) ifstream fin; fin.open("filename.txt"); if(!fin) { cout << "Error opening file" << endl; return -1; Always check for file errors! int num; fin >> num; RHS must be an lvalue cout << "You entered: " << num << endl; fin.close(); 16

File I/O: Reading to EOF fin >> x returns true when a value is successfully read, false otherwise ifstream fin; fin.open("input.txt"); int x; while(fin >> x) { cout << "Next number is: " << x << endl; fin.close(); Final time fin >> x is attempted, nothing is read into x, expression returns false 17

I/O: Dealing with Spaces >> operator uses whitespace as delimiter, leading to problems when a token has more than one word (e.g., a full name) Solution: getline(filestream, str) Reads an entire line (to a newline character) from the specified file stream (either cin or an ifstream object) Stores the data read from the file stream to string 'str' string input; ifstream namefile; namefile.open("names.txt"); getline(namefile, input); When used in combination with >>, must ignore leading whitespace characters left by >> operator, e.g.: cin.ignore(100, '\n'); // ignores the next 100 characters or // until newline encountered 18

Decision/Control Structures Compound statements ( block ) { statement1; statement2;... Procedural programming: list of instructions (often separated into subroutines) specifying what computer should do, step by step, from first instruction to next Sequence structure: statements executed in sequence, without any choices of direction (branches) Decision structure: allows some statements to be executed only under certain conditions No Yes? Do something 19

If/Else Statements If/Else If expression is true (non-zero), statement_block1 is executed If expression is false, statement_block2 is executed if(expression) statement_block1 else statement_block2 if(expression) { statement1; statement2; else { statement3; statement4; The else part is optional if(expression) statement_block1 Nested if/else if(expression1) statement_block1 else if(expression2) statement_block2 else if(expression3) statement_block3 else statement_block4 20

Switch Statements The value of a variable/expression determines where of several options the program will branch switch(expression) { case constant1: statements constantx must be case constant2: statements integer or char literal... default: statements < default case is optional Execution starts at case labeled with expression s value If no match, execution starts at default Use break; to exit a switch case (otherwise execution continues through following cases) switch(ch) { case a : case A : cout << "You chose A"; break; case b : case B : cout << "You chose B"; break; default: cout << "Invalid choice"; 21

Loops While loop while(expression) statement_block int x = 0; while(x <= 0) { cout << "Enter a positive integer: "; cin >> x; if expression is true, statement_block is executed; repeat Do-while loop do statement_block while(expression); int x; do { cout << "Enter a positive integer: "; cin >> x; while(x <= 0); For loop for(init_expr; test_expr; update_expr) statement_block for(int i = 0; i < 10; i++) { // statements here Equivalent to: init_expr; while(test_expr) { statements update_expr; 22

Terminating a Loop Iteration Sometimes you want to exit a loop iteration before the end of the loop body. 2 statements to do so: break: Terminates both the loop iteration and the loop itself, i.e., the condition will not be re-checked and execution will proceed from the closing curly brace that ends the loop scope continue: Skips the rest of the loop body and continues with the next loop iteration (after re-checking the loop entry condition) while(true) { char x; cout << "enter e to exit or c to continue: "; cin >> x; if(x == 'e') break; if(x == 'c') continue; cout << "you entered something other than e or c!" << endl; cout << "exited." << endl; 23

Nested Loops Lots of problems require nesting one loop inside another for(int hour = 0; hour < 24; hour++) { for(int minute = 0; minute < 60; minute++) { for(int second = 0; second < 60; second++) { cout << hour << "h "; cout << minute << "m "; cout << second << "s" << endl; $./a.out 0h 0m 0s 0h 0m 1s... 0h 0m 59s 0h 1m 0s... 0h 59m 59s 1h 0m 0s... 23h 59m 59s 24

Functions Function: collection of statements that perform specific, related task Divide problem into small, manageable pieces Allow for easy code reuse Function Definition: datatype identifier (parameter1, parameter2,...) { statements... datatype identifier datatype: the data type returned by the function identifier: the name by which the function can be called parameters: allow passing arguments to the function when it is called; from within the function, act as a local variable statements: The function s body; executed (with parameter values from call) when function is called 25

Functions #include <iostream> using namespace std; parameter int sum(int a, int b) { int result = a + b; return result; Function call: Causes control flow to branch to body of function named identifier parameter1 in function definition initialized to value of expression1, etc. Return statement: argument int main() { int s = sum(2, 7); cout << "The result is " << s << endl; identifier(expression1,...) return expression; Inside a function, causes function to stop & return control to caller Value of return expression (if present) becomes value of functional call expression 26

Functions Void function: a function that returns no value Initialization routines, display routines, etc. void printsum(int a, int b) { int result = a + b; cout << "The result is " << result << endl; int main() { printsum(2, 7); { Function prototype: placed before a function call to tell compiler details about fn s return type & parameters datatype identifier(datatype1, datatype2,...); Alternative is to place entire function definition before first call to function You can give parameter identifiers as well, but optional 27

Pass by Value vs. Pass by Reference Pass by value: when an argument is passed to a function, its value is copied behind-the-scenes into the parameter Parameter and argument are separate storage locations Changes to parameter in function body do NOT change value of the argument in the call This is what happens by default in C++ (except for arrays, sort of... stay tuned) Pass by reference: when an argument is passed to a function, the function has direct access to the original argument Single storage location (reference parameter acts as alias to argument) Changes to the parameter in function body DO change value of the argument in the call Implemented in C++ using reference parameters (add & after parameter type in function prototype and definition) void zeromyvalue(int &myvalue) { myvalue = 0; 28

Pass by Value Example #include <iostream> using namespace std; void zeromyvalue(int); int main() { int myvalue = 42; cout << "Inside main: myvalue = " << myvalue << endl; zeromyvalue(myvalue); cout << "Back inside main: "; cout << "myvalue = " << myvalue << endl; return 0; void zeromyvalue(int myvalue) { myvalue = 0; cout << "Inside zeromyvalue: "; cout << "myvalue = " << myvalue << endl; What is the program output? 29

Pass by Reference Example #include <iostream> using namespace std; void zeromyvalue(int &); int main() { int myvalue = 42; cout << "Inside main: myvalue = " << myvalue << endl; zeromyvalue(myvalue); cout << "Back inside main: "; cout << "myvalue = " << myvalue << endl; return 0; void zeromyvalue(int &myvalue) { myvalue = 0; cout << "Inside zeromyvalue: "; cout << "myvalue = " << myvalue << endl; What is the program output now? 30

Variable Scope A variable's scope defines in which parts of the program the variable can be accessed/"seen" Variables exist only inside their own scope, destroyed at the end of it Global variable (defined outside of all functions): accessible everywhere after its definition Local variable (defined inside a function): accessible inside the block { in which it is defined, after its definition Parameter: accessible anywhere inside of its function body Variables at the exact same scope cannot have the same name Variable defined in inner block will block a variable with same name in outer block int x = 10; { int x = 20; cout << x << endl; cout << x << endl; outputs: 20 10 31

Arrays An array is: A series of values of the same data type [0] [1] [2] [3] Stored in contiguous memory locations That can be individually referenced by index Declaration: datatype identifier[size]; int numbers[10]; datatype is the type of the array values identifier is the name of the array SIZE is the number of elements (literal or constant) Initialization: float scores[3] = {86.5, 92.1, 77.5; // initializes first 3 indices, zeroes the rest float scores[10] = {86.5, 92.1, 77.5; // determines array size from init list (3) float scores[] = {86.5, 92.1, 77.5; 32

Array Elements & Indexing To access the value of a particular array element: scores[2] = 77.5; If array scores is an array of floats, scores[2] is a float Can be used like any other float variable: as an lvalue (i.e., you can assign a new value to it) in arithmetic expressions passed as an argument to a function Subscripts/indexes always begin at 0, end at arraysize-1 Array index must have type int, but can be the result of any expression that yields an int Generally must operate on individual array elements, not entire array, e.g... Cannot assign one array to another Cannot input directly into an array Cannot use relational operators to compare one array to another 33

Passing Arrays to Functions In the function prototype: void showarray(int [], int); almost always want to pass array size or count of valid elements to functions that operate on arrays In the function definition: void showarray(int arr[], int size) {... In the function call, pass the array name (no brackets!) int numbers[5] = {1, 2, 3, 4, 5; showarray(numbers, 5); In C++, arrays are implicitly passed by reference If you pass an array to a function, function can modify the original array in the calling scope const keyword in front of type in parameter declaration to disallow 34

Array Function Example Find sum of all elements in an array int sumarray(const int [], int); int main() { const int NUM_ELEMENTS = 10; int numbers[num_elements];... // assign values to numbers[0] through numbers[9] int sum; sum = sumarray(numbers, NUM_ELEMENTS); int sumarray(const int arr[], int size) { int total = 0; for(int i = 0; i < size; i++) { total += arr[i]; return total; Other common array functions: find largest element, find smallest element, count occurrences of a value, etc. 35

Parallel Arrays vs. Arrays of Structs To store related data of different types, you could keep multiple arrays with shared subscripts int hoursworked[5]; double payrate[5];... double employee0grosspay = hoursworked[0] * payrate[0]; Or you could use an Array of Structures struct Employee { int hoursworked; double payrate; ;... Employee employees[5];... double employee0grosspay = employees[0].hoursworked * employees[0].payrate; 36

2-Dimensional Arrays You can think of a 2-D array as several 1-D arrays of the same size and type strung together into consecutive memory Definition: double scores[nrows][ncols]; row 0 row 1 col 0 col 1 col 2 col 3 [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] [1][2] [1][3] Element access: scores[row_num][col_num]; Nested loops and 2-D array iteration: for(int r = 0; r < NROWS; r++) { for(int c = 0; c < NCOLS; c++) { cout << "scores[" << r << "][" << c << "] = "; cout << scores[r][c] << endl; 37

Default Arguments Default argument: value passed to a parameter automatically if no argument is provided in function call Assigned in earliest occurrence of function name (usually this is the fn prototype) void printarea(int = 10, int = 5); void printarea(int a, int b) { cout << "The area is " << a * b << endl; If there's no function prototype, then default args go in function definition: void printarea(int a = 10, int b = 5) { cout << "The area is " << a * b << endl; Function can be called as follows: printarea(2, 6); // outputs: "The area is 12" printarea(); // outputs: "The area is 50" printarea(3); // outputs: "The area is 15" 38

Default Argument Rules If you leave an argument out of a function call, all arguments that come after it must also be left out printarea(, 1); // DOES NOT COMPILE If not all parameters to a function have default argument values, the parameters with defaults must come last void printarea(int, int = 5); // OK void printarea(int = 10, int); // NOT OK 39

Function Overloading Two (or more) functions may have the same name, as long as their parameter lists are different Different types and/or number of parameters Compiler determines which function to call by matching arguments # and type(s) in call to parameter lists int square(int number) { return number * number; double square(double number) { return number * number; int main() { cout << square(10) << "\n"; cout << square(1.2) << "\n"; double calcweeklypay(int hours, double payrate) { return hours * payrate; double calcweeklypay(double salary) { return salary / 52; 40