Thursday, March 4, 2021
Home C / C++ Functions in C++

Functions in C++

We need to write a function in order to simplify our main(). A function contains three terms that are its prototype, its definition and its calling or we can say invoking.these three steps are defined one by one below ie:

1)Function prototype(declaration):        return_data_type

                        e.g       int square(int);

2) Function definition:
                                Function Header             
                                                                Function Body
                                                e.g          int  greater_of_two_nums (int num1, int num2)
                                                {              if (num1>num2) return num1;
                                                                else return num2;
3)Function Call:
void main()
int x,y;
cout << “Enter two number” << endl;
cin >> x >> y;
cout << “The greater of two numbers that you entered are”   <<                      greater_of_two_nums (x,y) <<endl;
Now we have an example which is finding the square root of a given number by using the above concepts. lets look at the example:

  1. //writing functions in c++
  2. #include<iostream>
  3. using namespace std;
  4. int square(int); // function prototype
  6. int main()
  7. {
  8.     int a = 10;
  10.     int b = square(a);  // function call
  12.     cout<<b<<endl;
  13.     return 0;
  15. }
  17. // function definition
  18. int square(int y)
  19. {
  20.     return (y*y);
  21. }

here we defined a function “square” with return type “int” and a number of datatype “int” as an  argument, then in the main()  we called it by passing an integer and at the end we got the square root of that number by using “square” function.

- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....