0% found this document useful (0 votes)
142 views7 pages

Chapter 4 C++

Uploaded by

Tegha Lucas
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)
142 views7 pages

Chapter 4 C++

Uploaded by

Tegha Lucas
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/ 7

CHAPTER 4

Functions
4.1. What are C++ functions?
A function is a set of statements that takes input, does some specific computation, and produces
output. They are used to break down a program into smaller, more manageable parts, making it
easier to understand and maintain. If your program is very bulky, break it into smaller parts so
that each part does a specific job; then call these parts functions.

4.2. Functions Basics


C++ functions generally adhere to the following rules.
1. Every function must have a name.
2. Function names are made up and assigned by the programmer following the same
rules that apply to naming variables. They can contain up to 32 characters, they must
begin with a letter, and they can consist of letters, numbers, and the underscore (_)
character.
3. All function names have one set of parentheses immediately following them. This
helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after parentheses of the function
name, must be enclosed by braces.

There are two types of functions in C++, which are built-in functions and user defined
functions.

4.3. C++ Built-in functions


C++ has many built-in functions. In order to use them, the required library has to be imported
using #include.
Here a function named sqrt() is made available from the <cmath> library:
Example
#include <iostream>
#include <cmath>

int main() {
cout << sqrt(10);
// Output: 3.16228
}

We note here that the Library <cmath> has many functions and sqrt is one of them. Other
functions in the same Library include: log(), pow(), sin() and cos().

1
4.4. User defined functions
Function Declaration and Definition
A C++ function consist of two parts: function declaration and function definition.

return_type function_name (function parameters or inputs) {


// code to be executed
}

Example
int sum(int a, int b) {
return(a + b);
}

4.4.1. Function declaration


Function declaration, is done to tell the compiler about the existence of the function. It
consist of: return type, the name of the function, and parameters (if any)
Syntax

Example: void myFunction(num1, num2)


Here, this function returns nothing (void), the name of the function is myFunction and the
parameters are num1 and num2.
4.4.2. Function Definition
This is the body of the function (code to be executed).
Consider the function below
// Create a function
void ePrint() {
cout << "I just got executed!";
}
The part written in blue is the function declaration (which tells the compiler the existence of the
function) and the part written in red is the function definition (which tells the compiler what the
function does).

Consider the example below

#include < iostream>

2
using namespace std;

//declaring the function

int sum (int x, int y);

int main()

int a = 10;

int b = 20;

int c = sum (a, b); //calling the function

cout << c;

//defining the function

int sum (int x, int y)

return (x + y);

Here, initially the function is declared, without body. Then inside main() function it is called, as
the function returns summation of two values, and variable c is there to store the result. Then, at
last, function is defined, where the body of function is specified. We can also, declare & define
the function together, but then it should be done before it is called.

4.5. Calling a function


Functions are called by their names. If the function is without argument, it can be called directly
using its name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference

3
4.5.1. Call by Value
In this calling technique we pass the values of arguments which are stored or copied into the
formal parameters of functions. Hence, the original values are unchanged only the parameters
inside function changes.

void calc(int x);

int main()

int x = 10;

calc(x);

cout<< x ;

void calc(int x)

x = x + 10 ;

In this case the actual variable x is not changed, because we pass argument by value, hence a
copy of x is passed, which is changed, and that copied value is destroyed as the function ends
(goes out of scope). So the variable x inside main() still has a value 10.

Example 2
#include <iostream>
using namespace std;
int larger(int a, int b) {
if (a > b) {
return a;
}
else {
return b;

4
}
}
// Returns the larger of the two values.
int main() {
int bigger1 = larger(17, 42); // call the function larger
int bigger2 = larger(29, -3); // call the function again
int biggest = larger(bigger1, bigger2); // call the
function again
cout << "The biggest is " << biggest << "!!" <<
endl;
return 0;
}
The result from the console is as follows

4.5.2. Call by reference


In this we pass the address of the variable as arguments. In this case the formal parameter can be
taken as a reference or a pointer, in both the case they will change the values of the original
variable. NB: You need prior knowledge on pointers before you can call a function by reference.

void calc(int *p);

int main()

int x = 10;

calc(&x); // passing address of x as argument

cout<<x ;

}
5
void calc(int *p)

*p = *p + 10;

4.6. Recursive functions


A function which calls itself is said to be recursive. Recursion is a general programming
technique applicable to problems which can be defined in terms of themselves. Take the factorial
problem, for instance which is defined as:

• factorial of 0 is 1
• factorial of a positive number n is n time the factorial of n-1

The second line clearly indicates that factorial is defined in terms of itself and hence can be
expressed as a recursive function.
A recursive function must have at least one termination condition which can be satisfied.
Otherwise, the function will call itself indefinitely until the runtime stack overflows.

6
Example

// Factorial of n = 1*2*3*…*n

#include <iostream> using


namespace std;
int
factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}

Another example is a function that computes the sum of the first N positive integers 1,2,…,N.

Exercise
1. Write an int function cube() that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two formal
parameters h and w, where h is the height and w is the length of the base of the triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle using its
two float formal parameters h and w, where h is the height and w is the width of the rectangle.
4. Write a function called isEven() that uses the remainder operator(%) to determine whether
an integer is even or not.

You might also like