26 January 2015

Functions in C++

The below picture is a function in C++. Let's walk through it ..

This function was created to see what percentage of a dna string was cytosine and guanine. This function assumes that every string that's passed into it will only consist of four letters :
A, T, G, C
to represent Adenine, Thymine, Guanine, and Cytosine.



Line 2 : double tells you the data type that the function will return at the end.
ratio is the name of the function.
(string dna) is the parameter that the function takes in. When the function is called, whatever string is called with the function will be known to the function as dna.
The { is used to tell where the function begins and ends. You will see that it is matched with the one at the bottom on line 14. This is C++ syntax.

Line 4 : double is the data type for the variable you're making called length.
The = tells you that the variable length is being assigned to the value of dna.length().
Most lines in C++ end in a semicolon. That too is just syntax.
.length() is a function built in to the String class. It will return how many characters there are in the string that calls it, which in this case is dna.

Line 5 : double count is a variable declaration, and it's assigned the value, 0.

Line 6 : for (int i = 0; i < length; i++) is a for loop. For as many integers there are from 0 to the value, length, everything under the for loop (between the curly brackets) will iterate through. One again, the curly bracket at the end is the beginning of the loop.

Line 7 : This is an if statement. So, if the character located in the string dna at index i is a 'g' or 'c', the next line will iterate. (BTW, those two vertical lines together like that mean 'or'. If there were two ampersands (&&), that means 'and'.)

Line 8 : count++ is the same thing as count = count + 1 or count += 1. All three of these will increment the value count by 1. So, every 'g' or 'c' the loop finds will be counted, because when one is found, count is incremented. 

Line 9, 10 : The next two lines are just closing brackets. The one in line 9 closes the if statement, and the one in line 10 closes the for loop. 

Line 12 : return count / length is the double value that the function returns. Remember that both count and length are doubles. This is just dividing count by length, or returning the ratio of the number of 'c's and 'g's to the total number of characters in the string. 

Line 14 : A closing bracket for the entire function to let the computer know that it's gotten to the end of the function. 


Farewell pic : 

If you can't tell, this genius is parked on the grass .. He drove up onto the curb and decided to park in the grassy area between two real parking spots. 


                                                                                                        ~ Cici

                                                                                                           


No comments:

Post a Comment