Code Logo

Calculate Grocery Total

Published at19 Apr 2026
Easy 0 views
Like0

This problem comes from a normal shopping situation. You already have the prices of the items in your basket, and now you want to know how much everything costs in total.

The job here is not to do anything fancy with discounts or tax rules. You only need to add every price in the list and return the final sum.

For example, if the prices are [12, 5, 8, 10], the answer is 35. You just keep adding each value until you reach the end of the basket.

So the task is to go through the list of prices and calculate the total amount someone needs to pay.

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

A simple way to solve this is to keep a running total while you move through the list.

Start by creating a variable like total and set it to 0. That gives you a place to store the answer as it grows.

Then go through each price in the basket one by one. Every time you read a price, add it into total.

The update step looks like this:

total <- total + prices[i]

That line means the current item price gets added onto whatever total you already had.

After the loop finishes, total holds the full grocery cost, so that is the value you print.

The whole idea is just repeated addition, which is why this problem is short and easy to follow.

Best Answers

Solutions Coming Soon

Verified best solutions for this Challenge are still being analyzed and will be available soon.