Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

Lesson 3



Functions
Functions are everything when it comes to large programs. They split up the program into many smaller programs. They can be called from anywhere and the statements within it executed.
There is 3 parts to every function 1-Definition, 2-Call, 3-Actual function. First the definition, this line is written below the include files and above the main() function, so relatively its being defined as a global. Next is the Call, which you write out the function title anywhere in your program to call it. Lastly its the actual function, the first line is identical the the definition without the semicolin.
Example:

//Program to introduce funtions

#include <conio.h>
#include <iostream.h>

void My_function();		//Definition

void main()
{
	cout << "Calling function: ";
	My_function();		//Call
	getch();
}

void My_function()		//Actual function
{
	cout << "My_function";
}
Next we are going to pass a variable down to the function, for this you must specify the type of variable being passed down to the function, also if you are going to return a value, you must specify what type of value that is.
Example

//Program to Pass a variable to a function

#include <conio.h>
#include <iostream.h>

int My_function(int My_variable);		//Definition

void main()
{
	int Num1,Num2;
	Num1=5;
	Num2=My_function(Num1);			//Call - send Num1 to it
	cout << "Number 2 is: " << Num2;
	getch();
} int My_function(int My_variable) //Actual function { int Temp; Temp=My_variable*4; return Temp; }
First, because i was going to return an integer Temp i made the function an int. Also the number i sent to it was an int My_number so i had to define that to inside the brackets. Then i defined 2 variables Num1 and Num2 as integers, Num1 was assigned a value of 5, then Num1 was sent to My_function, i could have just wrote My_function(5); instead of My_function(Num1); but for learning purposes i send down Num1. In the function, Temp is calculated from effectively Num1*4 althrough it says My_variable this is because it does not have to match. Temp should be assigned a value of 5*4 = 20. Then Temp is returned and Num2 then is assigned the variable Temp. The final output should be Number 2 is: 20 .

After a small chapter its only fair to take the next Quiz - Click here


Back Home Next