Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Sum of all Elements in Array and Lists

If you want to write a program that displays the Fibonacci sequence, it's actually not too complicated. First off, you'll need to understand what the sequence is - essentially, it's a series of numbers where each number after the first two is the sum of the two preceding ones (e.g. 1, 1, 2, 3, 5, 8...). Once you've got that down pat, you can start coding. Typically this involves using loops and variables to generate each successive value in the sequence until your program reaches whatever endpoint you've specified (either a certain number of iterations or a maximum value for the generated numbers). Whether you're working in a language like Python or C++, there are plenty of resources out there with sample code and tutorials to help guide you through the process. All in all, writing a Fibonacci program can be a fun challenge that pays off with some nifty math-based visualizations!

(a.) C Code

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
        sum += arr[i];
    }

    printf("Sum of array elements: %d\n", sum);

    return 0;
}
Output:-
Sum of array elements: 15

(b.) C++ Code

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
        sum += arr[i];
    }

    cout << "Sum of array elements: " << sum << endl;

    return 0;
}
Output:-
Sum of array elements: 15

(c.) Python Code

def main():
    arr = [1, 2, 3, 4, 5]
    total = sum(arr)
    print("Sum of array elements:", total)

if __name__ == "__main__":
    main()
Output:-
Sum of array elements: 15

(d.) Java Code

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int sum = 0;

        for (int i = 0; i < arr.length; ++i) {
            sum += arr[i];
        }

        System.out.println("Sum of array elements: " + sum);
    }
}
Output:-
Sum of array elements: 15