Sunday 11 February 2018

Types of user-defined functions in C++

In this post, you will learn more about user-defined functions and how can you use user-defined functions in different ways?

Basically, functions are categorized on the basis of return value and arguments, user-defined functions can be categorized as:



  • 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
Consider a situation in which you have to make a program to find the cube of a number. You can use four different methods to solve this problem:-


Program -1: No arguments passed and no return value

#include<iostream>

using namespace std;

void fun(){   /* function with no arguments and return value */
 
 int a,c;
 
 cout<<"Enter a number: ";
 cin>>a;
 
 c=a*a*a;
 
 cout<<"cube is = "c;
 
}

int main(){
 
 fun();   // function call
 
 return 0;
}
In the above program, fun() have no arguments and also no return value because function return type is void.
function calling in main() function by the name of function i.e fun().

Program - 2: No arguments passed but a return value

#include<iostream>

using namespace std;

int fun(){  /* function with return value but no arguments */
 
 int a,c;
 cout<<"Enter any number: ";
 cin>>a;
 
 c=a*a*a;
 
 return c;
 
}
int main(){
 // function call
 cout<<"cube is = "<<fun();
 
 return 0;
}
In this program, function i.e. fun() have no arguments but return a value.In main() function, we call this function and also print it in main().


Program - 3: Arguments passed but no return value

#include<iostream>

using namespace std;

 void fun(int a){ /* function with argument but no return type */
  
  int c;
  
  c=a*a*a;
  
  cout<<"cube is = "<<c;
  
   }
   
int main(){
  
  fun(2); /* function calling and passing a value*/
  
  return 0;
}
Above program have an argument but no return value because the return type of function is void.
calling of function is in main() function and passing a value in fun().

Program - 4: Arguments passed and a return value

#include<iostream>

using namespace std;

int fun(int a){ /* function with argument and return value */
 
 int c;
 
 c=a*a*a;
 
 return c;
 
}

int main(){
// function call and value passing 
 cout<<"cube is = "<<fun(3); 
 
 return 0;
}
In the above program, fun() have an argument and also return value.

NOTE: C++ have the top to bottom approach that's why no function declaration.

Also, you can choose the above methods according to your need.

HAPPY CODING...