Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions.

Similar presentations


Presentation on theme: "Functions."— Presentation transcript:

1 Functions

2 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

3 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

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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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


Download ppt "Functions."

Similar presentations


Ads by Google