1. ## Functions.....

Ok, here is an example used in the tutorial: #include <iostream.h>

int mult(int x, int y);

int main()
{
int x, y;
cout<<"Please input two numbers to be multiplied: ";
cin>>x>>y;
cout<<"The product of your two numbers is "<<mult(x, y);
return 0;
}
int mult(int x, int y)
{
return x*y;
}

Now, here's what is much shorter and does the same thing: #include <iostream.h>

int main()
{
int a;
int b;
cout<<"enter two numbers to be multiplied: ";
cin>>a>>b;
int c = a*b;
cout<<"The product of your two numbers is: "<<c;
return 0;

}

Soo....whats the use of what they did in the tutorial? Also, I don't get it anyways, someone care to explain?

2. the function in the tutorial is pretty much useless...they just did it to show you an example.

Functions can be incredibly helpful, and are used in any and all professional code.

There are some things that you will need to use several times, and so you dont want to type it out several times. For example, lets say you wanted to sort a list of numbers (assuming you know basic arrays).

In a bubble sort, the code is:

int temp;
for(int x = 0; x < listlength; x++)
{
for(int y = 0; y < x; y++)
{
if(x > y) { //swap the vars
temp = x;
x = y;
y = temp;
}
}
}

Now, if you wanted to sort lots of list using the bubble sort, would you want to type it out 10000 times? No. So you use functions:

void BubbleSort (int list[], int listlength) {
int temp;
for(int x = 0; x < listlength; x++)
{
for(int y = 0; y < x; y++)
{
if(x > y) { //swap the vars
temp = x;
x = y;
y = temp;
}
}
}
}

Then, you could just say:

BubbleSort(myList, 10); //as an example, we will say the list is 10 elements long

Hope this helps.

3. It is just trying to give you an example of a function... a function can be used over and over again if you need to, so you don't have to keep re-writing the code. On a simple program it is easier to use what your example was, but on larger programs, it is better to use the function.

Popular pages Recent additions