Day 3: Functions

Source: Internet
Author: User

Why define your own functions?
Readability
Maintainability
Code reuse
Cpp Code
# Include <iostream>
Using namespace std;
Int raiseToPower (int base, int exponent ){
Int result = 1;
For (int I = 0; I <exponent; I = I + 1 ){
Result = result * base;
}
Return result;
}
Int main (){
Int threeExpFour = raiseToPower (3, 4 );
Cout <"3 ^ 4 is" <threeExpFour <endl;
Return 0;
}
 
 
Function delaration shocould be set before function invocation.
 
Returning a value
 
Up to one value may be returned
Must be the same type as the return type
No need to be at the end
Returns the value as soon as a return statement is executed
Fucntion overloading

Cpp Code
Void printOnNewLine (int x)
{
Cout <"1 Integer:" <x <endl;
}
Void printOnNewLine (int x, int y)
{
Cout <"2 Integers:" <x <"and" <y <endl;
}
 
Function prototypes are generally put into separate header files.

Recursion
Functions can call themselves
Base case
Recursive step
Pass by value (a) vs pass by reference (&)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.