Arrays — Easy
Quiz

Predict the output

Trace these small array snippets by hand and predict what they print.

5 questions
  1. Q01predict the output
    What does this C++ snippet print?
    C++
    #include <iostream>
    #include <vector>
    using namespace std;
    int main(){
      vector<int> a = {3, 1, 4, 1, 5};
      int m = a[0];
      for (int x : a) if (x > m) m = x;
      cout << m << endl;
      return 0;
    }
  2. Q02predict the output
    What does this Python snippet print?
    Python
    a = [1, 1, 2, 2, 3]
    w = 0
    for r in range(1, len(a)):
        if a[r] != a[w]:
            w += 1
            a[w] = a[r]
    print(w + 1)
  3. Q03predict the output
    What does this JavaScript snippet print?
    JavaScript
    const a = [0, 1, 0, 3, 12];
    let w = 0;
    for (let r = 0; r < a.length; r++) {
      if (a[r] !== 0) {
        [a[w], a[r]] = [a[r], a[w]];
        w++;
      }
    }
    console.log(a.join(' '));
  4. Q04predict the output
    What does this C++ snippet print?
    C++
    #include <iostream>
    #include <vector>
    using namespace std;
    int main(){
      vector<int> a = {1, 2, 3, 4, 5};
      int first = a[0];
      for (size_t i = 0; i + 1 < a.size(); i++) a[i] = a[i+1];
      a[a.size()-1] = first;
      for (int x : a) cout << x << ' ';
      cout << endl;
      return 0;
    }
  5. Q05predict the output
    What does this Python snippet print?
    Python
    a = [5, 5, 4, 4, 3]
    largest = float('-inf')
    second  = float('-inf')
    for x in a:
        if x > largest:
            second = largest
            largest = x
        elif x < largest and x > second:
            second = x
    print(second)