DEV Community

Daisy Rono
Daisy Rono

Posted on • Updated on

Data Structures 101: Introduction to Data Structures and Algorithms.

Problem

Given an array of integers, find the sum of its elements.
For example, if the array ar=[1,2,3],1+2+3=6,so return 6.

Function Description

Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

simpleArraySum has the following parameter(s):

  • ar: an array of integers

Input Format

The first line contains an integer, n, denoting the size of the array.
The second line contains n space-separated integers representing the array's elements.

Constraints
0 < n, ar[i] < 1000

Output Format

Print the sum of the array's elements as a single integer.

Sample Input

6
1 2 3 4 10 11
Enter fullscreen mode Exit fullscreen mode

Sample Output

31
Enter fullscreen mode Exit fullscreen mode

Explanation

We print the sum of the array's elements:
1+2+3+4+10+11=31

Solution

Here, three approaches are used to solve this problem.

1. Foreach
This approach does not require the the size of the array hence the most likely loop to be used for this problem.

function simpleArraySum($ar) {
    // Write your code here
    $sum = 0;
    foreach($ar as $value){
        $sum += $value;
    }
        return $sum;
}
Enter fullscreen mode Exit fullscreen mode

2. For Loop
The size of the array and the sum of the array are initialized before using for loop. The indices of the arrays to be summed are incremented by one to move to the next item in the array.

function simpleArraySum($ar) {
    $size = count($ar);
    $sum = 0;

    for($i=0 ; $i < $size; $i++){
      $sum += $ar[$i];
    }

    return $sum;
}
Enter fullscreen mode Exit fullscreen mode

3. While Loop

This is the same as for loop but the operation stops when the condition $i < count($ar) is no longer true.

function simpleArraySum($ar){
    $sum = 0;
    $i = 0;
    while($i < count($ar)){
        $sum += $ar[$i];
        $i++;
    }
    return $sum;

}
Enter fullscreen mode Exit fullscreen mode

The output of all three approaches is

31
Enter fullscreen mode Exit fullscreen mode

Top comments (0)