![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: May 2006
Posts: 12
Rep Power: 0
![]() |
Spoon feed me... (functions)
Guys IM starting starting to learn C++.
Im going thru a book that someone recommended to me. However I just cant seem to grasp functions. I know they are important but I cant seem to understand it... Ok so I need a prototype so it knows how to handle the data. But passing stuff to the function and using that information ... ugh I dont know why its so hard for me to grasp but it is... Can someone show me a simple function and then explain in dummy terms what it does? Then maybe show a harder function? Keep in mind my knowledge of c++ is very limited. The only things I have done is the hello world thing and simple variable assignments. Thanks everyone |
|
|
|
|
#2 |
|
The Oblivious One
Join Date: May 2005
Location: Ontario, Canada
Posts: 648
Rep Power: 4
![]() |
You seem like you read some material, but fail to grasp the idea. Fair enough.
Imagine some code like this: #include <iostream>
int main() {
std::cout << "Hello, Bob!" << std::endl;
std::cout << "Hello, Julie!" << std::endl;
std::cout << "Hello, Joseph!" << std::endl;
}OUTPUT Hello, Bob! Hello, Julie! Hello, Joseph! Now, looking at this code, it seems very repetetive. An ideal solution would be to automate the task of greeting somebody. How can this be accomplished? Parts of the output are the same every time, regardless of the specific person (or thing) that is beeing greeted. The desired action can be boiled down to this: "Hello, <name>!". Through the use of a function, we can automate this task. This is how it would be written (there are a few simplifications here that ignore some best practises like using references, and not using the std namespace). #include <iostream>
using namespace std;
void greet(string name);
int main() {
greet("Bob");
greet("Julie");
greet("Joseph");
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}This program will print the exact same thing as the code above. Since you understand declarations, I'll start right with the actual function. greet(string name) does just that. It will take a standard C++ string, called name, and substitute that name into a message printed to the screen. The function is declared void, which means that nothing is returned from the function. Lets look at a function that returns something. #include <iostream>
using namespace std;
int square(int number);
int main() {
//we are giving square() the value of 2 and the value of 4 is given back.
int squaredNumber = square(2);
//'squaredNumber' has a value of 4 stored in it
cout << "Value of \"square(2)\" is " << squareNumber << endl;
//alternatively, you don't have to store the return value
//of a function.
cout << "Value of \"square(6)\" is " << square(6) << endl;
}
int square(int number) {
return number * number;
}A function that returns a value could be thought of like this (I didn't come up with this analogy): Give a function a bunch of raw materials, and it will refine them into a finished product, and hand it back to you. I'm sure that some other people (hint, hint ) will add more to this explanation if they see fit, but keep reading and experimenting for now.
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS! |
|
|
|
|
#3 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Do you know what a mathematical function is? As in f(x)? The function, sqrt (x), will take x and give you its square root. It's pretty much the same thing. The inside of the function is the square root calculation. It accepts a value for x and returns the answer. The function, max (x,y), is another example. Plug in two numbers and get the largest one back. That's the interface. The work is done inside by someone who knows how to determine the maximum value, or a square root, or whatever. What the hell good is it? Well, do you want to write the code for extracting a square root every time you need one, or would you like to write it once and interface to it? Here's the key: don't let the strange crap drano your mind and buffalo you. It's a simple concept and you probably already have it, by now. Good job, Jesse.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
#4 |
|
Newbie
Join Date: Jun 2006
Location: Canada
Posts: 8
Rep Power: 0
![]() |
on the topic of functions...
i'm in the learning stages as well, and i've starting applying the use of the if-then-else clause. i'm making a simple math program in which a whole bunch of different math formulas are integrated within, and the user simply has to make selections within the command window to choose the branches to lead to whatever math task he/she wants to execute so for example, it would start off asking if you want to do arithmetic or geometry arbitrarily i'll pick arithmetic then the user picks from the submenu whether he/she wants to do addition, subtraction, multiplication, or division then once that selection is made, the actual data input and calculations can begin. my problem isn't that my program doesn't work. my problem is that it's very unpleasant to the eye and probably very inefficient, since i'm not calling functions, but rather taking ALL the paths using the if-then-else clause. it gets confusing when you get enough content in there, as i'm sure you all know. here's a snippet char mainSelection;
cout << "Welcome to Aron's math program" << endl << endl; //starting menu
cout << "1: ARITHMETIC" << endl;
cout << "2: GEOMETRY" << endl << endl;
cout << "Please make a selection: ";
cin >> mainSelection;
cout << endl;
while (mainSelection <= '0' || mainSelection >= '3')
{cout << "Invalid input";
cin >> mainSelection;
}
if (mainSelection == '1') //ARITHMETIC SELECTED
{
char subSelection;
cout << "You have selected ARITHMETIC" << endl << endl;
cout << "1: ADDITION" << endl;
cout << "2: SUBTRACTION" << endl;
cout << "3: MULTIPLICATION" << endl;
cout << "4: DIVISION" << endl << endl;
cout << "Please make a selection: ";
cin >> subSelection;
cout << endl;
while (subSelection <= '0' || subSelection >= '5')
{
cout << "Invalid input";
cin >> subSelection;
}
if (subSelection == '1') //arithmetic (addition)
{
float first;
float second;
float result;
cout << "You have selected ADDITION" << endl << endl;
cout << "Please enter your first number: ";
cin >> first;
cout << endl;
cout << "Please enter your second number: ";
cin >> second;
cout << endl;
result = first + second;
cout << first << " + " << second << " = " << result << endl << endl;
} |
|
|
|
|
#5 |
|
Battle Programmer
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 770
Rep Power: 3
![]() |
You could, for example, separate your menus and then operations each into their own functions. Then, when you display the main menu, the user makes a choice. If they were to choose arithmetic, you could have a function displaying the arithmetic menu and then handling the user's choice. For each option in that menu, you could have a function taking the user input and applying the selected operation. For your menu's, I would also suggest looking at switch statements, as if-elseif-else gets really long, really fast.
|
|
|
|
|
#6 |
|
Hobbyist Programmer
|
using functions also makes your code look nice by keeping things modular. evey thing you do in programming should be broken into functions, calls to functions from main and the minimal amount of other stuff you may need in main like UI or fromating.
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
void fillMap(int map[5][5]);
void printMap(int map[5][5]);
void makeMines(int map[5][5]);
void numMines(int map[5][5]);
int main()
{
int map[5][5];
fillMap(map);
makeMines(map);
printMap(map);
cout << endl;
numMines(map);
printMap(map);
return 0;
}
void fillMap(int map[5][5])
{
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
map[x][y] = 0;
}
}
}
void makeMines(int map[5][5])
{
srand( (unsigned)time( NULL) );
int rndLoop;
int rndLoc;
for (int y = 0; y < 5; y++)
{
rndLoop = rand()%3;
while (rndLoop > 0)
{
rndLoc = rand()%4;
map[rndLoc][y] = 9;
rndLoop--;
}
}
}
void numMines(int map[5][5])
{
int listX[8] = {1,1,0,-1,-1,-1,0,1};
int listY[8] = {0,-1,-1,-1,0,1,1,1};
int count = 0;
for (int startY = 0; startY < 5; startY++)
{
for (int startX = 0; startX < 5; startX++)
{
for (int i = 0; i < 8; i++)
{
if (map[startX][startY] != 9)
{
if ( (startX + listX[i] >= 0) && (startX + listX[i] <= 5) )
{
if ( (startY + listY[i] >= 0) && (startY + listY[i] <= 5) )
{
if (map[startX + listX[i]][startY + listY[i]] == 9)
count++;
}
}
}
}
if (count > 0)
{
map[startX][startY] = count;
count = 0;
}
}
}
}
void printMap(int map[5][5])
{
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
cout << map[x][y];
}
cout << endl;
}
}notice how main is mostly made of function calls and the other stuff is just formating and varriable declaration. by keeping things modular your main code doesnt get all jumbled and find problems is easier because you can trace it down to specific functions. when i started programming in BASIC i didnt see the point of functions untill i started a txt based rpg and realized how much repeted stuff i was doing which should be in functions. it made things so much easier.
__________________
i dont know much about programming but i try to help |
|
|
|
|
#7 |
|
Expert Programmer
Join Date: Sep 2004
Location: Ontario, Canada
Posts: 579
Rep Power: 5
![]() |
This is a simple example of a function for you
int add(int x, int y); //function will take 2 numbers and add them
int main()
{
int result;
//send 5 and 7 to the add function
//the add function RETURNS the sum
result=add(5,7);
}
//the add function returns an integer
//the values (5 and 7) get copied over to variables x and y
int add(int x, int y)
{
//z will hold the sum
int z;
z=x+y;
//send the sum back to wherever it was called from
return z;
}
__________________
Johnny was a chemist's son but Johnny is no more, for what Johnny thought was H2O was H2SO4 |
|
|
|
|
#8 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
int add (int x, int y)
{
return x+y;
}
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
#9 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5
![]() |
If you hate functions, or your job for that part, you can make some useless stupid functions like:
#include <iostream>
#include <cstdarg>
#include <csetjmp>
int badfunction(int, ...);
int main()
{
int a[3] = {3, 5, 7};
int *b = (int*)(&a+1);
int num = badfunction(3, 5, 7);
std::cout << "number is " << num << std::endl;
num=*a+*(b-1);
std::cout << "number is " << num << std::endl;
return 0;
}
int badfunction(int n, ...)
{
int a = 0, b;
b = a, b;
volatile int k = (n, b);
static jmp_buf buf;
va_list p;
if(setjmp(buf))
return k;
va_start(p, n);
for(int j = 0; j < n; ++j)
{
int i = va_arg(p , int);
for(; i; i &= i - 1)
++k;
}
k = (k != n) ? 8 : 2;
longjmp(buf, 1);
}
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for." -- Socrates |
|
|
|
|
#10 | |
|
Professional Programmer
|
Quote:
I think Jessehk's example is one of the best smaller-sized examples about functions that I have seen. It was easy to read and understand, and if the OP didn't get something out of it, I'll eat my hat. ![]()
__________________
The world's first athletic computer geek! The home of PrProgramsStudios How not to post a question: <-- Please don't reply |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|