Jump to content

Cplusplus: Difference between revisions

970 bytes added ,  26 February 2008
no edit summary
mNo edit summary
No edit summary
Line 377: Line 377:
...like so!
...like so!


==Functions: The Basics==
It's now time to move on to '''functions'''. A function is basically the same thing as a method in Java: it is a sequence of commands which can be called upon at any time, passed parameters and set to return a value.
main() is a function - the default function for a C++ program. But what if you have some code that you don't want to put into main? Use another function.
Let's say we want to add two numbers together and print out the result. The code could look something like this:
#include <iostream>
using namespace std;
int add(int a, int b)
{
    return a + b;
}
int main()
{
    int a = 2;
    int b = 5;
    cout << add(a,b) << endl;
    return(0);
}
This program adds 2 and 5 together to get 7, and displays this answer on-screen.
a and b are passed as ''parameters'' to the add function - they are then immediately added together and the answer is returned. Experiment with this code to do different things.
[[Category:Helpdesk]]
[[Category:Helpdesk]]
244

edits