Functions.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
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.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
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:
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Principle Prog Revision. Question 1 (a) Identify errors in the following program segment and how the errors can be corrected. void main(){ constant int.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
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.
UMBC CMSC 104 – Section 01, Fall 2016
Stack and Heap Memory Stack resident variables include:
EKT120: Computer Programming
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
CSE 220 – C Programming C Fundamentals.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
C Functions Pepper.
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
Functions and Structured Programming
Functions Dr. Sajib Datta
Functions Separate Compilation
Pointers.
C programming language
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Chapter 5 - Functions Outline 5.1 Introduction
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 5 Function Basics
Chapter 6 - Functions Outline 5.1 Introduction
Value returning Functions
CSCE 206 Lab Structured Programming in C
6 Chapter Functions.
Functions, Part 2 of 3 Topics Functions That Return a Value
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
File Review Declare the File Stream Object Name
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Structures vol2.
Qsort.
Revision.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Pointers.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
String manipulation string.h library
Functions continued.
Loops.
Bubble sort.
Let’s start from the beginning
Arrays.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
CSCE 206 Lab Structured Programming in C
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Revision.
Intro to Arrays Storing List of Data.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
ITM 352 Functions.
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Presentation transcript:

Functions

What is a function? It’s a group of statements that has a specific purpose and can be repeatedly executed as needed. Each time a function is called, you can give it different data 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. 2018 Risto Heinsar

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

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

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) Etc. Functions have headers (with return type, name and parameters) Functions need to be called (name, arguments) 2018 Risto Heinsar

Sample (1) – passing an argument #include <stdio.h>   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\n", number); 2018 Risto Heinsar

Sample (2) – multiple parameters #include <stdio.h>   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.\n", name, age); 2018 Risto Heinsar

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 (lifetime) The variables declared inside of a function will be “forgotten” after the function terminates. This also happens to the values they held. (lifetime) The same variable names can be used in different functions – this doesn’t make them the same (scope) If a function is called, the name of the variables become irrelevant. Only the copy of the value is passed or returned! (scope) 2018 Risto Heinsar

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

Sample (3) – code reuse #include <stdio.h>   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]); 2018 Risto Heinsar

Sample (4) – function returning a value #include <stdio.h> #include <stdlib.h> #include <time.h>   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 return 0; } int giveRandomNum(int numMin, int numMax) // a function returning an integer return (rand() % (numMax - numMin + 1)) + numMin; // return 2018 Risto Heinsar

Lab task 1 (calling functions with parameters) Use the sorting facility code You did a few weeks ago Let’s improve on our long and cumbersome main() function and divide it into multiple functions Output (without return, code reuse) Sorting (without return) Combining in sorting facility (without return) If You haven’t done the task, You can use our base code from the web 2018 Risto Heinsar

Advanced lab task 1 Generate weights using random number Ask the cargo amount for warehouse A and B. Maximums are set at 10 for A and 15 for B (use define). Create a function for this: parameters are min and max number of items, return value is the number user entered. Reuse this function for both! Fill warehouses with items (random numbers). Call a function that does this, reuse this function for both warehouses! Parameters: warehouse array, number of items The function created to fill the items in itself calls another function to generate a random number. This means that main() calls the fill function, fill function calls a function to generate items in a loop. Create a limit for the cargo exiting the sorting facility. 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. 2018 Risto Heinsar

Lab task 2 (functions with return) Create a program that will: Ask the user for 5 numbers, between -100 and 100 Find the sum of the number Find the average of the numbers (show 2 decimal places) Find the greatest number (don’t sort) Find the smallest number (don’t sort) All of the tasks above must be in separate functions, outside of main(). All functions, except input and output functions, must return the result to main(), where the result will be printed. Printing statements must not be a part of the code that finds the results. 2018 Risto Heinsar

Advanced lab task 2 Modify the functions so they would work with N digits. Reminder: arrays were passed by reference, single values as copies of those values. You can use #define to limit the maximum number Create a menu structure where the user can select the action and if necessary, input a new set of 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) 2018 Risto Heinsar