Functions in C++

Pointers in C++
Generate Random Numbers 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.

Pointers in C++
Generate Random Numbers in C++

Leave a Reply