Fundamentals of Programming: Constant Definitions

PAPER 1 - ⇑ Fundamentals of programming ⇑

← Boolean operations Constants Exception handling →


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)
   Code Output

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:

   Code Output

Insert radius: 5
area = 78.5398163
circumference = 31.4159265

Answer:

const pi as single = 3.14
dim r as single
console.write("Insert radius: ")
r = console.readline()
console.writeline("area = " & pi * r * r)
console.writeline("circumference= " & 2 * pi * r)
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

   Code Output

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:

const VAT as single = 0.175
dim price1, price2 as single
console.write("Insert price of item 1: ")
price1 = console.readline()
console.write("Insert price of item 2: ")
price2 = console.readline()
console.writeline("item 1 = " & price1 & " + " & price1 * VAT & " VAT = £" & price1 * (VAT + 1))
console.writeline("item 2 = " & price2 & " + " & price2 * VAT & " VAT = £" & price2 * (VAT + 1))
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.