0% found this document useful (0 votes)
4 views

Lecture 7

The document discusses functions in C programming. It defines what a function is, how functions are used to modularize programs, and function prototypes. It also provides examples of mathematical functions written as C functions to calculate values like area and circumference of a circle.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 7

The document discusses functions in C programming. It defines what a function is, how functions are used to modularize programs, and function prototypes. It also provides examples of mathematical functions written as C functions to calculate values like area and circumference of a circle.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

C How to Program

Functions

Dr. mhd. Mazen Al Mustafa


Lecture 7 - Functions
Outline
7.1 Program Modules in C
7.2 Math Library Functions
7.3 What is a function
7.4 Functions
7.5 Function Definitions
7.6 Function Prototypes
7.7 functionsCalling Functions: Call by Value and Call by Reference

7.8 Header Files


7.9 Passing Arrays to

Dr. mhd. Mazen Al Mustafa


7.1 Program Modules in C
• Functions
– Modules in C
– Programs combine user-defined functions with library functions
• C standard library has a wide variety of functions
• Function calls
– Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
– Function call analogy:
• Boss asks worker to complete task
– Worker gets information, does task, returns result
– Information hiding: boss does not know details

Dr. mhd. Mazen Al Mustafa


7.2 Math Library Functions

• Math library functions


– perform common mathematical calculations
– #include <math.h>
• Format for calling functions
– FunctionName( argument );
• If multiple arguments, use comma-separated list
– printf( "%.2f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of
its argument
• All math functions return data type double
– Arguments may be constants, variables, or
expressions
Dr. mhd. Mazen Al Mustafa
7.3 What is a function?

• This is an area where computer science has been stolen from the
mathematical community.
• First Definition (not the final one): A Function is a “black box”
that takes input, operates on it, and produces output.
• Here’s a simple function:

4 5

8 9

67 68

Dr. mhd. Mazen Al Mustafa


What is a function? (cont)

x Add1 x+1

• Functions have 3 parts:


– The input.
– The output.
– The operation.

• Example: The Add1 Function is fully described as follows –


– Input: An Integer, x.
– Output: An Integer, F(x).
– Operation: F(x) = x + 1.

Dr. mhd. Mazen Al Mustafa


What is a function? (cont)

x Add1 x+1

Function: A function is a “black box” that takes input,


operates on it, and produces output. A function is fully
defined by three things: input, output, and a description
relating the output to the input.

Example: The Add1 function:


Input - a number, x.
Output - a number, F(x)
Operation - F(x) = x + 1

Dr. mhd. Mazen Al Mustafa


What is a function? (cont)

• When we speak of functions, we focus


on WHAT is being done.
• Functions have three components:
– The input
– The output.
– The description of the operation (this
hides the details of the algorithm).

Dr. mhd. Mazen Al Mustafa


Examples of Notation

x Add1 x +1

• Typical notation for a function is borrowed from math:


– Add1(0) = 1
– Add1(1) = 2
– Add1(2) = 3, etc

Dr. mhd. Mazen Al Mustafa


Another Function Example

x Abs |x|

• The Abs function takes the absolute value of its input:


– Input: An Integer x.
– Output: An Integer, F(x).
– Operation: F(x) = | x |.

• Example notation and values:


– Abs(3) = 3.
– Abs(-3) = 3.

Dr. mhd. Mazen Al Mustafa


Function Composition

8 Add1 9 Add1 10

• What happens when we take the output of one function and use it as
the input of another?

• Once again, we steal from math, and use the concept of function
composition.

• Function composition occurs when two functions are combined to


form (or compose) a new function.

Dr. mhd. Mazen Al Mustafa


Function Composition (cont)

8 Add1 9 Add1 10
Add2

• In this case we can take the composition of the two Add1


functions, and describe a new function - Add2.

• Definition of Add2:
– Input: A number, X
– Output: A number, F(x)
– Operation: F(x) = x + 2

Dr. mhd. Mazen Al Mustafa


7.4 Functions
• Functions
– Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables

Dr. mhd. Mazen Al Mustafa


Why are Functions Important?
– Benefits of functions
• Divide and conquer
• Manageable program development
• Software reusability
• Use existing functions as building blocks for new
programs
• Abstraction - hide internal details (library functions)
• Avoid code repetition
• Using the concept of functions allows us to relate
mathematics to computation.
• By treating computer programs as functions we can draw
on mathematical principles to discuss properties of
programs.
• We can build large programs by composing small
functions.
• We can describe large programs by describing the
functions that make them up and how they are
composed.
Dr. mhd. Mazen Al Mustafa
for the Add1 Function:
Algorithm
Add1()

• Inputs: Number x

• Other Data: None

• Initialization: X is given to us

• Computation: X++;

• Outputs: return (x);

Dr. mhd. Mazen Al Mustafa


7.5 Function Definitions
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result
(default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares
parameters
• A type must be listed explicitly for each parameter
unless, the parameter is of type int
Dr. mhd. Mazen Al Mustafa
Function Definitions (Cont.)
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;

Dr. mhd. Mazen Al Mustafa


How do they look as Functions?

• Remember that functions are concerned with input and output.

• When we write the function that corresponds to an algorithm, we


need to give the function some input.
– The "thing" inside the bracket does that.
– Can be a constant or a variable or another function.
• We need to store the output in memory somewhere.
– The assignment operation does that ("=").

• Add1(x)
As used in a program:
y = Add1(4); <= this will set y to 5
y = Add1(x); <= this will take whatever value is stored at location 'x' and
add 1 to it, then store the result in location 'y'.

Dr. mhd. Mazen Al Mustafa


Algorithm to Find Area of a Circle:
CircleArea()

• Inputs: Number radius;

• Other Data: Number area; Number pi;

• Initialization: Assume radius is given to us.


pi = 3.14159;

• Computation: area = pi * radius * radius

• Outputs: return (area);

Dr. mhd. Mazen Al Mustafa


Algorithm to Find Circumference of a
Circle: CircleCircumference()

• Inputs: Number radius;

• Other Data: Number circ; Number pi;

• Initialization: Assume radius is given to us.


pi = 3.14159;

• Computation: circ = 2*pi * radius;

• Outputs: return (circ);

Dr. mhd. Mazen Al Mustafa


Now use the Circle Algorithms as
Functions: CircleProps()

• Inputs: Number radius;

• Other Data: Number area; Number circ; Number pi;

• Initialization: Assume radius is given to us.


pi = 3.14159;

• Computation: area = CircleArea( radius);


circ = CircleCircumference(radius);

• Outputs: return (area, circ );

Dr. mhd. Mazen Al Mustafa


1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int, int, int ); /* function prototype */
6 1. Function
7 int main()
8 { prototype (3
9 int a, b, c;
10
11 printf( "Enter three integers: " );
parameters)
12 scanf( "%d%d%d", &a, &b, &c );
13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
14
15
16 }
return 0;
2. Input
17
18 /* Function maximum definition */
values
19 int maximum( int x, int y, int z )
20 {
21 int max = x;
22
23 if ( y > max ) 2.1 Call
24 max = y;
25 function
26 if ( z > max )
27 max = z;
28
29 return max;
30 } 3.Function
Enter three integers: 22 85 17
Maximum is: 85 definition
Dr. mhd. Mazen Al Mustafa
7.6 Function Prototypes
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after
use in program
– The function with the prototype
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors
Dr. mhd. Mazen Al Mustafa
7.7 Calling Functions: Call by
Value and Call by Reference
• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• For now, we focus on call by value

Dr. mhd. Mazen Al Mustafa


7.8 Header Files

• Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions

Dr. mhd. Mazen Al Mustafa


7.9 Passing Arrays to Functions

• Passing arrays
– To pass an array argument to a function, specify the name of
the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
• Array size usually passed to function
– Arrays passed call-by-reference
– Name of array is address of first element
– Function knows where the array is stored
• Modifies original memory locations
• Passing array elements
– Passed by call-by-value
– Pass subscripted name (i.e., myArray[ 3 ]) to function

Dr. mhd. Mazen Al Mustafa


Passing Arrays to Functions

• Function prototype
void modifyArray( int b[], int
arraySize );
– Parameter names optional in prototype
• int b[] could be written int []
• int arraySize could be simply int

Dr. mhd. Mazen Al Mustafa


1 /* Fig. 6.13: fig06_13.c
2 Passing arrays and individual array elements to functions */
3 #include <stdio.h>
4 #define SIZE 5
5 1. Function
6 void modifyArray( int [], int ); /* appears strange */
7 void modifyElement( int );
definitions
8
9 int main()
10 { 2. Pass array to a
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; function
12
13 printf( "Effects of passing entire array call "
14 "by reference:\n\nThe values of the "
15 "original array are:\n" );
16
17 for ( i = 0; i <= SIZE - 1; i++ )
Entire arrays passed call-by-
18 printf( "%3d", a[ i ] ); reference, and can be modified
19
20 printf( "\n" ); 2.1 Pass array
21 modifyArray( a, SIZE ); /* passed call by reference */ element to a
22 printf( "The values of the modified array are:\n" );
23 function
24 for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-by-
25 printf( "%3d", a[ i ] ); value, and cannot be modified
26
27 printf( "\n\n\nEffects of passing array element call "
28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); 3. Print
29 modifyElement( a[ 3 ] );
30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
31 return 0;
32 }
Dr. mhd. Mazen Al Mustafa
33
34 void modifyArray( int b[], int size )
35 {
36
37
int j;
3.1 Function
38 for ( j = 0; j <= size - 1; j++ ) definitions
39 b[ j ] *= 2;
40 }
41
42 void modifyElement( int e )
43 {
44 printf( "Value in modifyElement is %d\n", e *= 2 );
45 }

Effects of passing entire array call by reference:

The values of the original array are:


0 1 2 3 4
The values of
0 2 4 6
the modified array are:
8
Program
Effects of passing array element call by value: Output
The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6

Dr. mhd. Mazen Al Mustafa


1 /* Fig. 6.22: fig06_22.c
2 Double-subscripted array example */
3 #include <stdio.h>
4 #define STUDENTS 3
5
6
#define EXAMS 4
3. Define
7 int minimum( const int [][ EXAMS ], int, int );
8 int maximum( const int [][ EXAMS ], int, int ); functions
9 double average( const int [], int );
10 void printArray( const int [][ EXAMS ], int, int );
11
Each row is a particular student,
12 int main() each column is the grades on the
13 { exam.
14 int student;
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
16 { { 77, 68, 86, 73 },
17 { 96, 87, 89, 78 },
18 { 70, 90, 86, 81 } };
19
20 printf( "The array is:\n" );
21 printArray( studentGrades, STUDENTS, EXAMS );
22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
23 minimum( studentGrades, STUDENTS, EXAMS ),
24 maximum( studentGrades, STUDENTS, EXAMS ) );
25
26 for ( student = 0; student <= STUDENTS - 1; student++ )
27 printf( "The average grade for student %d is %.2f\n",
28 student,
29 average( studentGrades[ student ], EXAMS ) );
30
31 return 0;
32 }
mr. mhd. Mazen Al Mustafa 7.30
33
34 /* Find the minimum grade */
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 {
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 double average( const int setOfGrades[], int tests )
64 {
mr. mhd. Mazen Al Mustafa 7.31
65 int i, total = 0;
66
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69
70 return ( double ) total / tests;
3. Define
71
72
}
functions
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
77 int i, j;
78
79 printf( " [0] [1] [2] [3]" );
80
81 for ( i = 0; i <= pupils - 1; i++ ) {
82 printf( "\nstudentGrades[%d] ", i );
83
84 for ( j = 0; j <= tests - 1; j++ )
85 printf( "%-5d", grades[ i ][ j ] );
86 }
87 }

mr. mhd. Mazen Al Mustafa 7.32


The array is:
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96
studentGrades[2] 70
87
90
89
86
78
81
Program
Lowest grade: 68 Output
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75

mr. mhd. Mazen Al Mustafa 7.33

You might also like