Download presentation
Presentation is loading. Please wait.
Published byBernadette Lamb Modified over 9 years ago
1
CSCI 130 Chapter 5 Functions
2
Functions are named uniquely Performs a specific task Is independent –should not interfere with other parts of program May return a value
3
Function Example #include int square(int, int); //function prototype int main( void ) { int a = 3; int b = 4; int c = 0; c = square (a,b);//calling the function printf("%d", c); }
4
Function Example - cont’d Function definition: int square(int x, int y) { //function header return (x*y); } Function name is: square Function arguments are: 2 integers (x and y) Function returns: 1 integer
5
How a function works Is not executed unless called Calling program sends in any arguments –information to perform the process Control returns to statement following function call
6
Parts of a function Prototype –function name –argument type(s) –return type Definition –header –actual code
7
Local Variables Variables declared within a function are local –only defined within the function –not accessible by other functions Arguments are local as well Memory used only for duration of function
8
Local Variables - Example 1 (In main function) radius = 3 c = calculateArea(radius); (Outside main function) float calculateArea(int a) { float pi = 3.14;//local variable return pi * a * a; }
9
Local variables - Example 2 (In main function)... int a = 3; b = squareANumber(a); printf(“%d ”, a); printf(“%d”, b); … (Outside main function) squareANumber (int a) { a = a * a; return a; } Output of this program is: 3 9
10
Local variables - Example 3 (In main function) radius = 3 c = calculateArea(radius); printf(“The value of pi used here is %f”, pi); //ERROR!!! (Outside main function) float calculateArea(int a) { float pi = 3.14;//local variable return pi * a * a; }
11
Return values Functions may have more than 1 return value, but only 1 is ever returned –bad structure, not suggested Ex: if (a > b) return a; else return b;
12
Return types Return type is declared in function header Actual value being returned is in return statement Ex: int mult(int a, int b) { //return type is int return (a * b); //returning a*b }
13
No return type void specifies that there is no return value no return statement in function Ex: void writeErrorMessage() { printf(“\nInvalid input”); printf(“\nPlease check specifications”); errorCount += 1; }
14
Calling a function Calling a function with no return –writeToFile(x); Calling a function with a return value –x = square(3); Calling a function as a parameter –c = sumTheValues(square(3), square(4)); Multiple functions in an expression –b = square(3) + square(4);
15
Global Variables Placed outside of all functions Scope of variable is entire program –can be accessed by any function –memory is used for span of program
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.