i am a newbie to programming and having a hard time understanding C++ functions. may someone please explain to me in layman's terms ,with examples, what a function is and how it is used. i would greatly appreciate any help.
Printable View
i am a newbie to programming and having a hard time understanding C++ functions. may someone please explain to me in layman's terms ,with examples, what a function is and how it is used. i would greatly appreciate any help.
Ok First of all a function is just a bit of code that could in theory be used without a function. Functions are generally used to make things easier on both the writer and the reader. Here's an example:
Ask me if you have any questions. Try to show me a function of your own and I'll tell you if it's good. You don't HAVE to have arguments. For example you could create a function like this:Code:#include <iostream.h>
float examplefunction( float number, float number2); /*declares function just like you declare a variable.*/
float examplefunction( float number, float number2)/*Defines the function so that it returns the quotient of 2 arguments it receives*/
{
return number/number2;
}
int main()
{
float number, number2;/*Declares the variables*/
cout<<"Type in first number: ";
cin>>number;
cout<<"Type in second number: ";
cin>>number2;
cout<<"The quotient is "<<examplefunction(number, number2);/*Takes the numbers inputted and inserts them into the function to be diveded*/
return 0;
}
That tells it that it has no arguments and then when you call the function it will just execute whatever's inside.Code:int examplefunction2(void);
Keep in mind the program I showed you uses floating point values...
Oh yeah and by the way, just to give you a further explanation, this could all be done WITHOUT a function like this:
Code:#include <iostream.h>
int main()
{
float number, number2;/*Declares the variables*/
cout<<"Type in first number: ";
cin>>number;
cout<<"Type in second number: ";
cin>>number2;
cout<<"The quotient is "<<number/number2;/*Takes the numbers inputted and divides them*/
return 0;
}
functions consist of a
(1)prototype
(2)call
(3)definition
functions are used to cut the program into smaller more manageable pieces.
This is an example of a simple function.Code:
//prototype
//data type (e.g. void), name (e.g. functionname), parameters inserted in the parentheses ()
//usually located in your header file
//see below
void functionname();
//call
//name of the function with the parameters you are passing
//this is the code in main that executes the code
//used in your driver file or implimentation file
funtionname();
//definition
//the code that the function executes
//usually located in your implimentation file
void functionname()
{
cout<<"hello world";
}
You can also make morecomplex functions by
passing parameters and returning data.