how to program
HOW TO PROGRAM . IT - learn how to program - online interactive programming tutorial and programming course
0
Variables

07. Variables allow you to add variety and flexibility to your program, and without them most programs are not very useful. A variable is a named placeholder which can store a value, a value that can be changed, referenced and substituted within a program...

Program Code:
Output:


In the above example a variable is first created, var strName, then a value is assigned to the variable, strName = "Fred", then the variable is reference multiple times in the output statements.

The str in the variable name strName is used in order to remind us that the variable is a string. This is merely a particular programming convention or style know as Hungarian notation and opinion differs between programmers, programming languages, and environments as to whether this is a good thing or not, but for this site we will use this notation as that is our preference.

Exercises:

1. Change the name of Fred to Wilma. Notice that you only had to change it in one place even though there are two output statements using the variable.
2. Comment out the 1st line (by inserting a // at the start). The variable declaration line is not absolutely necessary but it can be good practice to do this. In some programming languages it is necessary.
3. On the line where the variable is assigned a value (strName = ), you will notice that it accepts a string literal. Anywhere a string is accepted, we can also put in an expression that equates to a string, as in 2 strings being added together. Try this with "Fred" + " and Wilma "
4. Change the variable name from strName to Name (you will have to do this in 4 places).
5. Change the program to use 2 variables, strNameMan, and strNameWoman and output text using both of those variables.
6. Following on from exercise 5, introduce a third variable strNameCouple which is assigned a value of strNameMan + " and " + strNameWoman, and use this variable in the output statements

To return to previous page click here

 
0
by running the tutorial programs on this site, you are agreeing to our terms and conditions (please check these first).
Mon 10 Dec 2018 web design | login © 2018 Abstract Worlds Ltd