Variables
A variable is a name that we use to represent a value that we want the computer to store in its memory for us. When solving problems, we often need to hold some valuable pieces of information we will use in our solution. From the “Input-Process-Output” model above, an example of variables we would be placing in storage is the input from the user. The pieces of information could be people’s names, important numbers or a total in a purchase. We use a name that means something to us (and hopefully to the people that come after us and read our source code, commonly referred to as just code) so that we know right away when we read our code what it is holding. In math class you might be familiar with equations that involve variables like “x or y”. We would not name a variable x, if it is holding the number of students in class, we might call it numberOfStudents or number_of_students (depending on the style guide for a particular language). This has much more meaning to us and other people that also look at our code. Some people are still tempted to use a variable name like “x”, becasue they say it will save space. But once our code is converted to machine language, it does not matter what you called your variable it will be converted to something that takes the same space. So be a “nice” programmer and always use meaningful variable names
Depending on the type of programming language you are using, you might need to declare your variable (warn the computer we will be using a variable before we use it) before you use it in a program. Some programming languages do not enforce this rule, others do. Since you are new to programming, it is really good programming style to always declare a variable before using it, if that is possible. The process of declaring a variable is called a declaration statement.
In most programming languages you will have an identifier, which is the name you are giving your variable (ex. numberOfStudents or number_of_students) and the data type. The identifier will be the way that you refer to this piece of information later in your program. The data type determines what kind of data can be stored in the variable, like a name, a number or a date. In the computer world you will come across data types like integer, character, string & boolean. It is always important that you ensure you select the right kind of data type for the particular data that it is going to hold. You would not use an integer to hold your name and vice versa, you would not use a string to hold your age. The following is a table of some common built in types from several different languages that you might use:
Variable Type |
Type Range |
Boolean |
True or False (1 or 0) |
Unsigned Byte |
0 to 255 |
Signed Byte |
-128 to 127 |
Character |
A single character (like A or % or @) |
String |
Variable length number of characters |
Variable declaration usually should be grouped at the beginning of a section of code (sub, procedure, function, method…), after the initial comments. A blank line follows the declaration and separates the declaration from the rest of your code. This makes it easy to see where the declaration starts and ends. Ensuring that your code is easy to read and understand is as important in computer science as it is in English. It is important to remember that your code has two audiences, the computer that needs to compile or interpret it so that the computer can run your program and even more important, you and everyone else that looks at your source code that are trying to figure out how your program works. Here are some examples of declaring a variable:
1// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows declaring variables
6
7#include <stdio.h>
8#include <stdbool.h>
9
10int main() {
11 // variable definition
12 bool isCurrent = true; // bool
13 int age = 42; // int
14 float area = 42.42; // float
15 char someWords[13] = "Hello, World!"; // string
16
17 printf("%d\n", isCurrent);
18 printf("%d\n", age);
19 printf("%.2f\n", area);
20 printf("%s\n", someWords);
21
22 printf("\nDone.\n");
23 return 0;
24}
1// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows declaring variables
6
7#include <iostream>
8
9int main() {
10 // variable definition
11 bool isCurrent = true; // bool
12 int age = 42; // int
13 float area = 42.42; // float
14 std::string someWords = "Hello, World!"; // string
15
16 std::cout << isCurrent << std::endl;
17 std::cout << age << std::endl;
18 std::cout << area << std::endl;
19 std::cout << someWords << std::endl;
20
21 std::cout << "\nDone." << std::endl;
22}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program shows declaring variables
4*/
5
6using System;
7
8/*
9 * The Program class
10 * Contains all methods for performing basic variable usage
11*/
12class Program {
13 public static void Main (string[] args) {
14 // variable definition
15 bool isCurrent = true; // bool
16 int age = 42; // int
17 float area = 42.42F; // float
18 string someWords = "Hello, World!"; // string
19
20 Console.WriteLine(isCurrent);
21 Console.WriteLine(age);
22 Console.WriteLine(area);
23 Console.WriteLine(someWords);
24
25 Console.WriteLine("\nDone.");
26 }
27}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program shows declaring variables
5 */
6
7package main
8
9import (
10 "fmt"
11)
12
13func main() {
14 // variable definition
15 isCurrent := true // bool
16 age := 42 // int
17 area := 42.42 // float32
18 someWords := "Hello, World!" // string
19
20 fmt.Println(isCurrent)
21 fmt.Println(age)
22 fmt.Println(area)
23 fmt.Println(someWords)
24
25 fmt.Println("\nDone.")
26}
1/*
2 * This program shows declaring variables
3 * .... this was linted by GitHub Actions
4 *
5 * @author Mr Coxall
6 * @version 1.0
7 * @since 2020-09-01
8 */
9
10final class Main {
11 private Main() {
12 // Prevent instantiation
13 // Optional: throw an exception e.g. AssertionError
14 // if this ever *is* called
15 throw new IllegalStateException("Cannot be instantiated");
16 }
17
18 /** Some floating point number. */
19 public static final float SOME_FLOAT = 42.42F;
20
21 /**
22 * Main entry point into program.
23 *
24 * @param args nothing passed in
25 */
26 public static void main(final String[] args) {
27 // variable definition
28 boolean isCurrent = true; // bool
29 int age = 42; // int
30 float area = SOME_FLOAT; // float
31 String someWords = "Hello, World!"; // string
32
33 System.out.println(isCurrent);
34 System.out.println(age);
35 System.out.println(area);
36 System.out.println(someWords);
37
38 System.out.println("\nDone.");
39 }
40}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program shows declaring variables
5 */
6
7// variable definition
8var isCurrent = true // bool
9var age = 42 // int
10var area = 42.42 // float
11var someWords = "Hello, World!" // string
12
13console.log(isCurrent)
14console.log(age)
15console.log(area)
16console.log(someWords)
17
18console.log("\nDone.")
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module shows declaring variables
6"""
7
8
9def main() -> None:
10 """The main() function shows declaring variables, returns None."""
11 is_current = True # bool
12 age = 42 # int
13 area = 42.42 # float
14 some_words = "Hello, World!" # string
15
16 print(is_current)
17 print(age)
18 print(area)
19 print(some_words)
20
21 print("\nDone.")
22
23
24if __name__ == "__main__":
25 main()
Example Output
