26 January 2015

Functions in C++ 2

This function takes in a number of any size and a single digit. The function's job is to find how many times that digit shows itself in the number. 

Line 2 : int number_times_appear(int number, int digit) tells you that there is a function called number_times_appear that returns an int and takes in an int that the function will know as number and an int the function will know as digit

Line 4 : int integer = number declares an int variable named integer that is initialized as having the value number, which is the first parameter that the function takes in. 

Line 5 : int count = 0 initializes a variable count to 0. 

Line 6 : Does the same thing as line 5 except this variable is named times.

Line 7 : while (number) starts a while loop, and the loop will iterate as long as whatever is in the parenthesis is true. Once this statement is false and the loop stops iterating, count will be the number of digits in number.

Line 8 : Says, now number is equal to itself divided by ten. When a number is divided by another number, the output is how many times the denominator can go into the numerator. Note that these are both int values, so if the number is something like 123847 and you divide it by 10, the output will be 12384. No decimals or remainders. 

Line 9 : count++ increments count by 1.

Line 10 : The closing bracket for the while loop.

Line 12 : for (int i = 0; i < count; i++) means that the for loop will iterate as many times as there are integers from 0 to one less than count

Line 13 : int num = integer % 10 initializes a variable num to be equal to integer % 10. The % or modulus  returns the remainder from if you divide the first number by the second. So 12387 % 10 would equal 7.

Line 14 : if (num == digit) checks to see if the two variables are equal to each other. If they are, the next two lines will iterate. If not, line 19 will iterate.

Line 15 : Increments the variable by one.

Line 16 : Does the same thing line 8 does with this variable. 

Line 17 : The closing bracket for the if statement.

Line 18 : Starts to else statement.

Line 19 : Same thing as line 16.

Lines 20, 21 : Are closing brackets for the else statement, and then the for loop.

Line 23 : return times is the int the function returns. This tells you how many times the digit was in the number. 

Line 25 : Closing bracket for the function.

Farewell pic : 

A kitty from the zoo !!

                                                                                                  ~ Cici

No comments:

Post a Comment