-
Functions
Im C++ newbie im started understanding if commands,loops, and strings and even made a mini project by maiking a basic math quiz. the thing i wanna hit next is understandign functions. the tutorial is too plain can ne1 give a better example of when and how to use functions and explain it?
-
Let me show you, say, a function that squares it's input:
Code:
long square (long x)
{
return x*x;
}
This function takes one argument, which is named x and is of type long:
Code:
long square (long x)
It also returns a long:
Code:
long square (long x)
This is the line that returns the value:That's it! While this is a highly simplified example, it illustrates the basic concepts of functions.
-
-
but how would you use that square function in a program i tryed but got confused by ho to declare x
-
Sorry. Look at this:
Code:
long thenum = 3; //This is our number.
thenum = square(thenum); //This gets an argument of thenum and returns it's result into thenum.
-
Ok that explains it better but at the top I have to declare the function like int ( x and whatever
how would I declare the function by using only one variable?
-
so fricking confusedy if im being a pain
Code:
#include <iostream>
using namespace std;
int square x;
int main()
{
int x;
cout<<"Please input the number to be squared: ";
cin>> x ;
cin.ignore();
cout<<"The square is <<"\n";
cin.get();
}
long square (long x)
{
square x*x;
}
I know this is completely wrong but this is my futile attempt to apply what you just told me into a program. can u tell me wat i did wrong?
-
Just about everything. What you need is a good introductory book. See the sticky thread.
-
>int square x;
I think you meant that to be a function prototype. What you have done is created a
global variable.
>cin.ignore();
You do not need that in there at all
You need to pass the argument the function for it to calculate the result.
Oh, and you declared the prototype ( global variable ) of type int, when the function
square is defined as long. A function header and a function prototype must match in return types apart from function overloading - which is a different matter all togther. There are a few more errors too.
As cornbee said, it is best you read a tutorial or get a good beginners book. Check out the book recomendations on this site for some advise on what one(s) to get.
-
Read my posts (and forward declare as long square (long x);)