C++ Functions With Examples – Programming Code Examples
C++

C++ Functions With Examples5 min read

We have just seen how to vary the course of a program using loops and connections. Before that, I talked about variables. These are elements that are found in all programming languages. This is also the case of the notion that we will discuss in this chapter: functions.

All C ++ programs exploit functions and you have already used several, without necessarily knowing it.
The purpose of the functions is to cut out its program into small reusable elements, much like bricks. They can be assembled in a certain way to create a wall, or in another way to make a shed or even a skyscraper. Once the bricks are created, the programmer “just has to” assemble them.

 

Advantages of Function




Creating functions in a program is beneficial. They

  • Avoid repetition of codes.
  • Increase program readability.
  • Divide a complex problem into many simpler problems.
  • Reduce chances of error.
  • Makes modifying a program becomes easier.
  • Makes unit testing possible.

 

Components of Function

A function usually has three components. They are:

  1. Function prototype/declaration
  2. Function definition
  3. Function call

 

 

A simple function example

User-defined functions

 

C++ Functions Examples

 

Example 1: Library Function

 

Output:

 

Example 2: User Defined Function

C++ program to add two integers. Make a function add() to add integers and display sum in main() function.

Output:

 

Example 3: Check Prime Number

 

Example 4:

Similar to the addition function in the previous example, this example defines a subtract function, that simply returns the difference between its two parameters. This time, main calls this function several times, demonstrating more possible ways in which a function can be called.

 

Example 5: C++ program to swap two values using function (call by reference)

This program swaps the value of two integer variables. Two integer values are entered by user which is passed by reference to a function swap() which swaps the value of two variables. After swapping these values, the result is printed.

 

 

Output

 

Example 6: C++ program to use a static member function

 

This program is similar to the previous program but here we have used static member function to display the content of static data member. Static member function are called using class name and scope resolution operator (::) as called in the program:

Since, static member function can’t access other members of a class except static data member, so a separate function is used to display them.

Output

Leave a Comment