Lists
Since in many programming languages, when you create an array the size must be set during coding so that the memory can be allocated when it is compiled, there is no way to dynamically change the size of an array during run time. This can be a huge disadvantage. One great example of wanting to have dynamic arrays is the classic video game, Space Invaders. If you imagine that all the lazer you shoot are held in an array, then how big should the array be? You have no idea how fast the user can press the “A” button. You can not tell how many lazers might be on the screen at any given time! If you cannot change the size of the array, what can we do, just making a “huge” array is wasteful and not really practical. Fortunately in many programming languages there is a data structure called a list.
A List is similar to an array in that it is an ordered grouping of data. You still reference the items in the list using a positive integer index. The key difference is that the size of the list can shrink and grow, during run time as needed. As you need to add items, you just use an “Add” (or something similar like append). To remove an item you use “Remove” (or something similar like pop). The list usually has many useful methods for adding, sorting, clearing, finding the length an so on.
Here is an example of creating a list of items:
Code for Creating a List
// No list or Linked List standard in C.
// You can create dynamic arrays by using maloc(), but that is beyond the scope of this book.
// https://www.geeksforgeeks.org/dynamic-array-in-c/
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 | // Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program program uses a list
#include <iostream>
#include <list> // need this for Lists
int main() {
// this function uses a list
std::list<std::string> words;
std::string tempWord = "Go";
std::list<std::string> reversedWords;
// input
std::cout << "Please enter 1 word at a time. Enter 'S' to end." << std::endl;
while (tempWord != "STOP") {
std::cout << "Enter a word: ";
std::cin >> tempWord;
words.push_back(tempWord);
}
words.pop_back(); // remove the "Stop" that was added
std::cout << "" << std::endl;
// reversed words
std::cout << "Here are the words reversed.:" << std::endl;
while (!words.empty()) {
std::cout << words.back() << std::endl;
words.pop_back();
}
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
28
29
30
31
32
33
34
35
36
37 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a list
*/
using System;
using System.Collections.Generic;
/*
* The Program class
*/
class Program {
static void Main() {
// this function uses a list
List<string> words = new List<string>();
string temp_word = "Go";
Console.WriteLine("Please enter 1 word at a time. Enter STOP to end.");
while (temp_word != "STOP") {
Console.Write("Enter a word: ");
temp_word = Console.ReadLine();
words.Add(temp_word);
}
words.RemoveAt(words.Count - 1); // remove the "STOP" that was added
Console.WriteLine();
Console.WriteLine("Here are the words reversed:");
while (words.Count > 0) {
Console.WriteLine(words[words.Count - 1]);
words.RemoveAt(words.Count - 1);
}
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
27
28
29
30
31
32
33
34
35
36 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a list
*/
package main
import (
"container/list"
"fmt"
)
func main() {
// this function uses a list
words := list.New()
tempWord := "Go"
fmt.Println("Please enter 1 word at a time. Enter STOP to end.")
for tempWord != "STOP" {
fmt.Print("Enter a word: ")
fmt.Scan(&tempWord)
words.PushBack(tempWord)
}
words.Remove(words.Back()) // remove the "STOP" that was added
fmt.Println()
fmt.Println("Here are the words reversed:")
for singleWord := words.Back(); singleWord != nil; singleWord = singleWord.Prev() {
fmt.Println(singleWord.Value)
}
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 | /*
* This program uses a list
*
* @author Mr Coxall
* @version 1.0
* @since 2020-09-01
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// this function uses a list
List<String> words = new ArrayList<>();
String tempWord = "Go";
System.out.println("Please enter 1 word at a time. Enter STOP to end.");
Scanner scanner = new Scanner(System.in);
while (!tempWord.equalsIgnoreCase("STOP")) {
System.out.print("Enter a word: ");
tempWord = scanner.nextLine();
words.add(tempWord);
}
words.remove(words.size() - 1); // remove the "STOP" that was added
System.out.println();
System.out.println("Here are the words reversed:");
for (int loopCounter = words.size() - 1; loopCounter >= 0; loopCounter--) {
System.out.println(words.get(loopCounter));
}
System.out.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 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a list
*/
const prompt = require("prompt-sync")()
// input
const words = [];
let tempWord = 'Go';
console.log('Please enter 1 word at a time. Enter STOP to end.');
while (tempWord.toUpperCase() !== 'STOP') {
tempWord = prompt('Enter a word: ');
words.push(tempWord);
}
words.pop(); // remove the "STOP" that was added
console.log();
console.log('Here are the words reversed:');
for (let loopCounter = words.length - 1; loopCounter >= 0; loopCounter--) {
console.log(words[loopCounter]);
}
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
26
27
28
29
30
31
32
33
34 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module program uses a list
"""
def main() -> None:
"""The main() this function uses a list, returns None."""
# input
words = []
temp_word = "Go"
# input
print("Please enter 1 word at a time. Enter STOP to end.")
while temp_word.upper() != "STOP":
temp_word = input("Enter a word: ")
words.append(temp_word)
words.pop() # remove the "Stop" that was added
print("")
print("Here are the words reversed:")
for _ in range(0, len(words)):
print(words.pop())
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output