Java: Array with loop

后端 未结 9 1065
借酒劲吻你
借酒劲吻你 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: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);
    

提交回复
热议问题