150 likes | 251 Views
C++ Language Tutorial. Lesson 6 – Functions & returning values. Functions Returning a value Arguments. Reusing Code. Very often when we write software we need to repeat a task many times • Sometimes we need to repeat something a specific number of times
E N D
C++ Language Tutorial Lesson 6 – Functions & returning values • Functions • Returning a value • Arguments
Reusing Code Very often when we write software we need to repeat a task many times • Sometimes we need to repeat something a specific number of times • Sometimes we need to repeat something until some condition is satisfied • In C++ (and most other programming languages) we have structures called loops to do this
An example // You declare a function like this void PrintHello() { cout << “Hello World” << endl; } // And use it like this PrintHello();
What This Means void means the that this function returns nothing. • PrintHello is the label we have given the function. We can use this name to call it later • () These brackets must be present with every function declaration. They also have a use. We will find out what soon • {} The curly brackets must also always be present. The code inside the function will go between these brackets
Returning a Value • A function can return a value • You must declare the type of the return value in the function declaration e.g. – intmyFunction() // Returns an int – float myFunction() // Returns a float – Etc. • You return a value from function with the return keyword • A function can only return one value
Example int Add5and6() { return 5 + 6; } int Sum = Add5and6(); • This is a bit specific though, there’s a way to make it more general though
Arguments Values can be passed into a function and used inside • These values, called arguments, must be declared in the function declaration • You can pass in as many values as you like and they can be of any type
Example int Sum2Nums(int num1, int num2) { return num1 + num2; } int Sum = Sum2Nums(5, 6); • This is a bit more useful than the previous function
Passing an Array to a Function • You can also pass an array to a function • The syntax is similar to passing other values but you must indicate that it is an array • If you need to check the size of the array, you will have to pass that to the array
Example intanArray = {1,2,3,4,5}; void aFunction(intnums[]) { // Do something with an array } aFunction(anArray );
The end That concludes are last lesson you should now understand how to use functions to return a value. As allways the source code for the demonstration with fully explained comments (more extensive than the video), along with the execution able file is available on the site for download.