国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
introduce
Example 2
method
illustrate
Output
輸出
結(jié)論
Home Java javaTutorial Java 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

Sep 13, 2023 pm 09:05 PM
list while loop calculate

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 循環(huán),只要“i”小于列表的大小,該循環(huán)就會繼續(xù)。在循環(huán)內(nèi),我們將列表中的當前數(shù)字(使用“get”方法檢索)添加到總和中,并遞增“i”以移至列表中的下一個數(shù)字。

最后,一旦循環(huán)結(jié)束,我們使用 "println" 方法打印出列表中數(shù)字的總和。請注意,在這個例子中,我們使用的是 Double 值而不是 Integer 值,這允許我們在數(shù)字中包含小數(shù)位。

輸出

The sum of the numbers in the list is: 1.5

結(jié)論

  • 在本文中,我們討論了兩個使用while循環(huán)計算列表中數(shù)字總和的Java程序示例。在這兩個示例中,我們使用了類似的方法來迭代列表中的每個元素,在一個單獨的變量中累加它們的總和,然后輸出結(jié)果。

  • 我們還討論了這些程序的時間和空間復(fù)雜度。這兩個程序的時間復(fù)雜度都是 O(n),其中 n 是列表中元素的數(shù)量,因為我們需要迭代列表中的每個元素來計算它們的總和。兩個程序的空間復(fù)雜度都是 O(1),因為我們只需要使用幾個變量來存儲輸入列表、運行總和以及循環(huán)計數(shù)器,并且這些變量的大小不依賴于輸入。

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
CUDA's universal matrix multiplication: from entry to proficiency! CUDA's universal matrix multiplication: from entry to proficiency! Mar 25, 2024 pm 12:30 PM

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

How to calculate addition, subtraction, multiplication and division in word document How to calculate addition, subtraction, multiplication and division in word document Mar 19, 2024 pm 08:13 PM

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 count the number of elements in a list using Python's count() function How to count the number of elements in a list using Python's count() function Nov 18, 2023 pm 02:53 PM

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 Shopping List in the iOS 17 Reminders App on iPhone How to Make a Shopping List in the iOS 17 Reminders App on iPhone Sep 21, 2023 pm 06:41 PM

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

How to use the Math.Pow function in C# to calculate the power of a specified number How to use the Math.Pow function in C# to calculate the power of a specified number Nov 18, 2023 am 11:32 AM

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

Count the number of occurrences of a substring recursively in Java Count the number of occurrences of a substring recursively in Java Sep 17, 2023 pm 07:49 PM

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

How to create a grocery list: Use the Reminders app for iPhone How to create a grocery list: Use the Reminders app for iPhone Dec 01, 2023 pm 03:37 PM

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

PHP date processing tips: How to calculate the month difference between dates using PHP? PHP date processing tips: How to calculate the month difference between dates using PHP? Mar 20, 2024 am 11:24 AM

PHP date processing tips: How to calculate the month difference between dates using PHP? Date processing is a very common requirement in web development, especially in business logic that needs to be related to time. In PHP, calculating the month difference between dates can be achieved through some methods. This article will introduce how to use PHP to calculate the month difference between two dates and provide specific code examples. Method 1: Use the DateTime class. PHP's DateTime class provides a wealth of date processing methods, including calculating dates.

See all articles