Ch 6. Functions. Example: function calls function

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

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7

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

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

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

Getting started with C++ (Part 2)

! 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

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.

Module 7 b. -Namespaces -Exceptions handling

Programming Language. Functions. Eng. Anis Nazer First Semester

A First Program - Greeting.cpp

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

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Problem Solving: Storyboards for User Interaction

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Fundamentals of Programming CS-110. Lecture 2

Chapter Four: Loops II

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

WARM UP LESSONS BARE BASICS

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

CSCE 206: Structured Programming in C++

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

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

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.

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

Increment and the While. Class 15

Lab Instructor : Jean Lai

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

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

University of Michigan EECS 183: Elem. Programming Concepts Fall 2011 Exam 1: Part 1: Form 1. Professors: ML Dorf, Elliot Soloway

pointers + memory double x; string a; int x; main overhead int y; main overhead

Functions, Arrays & Structs

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

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011

Sample Code: OUTPUT Daily Highs & Lows

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

CSCI 111 Midterm 1, version A Exam Fall Solutions 09.00am 09.50am, Tuesday, November 24, 2015

Due Date: See Blackboard

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

Unit 14. Passing Arrays & C++ Strings

Local and Global Variables

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Computing and Statistical Data Analysis Lecture 3

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

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

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

CIS 130 Exam #2 Review Suggestions

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

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

CSc Introduction to Computing

Do not turn to the next page until the start of the exam.

Subprograms. Introduction to Programming (in C++) Subprograms: procedures and functions. Subprograms. Subprograms. Functions are defined as follows:

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

CMSC 202 Midterm Exam 1 Fall 2015

do { statements } while (condition);

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

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

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

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

File I/O Christian Schumacher, Info1 D-MAVT 2013

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

2 nd Week Lecture Notes

Topics. Functions. Functions

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

C++ For Science and Engineering Lecture 12

Introduction to Programming using C++

CS3157: Advanced Programming. Outline

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

Introduction to Programming EC-105. Lecture 2

Introduction to C++ (Extensions to C)

Unit 7. 'while' Loops

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

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

Summary of basic C++-commands

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

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

BITG 1233: Introduction to C++

The following is a typical execution run of this program:

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

a. a * c - 10 = b. a % b + (a * d) + 7 =

Program Organization and Comments

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

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

CSCE Practice Midterm. Data Types

1. In C++, reserved words are the same as predefined identifiers. a. True

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

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

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Transcription:

Ch 6. Functions Part 2 CS 1428 Fall 2011 Jill Seaman Lecture 21 1 Example: function calls function void deeper() { cout << I am now in function deeper.\n ; void deep() { cout << Hello from the function deep.\n ; deeper(); cout << Back in function deep.\n ; cout << Hello from Main.\n ; deep(); cout << Back in function Main again.\n ; Hello from Main. Hello from the function deep. I am now in function deeper. Back in function deep. Back in function Main again. 2

Example: call func more than once #include <iostream> #include <cmath> using namespace std; void pluses(int count) { for (int i = 0; i < count; i++) cout << "+"; cout << endl; int x = 2; pluses(4); pluses(x); pluses(x+5); pluses(pow(x,3.0)); ++++ ++ +++++++ ++++++++ 3 Example: multiple parameters #include <iostream> #include <cmath> using namespace std; void pluses(char ch, int count) { for (int i=0; i < count; i++) cout << ch; cout << endl; int x = 2; char cc = '!'; pluses('#',4); pluses('*',x); pluses(cc,x+5); pluses('x',pow(x,3.0)); #### **!!!!!!! xxxxxxxx 4

Passing Arguments by Value Pass by value: when an argument is passed to a function, its value is copied into the parameter. Parameter passing is implemented using variable initialization: int param = argument; Changes to the parameter in the function do not affect the value of the argument 5 Example: Pass by Value #include <iostream> using namespace std; void changeme(int); number is 12 myvalue is 200 Back in main, number is 12 int number = 12; cout << "number is " << number << endl; changeme(number); cout << "Back in main, number is " << number << endl; int myvalue = number; void changeme(int myvalue) { myvalue = 200; cout << "myvalue is " << myvalue << endl; 6

Pass by Value Parameter is initialized to a copy of the argument s value. Even if the body of the function changes the parameter, the argument in the calling function is unchanged. The parameter and the argument are stored in separate variables, separate locations in memory. 7 The return statement Used to end execution of a function Can be placed anywhere in a function--the function will transfer control back to where it was called from immediately. Statements that follow the return statement will not be executed - unless return is in an if-branch In a void function without a return statement, there is an implicit return statement before the last 8

return: example void somefunc (int x) { if (x < 0) cout << x must not be negative. << endl; else { // Continue with lots of statements, indented //... // so many it s hard to keep track of matching { The following function is equivalent, easier to read: void somefunc (int x) { if (x < 0) { cout << x must not be negative. << endl; return; // Continue with lots and lots of statements //... 9 return: don t do this The cout will never happen... ever void somefunc (int x) { if (x < 0) { return; cout << x must not be negative. << endl; // Continue with lots and lots of statements //... 10

Returning a value from a function You can use the return statement to send a value back to the function call. return expr; The value of the expr will be sent back. The data type of the value the function is returning is required in the function header: Return type: int doubleit(int x) { return x*2; 11 Calling a function that returns a value If the function returns void, the function call is a statement: pluses(4); If the function returns a value, the function call is an expression: int x = doubleit(4); The value of the function call expression is the value of the expr returned from the function. 12

Returning the sum of two ints #include <iostream> using namespace std; int sum(int,int); int value1; int value2; int total; cout << "Enter 2 numbers: " << endl; cin >> value1 >> value2; total = sum(value1, value2); cout << "The sum is " << total << endl; Enter 2 numbers: 12 45 The sum is 57 int sum(int x, int y) { return x + y; 13 Data transfer The function call from main: total = sum(value1, value2); The arguments are passed in to the function: int x = value1; int y = value2; The result, x+y, is returned to the call. total = sum(value1, value2); The value is the result of x + y 14

Function call expression When the function returns a value, the function call is an expression. The function call can occur in any context where an expression (of the return type) is allowed: - assign to variable (or array element) - output via cout - use in a more complicated expression - pass as an argument to another function The value of the function call expr is determined by the value of the expression returned from 15 the function. Calculating the area of a circle #include <iostream> #include <iomanip> using namespace std; double getradius(); double square(double); const double PI = 3.14159; double radius; double area; cout << fixed << setprecision(2); This works here too: radius = getradius(); area = PI * square(getradius()); area = PI * square(radius); cout << "The area is " << area << endl; 16

Calculating the area of a circle You can use a function that returns a value to input a value double getradius() { and return it to the main function double rad; cout << "Enter the radius of the circle: "; cin >> rad; return rad; double square(double number) { return number * number; Enter the radius of the circle: 1.2 The area is 4.52 17 Returning a boolean value bool isvalid(int number) { bool status; if (number >=1 && number <= 100) status = true; else status = false; return status; the above function is equivalent to this one: bool isvalid (int number) { return (number >=1 && number <= 100); 18

Returning a boolean value You can use the function as follows: bool isvalid(int); int val; cout << Enter a value between 1 and 100: cin >> val; while (!isvalid(val)) { cout << That value was not in range.\n ; cout << Enter a value between 1 and 100: cin >> val; 19 //...