Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Closed Thread
 
Thread Tools Display Modes
Old Jun 14th, 2006, 9:16 PM   #1
Zephirus
Newbie
 
Zephirus's Avatar
 
Join Date: May 2006
Posts: 12
Rep Power: 0 Zephirus is on a distinguished road
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
Zephirus is offline  
Old Jun 14th, 2006, 10:12 PM   #2
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 655
Rep Power: 4 Jessehk is on a distinguished road
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!
Jessehk is offline  
Old Jun 14th, 2006, 11:01 PM   #3
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
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
DaWei is offline  
Old Jun 14th, 2006, 11:52 PM   #4
aron_h
Newbie
 
Join Date: Jun 2006
Location: Canada
Posts: 8
Rep Power: 0 aron_h is on a distinguished road
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;
	  }
so as you can see, i'm bound by the path i follow. essentially what i want to know is how i can transform this into calls to functions arbitrarily placed within the program, rather than being bound by the order.
aron_h is offline  
Old Jun 15th, 2006, 12:31 AM   #5
Jimbo
Battle Programmer
 
Jimbo's Avatar
 
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 773
Rep Power: 3 Jimbo is on a distinguished road
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.
Jimbo is offline  
Old Jun 15th, 2006, 12:54 AM   #6
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 343
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
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
mrynit is offline  
Old Jun 15th, 2006, 8:24 AM   #7
Benoit
Expert Programmer
 
Benoit's Avatar
 
Join Date: Sep 2004
Location: Ontario, Canada
Posts: 591
Rep Power: 5 Benoit is on a distinguished road
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
Benoit is offline  
Old Jun 15th, 2006, 8:34 AM   #8
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
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
DaWei is offline  
Old Jun 15th, 2006, 10:41 AM   #9
nnxion
Programming Guru
 
nnxion's Avatar
 
Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5 nnxion is on a distinguished road
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
nnxion is offline  
Old Jun 15th, 2006, 11:15 AM   #10
Prm753
Professional Programmer
 
Prm753's Avatar
 
Join Date: Oct 2005
Location: United States
Posts: 447
Rep Power: 4 Prm753 is on a distinguished road
Send a message via AIM to Prm753 Send a message via MSN to Prm753
Quote:
If you hate functions, or your job for that part, you can make some useless stupid functions like:
I love useless, stupid functions that screw up the whole program.

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
Prm753 is offline  
Closed Thread

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 6:45 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC