Using an array list - java

Which code snippet calculates the sum of all the elements in even positions in an array?
a) int sum = 0;
for (int i = 1; < values.length; i+=2)
{
sum++;
}
b) int sum = 0
for (int i = 0; i < values.length; i++)
{
sum++;
}
c) int sum = 0;
for (int i = 0; i < values.lengthl; i++)
{
sum +=values [i];
}
d) int sum = 0;
for (int i = 0; i < values.length; i + 2)
{
sum +=values [i];
}
are any of these correct? because for my answer I got
int sum = 0;
for (int i = 0; i < values.length; i += 2)
{
sum +=values [i];
}
is my answer correct? or is it one of the multiple choices?

None of these answers appear to answer the question. Here is a code snippet which will compute the sum of all even elements of array values.
int sum = 0;
for (int i = 1; i < values.length; i = i + 2) {
sum +=values [i];
}
You have to increment the loop variable i by 2 in order to sum only even elements. Also note that I assume the first even position is the second position in the array, which is values[1].

A small correction you are using array in your code. ArrayList is different from Array. ArrayList doesn't have a length property, it's the property of an Array. I think the answer added by Tim Biegeieisen is correct for an array.
Similary, You can do the same thing for a array list like this -
int count=0;
int sum=0;
for(Integer i : values){
if(count%2==0){
sum = sum+i;
}
count++;
}
System.out.println(sum);
And here values is an ArrayList of Integer. Note you can not put int or any other primitive type in ArrayList. So you may declare your ArrayList used here (that is values) like -
List<Integer> values = new ArrayList<Integer>();
Hope it will Help.
Thanks.

A and B don't add elements of the array to sum; B and C process all elements. So if any of them are correct, it must be D. But since D does not change i, it cannot be right, either.

Related

How to reduce the number of loops if there is no change?

This code is radix sort in Java.
Now I can sort. But I want to reduce its functionality if there is no change in the
array, let it stop the loop and show the value.
Where do I have to fix it? Please guide me, thanks in advance.
public class RadixSort {
void countingSort(int inputArray[], int size, int place) {
//find largest element in input array at 'place'(unit,ten's etc)
int k = ((inputArray[0] / place) % 10);
for (int i = 1; i < size; i++) {
if (k < ((inputArray[i] / place) % 10)) {
k = ((inputArray[i] / place) % 10);
}
}
//initialize the count array of size (k+1) with all elements as 0.
int count[] = new int[k + 1];
for (int i = 0; i <= k; i++) {
count[i] = 0;
}
//Count the occurrence of each element of input array based on place value
//store the count at place value in count array.
for (int i = 0; i < size; i++) {
count[((inputArray[i] / place) % 10)]++;
}
//find cumulative(increased) sum in count array
for (int i = 1; i < (k + 1); i++) {
count[i] += count[i - 1];
}
//Store the elements from input array to output array using count array.
int outputArray[] = new int[size];
for (int j = (size - 1); j >= 0; j--) {
outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
count[(inputArray[j] / place) % 10]--;//decrease count by one.
}
for (int i = 0; i < size; i++) {
inputArray[i] = outputArray[i];//copying output array to input array.
}
System.out.println(Arrays.toString(inputArray));
}
void radixSort(int inputArray[], int size) {
//find max element of inputArray
int max = inputArray[0];
for (int i = 1; i < size; i++) {
if (max < inputArray[i]) {
max = inputArray[i];
}
}
//find number of digits in max element
int d = 0;
while (max > 0) {
d++;
max /= 10;
}
//Use counting cort d no of times
int place = 1;//unit place
for (int i = 0; i < d; i++) {
System.out.print("iteration no = "+(i+1)+" ");
countingSort(inputArray, size, place);
place *= 10;//ten's , hundred's place etc
}
}
1
I'm going to resist typing out some code for you and instead go over the concepts since this looks like homework.
If I'm understanding you correctly, your problem boils down to: "I want to check if two arrays are equivalent and if they are, break out of a loop". Lets tackle the latter part first.
In Java, you can use the keyword"
break;
to break out of a loop.
A guide for checking if two arrays are equivalent in java can be found here:
https://www.geeksforgeeks.org/compare-two-arrays-java/
Sorry if this doesnt answer your question. Im just gonna suggest a faster way to find the digits of each element. Take the log base 10 of the element and add 1.
Like this : int digits = (int) Math.log10(i)+1;

Insert value to 2d array

I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me

How to compare two arrays of different sizes?

So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?

return the sum of values in an array [duplicate]

This question already has answers here:
Computing sum of values in array
(2 answers)
Closed 7 years ago.
I am given an array of name 'array[]' with an unknown amount of elements. I am asked to return the sum of all of the values in the array, and I tried to write a for loop covering all of the values in the array and adding them together. I think that I am overthinking this, and I should be able to do this in one command but I can't remember.
Here is what I am given:
int arraySum(int[] array)
I tried:
for(int i = 0; i <= array.length; i++){
int sum = array[i];
}
return sum;
Use Java 8 Stream api which gives sum in one line .
Arrays.stream(array).sum();
You have the problem here:
int sum = array[i];
because you are creating a new variable sum each time the loop make an iteration. You should create your sum variable before using it on the loop:
int arraySum( int[] array) {
int sum = 0;
for(int i = 0; i <= array.length; i++){
sum = sum + array[i];
}
return sum;
}
Look that you have to initialize it to zero.
Also, remember that the arrays starts at the position 0. Because of that, you should use
i < array.length
instead of
i <= array.length
in your loop condition.
I expect it will be helpful for you!
This should do the trick:
int arraySum( int[] array) {
int sum = 0;
for (int i : array) {
sum += i;
}
return sum;
}
You need to declare (and initialize sum). Usually, a sum starts at 0. Then, you might use a for-each loop - you can read it like for-each value in the array, do something with the value - like add it to sum. Finally, return the sum. Like,
int arraySum(int[] array) {
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
Or, using an index variable like
int arraySum(int[] array) {
int sum = 0;
for (int index = 0; index < array.length; index++) {
sum += array[index];
}
return sum;
}
Or, you could use the new Java 8+ stream api with Arrays.stream(int[]) and IntStream.sum() like
int arraySum(int[] array) {
return Arrays.stream(array).sum();
}
And, as pointed out by #PaulBoddington, you could also use IntStream.of(int...) and IntStream.sum() like
int arraySum(int[] array) {
return IntStream.of(array).sum();
}
The scope of sum is within the for loop. You should declare it outside for loop to use it.
Also, the addition of sum isn't correct as well as the for loop condition.
The updated code should be something similar to following
int sum = 0;
for(int i = 0; i < array.length; i++){
sum+ = array[i];
}
return sum;
Declare variable sum outside the loop, else it will re initiate every time. Also, use += operator to add itself.
int sum = 0;
for(int i = 0; i <= array.length; i++){
sum += array[i];
}
return sum;

How to add a certain number in an array of numbers?

I'm currently using this code to add all the numbers in an int array:
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int total = sum;
For example if I had an array of numbers such as [1, 1, 2, 2, 3, 3, 1] and I only wanted to add all the 1's in the array, how would I go about doing so?
Just check if each array member is equal to 1 :
int sum = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i]==1)
sum += array[i];
}
you need to compare that number with array index i;
int sum = 0;
int num = 0;// this number will compare with array index
for (int i = 0; i < array.length; i++)
{
if (array[i]==num)
sum += array[i];
}
int total = sum;
It really depends on how you choose those numbers. For example, if the number you chose has certain property(such as adding all 1,2,3 or adding all even number), you can use if statement to get the number. If the choice is depends on the certain property of index of the array, (add the No.1, No.2, No.3, No.5, No.8, No.13 ...) you can add another loop inside the "for" loop.
Inside loop filter it as
if (yourNumberToCompare==array[i]) {
sum += array[i];
}
Where yourNumberToCompare is the number that you want to compare.
Final code will be
int sum = 0;
int yourNumberToCompare = 1; // this will be as per your choice
for (int i = 0; i < array.length; i++) {
if (yourNumberToCompare==array[i]) {// this is the filter I was talking about
sum += array[i];
}
}
int total = sum;
Java 8 version:
int[] integers = new int[]{1,2,3,4,5,6,7,8,9,1};
int sum = Arrays.stream(integers).filter(x -> x == 1).sum();

Categories