search
HomeJavajavaTutorialJava program to calculate the sum of numbers in a list using while loop

Java program to calculate the sum of numbers in a list using while loop

introduce

A Java program to calculate the sum of numbers in a list using while loop is a simple program that takes a list of integers and calculates their sum using a while loop structure. In this program, an ArrayList of integers is created and some numbers are added to the list. The program then uses a while loop to iterate through each element in the list, adding each element to the variable "sum", which keeps track of the running sum of the numbers. After the loop completes, the final value of "sum" is printed to the console, which is the sum of all the numbers in the list.

This program demonstrates a common technique for working with data collections in programming, which is to use a loop to iterate over each element in the collection and perform some calculation or transformation on each element. The program also highlights the use of ArrayList in Java, a common data structure used to store collections of data.

Example 1

method

  • First, we create an integer ArrayList named "numbers" and add some numbers to it. In this program we add the numbers 1, 2, 3, 4 and 5 to the list.

  • Then we declare two variables - "sum" and "i". "sum" is initialized to 0 because we want to sum the numbers starting from zero. "i" is initialized to 0 because this is the index of the first number in the list that we want to start adding to the sum.

  • We start a while loop that will continue execution as long as "i" is less than the size of the list. The size of the list can be obtained using the "size" method of the ArrayList class.

  • Within the loop, we use the "get" method of the ArrayList class to retrieve the current number in the list and add it to the sum. We then increase "i" by 1 to move to the next number in the list.

  • After the loop completes, we have calculated the sum of all the numbers in the list. We print out the sum using the "println" method.

In general, this method is relatively simple and straightforward. It uses a while loop to iterate over the elements of the list and accumulate their sum into a separate variable. This is a common technique in programming for working with lists and other data collections.

This is a Java program that uses a while loop to calculate the sum of numbers in a list -

import java.util.ArrayList;

public class SumOfListUsingWhileLoop {
   public static void main(String[] args) {
      ArrayList<Integer> numbers = new ArrayList<Integer>();
      numbers.add(1);
      numbers.add(2);
      numbers.add(3);
      numbers.add(4);
      numbers.add(5);

      int sum = 0;
      int i = 0;

      while (i < numbers.size()) {
         sum += numbers.get(i);
         i++;
      }

      System.out.println("The sum of the numbers in the list is: " + sum);
   }
}

illustrate

In this program, we first create an integer ArrayList named "numbers" and add some numbers to it. We then declare two variables: "sum" (initialized to 0), which stores the sum of the numbers in the list, and "i" (initialized to 0), which keeps track of the current value we are adding to the sum. Numeric index.

Next, we start a while loop that continues as long as "i" is less than the size of the list. Inside the loop, we add the current number in the list (retrieved using the "get" method) to the sum and increment "i" to move to the next number in the list.

Finally, once the loop ends, we use the "println" method to print out the sum of the numbers in the list.

Output

The sum of the numbers in the list is: 15

Example 2

method

  • First, we create an ArrayList of Double values ​​called "numbers" and add some numbers to it. In this program we add the numbers 2.5, 3.7, 1.8, 4.2 and 2.9 to the list.

  • Then we declare two variables: "sum" and "i". "sum" is initialized to 0.0 because we want to sum the numbers starting from zero. "i" is initialized to 0 because this is the index of the first number in the list where we want to start adding numbers to the sum.

  • We start a while loop that will continue execution as long as "i" is less than the size of the list. The size of the list can be obtained using the "size" method of the ArrayList class.

  • Within the loop, we use the "get" method of the ArrayList class to retrieve the current number in the list and add it to the sum. We then increase "i" by 1 to move to the next number in the list.

  • After the loop completes, we have calculated the sum of all the numbers in the list. We print out the sum using the "println" method.

Overall, the methods used in this program are very similar to those used in the previous examples. We use a while loop to iterate over the elements of the list and accumulate their sum into a separate variable. However, in this case, we use a Double value instead of an Integer value, which allows us to include decimal places in the number. Additionally, we use a different set of numbers in the list to demonstrate that the program can handle a variety of input values.

This is another example of a Java program that uses a while loop to calculate the sum of numbers in a list -

import java.util.ArrayList;

public class SumOfListUsingWhileLoop2 {
   public static void main(String[] args) {
      ArrayList<Double> numbers = new ArrayList<Double>();
      numbers.add(2.5);
      numbers.add(3.7);
      numbers.add(1.8);
      numbers.add(4.2);
      numbers.add(2.9);

      double sum = 0.0;
      int i = 0;

      while (i < numbers.size()) {
         sum += numbers.get(i);
         i++;
      }

      System.out.println("The sum of the numbers in the list is: " + sum);
   }
}

illustrate

In this program, we create an ArrayList of Double values ​​called "numbers" and add some numbers to it. We then declare two variables: "sum" (initialized to 0.0) to store the sum of the numbers in the list, and "i" (initialized to 0) to keep track of the index sum of the current number we want to add to.

接下来,我们启动一个 while 循环,只要“i”小于列表的大小,该循环就会继续。在循环内,我们将列表中的当前数字(使用“get”方法检索)添加到总和中,并递增“i”以移至列表中的下一个数字。

最后,一旦循环结束,我们使用 "println" 方法打印出列表中数字的总和。请注意,在这个例子中,我们使用的是 Double 值而不是 Integer 值,这允许我们在数字中包含小数位。

输出

The sum of the numbers in the list is: 1.5

结论

  • 在本文中,我们讨论了两个使用while循环计算列表中数字总和的Java程序示例。在这两个示例中,我们使用了类似的方法来迭代列表中的每个元素,在一个单独的变量中累加它们的总和,然后输出结果。

  • 我们还讨论了这些程序的时间和空间复杂度。这两个程序的时间复杂度都是 O(n),其中 n 是列表中元素的数量,因为我们需要迭代列表中的每个元素来计算它们的总和。两个程序的空间复杂度都是 O(1),因为我们只需要使用几个变量来存储输入列表、运行总和以及循环计数器,并且这些变量的大小不依赖于输入。

The above is the detailed content of Java program to calculate the sum of numbers in a list using while loop. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)