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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program shows declaring variables

#include <stdio.h>
#include <stdbool.h>

int main() {
    // variable definition
    bool isCurrent = true;  // bool
    int age = 42;  // int
    float area = 42.42;  // float
    char someWords[13] = "Hello, World!";  // string

    printf("%d\n", isCurrent);
    printf("%d\n", age);
    printf("%.2f\n", area);
    printf("%s\n", someWords);

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program shows declaring variables

#include <iostream>

int main() {
    // variable definition
    bool isCurrent = true;  // bool
    int age = 42;  // int
    float area = 42.42;  // float
    std::string someWords = "Hello, World!";  // string

    std::cout << isCurrent << std::endl;
    std::cout << age << std::endl;
    std::cout << area << std::endl;
    std::cout << someWords << std::endl;

    std::cout << "\nDone." << std::endl;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring variables
*/

using System;

/*
 * The Program class
 * Contains all methods for performing basic variable usage
*/
class Program {
    public static void Main (string[] args) {
        // variable definition
        bool isCurrent = true;  // bool
        int age = 42;  // int
        float area = 42.42F;  // float
        string someWords = "Hello, World!";  // string

        Console.WriteLine(isCurrent);
        Console.WriteLine(age);
        Console.WriteLine(area);
        Console.WriteLine(someWords);

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring variables
 */

package main

import (
	"fmt"
)

func main() {
	// variable definition
	isCurrent := true            // bool
	age := 42                    // int
	area := 42.42                // float32
	someWords := "Hello, World!" // string

	fmt.Println(isCurrent)
	fmt.Println(age)
	fmt.Println(area)
	fmt.Println(someWords)

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 * This program shows declaring variables
 * .... this was linted by GitHub Actions
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

final class Main {
  private Main() {
    // Prevent instantiation
    // Optional: throw an exception e.g. AssertionError
    // if this ever *is* called
    throw new IllegalStateException("Cannot be instantiated");
  }

  /** Some floating point number. */
  public static final float SOME_FLOAT = 42.42F;

  /**
   * Main entry point into program.
   *
   * @param args nothing passed in
   */
  public static void main(final String[] args) {
    // variable definition
    boolean isCurrent = true; // bool
    int age = 42; // int
    float area = SOME_FLOAT; // float
    String someWords = "Hello, World!"; // string

    System.out.println(isCurrent);
    System.out.println(age);
    System.out.println(area);
    System.out.println(someWords);

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring variables
 */

// variable definition
var isCurrent = true // bool
var age = 42 // int
var area = 42.42 // float
var someWords = "Hello, World!" // string

console.log(isCurrent)
console.log(age)
console.log(area)
console.log(someWords)

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module shows declaring variables
"""


def main() -> None:
    """The main() function shows declaring variables, returns None."""
    is_current = True  # bool
    age = 42  # int
    area = 42.42  # float
    some_words = "Hello, World!"  # string

    print(is_current)
    print(age)
    print(area)
    print(some_words)

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output