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 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
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
1 |
|
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 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
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 值,这允许我们在数字中包含小数位。
输出
1 |
|
结论
在本文中,我们讨论了两个使用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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





General Matrix Multiplication (GEMM) is a vital part of many applications and algorithms, and is also one of the important indicators for evaluating computer hardware performance. In-depth research and optimization of the implementation of GEMM can help us better understand high-performance computing and the relationship between software and hardware systems. In computer science, effective optimization of GEMM can increase computing speed and save resources, which is crucial to improving the overall performance of a computer system. An in-depth understanding of the working principle and optimization method of GEMM will help us better utilize the potential of modern computing hardware and provide more efficient solutions for various complex computing tasks. By optimizing the performance of GEMM

WORD is a powerful word processor. We can use word to edit various texts. In Excel tables, we have mastered the calculation methods of addition, subtraction and multipliers. So if we need to calculate the addition of numerical values in Word tables, How to subtract the multiplier? Can I only use a calculator to calculate it? The answer is of course no, WORD can also do it. Today I will teach you how to use formulas to calculate basic operations such as addition, subtraction, multiplication and division in tables in Word documents. Let's learn together. So, today let me demonstrate in detail how to calculate addition, subtraction, multiplication and division in a WORD document? Step 1: Open a WORD, click [Table] under [Insert] on the toolbar, and insert a table in the drop-down menu.

How to use Python's count() function to calculate the number of an element in a list requires specific code examples. As a powerful and easy-to-learn programming language, Python provides many built-in functions to handle different data structures. One of them is the count() function, which can be used to count the number of elements in a list. In this article, we will explain how to use the count() function in detail and provide specific code examples. The count() function is a built-in function of Python, used to calculate a certain

How to Make a GroceryList on iPhone in iOS17 Creating a GroceryList in the Reminders app is very simple. You just add a list and populate it with your items. The app automatically sorts your items into categories, and you can even work with your partner or flat partner to make a list of what you need to buy from the store. Here are the full steps to do this: Step 1: Turn on iCloud Reminders As strange as it sounds, Apple says you need to enable reminders from iCloud to create a GroceryList on iOS17. Here are the steps for it: Go to the Settings app on your iPhone and tap [your name]. Next, select i

Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive procedure. A recursive function is a function that calls itself within its definition. If str1 is "Iknowthatyouknowthatiknow" and str2 is "know" the number of occurrences is -3. Let us understand through examples. For example, input str1="TPisTPareTPamTP", str2="TP"; output Countofoccurrencesofasubstringrecursi

In C#, there is a Math class library, which contains many mathematical functions. These include the function Math.Pow, which calculates powers, which can help us calculate the power of a specified number. The usage of the Math.Pow function is very simple, you only need to specify the base and exponent. The syntax is as follows: Math.Pow(base,exponent); where base represents the base and exponent represents the exponent. This function returns a double type result, that is, the power calculation result. Let's

In iOS 17, Apple added a handy little list feature to the Reminders app to help you when you're out shopping for groceries. Read on to learn how to use it and shorten your trip to the store. When you create a list using the new "Grocery" list type (named "Shopping" outside the US), you can enter a variety of food and groceries and have them automatically organized by category. This organization makes it easier to find what you need at the grocery store or while out shopping. Category types available in alerts include Produce, Bread & Cereals, Frozen Foods, Snacks & Candy, Meat, Dairy, Eggs & Cheese, Baked Goods, Baked Goods, Household Products, Personal Care & Wellness, and Wine, Beer & Spirits . The following is created in iOS17

Before discussing the differences, let us first understand what Del and Remove() are in Python lists. Del Keyword in Python List The del keyword in Python is used to delete one or more elements from a List. We can also delete all elements, i.e. delete the entire list. Example of using del keyword to delete elements from a Python list #CreateaListmyList=["Toyota","Benz","Audi","Bentley"]print("List="
