Data · 10
Lists and arrays
Many values in a row: count, first and last, sum, transform all.
A list (array) holds several values in order.
The example below reads some numbers, prints the count, the first and last, and the sum, then doubles every value.
n = int(input())nums = list(map(int, input().split()))print(len(nums))print(nums[0], nums[-1])print(sum(nums))doubled = [x * 2 for x in nums]print(*doubled)const [n, ...nums] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.length);console.log(nums[0], nums[nums.length - 1]);console.log(nums.reduce((a, b) => a + b, 0));const doubled = nums.map((x) => x * 2);console.log(doubled.join(" "));import { readFileSync } from "node:fs";const [n, ...nums]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.length);console.log(nums[0], nums[nums.length - 1]);console.log(nums.reduce((a, b) => a + b, 0));const doubled: number[] = nums.map((x) => x * 2);console.log(doubled.join(" "));import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = sc.nextInt(); System.out.println(nums.length); System.out.println(nums[0] + " " + nums[n - 1]); int sum = 0; for (int x : nums) sum += x; System.out.println(sum); StringBuilder doubled = new StringBuilder(); for (int i = 0; i < n; i++) doubled.append(i > 0 ? " " : "").append(nums[i] * 2); System.out.println(doubled); }}using System;using System.Linq; class Program{ static void Main() { int n = int.Parse(Console.ReadLine()); int[] nums = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); Console.WriteLine(nums.Length); Console.WriteLine($"{nums[0]} {nums[^1]}"); Console.WriteLine(nums.Sum()); int[] doubled = nums.Select(x => x * 2).ToArray(); Console.WriteLine(string.Join(" ", doubled)); }}#include <iostream>#include <numeric>#include <vector> int main() { int n; std::cin >> n; std::vector<int> nums(n); for (int& x : nums) std::cin >> x; std::cout << nums.size() << '\n'; std::cout << nums.front() << ' ' << nums.back() << '\n'; std::cout << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; for (int i = 0; i < n; i++) std::cout << (i > 0 ? " " : "") << nums[i] * 2; std::cout << '\n';}#include <stdio.h> int main(void) { int n, nums[1000], sum = 0; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &nums[i]); printf("%d\n", n); printf("%d %d\n", nums[0], nums[n - 1]); for (int i = 0; i < n; i++) sum += nums[i]; printf("%d\n", sum); for (int i = 0; i < n; i++) printf(i > 0 ? " %d" : "%d", nums[i] * 2); printf("\n"); return 0;}n = Console.ReadLine().ToNumber();nums = Console.ReadNumbers();Console.WriteLine(nums.Count);Console.WriteLine(nums[0] + " " + nums[nums.Count - 1]);total = 0;doubled = [];foreach (x in nums){ total += x; doubled.Add(x * 2);}Console.WriteLine(total);Console.WriteLine(doubled);5 3 1 4 1 5
5 3 5 14 6 2 8 2 10
Key points
- Indexes start at 0, so the last value is at
count - 1. - There are two kinds: a fixed-size array and a list you can keep adding to.
Names and methods differ by language. - Sums and maximums come from one pass from start to end.
Some languages write a transformation like "double everything" in one line. b = ais not a copy.
It puts a second name on the same list, so adding tobchangesatoo (only a C++vectoris copied on assignment).- Reading past the end stops most languages with an error.
The ones that carry on with a wrong value are the dangerous ones.
How each language writes it
| Python | list — append, len(nums), last is nums[-1].Has sum and max; doubling is [x * 2 for x in nums].Out of range: IndexError |
|---|---|
| JavaScript | Arrays — push, length, last is nums.at(-1).Sum with reduce, maximum with Math.max(...nums), transform with map.Out of range quietly gives undefined |
| TypeScript | Same as JavaScript. Write the element type, as in number[] |
| Java | Fixed array int[] a = new int[n] (a.length), growable ArrayList<Integer> (add, size(), get(i)).Sum with Arrays.stream(a).sum() or a loop.Out of range: ArrayIndexOutOfBoundsException |
| C# | Fixed int[] (Length), growable List<int> (Add, Count).Last is nums[^1].LINQ Sum(), Max(), Average(), Select.Out of range: IndexOutOfRangeException |
| C++ | std::vector<int> — push_back, size(), last is back().Sum with std::accumulate, maximum with std::max_element.[] does not check the range; at(i) throws |
| C | Fix the size in advance, like int a[1000], and keep the count yourself.Sums, maximums and transforms are all loops. Reading out of range says nothing |
| Craykon | [ ] — Add, Count (up to 10,000 items), last is nums[nums.Count - 1].Sums and maximums are loops. Out of range stops with an error saying the list only has items 0–4 |
Common mistakes
Starting the maximum at 0
nums = [-3, -1]
best = 0
for x in nums:
if x > best: best = x
print(best)→ 0 — every value is negative, so it never changes (the answer is -1)
Start from the first value, nums[0].
Reading out of range does not stopJavaScript · TypeScript · C · C++
const nums = [3, 1, 4];
console.log(nums[3]);
console.log(nums[-1]);→ undefined twice, with no error. C and C++ [] read whatever is in nearby memory
Check that the index is between 0 and count - 1 before reading.
The average got cut to an integerJava · C# · C · C++
int sum = 14, n = 5;
double avg = sum / n;→ 2 — 14 / 5 is integer division first (not 2.8)
Convert before dividing: (double)sum / n → 2.8.
How languages differ
Printing a whole list looks different everywhere: Python
To print with spaces, use Python
Printing a whole list looks different everywhere: Python
[3, 1, 4], JavaScript [ 3, 1, 4 ], a Java array a tag like [I@1b6d3586, a C# array System.Int32[].To print with spaces, use Python
print(*nums), JavaScript nums.join(" "), C# string.Join(" ", nums) or a loop in Java; Craykon Console.WriteLine(nums) prints 3 1 4 directly.