Fundamentals of Programming: Constant Definitions

From Wikibooks, open books for an open world
Jump to: navigation, search

UNIT 1 - ⇑ Fundamentals of Programming ⇑

← Built-in data types Constant Definitions Selection →


Constants are like variables in their declarations and the ability to look at the value stored inside them, however you can not change the values while the program is running, the value of a constant remains (rather unsurprisingly) constant.

Example: Declaring pi as a constant
Const pi as Single = 3.14
console.writeline(pi)
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

3.14

If you try to change a constant value it will bring up an error. They are very useful for values that do not change or rarely change such as VAT, pi, e, etc. By using a constant you don't run the risk that you might accidentally change the value, you wouldn't want to accidentally change pi to equal 4 as All your calculations would go wrong!

Exercise: Constants

Write a program that works out the area and circumference of a circle, setting pi to a constant. Use the equations: area = Πr2 and circumference = 2Πr For example:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Insert radius: 5
area = 78.5398163
circumference = 31.4159265

Answer :

  1. const pi as single = 3.14
    
  2. dim r as single
    
  3. console.write("Insert radius: ")
    
  4. r = console.readline()
    
  5. console.writeline("area = " & pi * r * r)
    
  6. console.writeline("circumference= " & 2 * pi * r)
    
  7. console.readline()
    

Write a program that works out the cost of two clothing items showing the price, VAT, and price inclusive of VAT. VAT = 17.5%. For example

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

Insert price of item 1: 10.40
Insert price of item 2: 19.99
item 1 = 10.40 + 1.82 VAT = £12.22
item 2 = 19.99 + 3.49825 VAT = £23.48825

Answer :

  1. const VAT as single = 0.175
    
  2. dim price1, price2 as single
    
  3. console.write("Insert price of item 1: ")
    
  4. price1 = console.readline()
    
  5. console.write("Insert price of item 2: ")
    
  6. price2 = console.readline()
    
  7. console.writeline("item 1 = " & price1 & " + " & price1 * VAT & " VAT = £" & price1 * (VAT + 1))
    
  8. console.writeline("item 2 = " & price2 & " + " & price2 * VAT & " VAT = £" & price2 * (VAT + 1))
    
  9. console.readline()
    
Why might you want to use a constant in your code instead of a normal variable?

Answer :

Constants are fixed values, so you can't accidentally assign them new values in other parts of your code.

When is it suitable to use a constant?

Answer :

When you are using a value that doesn't need to change at run time and will be used in more than one location.