Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
PASSING PARAMETERS 1. 2 Parameter Passing (by Value) Parameters Formal Parameters – parameters listed in the header of the function Variables used within.
Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
Programming Functions: Passing Parameters by Reference.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
Computer Science 1620 Loops.
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Overview creating your own functions calling your own functions.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
C++ Programming: Basic Elements of C++.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Functions Pass by reference, or Call by reference Passing addresses Use of & part 3.
First steps Jordi Cortadella Department of Computer Science.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Input a number #include using namespace std; int main() { int num; cout num; return 0; }
Lecture 4 Function example. Example1 int max (int a, int b) { int c; if (a > b) c = a; else c = b; return (c); } void main ( ) {int x, y; cin>>x>>y; cout.
Instructor - C. BoyleFall Semester
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva.
User-Defined Functions (cont’d) - Reference Parameters.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
CCSA 221 Programming in C CHAPTER 3 COMPILING AND RUNNING YOUR FIRST PROGRAM 1 ALHANOUF ALAMR.
User-Written Functions
Chapter 7 User-Defined Methods.
Arrays Part-1 Armen Keshishian.
Pointers and Pointer-Based Strings
Extra.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS150 Introduction to Computer Science 1
Counting Loops.
Pass by Reference.
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
CS150 Introduction to Computer Science 1
Fundamental Programming
Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)
Functions Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva

2 The manager of a company Does he pay the bills? Does he pay the bills? Does he answer the phone? Does he answer the phone? Does he clean the office? Does he clean the office?

3 CLEAN THE OFFICE PAY THE BILLS ANSWER THE PHONE Division of Labor

4 Our programs until now … Display messages Display messages Read values for the variables Read values for the variables Calculate expressions Calculate expressions Display results Display results

5 It would be good … A part to read input values, A part to read input values, another to calculate results, and another to calculate results, and another to display the results another to display the results

6 Functions (Subprograms) Self-contained routines that are identified by a name and have the same structure as main(). Self-contained routines that are identified by a name and have the same structure as main(). They are executed when they are called (calling their names). They are executed when they are called (calling their names). main() is also a function but a special one. main() is also a function but a special one.

7 Building my house I will call: the architect builder the builder the ironmonger builder the builder the plumber the electrician builder the builder the painter the carpenter the designer

8 Procedures (void Functions) Functions return a value (see later). Functions return a value (see later). If a function is declared a void it does not return a value, and is called a procedure. If a function is declared a void it does not return a value, and is called a procedure. void is a special data-type. void is a special data-type. void main() { ……… } int main() { ……… return 0; }

9 Reasons for using Sub-programs Decrease the size of the program Decrease the size of the program Program becomes more readable Program becomes more readable Decrease of errors Decrease of errors

10 Top-Down Design #include using namespace std; // Global declaration section ……… void One() { ……… } float Two(float x) { ……… return ??; } void main() { ……… } Declaration section and function definition Main program Include libraries

11 Procedure structure void ( ) { }

12 Example: #include #include using namespace std; using namespace std; void Builder() { void Builder() { cout << ” * ” << endl; cout << ” * ” << endl; cout << ” * * ” << endl; cout << ” * * ” << endl; cout << ”*******” << endl; cout << ”*******” << endl; cout << ”* *” << endl; cout << ”* *” << endl; cout << ”*******” << endl; cout << ”*******” << endl; cout << endl; cout << endl; } void Gardener() { void Gardener() { cout << ” * ” << endl; cout << ” * ” << endl; cout << ” *** ” << endl; cout << ” *** ” << endl; cout << ” ***** ” << endl; cout << ” ***** ” << endl; cout << ”*******” << endl; cout << ”*******” << endl; cout << ” * ” << endl; cout << ” * ” << endl; cout << endl; cout << endl; } void main() { void main() { Builder(); Builder(); Gardener(); Gardener(); } * * * * * ******* * * ******* * * * * * ******* * * ******* * *** *** ***** ************ * * * * *** *** ***** ************ * * * Executed when we call them

13 Prototypes #include using namespace std; // Global declaration section void one(); float two(float x); ……… int main() { ……… return 0; } void one() { ……… } float two(float x) { ……… return ??; } Prototypes

14 Exercise 1 Write the following procedures: Write the following procedures: Line – to display 5 stars in one line, i.e. Line – to display 5 stars in one line, i.e. ***** Ex – to display an X of stars, i.e. Ex – to display an X of stars, i.e. * * * Write the main program to display the following shape: Write the main program to display the following shape:***** * * * * *****

15 Exercise 2 Write a procedure called “Display” that will prompt the user to enter two integer numbers n and m, and will display all the numbers from n until m. i.e. Write a procedure called “Display” that will prompt the user to enter two integer numbers n and m, and will display all the numbers from n until m. i.e. If n = 4, m = 9 it will display: Also, write the main program to call the procedure “Display”. Draw the flowchart of the above program. Draw the flowchart of the above program.

16 Exercise 3 Write a procedure called “Sum” that will prompt the user to enter two integer numbers n and m, and will display the sum of all the numbers from n until m. i.e. Write a procedure called “Sum” that will prompt the user to enter two integer numbers n and m, and will display the sum of all the numbers from n until m. i.e. If n = 2, m = 6 it will display: 20 since = 20

Programming in C++ Lecture Notes 7 Value Parameters Andreas Savva

18 #include using namespace std; void Show (int a, int b, float c) { cout << a << ’ ’ << b << ’ ’ << c; } void main() { Show (5, 2, 6); } Actual parameters Formal parameters Parameters (Arguments) Formal parameters Formal parameters Actual parameters Actual parameters 5 2 6

19 Example void pets( int cats) { cout << ”I have ” << cats << ” kittens\n”; }Name Formal parameter Functions are executed when we call them: pets(6);pets(6); pets(4+2*3);pets(4+2*3); I have 6 kittens I have 10 kittens

20 Memory Example #include using namesapce std; void Add (int x, int y) { int sum = x + y; cout << x << ” + ” << y << ” = ” << sum); } void main() { Add(5, 2); Add(3*2, 16-2); }Output = = 20sum x y Add

21 Flowchart #include using namespace std; void Add (int x, int y) { int sum = x + y; cout << x << ’ + ’ << y << ’ = ’ << sum; } void main() { int n, m; cout << ”Enter two numbers: ”; cin >> n >> m; Add(n, m); } Start Add(n,m) Read n,m Finish Main Program Display sum Entrance sum = x + y ExitAdd(x,y)

22 Exercise 1 Write a program to ask for the price of a product and display the discount. The discount which is 15% will be calculated and displayed in the procedure “Discount”, that will take the price as a value formal parameter. Write a program to ask for the price of a product and display the discount. The discount which is 15% will be calculated and displayed in the procedure “Discount”, that will take the price as a value formal parameter. Draw the flowchart of the above program. Draw the flowchart of the above program.

23 Exercise 2 Write a program that will ask the user to enter the base and height of a right-angle triangle and will display its area. The area will be calculated and displayed in the procedure “Area”, that will take the base and height as value formal parameters. Write a program that will ask the user to enter the base and height of a right-angle triangle and will display its area. The area will be calculated and displayed in the procedure “Area”, that will take the base and height as value formal parameters. Area = (base x height) / 2

24 Exercise 3 Write a procedure called “Times” that will take an integer number n and a character and it will display the character n times, i.e. Write a procedure called “Times” that will take an integer number n and a character and it will display the character n times, i.e. Times(5,’?’) will display: ????? Times(8,’Α’) will display: ΑΑΑΑΑΑΑΑ Also, write the program that will prompt for the number and the character and will call the procedure “Times”. Also, write the program that will prompt for the number and the character and will call the procedure “Times”.

25 Exercise 4 Write a procedure called “Display” that will take two integer numbers n and m, and will display all the numbers from n until m. i.e. Write a procedure called “Display” that will take two integer numbers n and m, and will display all the numbers from n until m. i.e. Display(4,9) will display: Also, write the program that will ask the user to enter the two numbers and call the procedure “Display”. Draw the flowchart of the above program. Draw the flowchart of the above program.

26 Exercise 5 Write a procedure called “Even” that will take two integer numbers n and m, and will display all the even numbers from n until m. i.e. Write a procedure called “Even” that will take two integer numbers n and m, and will display all the even numbers from n until m. i.e. Even(4,13) will display: Also, write the program that will ask the user to enter the two numbers and call the procedure “Even”.

27 Exercise 6 Write a procedure called “Line” that will take a character ch and an integer number n and will display ch in line n, i.e. Write a procedure called “Line” that will take a character ch and an integer number n and will display ch in line n, i.e. Line(’?’,5) will display: line 1 line 2 line 3 line 4 line 5 line 6 line 7 ?

28 Exercise 7 Write a procedure called “Position” that will take a character ch and two integer numbers n and m and will display ch in row n, and column m, i.e. Write a procedure called “Position” that will take a character ch and two integer numbers n and m and will display ch in row n, and column m, i.e. Position(’A’,4,7) will display: A

29 Exercise 8 Write a procedure called “Sum” that will take two integer numbers n and m, and will display the sum of all the numbers from n until m. i.e. Write a procedure called “Sum” that will take two integer numbers n and m, and will display the sum of all the numbers from n until m. i.e. Sum(2,6) will display: 20 since = 20

Programming in C++ Lecture Notes 8 Reference Parameters Andreas Savva

31 #include using namespace std; void First (int a, int b, float c) {... } void main() { int a = 1, b = 3, c = 7;... First (5, c, a); } Actual parameters Formal parameters Parameters (Arguments) Formal Formal Actual Actual

32 Formal parameters Value formal parameters Value formal parameters Reference (Variable) formal parameters Reference (Variable) formal parameters void Display (int x, int &y) { x = x + y; y = x + y; } Display(3, Num); ValueFormalparameter Reference formal parameter

33 Memory Global x y z Display x y Example: #include using namespace std; int x, y, z; & void Display (int x, int &y) { x = x + y; y = x + y; z = z + 1; cout << x << ” ” << y << ” ” << z << ’\n’; } void main() { x = 2; y = 5; z = 3; Display(y, x); cout << x << ” ” << y << ” ” << z; } 52Output

34 Memory Global x y z Display x y THE CORRECT WAY – Same example #include using namespace std; int x, y, z; & void Display (int x, int &y) { x = x + y; y = x + y; z = z + 1; cout << x << ” ” << y << ” ” << z << ’\n’; } void main() { x = 2; y = 5; z = 3; Display(y, x); cout << x << ” ” << y << ” ” << z; } 5Output The reference formal parameter is a pointer to the address in memory of the actual parameter.

35 Memory Num Global Reference formal parameter: #include using namespace std; int Num; && void Display (int &x, int &y) { x = x + y; y = x + y; } void main() { Num = 10; Display(Num, Num); cout << Num; }Output Display x y This example will help you to understand.

36 Memory Num Global Exercise: #include using namespace std; int Num; & void Display (int x, int &y) { x = x + y; y = x + y; } void main() { Num = 10; Display(Num, Num); cout << Num; }Output x y Display

37 Memory Num Global Exercise: #include using namespace std; int Num; void Display (int x, int y) { x = x + y; y = x + y; } void main() { Num = 10; Display(Num, Num); cout << Num; }Output x y Display

38 Only in C++ Only in C++ In C and C++ In C and C++ void add(int a, int b, int &c) { c = a + b; } void main() { int x=3, y=5, z; add(x, y, z); cout << z; } void add(int a, int b, int *c) { *c = a + b; } void main() { int x=3, y=5, z; add(x, y, &z); cout << z; } Passing Parameters by Reference

39 Sub-programs #include using namespace std; const int PI = ; float x, y; void one(int num) { int n, m; char c; ……… } void two(float &x) { int z; char y; ……… } void main() { int p, y; ……… } Variables Variables Local Local Global Global One Two main Local Global num, n, m, cPI, x, y x, y, zPI p, yPI, x

40 Exercise 1 Write a void function “Calculate” that will take two numbers α and β and a character ch, and it will return through a reference formal parameter called “result” the following which depends on the value of ch: Write a void function “Calculate” that will take two numbers α and β and a character ch, and it will return through a reference formal parameter called “result” the following which depends on the value of ch: chresult ’+’α + β ’–’α – β ’*’α * β ’/’α / β otherwise0

41 Exercise 2 Write a procedure “Swap” that will accept two integer numbers, swap and return their values. Write a procedure “Swap” that will accept two integer numbers, swap and return their values.

42 Exercise 3 Write a procedure “Summation” that will take two integer numbers n and m and return through a reference formal parameter the sum of all the numbers from n until m. If n > m then the sum should be zero. Write a procedure “Summation” that will take two integer numbers n and m and return through a reference formal parameter the sum of all the numbers from n until m. If n > m then the sum should be zero.i.e. If n = 1 and m = 4 then Sum = = 10 If n = 1 and m = 4 then Sum = = 10 If n = 4 and m = 9 then Sum = = 39 If n = 4 and m = 9 then Sum = = 39 If n = 7 and m = 7 then Sum = 7 If n = 7 and m = 7 then Sum = 7 If n = 7 and m = 2 then Sum = 0 If n = 7 and m = 2 then Sum = 0

43 Exercise 4 Write a procedure “Money” that will take a an amount in pounds (real number), and it would return through two integer reference formal parameters the number of pounds and the number of cents. Write a procedure “Money” that will take a an amount in pounds (real number), and it would return through two integer reference formal parameters the number of pounds and the number of cents.i.e. if amount = then pounds = 36 and cents = 78

44 Exercise 5 Write a procedure “Euro” that will accept an amount in Cyprus pounds and return the respective amount in EURO. The rate should also be passed to the procedure as a value formal parameter. Write a procedure “Euro” that will accept an amount in Cyprus pounds and return the respective amount in EURO. The rate should also be passed to the procedure as a value formal parameter.

45 Exercise 6 Given the names of four students and three exam-marks for each one: Given the names of four students and three exam-marks for each one: 1. Write a procedure to take three marks, calculate and return their average and the highest of the three. 2. Write the main program to read the four students names and marks and display a list with their names, their average mark, and the highest mark for each student.

46 Default Parameters #include using namespace std; void print(int n = 1, int m = 10) { cout << n << ’\t’ << m; } void main() { print(6,8); print(); print(3); }

47 Default Parameters are defined only ONCE #include using namespace std; void print(int n, int m = 10); void main() { print(6,8); print(3); } void print(int n, int m) { cout << n << ’\t’ << m; } #include using namespace std; void print(int n, int m); void main() { print(6,8); print(3); } void print(int n, int m = 10) { cout << n << ’\t’ << m; } ERROR HERE: print takes two parametersRight-to-Left void print(int n = 10, int m); //ERROR void print(int x = 1, int y = 2, int z = 3);... print(7,5); //CORRECT print(,, 6); //ERROR

48 Overloading Functions #include using namespace std; void display(int n) { cout << n << endl; } void display(char c) { cout << c << endl; } void display(int x, int y) { cout << x << ’\t’ << y << endl; } void display(int n, float m){ cout << n << ’\t’ << m << endl; } void main() { display(6); display(’?’); display(3,8); display(2,(float)4.2); } 6 ? A function can be defined more than ones but with different number or/and type of parameters. A function can be defined more than ones but with different number or/and type of parameters.

49 More about Functions Functions can also be called as procedures (the return value will be lost). Functions can also be called as procedures (the return value will be lost). int max (int a, int b) { cout << a+b << endl; cout << a+b << endl; if (a>b) return a; if (a>b) return a; else return b; else return b;} int main() { cout << max(5,9) << endl; cout << max(5,9) << endl; max(3,1); // Return value is lost max(3,1); // Return value is lost} C++ will give a warning (not an error): main() does not return a value