I need to create an array of 1 to 100 and print the summation of the elements.
Actually, I have used for loop and Array together! But it won't work.
int i, sum = 0;
for(i = 1; i < 100; i ) {
int [] arr = new int [] {i};
sum = sum arr[i];
}
System.out.println("Sum of all the elements of an array: " sum);
}
CodePudding user response:
A "one-liner" solution.
int[] arr = {...}; // Your array here
int sum = 0;
for (int i = 0; i < arr.length; i ) {
sum = sum arr[i]; // can also be written as sum = arr[i];
}
System.out.println("Sum of all the elements of an array: " sum);
If the array is empty, the sum will be zero. Otherwise, it is the accumulated sum. The best thing to do is to declare and increment the loop counter variable inside the for structure and not outside. That's how it is designed. If you need this variable accessible outside the loop, use a while loop instead.
UPDATE: In case you're curious for a while loop equivalent:
int[] arr = {...}; // Your array here
int sum = 0;
int i = 0;
while (i < arr.length) {
sum = sum arr[i]; // can also be written as sum = arr[i];
i ; // always increment the variable at the end of the loop
}
CodePudding user response:
I think you are looking for something like this:
int i, sum = 0;
int[] arr = new int[100];
for(i = 0; i < arr.length; i ) {
arr[i] = i 1;
sum = arr[i];
}
System.out.println("Sum of all the elements of an array: " sum);
