This week we learned about the creations of functions and loops. A function is a piece of code that performs a certain task. The function can be called several times throughout the program without having to rewrite the code each time. This makes coding faster and easier. Functions can be defined to take in values or use predefined values. A function has a certain return type that must be returned at the end of the function. Functions can be defined for several different uses such as computing an average or printing out a message. The use of functions will be very important in our final project. Loops are used to repeat the same few lines of code several times in a row. There are two main types of loops, the while loop and the for loop. The while loop is less rigid than the for loop. In a while loop, a statement is made that is either true or false. The code inside the loop keeps being repeated until the statement is false. This type of loop allows the programmer to change how many times the loop runs based on input from the user. In a for loop the number of times the code will run is more defined. The programmer must choose a variable, a statement, and a way to change the variable. The variable is changed in the same way every time the code runs. This allows for less change in the way the loop will run. The picture shows a for loop that is used to print out the phrase four times in a row.
No comments:
Post a Comment