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();
Related
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;
I'm trying to add all the elements together in an array that was decided through user input, Every time I run the code that I've constructed below I get a number that is obviously not the sum of the elements. What am I doing wrong?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
You probably want to prompt the user to enter the size of the array if you're going to do this.This line of code is allowing whatever the user enters to be the size of your array.
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
scan doesn't exist in the currrent context:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
I would do this to keep adding elements to the array:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
This code will give you the sum of the elements if you just add one element at a time instead of two to the sum variable:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
Adding some logic to only allow the user to enter so many numbers to the array would be helpful as well. You will need to move on from them entering data into the array at some point. Then also remember to close the scanner when you're finished getting data from the user:
input.close();
Your problem is in the following lines of code:
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
it should look something like
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum = sum + array1[i];
}
System.out.print(sum);
The first change is to declare the variable "sum" outside of the loop. The way it's written, it will get declared, then disappear, then declared, then disappear for every loop iteration. You also probably want to initialize it to 0
The second change is to your summation logic. Lets assume your array contains the three numbers [1, 2, 3] and walk through your logic.
j = array1[0] //(j == 1)
k = array1[0] + 1 //(k == 1 + 1 == 2)
sum = j + k //(sum == 1 + 2 == 3)
You then throw out the variable "sum" like I mentioned earlier, and start over with the same logic on the second array element, then again on the third.
i.e. j = 2, k = 2+1, sum = 2 + 2 + 1. followed by j = 3, k = 3 + 1, sum = 3 + 3 + 1.
You can probably see how this isn't the sum, and results in you logging the three digits 3, 5, and 7 for this example case.
In my updated logic, we simply loop through each element and add it to the current running total.
hope this helps
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.
So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));
How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10];
int i, userIn;
Scanner KyBdIn = new Scanner(System.in);
System.out.println("Please enter 10 integer numbers ");
for(i = 0; i < tenIntArray.length; i++){
System.out.println("Please enter integer " + i);
userIn = KyBdIn.nextInt();
tenIntArray[i] = userIn;
}
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds - [50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "The smallest value is 1 at position 5 in array"
This figure should be helpful :
Then to answer your question, what would you do on paper ?
Create and initialize the min value at tenIntArray[0]
Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
Loop through the elements of your array
If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
You're done
Writing the algorithm should be straightforward now.
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
The method I am proposing will find both min and max.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min and max values. Output is:
min: 10
max: 69
int[] input = {12,9,33,14,5,4};
int max = 0;
int index = 0;
int indexOne = 0;
int min = input[0];
for(int i = 0;i<input.length;i++)
{
if(max<input[i])
{
max = input[i];
indexOne = i;
}
if(min>input[i])
{
min = input[i];
index = i;
}
}
System.out.println(max);
System.out.println(indexOne);
System.out.println(min);
System.out.println(index);
Here is the function
public int getIndexOfMin(ArrayList<Integer> arr){
int minVal = arr.get(0); // take first as minVal
int indexOfMin = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then minVal
if(arr.get(i) < minVal ){
minVal = arr.get(i); // put it in minVal
indexOfMin = i; // put index of current min
}
}
return indexOfMin;
}
the first index of a array is zero. not one.
for(i = 0; i < tenIntArray.length; i++)
so correct this.
the code that you asked is :
int small = Integer.MAX_VALUE;
int i = 0;
int index = 0;
for(int j : tenIntArray){
if(j < small){
small = j;
i++;
index = i;
}
}
System.out.print("The smallest value is"+small+"at position"+ index +"in array");