For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
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.
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.
Functions in C++ provide vital advantages that help produce more dependable, manageable, and efficient code. These are the reasons why we need functions:
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.
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.
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.
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.
Functions promote a programming concept called "separation of concerns," which holds that each function should have a single responsibility.
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.
Functions in C++ support teamwork in collaborative settings.
Every function type in C++ has a particular use. Here are the popular types:
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;
}
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;
}
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;
}
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 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;
}
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;
}
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;
}
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;
}
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;
}
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.
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.
You declare a function in C++ by specifying its return type, name, and parameter list, followed by a semicolon or a code block.
Although a C++ function cannot return multiple values simultaneously, you can accomplish this with reference arguments, structures, and classes.
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.
Function overloading in C++ is a feature that allows multiple functions to have the same name but different parameter lists.
Functions in C++ indeed have the ability to call themselves to solve problems through recursion or repeated iterations.
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.
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.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.