Just think of functions as mini-programs. Here's an example of one I had to use for an assignment:
Code:
//This is the function prototype:
void compute_coin(int coin_value, int& num_coins, int& amt);
//This function will be used to calculate the amount of coins for
//each coin (quarter, dime, nickel and penny). It will also reduce
//the amount left to be calculated.
//This is the function 'call' in the 'main' program:
compute_coin(value_quarter, num_quarters, amt_left);
compute_coin(value_dime, num_dimes, amt_left);
compute_coin(value_nickel, num_nickels, amt_left);
compute_coin(value_penny, num_pennies, amt_left);
//This is how the function works (located after the end of the 'main' program:
void compute_coin(int coin_value, int& num_coins, int& amt)
{
int total_coins_value;
num_coins = amt / coin_value;
total_coins_value = num_coins * coin_value;
amt = amt - total_coins_value;
return;
Instead of writing out the calculations four times, I just had to write it once, then use it four times. They can be really helpful, if you have logic errors, it can be easier to narrow down where the problem is located.