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

05 - CSC 201 - Functions & Array

Uploaded by

Don J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

05 - CSC 201 - Functions & Array

Uploaded by

Don J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Content

- 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.

There are two main types of functions in C++:

Type of Functions

Standard Library User-De ned


Functions 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.

Advantages of C++ Functions


- Functions help us reduce code redundancy: If functionality is performed at multiple
places in software, then rather than writing the same code repeatedly, we create a function
and call it everywhere. This also helps in maintenance as we have to change in one place if we
make future changes to the functionality.
- Functions make code modular: Consider a big le having many lines of code. Reading and
reusing the code becomes really simple if it is divided into functions.
- Functions provide abstraction: For example, we can use library functions without worrying about
their internal work.

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>

using namespace std;

char grade (int); Function prototype

int main ()

int total = 60;

char grd = grade(total); Calling a Function Main Function

cout “Grade for ” total “ is ” grd;

return 0;

char grade (int score) Function Header

if(score 50){

return ‘P’; Function De nition


Function Body
} else {

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 ()

int total = 60;

char grd = grade(total);

cout “Grade for ” total “ is ” grd;

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

Functions with no parameters and no return value


#include <iostream>

using namespace std;

void sumOneToTenPrint()

int sum = 0;

for(int i = 1; i 10; i ){

sum += i;

cout sum endl;

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>

using namespace std;

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.

Functions with parameters but no return value


#include <iostream>

using namespace std;

void sumOneToTenInput(int n)

int sum = 0;

for(int i = 1; i n; i ){

sum += i;

cout sum endl;

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>

using namespace std;

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.

Example Overloaded Function:


int multiply(int a) { … }

int multiply(int a, int b) { … }

float multiply(float a) { … }

double multiply(int a, float b) { … }

Overloaded functions may or may not have different return types, but they must have different arguments.

C++ Storage Class


Every variable in C++ has two features: type and storage class.
- Type speci es the type of data that can be stored in a variable. For example, int, oat, char etc.
- Storage class controls two different properties of a variable: lifetime (determines how long a variable
can exist) and scope (determines which part of the program can access it). Depending upon the
storage class of a variable, it can be divided into three major types:
- Local variable
- Global variable
- Static local variable
Page 7 of 14
fi
<
=
+
+
fl
Local Variable
A variable de ned inside a function (de ned inside the function body between braces) is called a local
variable or automatic variable. Its scope is only limited to the function where it is de ned. In simple terms,
a local variable exists and can be accessed only inside a function. The life of a local variable ends (It is
destroyed) when the function exits.

Example of a Local Variable


#include <iostream>

using namespace std;

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>

using namespace std;

int g = 10 This is a global variable because it is the declared outside a function

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>

using namespace std;

void test()

static int i = 0; This is a static variable

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>

Using namespace std;

int sum(int n);

int main() {

cout sum(10) endl;

return 0;

int sum(int n){

if(n 1){

return 1; Base case

return n + sum(n - 1); Recursive case

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.

C++ Array Declaration


Like variables, arrays must be declared before they can be used in a C++ program. Arrays can be
declared using the C++ array declaration syntax: dataType arrayName[arraySize];

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.

Access Elements in C++ Array


In C++, each element in an array is associated with a number. The number is known as an array index.
We can access elements of an array by using those indices. Syntax to access elements of an array
array[index]

For example, consider the array `score` having ve elements:

Array members score[0] score[1] score[2] score[3] score[4]

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};

Using Loop to Insert Array Elements


We can use loops to insert elements into an array, as shown in the example below:

#include <iostream>

using namespace std;

int main() {

Int n = 5;

int scores[n];

cout "Enter 5 scores: " endl;

for (int i = 0; i < n; i) {

cin scores[i];

cout "The scores are: ";

for (int j = 0; j < n; j) {

cout scores[j] " ";

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.

Using a for loop Using a Range-based for loop

#include <iostream> #include <iostream>


using namespace std; using namespace std;

int main() int main()


{ {
int numbers[] = {12, 34, 17, 23, 10} int numbers[] = {12, 34, 17, 23, 10}

for(int i = 0; i < 5; i ){ for(const int &I: numbers){


cout numbers[I] endl; cout i endl;
} }
return 0; return 0;
} }

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>

using namespace std;

int main()

int numbers[] = {3, 6, 4, 7, 2, 3, 8, 9, 2, 4};

int sum = 0;

for(const int &num : numbers){

sum += num;

cout “Sum of the array is: ” sum;

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.

C++ MULTIDIMENSIONAL ARRAYS


Two-dimensional Array
It is a collection of data elements of the same data type arranged in rows and columns (that is, in two
dimensions).
Example: int nums[3][4] = { {5, 4, 5, 8}, {4, 2, 1, 9}, {9, 3, 5, 6}};

The above example is a two-dimensional array with three rows and four columns. Represented as follows:

Column 1 Column 2 Column 3 Column 4

Row 1 5 4 5 8

Row 2 4 2 1 9

Row 3 9 3 5 6

Iterating Over a Multidimensional Array


Multidimensional arrays can be traversed using nested loops to perform operations on each element.
Each loop represents a speci c dimension, allowing you to access elements using the corresponding
indices.
Example:
#include <iostream>

using namespace std;

int main() {

int nums[3][2] = {{2, 5}, {4, 0}, {9, 1}};

for (int i = 0; i < 3; i) {

for (int j = 0; j < 2; j) {

cout "nums[" i "][" j "] = " nums[i][j] endl;

return 0;

Page 14 of 14
<
<
+
+
<
fi
<
+
+
<
<
<
<
<
<
<
<
<
<

You might also like