Lab 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Lab 3.

Functions Fundamentals of Programming CSC10012

Lab 3

Functions
In this lab, we will learn about functions, which allow us to divide the program into smaller,
reusable components, make the source code more modular, easier to read and maintain.

Instructions
1. Function Definition, Declaration and Call
A function is a block of code that performs a specific task. To use a function, it must be declared
(prototype) and then defined.

• Function declaration: Specifies the function’s name, return type, and parameters.

returnType functionName(parameter1Type parameter1, ...);

For example:
1 int sum ( int a , int b ) ;

• Function definition: Contains the actual body of the function where the task is performed.
For example:
1 // Function definition
2 int sum ( int a , int b )
3 {
4 int ans = a + b ;
5 return ans ; // Return statement ( the outcome of the function )
6 }

• Function call: After function is defined, you can call it by its name and passing arguments.
For example:
1 int main ()
2 {
3 int a , b ;
4 cin >> a >> b ;
5 cout << " a + b = " << sum (a , b ) << endl ; // Function call
6 return 0;
7 }

University of Science Faculty of Information Technology Page 1


Lab 3. Functions Fundamentals of Programming CSC10012

2. Return Type
Functions can return a value, which is specified by the returnType in the function declaration.
When the function does not return anything, use void as the return type.

• Return a value:
1 int sum ( int a , int b )
2 {
3 return a + b ; // Returns the sum of a and b
4 }

• Void functions (no return value):


1 void printHello ()
2 {
3 cout << " Hello , world ! " << endl ;
4 }

3. Parameters: Pass by Value and Pass by Reference


Information can be provided to functions in the form of parameters, act as variables in the function.
Parameters are specified after the function name, inside the parentheses.
There is no limit to the number of passed parameters; then if multiple parameters are required,
they should be separated by commas.
There are two ways to pass arguments to functions in C/C++: by value and by reference.

• Pass by value: The function gets a copy of the argument, and changes made inside the
function do not affect the original variable.
1 void increment ( int x )
2 {
3 x = x + 1; // Does not change the original value
4 }

• Pass by reference: The function gets a reference to the argument, and changes made inside
the function will affect the original variable. Indicated by attaching the ampersand sign (&).
1 void increment ( int & x )
2 {
3 x = x + 1; // Changes the original value
4 }

University of Science Faculty of Information Technology Page 2


Lab 3. Functions Fundamentals of Programming CSC10012

Exercises
Exercise 1. Swap two numbers
Implement a function swap that exchanges the values of two integers. Then, write a program to
input two integers, use the swap function to exchange their values, and print the swapped values.

Example:

Input Output
10 20 20 10

Exercise 2. Calculate BMI


Implement a function calculateBMI that takes two arguments: weight W (kg) and height H (m),
and returns the Body Mass Index (BMI). The formula for BMI is:

W
BM I =
H2
Write a program to input weight and height, print BMI result using calculateBMI function.

Example:

Input Output
70 1.75 22.8571

Exercise 3. Calculate the sum of the first n natural numbers


Implement a function sumUpToN that calculates the sum of the numbers from 1 to n as follow:

S = 1 + 2 + 3 + ... + n

Write a program to input n, calls the sumUpToN function, and prints the result.

Example:

Input Output
5 15

University of Science Faculty of Information Technology Page 3


Lab 3. Functions Fundamentals of Programming CSC10012

Exercise 4. Calculate Factorial


Implement a function factorial that calculates the factorial of a number n as follow:

n! = n × (n − 1) × ... × 1

Write a program to input n, then print n! by using the factorial function.

Example:

Input Output
5 120

Exercise 5. Fibonacci
Implement a function fibonacci that returns the nth Fibonacci number which is defined as follow:

• F0 = 0

• F1 = 1

• Fn = Fn−1 + Fn−2 (for n ≥ 2)

Write a program to input n, calls the fibonacci function, and prints the result.

Example:

Input Output
7 13

Exercise 6. Check for a Perfect Square


Implement a function isPerfectSquare that checks whether a given number n is a perfect square.
The function must return a boolean value (true or false).
Write a program to input n, check if n isPerfectSquare and print the result.

Example:

Input Output
16 true

University of Science Faculty of Information Technology Page 4


Lab 3. Functions Fundamentals of Programming CSC10012

Exercise 7. Count the Number of Digits


Implement a function countDigits that counts and returns the number of digits in a integer n.
Write a program to input n, and print the number of digits using countDigits function.

Example:

Input Output
12345 5

Exercise 8. Sum of the Digits


Implement a function sumDigits that calculates and returns the sum of the digits of a integer n.
Write a program to input n, and print the sum of digits using sumDigits function.

Example:

Input Output
12345 15

Exercise 9. Greatest Common Divisor (GCD)


Implement a function gcd that returns the GCD of two integers using Euclid’s algorithm.
Write a program to input a and b, and print the Greatest Common Divisor using gcd function.

Example:

Input Output
24 36 12

Exercise 10. Convert Decimal to Binary


Implement a function decimalToBinary that converts a decimal number to its binary equivalent.
Write a program to input n, and print the binary equivalent using decimalToBinary function.

Example:

Input Output
10 1010

University of Science Faculty of Information Technology Page 5

You might also like