Java: Array with loop

后端 未结 9 1002
借酒劲吻你
借酒劲吻你 2020-12-06 04:49

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).

I don\'t want to enter these numbers into the a

相关标签:
9条回答
  • 2020-12-06 05:06

    If all you want to do is calculate the sum of 1,2,3... n then you could use :

     int sum = (n * (n + 1)) / 2;
    
    0 讨论(0)
  • 2020-12-06 05:08

    If your array of numbers always is starting with 1 and ending with X then you could use the following formula: sum = x * (x+1) / 2

    from 1 till 100 the sum would be 100 * 101 / 2 = 5050

    0 讨论(0)
  • 2020-12-06 05:08

    The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.

    Public Class Program
    {
    
    public static void main(String args[])
    
    {
     //Array Intialization
     int my[] = new int[6];
    
     for(int i=0;i<=5;i++)
    
    {
    
    //Storing array values in array
    my[i]= i;
    
    //Printing array values
    
    System.out.println(my[i]);
    
    }
    
    }
    
    }
    
    0 讨论(0)
  • 2020-12-06 05:13

    Here's how:

    // Create an array with room for 100 integers
    int[] nums = new int[100];
    
    // Fill it with numbers using a for-loop
    for (int i = 0; i < nums.length; i++)
        nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99
    
    // Compute sum
    int sum = 0;
    for (int n : nums)
        sum += n;
    
    // Print the result (5050)
    System.out.println(sum);
    
    0 讨论(0)
  • 2020-12-06 05:14

    To populate the array:

    int[] numbers = new int[100];
    for (int i = 0; i < 100; i++) {
        numbers[i] = i+1;
    }
    

    and then to sum it:

    int ans = 0;
    for (int i = 0; i < numbers.length; i++) {
        ans += numbers[i];
    }
    

    or in short, if you want the sum from 1 to n:

    ( n ( n +1) ) / 2

    0 讨论(0)
  • 2020-12-06 05:16
    int count = 100;
    int total = 0;
    int[] numbers = new int[count];
    for (int i=0; count>i; i++) {
        numbers[i] = i+1;
        total += i+1;
    }
    // done
    
    0 讨论(0)
提交回复
热议问题