Java 程序查找数组元素的总和

编写一个 Java 程序,使用 For 循环、While 循环和函数(带示例)查找数组元素的总和。

Java 程序使用 For 循环查找数组元素的总和

此程序允许用户输入大小和数组元素。接下来,它将使用 For 循环查找此数组中所有现有元素的总和。

import java.util.Scanner;

public class SumOfAllElements1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int Size, i, Sum = 0;
		sc = new Scanner(System.in);
	 
		System.out.print(" Please Enter Number of elements in an array : ");
		Size = sc.nextInt();	
		
		int [] a = new int[Size];
		
		System.out.print(" Please Enter " + Size + " elements of an Array  : ");
		for (i = 0; i < Size; i++)
		{
			a[i] = sc.nextInt();
		}   

		for(i = 0; i < Size; i++)
		{
			Sum = Sum + a[i]; 
		}		
		System.out.println("\n The Sum of All Elements in this Array = " + Sum);
	}
}
Java Program to find Sum of Elements in an Array 1

首先,我们使用 for 循环迭代每个元素。在 For 循环 中,我们将每个元素(位置的值)添加到 Sum 中。

用户插入的值为 a[5] = {10, 25, 30, 65, 92}} 且 Sum = 0

第一次迭代: for (i = 0; 0 < 5; 0++)
i 的值为 0,并且条件 (i < 5) 为 True。因此,它将开始执行循环内的 Java 语句,直到条件失败。

Sum = Sum + a[0]
Sum = 0 + 10 = 10

第二次迭代: for (i = 1; 1 < 5; 1++)
条件 (1 < 5) 为 True。

Sum = 10 + 25 = 35

第二次迭代:for (i = 2; 2 < 5; 2++)
条件 (2 < 5) 为 True。

Sum = 35 + 30 = 65

请对剩余的迭代执行相同的操作,直到条件 (i < 5) 失败。

Java 程序使用 While 循环查找数组元素的总和

Java 程序与上面相同。但这次,我们使用了 While 循环 来计算 数组 中所有元素的总和。

import java.util.Scanner;

public class Example2 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int Size, i = 0, j = 0, tot = 0;
		sc = new Scanner(System.in);
	 
		System.out.print(" Please Enter Number of elements : ");
		Size = sc.nextInt();	
		
		int [] a = new int[Size];
		
		System.out.print(" Please Enter " + Size + " elements  : ");
		while(i < Size)
		{
			a[i] = sc.nextInt();
			i++;
		}   

		while(j < Size)
		{
			tot = tot + a[j];
			j++;
		}		
		System.out.println("\n The Sum of All Elements in this Array = " + tot);
	}
}
 Please Enter Number of elements : 7
 Please Enter 7 elements  : 10 20 33 55 77 88 99

 The Sum of All Elements in this Array = 382

使用函数查找数组元素的总和

程序 与第一个示例相同。在这里,我们将逻辑分离出来,使用方法查找数组元素的总和。

import java.util.Scanner;

public class Example3 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int Size, i, Sm = 0;
		sc = new Scanner(System.in);
	 
		System.out.print(" Please Enter Number of elements : ");
		Size = sc.nextInt();	
		
		int [] a = new int[Size];
		
		System.out.print(" Please Enter " + Size + " elements  : ");
		for (i = 0; i < Size; i++)
		{
			a[i] = sc.nextInt();
		}   

		Sm = SmOfArr(a, Size);
		System.out.println("\n The Sum of All Elements in this Array = " + Sm);
	}
	public static int SmOfArr(int[] a, int Size)
	{
		int i, Sm = 0;
		
		for(i = 0; i < Size; i++)
		{
			Sm = Sm + a[i]; 
		}	
		return Sm;
	}
}
 Please Enter Number of elements : 10
 Please Enter 10 elements  : 5 10 15 20 25 30 35 40 125 895

 The Sum of All Elements in this Array = 1200