Java: Array with loop

后端 未结 9 1003
借酒劲吻你
借酒劲吻你 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:23

    this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.

    int i = 100;
    // Implement the fomrulae n*(n+1)/2
    int sum = (i*(i+1))/2;
    System.out.println(sum);
    
    0 讨论(0)
  • 2020-12-06 05:24

    I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:

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

    Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]

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

    int[] nums = new int[100];

    int sum = 0;

    // Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++)

    { 
         nums[i] = i + 1;
        sum += n;
    }
    

    System.out.println(sum);

    0 讨论(0)
提交回复
热议问题