A function is a collection of statements that collectively operate a task. Every single C++ program includes a minimum of one function that is main(), and all the the majority of small programs can define other functions.
You may split up your code into different functions. A function name employs the similar rules that have been employed on our variables until now .Further to this,make use of a name that specifies exactly what the function |is predicted to do.
FUNCTION DECLARATION
In an effort to construct and apply a function, you need to let the compiler know. Allowing the compiler know about your function implies you “declare” it. The syntax of declaring a function is:
Return_type Function_name(parameter_list);
An activity, considered a function, is made of 3 parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor.ReturnType can be void or int,float etc.Using void as a returntype keyword signifies that a function does not return a value.But using keywords like int,float we have to return the result at the end of the function.More about this will be discussed later.Parameter list refers to the values that you want to include in your function from the program or from the user's side.Parameter list can be empty if you don't want to use any parameters.
Say, If you have an addition of two numbers function and you want that this function can accept values entered by the user at the run time then you should have two parameters. For eg.
void/int add(int a,int b);
FUNCTION DEFINITION
In an effort to use a function you need to allow the compiler to know what the function basically do,how the function will be executed.This is referred to as defining a function.Its syntax is as followed:
Return_type Function_name(parameter_list)
{
statements;
}
Statements include the code which is used for the implementation of the function.For eg.
Function for the addition of two numbers:
void add(int a,int b)
{
int c;
c=a+b;
cout<<"addition of two numbers is %d"<<c;
}
FUNCTION CALLING
After defining and declaring a function you definitely want to use the function in your program.Using function in a program is referred to as Function calling.Wherever you want to use a function in a program just call that function by the following syntax:
function_name(parameter_list);
SIMPLE C++ PROGRAM USING FUNCTION
#include <iostream>
using namespace std;
// function declaration
int max(int a, int b);
int main ()
{
// local variable declaration:
int m = 100;
int n = 200;
int res;
// calling a function to get max value.
res = max(m, n);
cout << "Max value is : " << res << endl;
return 0;
}
// function returning the max between two numbers
int max(int a, int b)
{
// local variable declaration
int result;
if (a > b)
result = a;
else
result = b;
return result;
}
Monday
//
Labels:
c++
//
0
comments
//
0 comments to "Functions"
Powered by Blogger.
Post a Comment