{ }codelper
scopeP0441

A total for each receipt, sales at the end of the day

A shop's checkout printed n receipts today.
Each receipt lists the prices of the items bought.
The first line of input gives n.
Each of the next n lines gives one receipt.
A receipt line holds the number of items k and then k prices, separated by single spaces.
In the order the receipts are given, print the sum of each receipt's k prices, one per line.
On the last line print the day's sales, the sum of the totals of all n receipts.
Write a function that receives the prices of one receipt and returns their sum.
Count the receipt total in a variable made inside that function, and count the day's sales in a variable placed outside the function at the top of the program (a static field in Java and C#).
Grading looks only at the output.

Input
1 ≤ n ≤ 100, 1 ≤ k ≤ 100, 1 ≤ price ≤ 100,000 (all integers)
Output
n + 1 lines.
The first n lines are the receipt totals, and the last line is the day's sales.
Print plain digits without commas
Example 1 · stdin
3
2 1500 3000
1 800
3 1200 1200 500
stdout
4500
800
2900
8200
Example 2 · stdin
1
1 7000
stdout
7000
7000
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

This problem shows what changes from language to language when a variable inside a function has the same name as one outside it.
In seven of the solutions (all but Craykon) both the day's sales outside and the receipt total inside the function are named total.
When you declare a new variable inside the function, as in let total = 0; in JS/TS or int total = 0; in Java, C#, C and C++, you get a local variable that hides the outer total; it is created afresh on every call and disappears when the function ends.
The outer total is a top-level let in JS/TS, a static field in Java and C#, and a global variable in C and C++.
Python has no word for declaring, so merely assigning inside the function, as in total = 0, makes that name a local variable throughout the function.
Craykon is the opposite: assigning inside a function to a name that already exists at the top level changes the outer variable, and apart from parameters there is no way to make a separate local variable with the same name.
So the Craykon solution uses different names, sales outside and sum inside.
Using sum, first created inside the function, outside it is a compile error.
Trap one: if the receipt total lives outside the function, it does not go back to 0 on each call.
The totals of earlier receipts keep piling up, and the output for example 1 becomes 4500, 5300, 8200, 18000.
Trap two: writing total = 0; inside the function without a declaration creates no new variable; it assigns to the outer total.
JS, TS, Java, C#, C and C++ all run this without any error.
Naming the inner sum sales in Craykon does the same.
Every time a receipt total is computed the day's sales are overwritten by it, and then the returned total is added once more, so the last line of example 1 becomes 5800 (2900 + 2900) instead of 8200.
In JS, TS, Java and C#, however, writing it in one line as total += receiptTotal(…) reads the value of total before the function is called, so this mistake does not show in the output.
It is hidden, but the code is still wrong.
Trap three: in Python, if the function tries to add to the outer total with total += s, the function contains a line that assigns to total, so total becomes local, and reading it before it has a value stops the program with UnboundLocalError.
To change an outer variable inside a function you must first write global total.
Returning the total and adding it at the caller, as this solution does, needs no global.

Pythonmain.py · 25 lines
import sys # 하루 매출: 함수 밖(맨 위)에 둔 변수total = 0  def receipt_total(prices):    # 함수 안에서 값을 넣으면 Python은 그 이름을 지역 변수로 만든다.    # 그래서 이 total은 바깥 total과 이름만 같은 다른 변수이고, 부를 때마다 0에서 시작한다    total = 0    for p in prices:        total += p    return total  lines = sys.stdin.read().split("\n")n = int(lines[0])out = []for i in range(1, n + 1):    nums = list(map(int, lines[i].split()))    r = receipt_total(nums[1:])    out.append(r)    total += rout.append(total)print("\n".join(map(str, out)))
JavaScriptmain.js · 21 lines
// 하루 매출: 함수 밖(맨 위)에 둔 변수let total = 0; function receiptTotal(prices) {  // let으로 새로 만들었으니 바깥 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다  let total = 0;  for (const p of prices) total += p;  return total;} const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const out = [];for (let i = 1; i <= n; i++) {  const nums = lines[i].trim().split(/\s+/).map(Number);  const r = receiptTotal(nums.slice(1));  out.push(r);  total += r;}out.push(total);console.log(out.join("\n"));
TypeScriptmain.ts · 23 lines
import { readFileSync } from "node:fs"; // 하루 매출: 함수 밖(맨 위)에 둔 변수let total = 0; function receiptTotal(prices: number[]): number {  // let으로 새로 만들었으니 바깥 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다  let total = 0;  for (const p of prices) total += p;  return total;} const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const out: number[] = [];for (let i = 1; i <= n; i++) {  const nums: number[] = lines[i].trim().split(/\s+/).map(Number);  const r: number = receiptTotal(nums.slice(1));  out.push(r);  total += r;}out.push(total);console.log(out.join("\n"));
JavaMain.java · 29 lines
import java.util.Scanner; public class Main {    // 하루 매출: 메서드 밖에 둔 static 필드    static int total = 0;     static int receiptTotal(int[] prices) {        // 타입을 붙여 새로 선언했으니 필드 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다        int total = 0;        for (int p : prices) total += p;        return total;    }     public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            int k = sc.nextInt();            int[] prices = new int[k];            for (int j = 0; j < k; j++) prices[j] = sc.nextInt();            int r = receiptTotal(prices);            out.append(r).append('\n');            total += r;        }        out.append(total).append('\n');        System.out.print(out);    }}
C#Main.cs · 29 lines
using System;using System.Linq; class Program{    // 하루 매출: 메서드 밖에 둔 static 필드    static int total = 0;     static int ReceiptTotal(int[] prices)    {        // 타입을 붙여 새로 선언했으니 필드 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다        int total = 0;        foreach (int p in prices) total += p;        return total;    }     static void Main()    {        int n = int.Parse(Console.ReadLine());        for (int i = 0; i < n; i++)        {            int[] nums = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();            int r = ReceiptTotal(nums[1..]);            Console.WriteLine(r);            total += r;        }        Console.WriteLine(total);    }}
C++main.cpp · 27 lines
#include <iostream>#include <vector> // 하루 매출: 함수 밖에 둔 전역 변수int total = 0; int receiptTotal(const std::vector<int>& prices) {    // 타입을 붙여 새로 선언했으니 전역 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다    int total = 0;    for (int p : prices) total += p;    return total;} int main() {    int n;    std::cin >> n;    for (int i = 0; i < n; i++) {        int k;        std::cin >> k;        std::vector<int> prices(k);        for (int& p : prices) std::cin >> p;        int r = receiptTotal(prices);        std::cout << r << '\n';        total += r;    }    std::cout << total << '\n';}
Cmain.c · 27 lines
#include <stdio.h> // 하루 매출: 함수 밖에 둔 전역 변수int total = 0; int receipt_total(const int prices[], int k) {    // 타입을 붙여 새로 선언했으니 전역 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다    int total = 0;    for (int j = 0; j < k; j++) total += prices[j];    return total;} int main(void) {    int n;    if (scanf("%d", &n) != 1) return 0;    for (int i = 0; i < n; i++) {        int k, prices[100];        if (scanf("%d", &k) != 1) return 0;        for (int j = 0; j < k; j++)            if (scanf("%d", &prices[j]) != 1) return 0;        int r = receipt_total(prices, k);        printf("%d\n", r);        total += r;    }    printf("%d\n", total);    return 0;}
Craykonmain.cray · 24 lines
// 하루 매출: 맨 위에 둔 변수매출 = 0; // 크레이콘에서는 맨 위에 있는 이름에 함수 안에서 넣으면 그 바깥 변수가 바뀐다.// 그래서 영수증 합은 바깥에 없는 이름(합)으로 함수 안에서 만든다. 부를 때마다 0에서 시작한다영수증합(가격들){    합 = 0;    foreach (p in 가격들)    {        합 = 합 + p;    }    return 합;} n = Console.ReadLine().ToNumber();for (i = 0; i < n; i++){    수들 = Console.ReadNumbers();    r = 영수증합(수들.GetRange(1, 수들.Count - 1));    Console.WriteLine(r);    매출 = 매출 + r;}Console.WriteLine(매출);