Bird
0
0
DSA Cprogramming~30 mins

Prefix Sum Array in DSA C - Build from Scratch

Choose your learning style9 modes available
Prefix Sum Array
📖 Scenario: Imagine you have a list of daily sales numbers for a small shop. You want to quickly find the total sales from the start up to any given day.
🎯 Goal: You will build a prefix sum array that stores the running total of sales up to each day. This helps answer total sales queries efficiently.
📋 What You'll Learn
Create an integer array called sales with exactly these values: 5, 3, 8, 6, 2
Create an integer array called prefix_sum with the same length as sales
Create an integer variable called n and set it to the length of sales
Use a for loop with variable i from 0 to n - 1 to fill prefix_sum
Print the prefix_sum array elements separated by spaces
💡 Why This Matters
🌍 Real World
Prefix sums are used in finance to quickly calculate cumulative totals like sales or expenses over time.
💼 Career
Understanding prefix sums helps in data analysis, algorithm optimization, and solving range query problems efficiently.
Progress0 / 4 steps
1
Create the sales data array
Create an integer array called sales with exactly these values: 5, 3, 8, 6, 2.
DSA C
Hint

Use curly braces to list the values inside the array.

2
Create prefix sum array and length variable
Create an integer array called prefix_sum with length 5 and an integer variable called n set to 5.
DSA C
Hint

Declare prefix_sum as an integer array of size 5 and n as an integer with value 5.

3
Fill the prefix sum array
Use a for loop with variable i from 0 to n - 1 to fill prefix_sum so that each element is the sum of all sales elements up to index i. For i == 0, set prefix_sum[0] to sales[0]. For other i, set prefix_sum[i] to prefix_sum[i - 1] + sales[i].
DSA C
Hint

Use an if inside the loop to handle the first element separately.

4
Print the prefix sum array
Use a for loop with variable i from 0 to n - 1 to print each element of prefix_sum followed by a space. Then print a newline character.
DSA C
Hint

Use printf("%d ", prefix_sum[i]) inside the loop and printf("\n") after the loop.