print the summation of an array - java

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);
}

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
}

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);

Related

print max num in an array in java

import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
for (int i = 1; i < size; i++)
for (int j = 0; j < size - i; j++)
if (nums[i] > nums[i + 1]) {
temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
System.out.print(nums[size - 1]);
}
}
Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.
The error I get for size=5:
Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at maxnuminarray.main(maxnuminarray.java:15)
Once you read in the values, iterate over the array like this.
int max = Integer.MIN_VALUE;
for (int n : nums) {
max = Math.max(max, n);
}
You're trying to get a value with an index that doesn't exist. For instance, at if (nums[i] > nums[i + 1]). Let's say you have 3 numbers in total, your array size will be 3, but your index starts at 0.
Index 0
Index 1
Index 2
5
10
21
If you try to get i + 1 when i = 2 you get an error since i = 3 does not exist.
Also, if you're trying to get the largest number out of the array, you only need to go through the array once.
int[] nums = new int[]{1, 10, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++)
if (max < nums[i])
max = nums[i];
Or you can use Collections with the Integer[] array.
int max = Collections.max(Arrays.asList(num));
If you are just looking to find the maximum in the array, #Nouredine's code should do the trick.
Your code is comparing consecutive numbers one by one through the array, and swapping them in a bubble sort kind of way.
But if you are really looking to move the maximum in the array to the last position in the array, you can use this piece of code.
The issue in your code is you are accessing 5th index in an array of size 5, where only 0,1,2,3,4 are allowed.
for (int i = 1; i < size; i++)
if (nums[i - 1] > nums[i]) {
temp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = temp;
}
}
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
int max = nums[0];
for (int i = 1; i < size; i++)
if(max < nums[i])
max = nums[i];
}
System.out.println("Max " + max);
}

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

computing an average from an array list

I get an error for
sum = sum + arr[i]; // "i cannot be resolved to a variable"
Why is that?
"i" was declared earlier and I'm trying to use the value arr[i] to find and average of an arraylist from a text file called numbers.txt
public class Statistics {
public static void main(String[] args) {
int [] numbers = readFiles("./bin/q1/numbers.txt");
System.out.println(Arrays.toString(numbers));
}
private static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int ctr = 0;
//counting number of integers in numbers.txt
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
int [] arr = new int[ctr];
Scanner s1 = new Scanner(f);
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
int sum = 0;
sum = sum + arr[i];
float average = sum / (float) arr.length;
System.out.println("average of array is: " + average + "\n");
System.out.println("length of array is: " + arr.length + " integers \n");
return arr;
}
catch (Exception e) {
return null;
}
}
};
The problem you encounter is, the i you declared only exists in the previous for-loop
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
The i will be destroyed after for-loop, which means you cannot access the i anymore, you may find more details in here
To solve your problem, you have many options, for example:
Created another for-loop
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
int sum = 0;
for (int i = 0; i < arr.length; i ++)
sum = sum + arr[i];
float average = sum / (float) arr.length;
Include in the previous for-loop
//reads integers from file and assigns it to array
int sum = 0;
for (int i = 0; i < arr.length; i ++) {
arr[i] = s1.nextInt();
sum = sum + arr[i];
}
float average = sum / (float) arr.length;

sum of columns in a 2 dimensional array

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)
Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.
Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}
for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop
So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}
for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}

Computing sum of values in array

The problem im getting is that with oddSum the value outputted is the same as evenSum, and the value for sum of all elements is 0.
I cant quite see where im going wrong as the loops are pretty similar and if the even one works the others should too?
Here is my code anyway:
int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
}
else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
evenSum =evenData[evenIndex] + evenSum;
}
System.out.print("Sum of even elements: " + evenSum);
for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{
oddSum = oddData[oddIndex] + oddSum;
}
System.out.print("Sum of odd elements: " + oddSum);
for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);
You are getting same value for even and odd because you are printing the same value: -
System.out.print("Sum of odd elements: " + evenSum);
Also, your final sum is zero because you are making out all the elements of your original array as zero, as you are swapping your elements with the elements in evenData and oddData, which are zero initially.
int temp = data[index];
data[index] = evenData[index]; // This code assigns a value 0 to current index.
evenData[index] = temp;
So, you are iterating your array, and assigning 0 to each of your index, while adding the previous element to the new array.
I would say that you are needlessly using 2 extra array and 3 extra loops. Why not just create a sum in the place where you are iterating your original array?
In fact, all your sums can be computed in a single loop: -
for(int index = 0; index < data.length; index++)
{
sum += data[index];
if (data[index] % 2 == 0)
{
// int temp = data[index];
// data[index] = evenData[index];
// evenData[index] = temp;
evenSum += data[index];
}
else
{
// int temp = data[index];
// data[index] = oddData[index];
// oddData[index] = temp;
oddSum += data[index];
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
System.out.println("Total Sum: " + sum);
So, you don't need to create extra arrays for even and odd numbers.
And, also your 4 loops have now been condensed to just a single loop.
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
Looking at your above lines, evenDate is empty and in second line you are setting your data array to be empty. You are repeating the same mistake in oddDate line as well.
Why don't you use just try the following?
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0) {
int temp = data[index];
evenData[index] = temp;
} else {
int temp = data[index];
oddData[index] = temp; }
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
//since length of all 3 data,even, odd arrays are the same
//you can put both sum operation in one for loop
evenSum = evenData[evenIndex] + evenSum;
oddSum = oddData[evenIndex] + oddSum;
sum = data[evenIndex] + sum;
}
System.out.print("Sum of even elements: " + evenSum);
//you have put evenSum for below odeUm printing in ur code
System.out.print("Sum of odd elements: " + oddSum);
System.out.print("Sum of all elements: " + sum);

Categories

Resources