Website For Developers

User defined functions in C++




Example with Void Return-type and null arguments

#include<iostream>
#include<conio.h>
using namespace std;
//function prototype
void show();
int main(){
  cout<<"This line is written in the main function.";
  // function calling
  show();
  getch();
  return 0;
}

//Function definition
void show(){
  cout<<"This line is written in the user defined function.";
}

Output

This line is written in the main function.
This line is written in the user defined function.


Example with a Return-type and null arguments

#include<iostream>
#include<conio.h>
using namespace std;
//function prototype
string send();
int main(){
  cout<<"This line is written in the main function.";
  //function calling
  string s = send();
  cout<<s;
  getch();
  return 0;
}
//function definition
string send(){
  string line = "This line is send from user defined function.";
  return line;
}

Output

This line is written in the main function.
This line is written in the user defined function.


Example with Void Return-type but has arguments

#include<iostream>
#include<conio.h>
using namespace std;
//function prototype
void sum(int a, int b);
int main(){
  int a,b;
  cout<<"Enter First Number:";
  cin>>a;
  cout<<"Enter Second Number:";
  cin>>b;
  //function calling
  sum(a, b);
  getch();
  return 0;
}
//function definition
void sum(int a, int b){
  cout<<"Total is:"<<a+b;
}

Output

Enter First Number: 3
Enter Second Number: 7
Total is: 10


Example with a Return-type and has arguments.

#include<iostream>
#include<conio.h>
using namespace std;
//function prototype
int sumFactory(int a, int b);
int main(){
int a,b;
  cout<<"Enter First Number:";
  cin>>a;
  cout<<"Enter Second Number:";
  cin>>b;
  //function calling
  int x = sumFactory(a, b);
  cout<<x;
  getch();
  return 0;
}
//function definition
int sumFactory(int a, int b){
  int total = a+b;
  return total;
}

Output

Enter First Number: 321
Enter Second Number: 123
444