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 arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written. But it's in important that it's in arrays so I can also say later, "How much is array 55"开发者_C百科 and I can could easily see it.
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);
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;
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
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...]
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
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
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);
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);
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]);
}
}
}
精彩评论