Functions. What is a function? It’s a group of statements that has a specific purpose and can be be repeatedly executed as needed. By using functions:

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
File Review Declare the File Stream Object Name –ofstream for output to file –ifstream for input from file Associate a File Name with the File Stream Object.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Functions g g Data Flow g Scope local global part 4 part 4.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Parameters. Overview A Reminder Why Parameters are Needed How Parameters Work Value Parameters Reference Parameters Out Parameters.
CMSC 1041 Functions II Functions that return a value.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
Principles of Programming - NI Chapter 6: Function In this chapter, you will learn about Introduction to function User define function Function prototype.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 Unstructured Programming The Need for Procedures/Functions Procedural Programming Function Declaration/Prototypes/Invocation Example Functions Function.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
1 ICS103 Programming in C Lecture 8: Functions I.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Principle Prog Revision. Question 1 (a) Identify errors in the following program segment and how the errors can be corrected. void main(){ constant int.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
Bubble sort. Quite slow, but simple Principles: Compare 2 numbers next to each other (lets call it current and the one next to it) If the current number.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Revision. Generating a pseudo-random number Necessary libraries: and Seeding: srand(time(NULL))  We set the seed based on the current time  NB! Time-dependent.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Chapter 6 Modularity Using Functions
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
EKT120: Computer Programming
User-Written Functions
Chapter 6: User-Defined Functions I
CSE 220 – C Programming Pointers.
Functions Dr. Sajib Datta
Pointers.
CSCE 206 Lab Structured Programming in C
6 Chapter Functions.
Pointers.
Functions.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
IPC144 Introduction to Programming Using C Week 4 – Lesson 2
Arrays.
CSCE 206 Lab Structured Programming in C
Revision.
CPS125.
Presentation transcript:

Functions

What is a function? It’s a group of statements that has a specific purpose and can be be repeatedly executed as needed. By using functions: We can write less code, a lot less We can reuse our code, including in different programs We improve readability We can divide our code between different files It’s the foundation of code sharing in projects, where there are multiple developers etc

What makes a function return_type FunctionName(parameters) { function statements; } Functions have prototypes. They are placed before the main() function return_type FunctionName(parameters); 20153

main() is also a function int main(void) { printf("Hello world\n"); return 0; } 20154

Function properties Function prototype Return type void (no return) int (function must return an integer) double (function must return a double) char (function must return a character) e.t.c. Functions have headers (with parameters) Functions have calls (with arguments) 20155

Sample (1) – passing an argument #include void PrintNum(int number); // function prototype int main(void) // main() function header with return type and no parameters { int nr; printf(“Hello, give me a number!\n"); scanf("%d", &nr); PrintNum(nr); // call function PrintNum() with arguments return 0; // main function return } void PrintNum(int number) // PrintNum() function header with return type and parameters { printf(“You gave me: %d", number); } 20156

Sample (2) – multiple parameters #include void greet(int age, char name[]); //function prototype int main(void) { int number; char name[15]; printf(“Hi, what’s Your name?\n"); scanf("%s", name); printf("How old are You?\n"); scanf("%d", &number); greet(number, name); //call to function greet(), passing 2 arguments return 0; } void greet(int age, char name[]) // function greet() header, taking 2 parameters { printf(“Hi, %s. You’re %d year(s) old.", name, age); } 20157

Using variables in functions Every variable and their value has a lifetime and visibility scope! The variable and its value can only be used within the function it is created in The variables declared inside of a function will be “forgotten” after the function terminates. This also happens to the values they stored. The same variable names can be used in different functions – this doesn’t make them the same 20158

Copy or an original? (simplified) Copies: single variables By changing the value in a subfunction, the original stays unchanged int number; char singleLetter; float itemCost; Original data: arrays By changing a member of an array in a subfunction, the original is modified int numArray[10]; char name[15]; float invoiceItemCosts[5]; We can pass multiple values to a function, but only return It’s important to know whether the value passed is a copy or related to the original data (by value, by reference)

Sample (3) – code reuse #include void printArray(int numArray[], int arrayLength); int main(void) { int firstNumArray[] = {5, 8, -2, 65, 1, 36}; int secondNumArray[] = {7, 97, -24, -74}; printArray(firstNumArray, sizeof(firstNumArray) / sizeof(int)); printArray(secondNumArray, sizeof(secondNumArray) / sizeof(int)); return 0; } void printArray(int numArray[], int arrayLength) { int i; for(i = 0; i < arrayLenght; i++) { printf("%d\n", numArray[i]); }

Sample (4) – function returning a value #include int giveRandomNum(int numMin, int numMax); int main(void) { int num; srand(time(NULL)); num = giveRandomNum(5, 25); // function call and storing the result of the return printf("Got num %d\n", num); num = giveRandomNum(75, 100); // function call and storing the result of the return printf("Got num %d\n", num); return 0; } int giveRandomNum(int numMin, int numMax) // a function returning an integer { return (rand() % (numMax - numMin + 1)) + numMin; // return }

Lab task 1 (calling functions with parameters) This task will use the voluntary homework that we gave you as base Let’s improve on our long and cumbersome main() function and divide it into multiple functions 1.Output (without return, code reuse) 2.Sorting (without return) 3.Combining the warehouses (without return) If You haven’t done the task, You can use our base code from the web

Advanced lab task 1 Ask for how many items the warehouse will store (in between EMPTY … MAX_UNITS) Use the same function for both of the warehouses, choose a return type. Use a function to fill the warehouses with cargo. Use the same function for both of the warehouses, choose suitable arguments. The function used to fill the warehouses should also call out a function to generate the cargo main() calls the fill function, the fill function calls the function to generate a random number Create a limit for the cargo exiting the Intermediary storage (so-called sorting center). E.g. a truck can deliver up to 1500kg at once. Fit heavier items first, but how many as possible – e.g. when one item doesn’t fit, look for smaller items that may still fit

Lab task 2 (functions with return) Create a program that will: Ask the user for 3 numbers, all greater than 0 Find the sum of the number Find the average of the numbers (don’t lose the fractions!) Find the greatest number Find the smallest number All of the functions must return the result to the main() function, where they will be printed out. There can’t be any output in the functions themselves

Advanced lab task 2 Modify the functions so they would work with N digits. Instead of 3 numbers, use N numbers. Create a menu structure where the user can select the action and if necessary, create new numbers. Use random numbers for generation Find both of the extreme values in the same function. No sorting allowed. Also remember, that you can only return a single value (find help in the by reference sample)