element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ Tutorial - Functions
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: oneleggedredcow
  • Date Created: 2 Feb 2013 4:38 PM Date Created
  • Views 1572 views
  • Likes 0 likes
  • Comments 1 comment
  • code_exchange
  • Code Exchange
  • raspberry_pi
  • rpi
  • c++
  • learnc++
Related
Recommended

C++ Tutorial - Functions

oneleggedredcow
oneleggedredcow
2 Feb 2013

Introduction

In the previous tutorial, we learned how to make our code more robust by using while loops to screen out bad user input.  In this tutorial, we are going to learn how to make our code more modular and reusable by utilizing functions.  Functions are a way of abstracting out common tasks.  A great example of this would be something like computing the factorial of an integer.  It's a common mathematical operation, so you just want to take an integer and compute the factorial of it.  If you had to write the same 5 lines of code (or more) every time you wanted to compute a factorial, it would be a bit tedious.  Functions allow us to write the code once and reuse it in many places.

Code

So here's an example of a factorial function:

 

int Factorial(int n)

{

int ret = 1;

for(int i = n; i > 1; i--)

{

ret = ret * i;

}

 

return ret;

}


We have seen something similar to this in the first tutorial, with the main function.  The first line specifies the output type (int), the function name (Factorial), and the input arguments (one input argument of type int and its name is n).  This first line contains all of the information that the caller of the function cares about: what goes in, what comes out, and the functions name.  The rest of the function does the transformation from the input to the output.  The factorial function in math is defined as:

 

n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1

 

so as an example:

 

5! = 5 * 4 * 3 * 2 * 1 = 120

 

So, we can readily see how the function given above computes the factorial of a number using a for loop.  This is very powerful because now that we've written the function, we no longer need to remember the internal details about how to compute a factorial, we can just call the function that we created and get the right answer.  Also, this will greatly reduce the amount of code that we need to write, in the case that we need to compute multiple factorials.

Take for instance the combination function from probability.  This is used to determine how many combinations of x selections can be made from n total items ignoring order (n choose x), and the formula looks like this:

 

C(n, x) = n! / (x! * (n - x)!)

 

A concrete example is how many two letter combinations can be made from the four letters A, B, C, and D.  The answer is:

 

C(4, 2) = 4! / (2! * (4 - 2)!) = 4! / (2! * 2!) = 24 / (2 * 2) = 24 / 4 = 6

 

Which we can also show by listing out the combinations:

 

AB

AC

AD

BC

BD

CD

 

So, if we wanted to code this using our Factorial function, it would look like:

 

int Combination(int n, int r)

{

return Factorial(n) / (Factorial(r) * Factorial(n-r));

}

 

This is much better than the alternative that doesn't use our function:

 

int Combination2(int n, int r)

{

// Factorial(n)

int fn = 1;

for (int i = n; i > 1; i--)

{

fn = fn * i;

}

 

// Factorial(r)

 

int fr = 1;

for (int i = r; i > 1; i--)

{

fr = fr * i;

}

 

// Factorial(n-r)

 

int fnr = 1;

for (int i = n - r; i > 1; i--)

{

fnr = fnr * i;

}


 

return fn / (fr * fnr);

}

 

Look at how much more code that is!  Imagine if we had made a mistake in computing the factorial, then we would have to look throughout our code and find all of the places that we had copied and pasted the factorial computation and fix them, rather than if we created a function, we would only have to fix it in one place.  This can be a life saver.

 

Something else interesting to note from the previous example is that you can call a function from within a function.  This helps build up complexity in a manageable way.  What might not be obvious or intuitive a first is that you can call the same function from within a function.  This is called recursion, and it looks like this:

 

int Factorial(int n)

{

if(n < 2)

{

return 1;

}

 

return n * Factorial(n - 1);

}

 

Notice that the factorial function calls itself with the last line.  This is essentially doing:

 

n! = n * (n-1)!

 

It keeps doing this until n is less than 2, and then it returns one, because 1! = 1 and 0! = 1.  Recursion is an interesting way to create a loop without using a for or a while loop.  In my experience, recursion isn't very common, but it is still good to know about in case you run across it one day.

Summary

In this tutorial, we learned how to make our code more reusable by creating functions.  We then went on to discuss how you can use functions to help manage complexity by breaking it down into smaller pieces.

 

In the next tutorial, we go over the various data types and the strengths and weaknesses of each data type.

 

If you have any questions or comments about what was covered here, post them to the comments.  I watch them closely and will respond and try to help you out.

Tutorial Index

01 - Hello Raspberry Pi

02 - Reading User Input

03 - If Statement

04 - For Loops

05 - While Loops

06 - Functions

07 - Data Types

08 - Arrays

09 - Structures

10 - Classes

11 - Pointers

12 - Dynamic Arrays

13 - Linked List

14 - Linked List Operations

15 - STL List/Vector

16 - Templates

17 - Inheritance

18 - File I/O

19 - Strings

20 - Constants

21 - Hash Tables

  • Sign in to reply
  • oneleggedredcow
    oneleggedredcow over 12 years ago

    So, it dawned on me after I wrote the article, that a better implementation of the combination fuction would look something like this:

     

    int Combination(int n, int r)

    {

       int ret = 1;

       for(int i = n; i > n - r; i--)

       {

          ret = ret * i;

       }

     

          return ret / Factorial(r);

    }

     

    This is an improvement, because it will handle much larger values of n.  So, say you wanted to compute the number of 5 card hands that could be made with a standard deck of cards.  The answer would be Combination(52, 5).  The problem is that 52! is a very large number.  Much larger than what can be stored in an integer, as we will go over in the next tutorial.  So, when you go to compute this, you won't get what you expect. This new implementation helps by computing 52!/47! much how you would by hand.  Namely that it is 52*51*50*49*48*47!/47!, and the 47! cancels out and leaves us 52*51*50*49*48.  This means that you never have to compute 52! or 47!, which saves us from those very big numbers.

     

    Unfortunately, it doesn't show the use of functions as nicely, so maybe it is better that I didn't think of it after all!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube