Write a program to Add All the Elements of an Array in C
Write a program to Add All the Elements of an Array in C++
Write a program to Add All the Elements of an Array in Python
Write a program to Add All the Elements of an Array in PHP
Write a program to Add All the Elements of an Array in Java
Write a program to Add All the Elements of an Array in Java Script
Write a program to Add All the Elements of an Array in C#
Explanation:
Steps:
Initialize Sum Variable:
Start with a variable sum = 0
Traverse the Array:
Use a loop to iterate through each element of the array.
Add the current element to the sum
Output the Sum:
After the loop ends, sum will contain the total of all the elements.
Program to Add All the Elements of an Array
C
C++
Python
PHP
JAVA
Java Script
C#
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
printf("Sum of all elements in the array: %d\n", sum);
return 0;
}
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950"><div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-cpp">#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
cout << "Sum of all elements in the array: " << sum << endl;
return 0;
}
arr = [10, 20, 30, 40, 50] # Example array
print("Sum of all elements in the array:", sum(arr))
<?php
$arr = array(10, 20, 30, 40, 50); // Example array
echo "Sum of all elements in the array: " . array_sum($arr) . "\n";
?>
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50}; // Example array
int sum = 0;
for (int element : arr) {
sum += element;
}
System.out.println("Sum of all elements in the array: " + sum);
}
}
const arr = [10, 20, 30, 40, 50]; // Example array
const sum = arr.reduce((acc, val) => acc + val, 0);
console.log("Sum of all elements in the array:", sum);
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50}; // Example array
int sum = 0;
foreach (int element in arr) {
sum += element;
}
Console.WriteLine("Sum of all elements in the array: " + sum);
}
}