Code Logo

Calculate Grocery Total

Published at19 Apr 2026
Calculations & Math Easy 5 views
Like0

Given an array of grocery item prices, calculate the total cost by summing all prices. Return the total as a single number.

For example, prices [3, 5, 2] total to 10. A single item [7] totals 7. An empty list totals 0. Negative prices are not expected.

Summation is the most fundamental aggregation operation. It is used in calculating bills, computing averages, totaling scores, and accumulating measurements. The pattern of accumulating a running total by iterating through a collection is essential for all data processing work.

The solution initializes a total variable to 0 and adds each price to it during iteration. After the loop, return the total. This runs in O(n) time with O(1) space.

Edge cases include an empty array (return 0), a single element (return that element), and very large arrays where the sum might exceed typical integer ranges.

Learn about our pseudocode specification
Guide

Example Input & Output

Example 1
Input
prices = []
Output
0
Explanation

An empty basket has no cost, so the total stays 0.

Example 2
Input
prices = [12, 5, 8, 10]
Output
35
Explanation

Add 12 + 5 + 8 + 10 to get the full total.

Example 3
Input
prices = [7]
Output
7
Explanation

With only one item, the answer is just that item price.

Algorithm Flow

Recommendation Algorithm Flow for Calculate Grocery Total
Recommendation Algorithm Flow for Calculate Grocery Total

Solution Approach

Iterate through the array and accumulate the sum of all prices into a running total.

function groceryTotal(prices)
  total = 0
  for each p in prices
    total = total + p
  return total

Initialize total to 0. Loop through each price and add it to the running total using the addition operator. After all items are processed, return the accumulated total. For an empty array, the loop never executes and total remains 0.

Time complexity is O(n), space complexity is O(1).

Best Answers

Pseudocode - Approach 1
program calculate_grocery_total
dictionary
   prices: array[1..100] of integer
   total, i, n: integer
algorithm
   input(prices)
   total <- 0
   n <- prices.length
   for i <- 0 to n - 1 do
      total <- total + prices[i]
   endfor
   output(total)
endprogram