Add two array elements using loop - java

I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {
public static void main(String []args)
{
int[] nums = new int[2];
for (int i = 0; i < 100; i++)
{
nums[i] = i + 1;
System.out.println(i);
}
System.out.println(nums[1]);
System.out.println(nums[2]);
if (nums[0]+nums[1]<=50)
{
System.out.printf("Sucessfully finished");
}
}
}
Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .

There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] <= 50) {
System.out.println("sum is less than or equal to 50");
break;
}
}
What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] > 50) {
System.out.println("sum was NOT less than or equal to 50");
break;
}
}
As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;
// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);
System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);
The output is min increments with sum > 50 was 25 and 26.

I believe, you need 1 more for loop, to go about checking each num[i] + num[i+1]. You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{
public static void main(String[] args) {
int[] nums = new int[100];
for (int i = 0; i < 100; i++) {
nums[i] = i + 1;
System.out.println(i);
}
for (int i = 0; i < 99; i++) {
System.out.println(nums[i]);
System.out.println(nums[i+1]);
if (nums[i] + nums[i+1] == 50) {
System.out.printf("Successfully finished");
}
}
}
}

I'm not sure if this is what you meant. Have a try.
public static void main(String[] args) {
int[] nums = new int[100];
nums[0] =1;
for (int i = 1; i < 100; i++) {
nums[i] = i + 1;
if ((nums[i] +nums[i-1]) >= 50) {
System.out.printf("Successfully finished");
}
}
}

I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
int j = i+1;
int total = i+j;
if((i+(i+1)) < 50) {
System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
}
}
This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)

Related

Need help to create an array of randomly generated numbers within a range and then displaying the frequency of each number in that range

As the title implies I'm having trouble writing a code that can do as asked. What I have is:
public static void main(String[] args) {
int[] runs = new int[24];
for(int i = 0; i < runs.length; i++) {
runs[i] = (int)(Math.random()*3 + 1);
int count = 1;
for (int j = i+1; j<i;j++) {
if (runs[i] == runs[j]) {
count++;
}
}
System.out.println(runs[i] + " " + count);
}
}
However, whenever I run my program, it will just list the randomly generated numbers and then a 1 next to them. Any help is appreciated, thank you!
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
for(int i = 0; i < runs.length; i++) {
runs[i] = (int)(Math.random()*3 + 1);
if (runs[i] == 1) {
count1++;
} else if (runs[i] == 2) {
count2++;
} else if (runs[i] == 3) {
count3++;
} else {
count4++;
}
}
System.out.println("1's Frequency is: " + count1);
System.out.println("2's Frequency is: " + count2);
System.out.println("3's Frequency is: " + count3);
System.out.println("4's Frequency is: " + count4);
The block of code I have provided above should work. One of the problems with your code is you haven't generated all the numbers in the array prior to searching through the array to look for each number's frequency. Furthermore, the block of code within the nested loop of your code would not accomplish the task of finding out each numbers frequency.
What I did here is that it goes through the loop and assigns a random number to each spaces in the array. And, each time that it assigns a random number it also go through a series of conditional statements to count or increment the frequency of each number within the range.

For loop printing an unexpected number of times

public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("Please enter five numbers. \na=");
array[0] = input.nextInt();
System.out.print("\nb=");
array[1] = input.nextInt();
System.out.print("\nc=");
array[2] = input.nextInt();
System.out.print("\nd=");
array[3] = input.nextInt();
System.out.print("\ne=");
array[4] = input.nextInt();
boolean totalIsZero = false;
for (int i=0;i<array.length ;i++) {
for (int j=1;i>j ;j++ ) {
if ((array[i] + array[j])==0) {
System.out.println("The numbers " + array[i] + " and " + array[j] + " have a total sum equal to 0.");
totalIsZero = true;
}
}
}
if (!totalIsZero) {
System.out.print("None of the numbers have a total sum of 0 with each other. ");
}
}
Here is some simple code I just wrote. Its task is to check if the sum between every two numbers in an array (consisting of five numbers) is equal to zero.
The problem I have is that when there are two pairs of numbers, both equal to 0, at the end of the program there is a message for one of the pairs only, not for both, as I expected.
How can I fix that, so the user can read that there are two pairs of numbers equal to 0?
Not sure if this will work perfectly because I haven't tested it and I haven't used java in a while, but just create the array the same way you do it in your post, but try the rest for the actual bulk of the function.
// various input calls above^ to create array
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = i + 1; j < array.length; j++)
{
if(array[i] + array[j] == 0)
{
System.out.println("The numbers " + array[i] + " and " +
array[j] +
" have a sum equal to zero.");
count++;
}
}
}
if(count == 0)
{
System.out.println("No sum between any numbers is equal to 0");
}

Math.random won't randomize number 9 whenever it has to be assigned to last array slot

My code creates an array of size 10, it randoms numbers from 0 to 9 to fit in each slot. The problem comes when the number 9 is not picked until the last space. Math.random keeps randomizing numbers but it will never pick the number 9. I ran the program for about 1 minute and it never picked it.
Here is my program
public class GenerateRandomNumbers{
// main method
public static void main(String[] args) {
int aSize = 10;
int[] a = new int[aSize];//setting size of array
for(int i = 0; a.length > i; i++){//looping through the whole array
a[i] = (int)(Math.random()*9) + 1;//assigning random number to each slot of array
System.out.println("assign " + a[i] + " to i" + i);
//looping through filled array slots.
for(int k = i-1; -1 < k; k--){
System.out.println("Check if " + a[i] + " i"+ i + " = " + a[k]+ " k"+ k );
//if not unique give a new number
if(a[i] == a[k]){
System.out.println("CHANGE HERE");
a[i] = (int)(Math.random()*9) + 0;
System.out.println("assign " + a[i] + " to " + i);
k = i;//reset loop so it checks all over again
}
}
System.out.println("ACCEPT");
}
for(int i = 0; a.length > i; i++){
System.out.println(a[i]);
}
}
}
Can someone explain me what is causing the bug?
Your line a[i] = (int)(Math.random()*9) + 0; is different from the time you used Math.random() above. Above you said (int)(Math.random()*9) + 1, that will give you a random number in the range of [1,9].
(int)(Math.random()*9) + 0 will never evaluate to 9, its range is [0,8].

adding only odd numbers

So the question I'm trying to solve the user is supposed to enter any positive number. Then I'm trying to write a program that adds only the odd numbers up to the number the user enters and displays the total. So for example if the user enters 4 my program should add four odd numbers. 1 + 3 + 5 + 7 = 16. The only tools I have available are for statement, if, if/else if,while loop and println.
I can only figure out how to print out the odd numbers. I know I want to create a variable named total to store the value of adding up all the odd numbers but I don't know how that fits into the program.
import acm.program.*;
public class AddingOddNumbers extends ConsoleProgram {
public void run() {
int n = readInt("enter a positive nunber: ");
int total = 0;
for (int i = 0; i < n; i++) {
if (n == 1) {
println(1);
} else {
println((i * 2) + 1);
}
}
}
}
import acm.program.*;
public class AddingOddNumbers extends ConsoleProgram {
public void run() {
int n = readInt("enter a positive nunber: ");
int total = 0;
for (int i = 0; i < n; i++) {
if (n == 1) {
println(1);
} else {
println((i * 2) + 1);
total += (i * 2) + 1;
}
}
println("total : " + total);
}
}
sum = 0;
for (i = 1; i < n*2; i=i+2)
sum = sum + i;
This will give you the odd number sum.
if (n>0)
{
total=0;
for (int i = 1; i < n; i ++){
if (i%2 == 1)
total+=i;
}
}
If you want to inclusive of n, then change the condition to i<=n.
Maybe you know how to compute the sum of all numbers up to a given number n? The formula is quite simple: (n * (n+1))/2. Now getting the sum of only the odd numbers is a bit trickier but - no worries you can make use only of the previous formula for that. First notice that the sum of all even numbers up to a given number n is:
(((n/2)* (n/2+1))/2) * 2 if N is even(i.e. the sum of all numbers up to n/2 times two that is because you have 2+4+6+8+...N = 2*(1+2+3+...n/2))
((((n-1)/2)* ((n-1)/2+1))/2) * 2 if N is odd
In fact if you have integer division the formula is always: (((n/2)* (n/2+1))/2) * 2 = (n/2)* (n/2+1)
So to compute the sum of all the odd numbers up to n you simply subtract the sum of the even numbers from the sum of the all numbers:
(n * (n+1))/2 - (n/2)*(n/2+1)
In fact if you observe closely you will notice that the sum 1+3+...(2*n-1) always equals to n^2.
This answer should help you solve your problem in all languages and I am leaving the code to you. It is literally one line.
I would use a loop for the odd numbers as well.
for (int i = 0, j = 1; i < n; i++, j += 2) {
println(j);
total += j;
}
println(total);
int oddSum = 0;
for (int i = 0; i < n; i++){
oddSum = oddSum + (i*2) + 1;
}

Reverse Number in Java using Array

So, I'm supposed to write a program determining Ermips. I've got the rest figured out, but I'm not sure how to reverse the number correctly. I'm supposed to use an array to reverse it.
For example, the number 357.
I use the mod operator to take the last digit and put it in the first index of the array.
357%10 = 7
myArray[0] = 7
357/10 = 35 for a remainder
Use the remainder 35 to start over.
35%10 = 3
myArray[1] = 3
35/10 = 3 for a remainder
etc. ...
I need to basically loop this so I can do any length number to reverse it.
Then, after I have that array, display the array to produce the number in reverse....753.
public class Reverse {
public static void main(String[]args) {
int n = 357;
int MAX_NUMBERS = 20;
int currentNumber = 0;
int reverseNumber = 0;
int remain = 0;
int sum = 0;
int [] holdDigits = new int [MAX_NUMBERS];
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
//sum array
int count = holdDigits.length;
while (count > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
count--;
index++;
}
while (index < holdDigits.length){
reverseNumber += holdDigits[index]*Math.pow(10,count-exp);
index--;
System.out.println("sum so far: " + sum);
}
System.out.println("Number reversed: " + reverseNumber);
}//end of main
}//end of class
Totally figured it out now, thanks to Yogendra Singh !
Check it out:
public class Reverse2 {
public static void main(String[]args) {
int n = 76495;
int MAX_NUMBERS = 20;
int reverseNumber = 0;
int index = 0;
//declare an array to hold the digits while reversing
int [] holdDigits = new int [MAX_NUMBERS];
//the exponent is the number of spaced used in the array
int exp = holdDigits.length;
//while the number is greater than 0, use mod to put the right-most
//digit in index 0, divide the remaining number and increase the index
//to put it in the next open slot of the array.
while (n > 0){
holdDigits[index] = n%10;
n = n/10;
index++;
}
//decrease the index by one so it doesn't add the remaining zero as
//a placeholder in the number
index--;
//count is the index because below, you subtract it, making the display
//of the array reversed.
int count= index;
//while the index is greater than zero, by starting at the last filled
//slot of the array, the reverse number is added onto each time by
//multiplying the number times 10 to the power of whichever place it
//is which happens to be the index.
//EXAMPLE: to turn 7 into 700, multiply by 7x10^3
while (index >= 0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
//lower the index to do the next number of the array
index--;
}
System.out.println("Reversed number: " + reverseNumber);
}//end of main
}//end of class
There are some issues in the code as below:
Run the first loop until remainder of division is 0
Count the digits found in the division process
Reduce the index by 1 after first loop as it is post incremented by one in the while loop
Sample corrected code could be as below:
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
while (n > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
index++;
}
index--;
int count= index;
while (index >=0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
index--;
System.out.println("sum so far: " + sum);
}
i apology if already you have got an answer but this is an short way to get reverse number using array with for loop.
var val = prompt("enter number");
var New = val.split("");
var arr1 = [];
console.log(New);
for (i = New.length - 1; i >= 0; i--) {
arr1 += New[i] + ',';
} console.log(arr1);

Categories