05 - CSC 201 - Functions & Array
05 - CSC 201 - Functions & Array
- C++ Functions
- C++ Arrays
- C++ Multidimensional Arrays
Page 1 of 14
FUNCTIONS
A function is a reusable block of code that performs a speci c task. They provide a way to modularise
code by breaking it into smaller, manageable units. They can also be used to avoid repeating code,
which can help to improve performance.
Type of Functions
- Standard library functions: also called built-in functions, are prede ned functions that the C++
standard library provides. Programmers can use library functions by invoking them directly; they
don't need to write them themselves. Some common library functions in C++
are sqrt(), abs(), isdigit(), etc. To use library functions, we usually include the header le in which
these library functions are de ned. For instance, to use mathematical functions such
as sqrt() and abs(), we need to include the header le cmath.
- User-de ned functions: are functions that are written by the programmer. User-de ned functions
can be used to perform any task that the programmer needs. We will focus on user-de ned functions
in this class.
Function Declaration
The declaration, the FUNCTION PROTOTYPE, informs the compiler about the functions to be used in a
program, their argument, and the type of value they return.
Syntax: returnType functionName (parameter_1, parameter_2,…, parameter_n);
Examples: char grade(int score); function name is grade, the return type is char, and it accepts
one argument of type int; Note that the parameter name is not important in the function declaration.
So, it can be written as char grade(int);
Page 2 of 14
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Function De nition
The function de nition tells the compiler what task the function will be performing. The function prototype
and the function de nition must have the same return type, name, and parameters. A semicolon is the
only difference between the function prototype and the function header. The function de nition consists of
the function header and its body. The header is EXACTLY like the function prototype, EXCEPT that it
contains NO terminating semicolon.
Below is an example C++ program where a function is declared (prototyped), de ned and called (or
used) inside the main function. When a function is de ned, the variables in the parenthesis () are called
parameters, while when the function is called, the values passed to the function are called arguments.
#include <iostream>
int main ()
return 0;
if(score 50){
return ‘F’;
The return type speci es the type of value the function returns or void if it doesn't return a value. In the
example above, the return type of our grade function is `char`. The return type speci es the type of value
the function returns or void if it doesn't return a value.
Page 3 of 14
fi
fi
<
fi
<
>
fi
=
fi
<
<
<
<
fi
<
<
fi
fi
fi
Calling a Function
Functions are called by using the function name followed by parentheses. The arguments passed in the
function call correspond to the parameters in the function declaration or de nition. The value returned by
a function can be assigned to a variable or used in an expression. In the example C++ program above,
we assigned the result of calling our grade function to a variable `grd`. Note that the variable type is the
same as the type returned by the function. Note that the main is called automatically when a C++
program is executed. Below is how a function call works:
int main ()
return 0;
Function Call
}
Return
Call
char grade (int score)
if(score 50){
return ‘P’;
} else {
return ‘F’;
From the above example, our grade function could return a `P` or `F` based on the value of the score.
What happens here is that when the grade function is called, the program control is transferred to the
function, and then the function returns program control to the next line of code when it is done.
Function Parameters
Parameters are placeholders for values that are passed to a function when it is called. Parameters allow
functions to receive input values and operate on them. Parameters can be of any data type, including
fundamental types, arrays, and user-de ned types. From the above code example, our grade function has
one parameter named `score` and `total` is passed as an argument to the function when it was called in
the main function.
Page 4 of 14
<
<
>
=
<
<
fi
<
<
<
<
fi
Return Statement
The return statement exits a function and optionally returns a value. It can be used anywhere inside the
function body, even multiple times. The return type speci ed in the function declaration or de nition must
match the type of value being returned or void if no value is returned.
Function Types
In C++, functions can be classi ed into four types based on their characteristics and usage:
- Functions with no parameters and no return value
- Functions with no parameters but return a value
- Function with parameters but no return value
- Function with parameters and return value
void sumOneToTenPrint()
int sum = 0;
for(int i = 1; i 10; i ){
sum += i;
The above function, named `sumOneToTenPrint`, is an example of a function with no parameters and no
return value. The function sums 1 to 10 and prints out the value. Note that the return type is void, and no
return statement exists.
Page 5 of 14
<
<
<
<
<
=
fi
+
+
fi
fi
Functions with no parameters but return a value
#include <iostream>
int sumOneToTenReturn()
int sum = 0;
for(int i = 1; i 10; i ){
sum += i;
return sum;
The above function, named `sumOneToTenReturn`, is an example of a function with no parameters but
returns a value. The function sums 1 to 10 and returns the sum.
void sumOneToTenInput(int n)
int sum = 0;
for(int i = 1; i n; i ){
sum += i;
The above function, named `sumOneToTenInput`, is an example of a function with parameters but no
return value. The function sums 1 to n and prints the sum.
Page 6 of 14
<
<
<
<
<
<
=
=
+
+
+
+
Functions with parameters and return value
#include <iostream>
int sumOneToTenInputReturn(int n)
int sum = 0;
for(int i = 1; i n; i ){
sum += i;
return sum;
The above function, named `sumOneToTenInputReturn`, is an example of a function with parameters and
a return value. The function sums 1 to n and returns the sum.
Function Overloading
C++ allows multiple functions with the same name but different parameter lists. This is called function
overloading. Functions can be overloaded based on the number, type, or order of parameters. The
compiler selects the appropriate function based on the arguments provided in the function call.
float multiply(float a) { … }
Overloaded functions may or may not have different return types, but they must have different arguments.
void test();
int main()
int i = 5;
test();
j = 9; invalid `j` cannot be accessed because it was declared in the test function
void test()
int j;
j = 6;
cout i; invalid `i` cannot be accessed because it was declared in the main function
Global Variable
If a variable is de ned outside all functions, it is called a global variable. The scope of a global variable
is the whole program. This means It can be used and changed at any part of the program after its
declaration. Likewise, its life ends only when the program ends. Below is an example of a global
variable:
#include <iostream>
int main()
int i = 5;
test();
j = 9; invalid `j` cannot be accessed because it was declared in the test function
}
Page 8 of 14
<
<
/
/
/
/
/
/
fi
/
/
fi
fi
fi
Static Local variable
Keyword static is used for specifying a static variable. For example, A static local variable exists only
inside a function where it is declared (similar to a local variable), but its lifetime starts when the function
is called and ends only when the program ends. The main difference between a local variable and a
static variable is that the value of the static variable persists at the end of the program.
#include <iostream>
void test()
i;
cout i endl;
int main()
test();
test();
return 0;
The test() function is invoked twice in the above program. During the rst call, variable `i` is declared as
a static variable and initialised to 0. Then one is added to `i`, which is displayed on the screen. When the
function test() returns, variable `i` still exists because it is a static variable. During the second function
call, no new variable `i` is created. The same `i` is increased by one and then displayed on the screen.
Recursive Functions
Recursive functions are functions that call themselves during their execution. They allow solving problems
by breaking them down into smaller, similar subproblems. Recursive functions consist of base cases and
recursive cases.
Page 9 of 14
+
+
<
<
<
<
/
/
fi
Example of Recursive Function
#include <iostream>
int main() {
return 0;
if(n 1){
As we can see, the sum() function is calling itself. However, during each call, we decreased the value
of n by 1. When n equals 1, the sum() function returns the output. The example sum function above
calculates the sum of 1 to n numbers, just like the example on page 6.
Note that all recursive functions can be written iteratively, but not iterative functions can be written
recursively.
Page 10 of 14
<
=
<
=
<
<
C++ ARRAYS
Arrays in C++ are used to store a collection of elements of the same data type. They provide a way to
organise and access multiple values using a single variable name.
For example, suppose a class has 13 students, and we need to store all their scores. Instead of creating
13 separate variables, we can simply create an array: int score[13]; Here, `score` is an array that
can hold a maximum of 13 elements of int type. In C++, the size and type of arrays cannot be changed
after its declaration. From this example:
- int: datatype of the array
- score: name of the array
- 13: the size of the array.
score 45 80 53 57 61
Array indices 0 1 2 3 4
score[2] can be used to access the third element, which has a value of 53. Note that the index of the
third element is 2 (3-1).
Properties of an Array
- The array indices start with 0 or are zero-based indexed. Meaning that score[0] is the rst element
stored at index 0.
- If the size of an array is n, the last element is stored at index (n-1). In the above example, score[4] is
the last element.
- Elements of an array have consecutive addresses. For example, suppose the starting address
of score[0] is 2120. Then, the address of the next element score[1] will be 2124, the address
of score[2] will be 2128, and so on. Each is increased by four because the size of int is 4 bytes.
Page 11 of 14
fi
fi
C++ Array Initialization
An array can be initialised along with a declaration. For array initialisation, it is required to place the
elements separated by commas enclosed within braces.
int arr[5] = {10, 12, 2, 24, 55};
It is possible to leave the array size open. The compiler will count the array size.
int arr[] = {16, 71, 48, 29, 15, 17};
#include <iostream>
int main() {
Int n = 5;
int scores[n];
cin scores[i];
return 0;
In the above C++ program, we declared an array of size ve named `scores`. Then, we asked the user
to enter ve scores, which were entered into the array. Lastly, we printed out all the scores on the screen.
Page 12 of 14
fi
<
<
<
<
>
>
<
<
<
+
+
<
+
+
<
<
fi
Displaying Array Elements
To display elements of an array, we can use a for loop, as shown in the example above or a C++ range-
based for loop.
The two example code above will print out the elements of the `numbers` array.
Note: In our range-based loop, we have used the code const int &i instead of int i as the range
declaration. However, the const int &i is more preferred because:
- Using int i simply copies the array elements to the variable `i` during each iteration. This is not
memory-ef cient. &i, however, uses the memory address of the array elements to access their data
without copying them to a new variable. This is memory-ef cient.
- We are simply printing the array elements, not modifying them. Therefore, we use const to avoid
accidentally changing the array's values.
Example Code: Write a program to compute the sum of elements in an integer array.
#include <iostream>
int main()
int sum = 0;
sum += num;
return 0;
Page 13 of 14
fi
<
<
<
<
<
<
<
<
+
<
+
<
<
<
fi
In the above program:
- We have initialised an integer array named numbers but without specifying its size. We also declared
one integer variable, `sum`.
Here, sum = 0.
- Then we used a range-based for loop to print the array elements. In each loop iteration, we add the
current array element to `sum`.
- After printing all the elements, we print the sum of all the numbers.
Exercises:
1. Modify the example code to compute the product of the array
2. Write a C++ program to compute the sum of squares of an integer array
3. Write a C++ program to compute the average of an integer array.
The above example is a two-dimensional array with three rows and four columns. Represented as follows:
Row 1 5 4 5 8
Row 2 4 2 1 9
Row 3 9 3 5 6
int main() {
return 0;
Page 14 of 14
<
<
+
+
<
fi
<
+
+
<
<
<
<
<
<
<
<
<
<