Condensing Your Code with Variables, and more!
Variables are one of the best tools used in programming. They represent an address in your computer’s memory where a value is located. Think of your computer’s memory as a series of mailboxes where each variable represents a different box, and the value of the variable is the mail inside.
isTall = true, age = 99, name = Rick. isTall, age, and name, would be the variables, or mailbox. true, 99, and Rick, would be the values, or mail.
If only we could change the value of our mail boxes in real life.
hasOneMillionDollars = true;
Be sure to give your variables meaningful names so you can better keep track of your progress in your program. (see hasOneMillionDollars for a reminder). Each language has its own syntax regarding the use of variables, but they all work the same way. And oh boy do they save time when programming.
I recently wrote a program that displays the sum of digits in an integer entered by a user. I used variables to store user input as well as the results from different mathematical operations performed in order to produce the final result. Variables and Compound Assignment Operators helped me condense my code and avoid multiple lines of messy mathematical operations.
CAOs function like Legos for performing arithmetic in a program by using recursion to build on a variable using its pre-existing value. Say you want to double the value assigned to a variable annualSalary. Rather than typing annualSalary = annualSalary * 2, you can type annualSalary *= 2. Both of these examples tell the computer to take the original value of annualSalary, multiply it by two, then reassign the result to annualSalary. However, the compound multiplication operator makes the code cleaner and slightly easier to read.
Sometimes less is more.
It might seem small, but when writing multiple lines of code, these basic concepts can save you a lot of time and many headaches. For another example of variables and compound assignment operators, check out my updated version of Population Estimation
Peaceful in action, manic in thoughts.
Coding Fanatic