A function is a block of code that performs a specific task.
The syntax to declare a function is:
returnType functionName(parameter1,parameter2,......)
{
// Function body
}
Suppose we need to create a program to create a circle and
color it. We can create two functions to solve this problem:
- a function to draw the circle
- a function to color the circle
Dividing a complex problem into smaller chunks makes our
program easy to understand and reusable.
There are two types of function:
- Standard
Library Functions: Predefined in C++
- User-defined
Function: Created by users
Library Functions
Library functions are the built-in functions in C++
programming.
Programmers can use library functions by invoking the
functions directly; they don't need to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(),
etc.
In order to use library functions, we usually need to
include the header file in which these library functions are defined.
For instance, in order to use mathematical functions such
as sqrt() and abs(), we need to include the header file cmath.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 49.0;
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output:
Square root of 49 = 7
Process returned 0 (0x0) execution time : 2.622 s
Press any key to continue.
User-defined Function
C++ allows the programmer to define their own function.
A user-defined function groups code to perform a specific
task and that group of code is given a name (identifier).
User-defined functions can be in various forms like:
- Function with no argument and no return value
- Function with no argument but return value
- Function with argument but no return value
- Function with argument and return value
Function with no argument and no return value
#include <iostream>
using namespace std;
void show_output();
int main() {
// no argument is passed to the function
show_output();
return 0;
}
void show_output() {
cout << "Hello World!";
}
Output:
Hello World!
Process returned 0 (0x0) execution time : 2.353 s
Press any key to continue.
Function with no argument but return value
Program
#include <iostream>
using namespace std;
string get_username();// declare a function with no argument and return type string
int main() {
string user_name = get_username();
cout << "Hello, " << user_name;
return 0;
}
string get_username() {
string name;
cout << "Enter your user name\n";
cin >> name;
return name;
}
Output:
No comments:
Post a Comment