Returning Structures Lesson xx

Slides:



Advertisements
Similar presentations
Parameter passing mechanism: pass-by-reference. The Pass-by-reference mechanism - the agreement Recall: Parameter passing mechanism = agreement between.
Advertisements

Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
True or false A variable of type char can hold the value 301. ( F )
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Chapter 6: Functions.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
More Storage Structures A Data Type Defined by You Characteristics of a variable of a specific ‘data type’ has specific values or range of values that.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++
1 CS161 Introduction to Computer Science Topic #3.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
1 CS161 Introduction to Computer Science Topic #10.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
C++ Programming Lecture 12 Functions – Part IV
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Lesson xx Why use functions Program that needs a function Function header Function body Program rewritten using a function.
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.
Bill Tucker Austin Community College COSC 1315
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Popping Items Off a Stack Using a Function Lesson xx
User-Written Functions
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Two-Dimensional Arrays Lesson xx
Basic Elements of C++.
A Lecture for the c++ Course
CO1401 Programming Design and Implementation
Variables A piece of memory set aside to store data
Introduction to C++ October 2, 2017.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
void Pointers Lesson xx
Basic Elements of C++ Chapter 2.
Arrays & Functions Lesson xx
Structures Lesson xx In this module, we’ll introduce you to structures.
Pointer to a Structure & Structure Containing a Pointer Difference Lesson xx  In this presentation, we will illustrate the difference between a pointer.
Linked List Lesson xx   In this presentation, we introduce you to the basic elements of a linked list.
One-Dimensional Array Introduction Lesson xx
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
File I/O with Records Lesson xx
Passing Structures Lesson xx
Please use speaker notes for additional information!
Today in CS161 Week #3 Learn about… Writing our First Program
Popping Items Off a Stack Lesson xx
Value returning Functions
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.
Arrays Kingdom of Saudi Arabia
Exceptions CSCE 121 J. Michael Moore
Pointer to Structures Lesson xx
Functions Pass By Value Pass by Reference
Function “Inputs and Outputs”
Chapter 6: User-Defined Functions I
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Functions Divide and Conquer
Programs written in C and C++ can run on many different computers
Fundamental Programming
Capitolo 1 – Introduction C++ Programming
Reference variables, pass-by-reference and return-by-reference
Presentation transcript:

Returning Structures Lesson xx In this module, we’ll talk about returning structures from functions.

Objectives Review return value from a function Returning structures Program returning a structure Our goal is to review returning a value from a functions. Then, we’ll talk about returning a structure from a function. Lastly we’ll write a program to demonstrate another use of structures.

Passing Arguments int ans = compute ( z ); int compute ( float zz) { . . . return a; } Let’s review functions. The statement in red is how you call a function that returns a value. On the left hand side of the = sign, you put a variable with the same data type as the return type of the function. Since function compute returns an int, the variable ans must be an int. On the right hand side of the = sign, you put the name of the function followed by the argument list in ( )s. In this case, we are calling function compute() and sending in z. Notice that z should be a float. The header of the function is: int compute (float zz). int means that the function returns a number that is an integer. compute is the name of the function. float zz means that we have 1 floating point argument that is sent in.

Returning Structures struct student { long id; int age; char sex; }; int main ( ) student s; . . . s = fun (3); } student fun (int n) student found; return found; Here is an example of how you return a structure from a function. We have defined a structure called student at the beginning of our code. In order to declare a structure variable, we write student s; in main(). We can call function fun and pass in the #3 as an argument. When we get into the function, 3 is stored in the local variable n. At the end of function fun(), we have the statement return found; Notice that the data type of found is a structure of the type student.

Why Return a Structure ? struct student { long id; int age; char sex; }; int main ( ) student s; . . . s = fun (3); } student fun (int n) student found; return found; Let’s look at the same example again. Why would you want to return a structure? Suppose the purpose of function fun() is to lookup student record n. In other words if we send in the # 3 for n, function fun() will return the id, age and sex of student #3. One way to get this information back is to return 1 structure that contains 3 parts, the id, age, and sex.

Program Specifications Write a program that will: Read in a start time and end time in the form hh mm. 2. Calculate and print the total time worked. Let’s now write a program that demonstrates returning a structure. We’ll read in a starting and ending time in the form hh mm. Then, we’ll calculate and print the total time worked.

Program Code Part 1 #include <iostream> using std::cin; using std::cout; using std::endl; struct time { int hr; int min; }; int main() time start, end, hoursworked; int i; time calc_hrs (time s, time e); The first part of the program contain the preprocessor directives, the structure definition and other declarations.

Program Code Part 2 cout << "enter starting time in the form hh mm "; cin >>start.hr >>start.min; cout << "enter ending time "; cin >>end.hr >>end.min; hoursworked = calc_hrs (start, end); cout << "hours worked = " << hoursworked.hr << " minutes = “ << hoursworked.min; return 0; } Part 2 of the code does the input, calculations and the output.

Program Code – Part 3 /**************function to calculate number of hrs worked******/ struct time calc_hrs (struct time s, struct time e) { struct time hw; if (s.hr > e.hr) hw.hr = 24-s.hr +e.hr; /*s = 2300 e = 0115*/ else hw.hr = e.hr - s.hr; /*s = 0115 e = 0315*/ if (e.min < s.min ) /*s = 1215 e = 1509*/ hw.min = 60 - s.min + e.min; hw.hr--; } hw.min = e.min - s.min; /*s = 1212 e = 1413*/ return (hw); Part 3 is a listing of the calc_hr ( ) function which calculates the time worked. Now, let’s go through the program in detail.

Structure Definition struct time { int hr; int min; }; Our goal in this program is to read in a starting time, an ending time and then calculate the time worked. For example, the person might start work at 9:32 and work until 11:35. In this case the person worked 2 hr and 3 mins. Each of those times contains an hour and a minute. Our structure called time allows us to group these items together and think of a time as 1 object rather than 2 separate items.

Declarations int main() { time start, end, hoursworked; int i; time calc_hrs (time s, time e); end.hr end end.min start.hr start.min start hoursworked.hr hoursworked hoursworked.min In main(), we have declared 3 date variables called start, end and hoursworked. We have a prototype for function calc_hrs() which calculates the time a person worked. Shown at the bottom of the slide is a picture of the structure variables which are sometimes called objects. We can say that we have 3 objects of the type time.

Inputs cout << "enter starting time in the form hh mm "; cin >>start.hr >>start.min; cout << "enter ending time "; cin >>end.hr >>end.min; 9 32 start.hr start.min start 11 35 end.hr end end.min hoursworked.hr hoursworked hoursworked.min These lines of code prompt the user for the starting and ending time. If he user enters 9:32 and 11:35 for the starting and ending time respectively, the memory looks as shown. Start.hr has 9 and start.min has 32. end.hr has 11 and end.min has 35. hoursworked is uninitialized.

Function Call hoursworked = calc_hrs (start, end); This statement is the call to the calc_hrs () function which calculates the time worked. We pass in the starting and ending time which were read into start and end. Notice that on the left side of the = sign, we have a structure variable of the form time. calc_ hrs() returns a structure, hoursworked.hr will have the # of hours the person worked and hoursworked.min will have the # of minutes.

Print Time Worked << " minutes = “ << hoursworked.min; cout << "hours worked = " << hoursworked.hr << " minutes = “ << hoursworked.min; When we return from the function, all we have to do is to print hoursworked.hr and hoursworked.min to obtain our answer.

calc_hrs ( ) Function time calc_hrs (time s, time e) { struct time hw; hoursworked = calc_hrs (start, end); time calc_hrs (time s, time e) { struct time hw;   We get to the calc_hrs() function from main() with the call statement in red. Into the calc_hrs() function, we send 2 objects which contain the start time and end time. After we execute the 1st line of code in the function, the memory of the computer looks as shown: we have the objects s, e and hw. s and e contain the information passed in from start and end respectively. hw is a local variable which will hold the time worked. 11 35 e.hr e e.min 9 32 s.hr s.min s hw.hr hw hw.min

Calculate Hours Worked if (s.hr > e.hr) hw.hr = 24-s.hr +e.hr; /*s = 2300 e = 0115*/ else hw.hr = e.hr - s.hr; /*s = 0115 e = 0315*/ This is the code in the function that calculates the # hours worked. In the if statement, we check to see if the starting hour is > the ending hour. If it is, this implies that the person started work one day and finished on the next day. In either case, hw.hr contains the # of hours the person worked

Calculate Minutes Worked if (e.min < s.min ) /*s = 1215 e = 1509*/ { hw.min = 60 - s.min + e.min; hw.hr--; } else hw.min = e.min - s.min; /*s = 1212 e = 1413*/ This part of the code calculates the # of minutes the person worked. Normally, you would take the ending minutes and subtract the starting minutes but, we have to account for the situation where the ending minutes are < the starting minutes. When we finish this code, hw.min contains the # of minutes the person worked.

Returning the Time Worked return (hw); 11 35 e.hr e e.min 9 32 s.hr s.min s 2 3 hw.hr hw hw.min The object hw looks like the picture drawn if the person started work at 9:32 and ended at 11:35. hw.hr has the # 2 and hw.min has the # 3 The last statement of the calc_hrs() function is return hw; This will send a copy of the of hw back to main(). In the next slide, we’ll show you the passing and returning mechanism of a function.

Passing & Returning Mechanism hoursworked = calc_hrs (start, end); time calc_hrs (time s, time e) { struct time hw; . . . return hw; }   The statement in red is how we call the function. The variables start and end are passed by value in to the local variable s and e. In the function, we have a local variable called hw where we store the hours and minutes the person worked. Remember, local objects and variables are destroyed upon completion of a function, therefore, we have the statement: return hw; which returns a copy of hw in to the variable hoursworked in main() 11 35 e.hr e e.min 9 32 s.hr s.min s 2 3 hw.hr hw hw.min

Why Return a Structure time calc_hrs (time s, time e) { struct time hw; . . . return hw; }   Let’s talk about why you might want to return a structure. In a function, you can only return 1 item. Well, what if you need to return several items like in our case, you need to return the hours and minutes worked. One way to solve the problem is to return a structure that contains several parts as we have shown you in this example.

Summary Review return value from a function Returning structures Program returning a structure In this module, we reviewed return value from a function. We discussed returning structures from functions and finally we wrote a program where we returned a structure from a function.