1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
6

Functions in C++: A Comprehensive Guide for Beginners

Updated on 19/09/2024418 Views

Every software developer like me will vouch for the immense importance of C++ in their programming journey. Functions in this programming language are focal elements that helped me organize code, enhance its reusability, and improve overall readability.

In this tutorial, I'll detail the various types of functions in C++, briefly explaining user-defined functions, string operations, vectors, stacks, file handling, the STL, function overloading, and mathematical functions in C++ with examples.

Understanding functions in C++

In C++, a function is a reusable code block that carries out a specific function. Return values are outputs of tasks that can be produced from inputs or parameters. You won't have to write the same code continuously because you can call these functions from other application sections. Functions in C++ enable you to concentrate on specific tasks rather than becoming overburdened by the whole program at once.

Why do you need functions in C++?

Functions in C++ provide vital advantages that help produce more dependable, manageable, and efficient code. These are the reasons why we need functions:

1. Code reusability

Functions let you package a particular operation or work inside a line of code. Once defined, this block can be recurrently used in several programs or various program sections.

2. Code organization and modularity

Functions in C++ help you divide difficult jobs into smaller, easier-to-manage bits. They also facilitate understanding of your program’s structure and the isolation of particular activities.

3. Code readability

Functions help simplify and improve your code's readability by proffering various operations meaningful names. This is especially useful when working with others or returning to code after a while.

4. Code maintainability

Functions in C++ give your code a logical structure, which helps with maintainability. If a function has a defined task, you can change or update it without affecting other program sections.

5. Separation of concerns

Functions promote a programming concept called "separation of concerns," which holds that each function should have a single responsibility.

6. Testability

Functions in C++ make tests on specific code sections easier. Unit tests can be written to guarantee each function works as intended when you have discrete tasks with well-defined roles.

7. Working together in teams

Functions in C++ support teamwork in collaborative settings.

Types of functions in C++

Every function type in C++ has a particular use. Here are the popular types:

String functions in C++

Strings are essential in C++, as in every other programming language. Numerous string C++ functions provided by the C++ Standard Library simplify operations like determining a string's length, extracting substrings, and concatenating several strings.

When I initially began using C++, looping through a string's characters frequently required me to know its length. Given the number of characters in a string with a single call, the length() method was a lifesaver. Similarly, the substr() function extracts particular portions of a string, which is helpful for parsing user input or obtaining data from a bigger text block.

Here is a string functions in C++ with example:

#include <iostream>

#include <string>

using namespace std;

int main() {

string s1 = "Hello, World!";

// Getting the length of the string

cout << "Length of the string: " << s1.length();

// Extracting a substring

string s2 = s1.substr(7, 5); // Starting from index 7, extract 5 characters

cout << "\nSubstring: " << s2;

return 0;

}

String Function in C++

Vector functions in C++

Vector C++ functions are dynamic arrays useful for handling data collections. Vectors make adding and deleting components simple without worrying about the underlying memory management.

The push_back() function is perfect for dynamic list construction because it allows you to add elements to the end of a vector. Knowing how many items are in a vector is made more accessible when you need to loop through it or verify that it has sufficient capacity using the size() function.

Example-

#include <iostream>

#include <vector>

using namespace std;

int main() {

vector<int> v = {1,2,3,4};

v.push_back(5);

int n = v.size();

cout << "The last element is: " << v[n - 1];

return 0;

}

Vector Function in C++

User defined functions in C++

Any C++ application's core is its user-defined functions. These are the functions you write to carry out particular jobs, enabling you to reuse code and encapsulate logic. I mainly depend on user-defined functions to maintain the logic and coherence of my code.

Assume that you have an extensive program with many chores to complete. Maintaining and troubleshooting would not be accessible if all code were written in one location without user-defined functions. These functions in C++ allow you to divide difficult jobs into smaller, function-representable chunks. As you may call these methods from other program sections, this method simplifies code management and encourages reusability.

Example-

#include <iostream>

#include <stdio.h>

using namespace std;

// Function declaration

int isGreater(int x, int y) {

if (x > y) {

cout << "x is greater";

return x;

} else {

cout << "y is greater";

return y;

}

}

// Driver code

int main() {

int x = 10, y = 11;

// Function call

int result = isGreater(x, y);

printf("\nThe greater number from %d and %d = %d ", x, y, result);

return 0;

}

User-defined Function in C++

If you're new to C++, I suggest checking out some programming projects to work on so you can better understand its operation.

Stack functions

Stack functions in C++ are fundamental data structures used to manipulate elements’ positions. The tenet that governs stack operations is Last-In, First-Out (LIFO); the last item added is the first to be deleted.

Push() removes the top element from the stack; pop() adds it. These routines are handy when preserving an order of operations, such as in undo/redo or expression evaluation. The top() method makes checking what's at the top of the stack at any given time simple.

Example-

#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of strings

stack<string> colors;

// add element to the Stack

colors.push("Red");

colors.push("Blue");

colors.push("Orange");

// print top element

cout << "The topmost element is: " <<colors.top();

return 0;

}

Stack Function in C++

File handling functions

Many programs depend heavily on file management, and file handling functions in C++ offer several file-related features. The Standard Library provides all you need to read from and write to files.

Use std::ofstream to create and write text to a file. Conversely, std::ifstream enables you to read from a file and access and handle data from outside sources. Applications requiring reading external inputs or storing data depend on these file-handling features.

Creating a file:

#include <iostream>

#include <fstream>

int main() {

std::ofstream newFile("new_filewrite.txt"); // Using ofstream for writing to file

if (!newFile) {

std::cout << "File creation failed";

} else {

std::cout << "New file created";

newFile << "FILE HANDLING IN C++" << std::endl; // Writing to file with newline

newFile.close();

}

return 0;

}

Reading from the created file:

#include <iostream>

#include <fstream>

int main() {

std::ifstream newFile("new_filewrite.txt"); // Using ifstream for reading from file

if (!newFile) {

std::cout << "No such file";

} else {

char ch;

while (newFile.get(ch)) { // Using get() to read characters

std::cout << ch;

}

newFile.close();

}

return 0;

}

File Handling Function in C++

Mathematical functions in C++

Numerous mathematical functions in C++ make calculations more accessible, and mathematics is at the heart of any programming job. The C++ Standard Library offers functions to support you whether you're working with more complicated operations or fundamental arithmetic.

You can compute a number's power with functions like std::pow() and discover its square root with std::sqrt(). Working with mathematical models, scientific computations, or geometry-related chores requires these services. These mathematical functions in C++ will be helpful as you learn C++ to streamline intricate procedures.

#include <cmath>

#include <iostream>

using namespace std;

// Computing the power of given number

int main() {

double base = 2.0;

double exponent = 3.0;

double result = std::pow(base, exponent);

cout << base << " raised to the power of " << exponent << " is " << result;

// Computing the square root of given number

double number = 25.0;

double squareRoot = std::sqrt(number);

cout << "\nSquare root of " << number << " is " << squareRoot;

return 0;

}

Mathematical Function in C++

STL functions in C++

A mainstay of C++, the Standard Template Library (STL) provides many capabilities for interacting with different data structures and algorithms. Whether working with associative containers like maps and sets, sorting data, or discovering elements, the STL has a use for it.

While std::find() facilitates searching for particular objects, std::sort() lets you sort elements in a container. These features are priceless when handling humongous amounts of data that require effective methods to work with. Any C++ programmer needs to be able to use and understand STL functions because they offer a standardized approach to carrying out repetitive operations.

Example-

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main() {

vector<int> numbers = {23, 25, 21, 22, 24};

sort(numbers.begin(), numbers.end());

cout << "\nSorted numbers: ";

for (int num : numbers) {

cout << num << " ";

}

return 0;

}

Function overloading in C++

The most common overloading in C++ is function overloading. As long as the number or type of parameters vary, function overloading lets you define several functions under the same name. Using a single function name to describe several operations makes it valuable.

Example-

#include <iostream>

using namespace std;

// Function to calculate the sum of two integers

int add(int a, int b) {

return a + b;

}

// Overloaded function to calculate the sum of three integers

int add(int a, int b, int c) {

return a + b + c;

}


// Driver Code

int main() {

cout << "Sum of 10 and 4: " << add(10, 4) << std::endl;

cout << "Sum of 10, 4, and 6: " << add(10, 4, 6) << std::endl;

return 0;

}

Function Overloading in C++

Wrapping Up

Functions in C++, thus simplify difficult chores, encourage code reuse, and improve code management. Functions are at the core of everything, whether you work with texts, vectors, stacks, file processing, mathematical calculations, or the STL. When learning C++, try each type of function and observe how it affects your code.

If you aim to become a full-stack developer, consider upGrad. Its PG Course in Software Development specializes in this field and teaches you the skills to create effective applications.

Take the first step toward a successful career in technology with upGrad.

Frequently Asked Questions

  1. What is a function in C++?

A function in C++ is a block of code that performs a specific task. It takes input, processes it through defined statements, and optionally returns a value as output.

  1. How do you declare a function in C++?

You declare a function in C++ by specifying its return type, name, and parameter list, followed by a semicolon or a code block.

  1. Can a function return multiple values in C++?

Although a C++ function cannot return multiple values simultaneously, you can accomplish this with reference arguments, structures, and classes.

  1. What are function parameters in C++?

In C++, variables or values supplied into a function upon call enable the function to work with particular data. These are known as function parameters.

  1. What is function overloading in C++?

Function overloading in C++ is a feature that allows multiple functions to have the same name but different parameter lists.

  1. Can functions be recursive in C++?

Functions in C++ indeed have the ability to call themselves to solve problems through recursion or repeated iterations.

  1. What is a default argument in C++ functions?

When you call a C++ function without explicitly passing in an argument, the function's default argument is a parameter with a pre-defined value.

  1. What is a function template in C++?

A function template is a blueprint to write functions in C++ that work with generic types, allowing the same function to be used with many data types.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...