Using FOR loop and summing values between rounds in Java - java

this is my task:
"Write program LoopForNumberSum.java. Display only every second number, starting from 2, to the screen and sum in parenthesis between the last round and current round so far. The looping range is defined in separate variables. Use FOR-loop to solve the problem."
This is the code I have so far:
public class LoopForNumberSum {
public static void main(String args[]) {
int min = 2;
int max = 10;
for(int i = min; i <= max; i+=2) {
int j = i+i;
System.out.println(i + "(" + j + "), ");
}
}
}
^This code prints:
2(4),
4(8),
6(12),
8(16),
10(20),
But I need the number in the parenthesis to start from 2 and the rest would need to be 6, 10, 14 and 18. Like this: "2(2), 4(6)..."

Try:
int sum = 0;
for(int i = 2 ; i <= 10 ; i += 2) {
sum += i;
System.out.println(i + "(" + sum + "), ");
}

Related

I want to subtract the largest possible number from the Fibonacci sequence by decreasing it in

I want to get n from user and subtract the largest possible number from the Fibonacci sequence by decreasing it in sequence and continue this process until it reaches zero. Our Fibonacci sequence starts from 1. The number 88 can be The form 1 + 3 + 8 + 21 + 55 wrote that these numbers are the sentences 1, 3, 5, 7 and 9 of the Fibonacci sequence, respectively.
Input: 88
Output: 9 7 5 3 1
My code:
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] fibo = new int[1000];
int[] arr = new int [100];
int d = 0;
int b = 0;
fibo[1] = 1;
fibo[2] = 2;
for (int i = 3, j = 1; i <= 20; i++, j++)
fibo[i] = fibo[i - 1] + fibo[i - 2];
b = n;
for (int i = 1, j = 1; i <= 20 && b >= 0; i++, j++) {
if (b == fibo[i] || b + 1 == fibo[i] || b - 1 == fibo[i]) {
d = i;
b -= fibo[d - 1];
System.out.println("B= " + b);
arr[j] = d - 1;
System.out.println("arr= " + arr[j]);
}
}
}
}
The first problem is that, every time you subtract something from your number, the next number you will subtract will have to be smaller - because your number itself is smaller now - whereas in your code, the numbers just keep getting bigger.
For instance, after you try the 9th fibonacci number 55, you are trying 89, whereas you should be trying 34.
This can be solved by iterating backwards through the fibonacci numbers, as in starting from the biggest number at the end of the array, so that as the loop iterates, the numbers get smaller.
The second problem is your check in the if statement, which is only satisfied if there happens to be a fibonacci number very close to the number you are at.
Instead, if you want to select the largest fibonacci number that is smaller than your number, you can just check for the 'smaller than your number' part, since 'the largest fibonacci' part is already taken care of by how the for loop works.
Here is the working code. You will also notice a lot fewer variables. Also I hard-coded the input number for testing, you'll have to add the scanner stuff back in. Sorry.
public class Main {
public static int len = 20; // the program considers this many fibonacci numbers
public static void main(String args[])
{
int n = 88;
int[] fibo = new int[len];
for(int i=0; i<len; i++)
{
if (i < 2) fibo[i] = i+1; // for 1 and 2
else fibo[i] = fibo[i-1] + fibo[i-2]; // for 3 and 5 and ...
}
for(int i=len-1; i>=0; i--)
{
if (fibo[i] <= n)
{
System.out.format("%d: %d - %d = %d\n",
i+1, // to correct for 0-indexing
n, fibo[i], n-fibo[i]);
n -= fibo[i];
}
}
}
}

Stop a loop after a certain amount of iterations, instead of when a max value is met

JAVA:
I want a for loop that doesnt stop when i is a certain number, but rather after x iterations. Is there any way to do that?
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7; i <= WHAT GOES HERE; i = i * 10 + i) {
sum = sum + i;
}
return sum;
}
You can declare multiple variables of the same type in a for-loop:
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7, iterations = 0; iterations < (number of iterations); i = i * 10 + i, iterations++) {
sum = sum + i;
}
return sum;
}
Let's assume you have a certain value summing up in your loop and you want to stop the loop if the value exceeds a certain border. You can just add an if statement that checks the value:
public static void main(String args[]) {
// some value to hold a sum
int valueSum = 0;
for (int i = 0; i < 1000; i++) {
// in every iteration step, add the current value of i to valueSum
valueSum += i;
// print the current values of i and valueSum
System.out.println("Iteration no " + i + ", value sum = " + valueSum);
// stop looping if valueSum becomes 500 or greater
if (valueSum >= 500) {
break;
}
}
}
Please check the console output to get a better understanding of for loops and iteration in general.
The only case i can think of is: if x (number of iterations) is greater than i (your index which may depend on some input values like array length etc.) If that is the case you can combine an infinite loop with a break statement:
int iterations = 0;
for(int i = 0; true ; i++){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
or even without declaring an index:
int iterations = 0;
for( ; ; ){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
or if you need two or more independent variables
int x = 10; //number of iterations wanted
for(int i = 7, j = 0; j<= x; i = i * 10 + i , j++){
// do something
}

How to use printf to print out in a certain format

How do I use the command printf to print my output the same way in the attached output file?
this is my code currently:
else if (args[0].equals("fib")) {
for (int i = 0; i < (Integer.parseInt(args[1]) + 1); ++i) {
System.out.println(getFib(i));
}
}
How do i change it to make it print like the attached picture?
Thank you guys for your help!
Here is an example.
Instead of instant printing add all numbers into a list:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= number; i++) {
numbers.add(fibonacci(i));
}
Then make a pattern for printf():
String pattern = "%" + (numbers.get(numbers.size()-1).toString().length() + 10) + "d";
where (numbers.get(numbers.size()-1).toString().length() + 10) is the sum of the number of characters in the largest number plus 10 spaces between columns.
Then print all elements of the list. The counter is needed in order to have no more than 6 columns:
int counter = 0;
for (Integer integer : numbers) {
if (counter == 6) {
System.out.println(" ");
counter = 0;
}
System.out.printf(pattern, integer);
counter++;
}

what is the best way to write these java arrays?

I am stuck on my class work:
Create an application containing an array that stores eight integers. The application should
display all the integers, (done)
display all the integers in reverse order,
display the sum of the eight integers, (done)
display all values less than 5,
display the lowest value, (done)
display the highest value, (done)
calculate and display the average, (Done)
display all values that are higher than the calculated average value.
I must use (or attempt to use) an array; also must use at least one loop to "traverse" (move through) the array. This also due # 23:59 mountain standard time tonight
What am I doing wrong?
package numberlistdemo;
import java.util.Arrays;
public class NumberListDemo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int n[]= {1,2,3,4,5,6,7,8};
int lowest = 1000;
int highest = 0;
int sum = 0;
int five = 0;
int OverF = 0;
int rev = 0;
int OverAve= 0;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
double ave = sum / n.length;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur > ave) OverAve = cur;
}
for (int i=0;i<n.length;i++)
{
int LowF = n[i];
if (LowF < 5) five = LowF;
if (LowF > 5) OverF = LowF;
}
//3
System.out.println("Total of the Array is " + sum );
//1
System.out.println("The number we are using are " + Arrays.toString(n));
//4
System.out.println("All values lower the 5 are " + five );
////2
for (int counter=n.length - 1; counter >= 0; counter--)
{
System.out.println("The reverse order of the numbers are " + (n[counter]));
}
//5
System.out.println("The lowest value is " + lowest);
//6
System.out.println("The highest value is "+ highest);
//7
System.out.println("The average is " + ave);
//8
System.out.println("All numbers higher than the average are: " + OverAve);
}
}
I get this
Total of the Array is 36
The number we are using are [1, 2, 3, 4, 5, 6, 7, 8]
All values lower the 5 are 4
The reverse order of the numbers are 8
The reverse order of the numbers are 7
The reverse order of the numbers are 6
The reverse order of the numbers are 5
The reverse order of the numbers are 4
The reverse order of the numbers are 3
The reverse order of the numbers are 2
The reverse order of the numbers are 1
The lowest value is 1
The highest value is 8
The average is 4.0
All numbers higher than the average are: 8
Sample loop to obtain sum, lowest, and highest integer from an array
int lowest = 1000;
int highest = 0;
int sum = 0;
for (int i = 0; i < array.length; ++i) {
int cur = array[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
Edit: the latest code updates made some progress, but likely do not quite meet the specified requirements. There are some difficulties in knowing the full requirement (e.g., output format).
Output Only
The current example is displaying the output (one entry per line). It is not clear if one only needs to display the output or actually reverse the array. If the only requirement is to output the reversal, the numbers larger than 5 and larger than 8, the the following three loops will work. One is mostly already in the suggested code.
System.out.println("The reversed array is: ");
for (int counter < n.length - 1; counter >= 0; counter--) {
System.out.print(n[counter] + " ");
}
System.out.println();
Note that these two should probably be in a method
final int lessThan = 5;
System.out.println("The numbers in the array less than " + lessThan + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] < lessThan) {
System.out.print(n[i] + " ");
}
}
System.out.println();
System.out.println("The numbers in the array greater than the mean " + ave + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] > ave) {
System.out.print(n[i] + " ");
}
}
System.out.println();
Create a new reversed array
It would make more sense for the assignment to require actually reversing the array. In that case, there are a couple of approaches. Probably the easiest is to create a new array and reverse the elements into it. Essentially it is the same loop as above, but placing the elements of n into the array rather than outputing them to the screen. (Note: #Debosmit proposed an example that does not require the additional index variable).
int[] reversed = new int[n.length];
int idx = 0;
for (i = n.length - 1; i >= 0; --i) {
reversed[idx++] = n[i]];
}
Later then one can use the same output approach as was used for displaying all of the original entries:
System.out.println("The reversed array is: " + Arrays.toString(reversed));
What is the error message?
since you are not using curly braces{ } your local variable int i will only exist within these lines:
for (int i=0;i<n.length;i++)
sum = sum + n[i];
and NOT these:
double rev = n.length - i - 1;
boolean l = (n[i] < 5);
Ah! Well... I'll contribute. Here is how to reverse...
// note this will change the original array
for(int i = 0 ; i < n.length ; i++) {
int t = n[i];
n[i] = n[n.length - 1 - i];
n[n.length - 1 - i] = t;
}
// this will not change the original array
int[] newArr = new int[n.length];
for(int i = 0 ; i < n.length ; i++) {
newArr[n.length - 1 - i] = n[i];
}
// you can now return `newArr` or something since it is `n` reversed
Now to look at all values that are higher than the calculated average value. I think you already have the sum of the numbers. Lets call it sum. avg = sum/n.length.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] > avg)
System.out.println(n[i]);
}
All numbers less than 5.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] < 5)
System.out.println(n[i]);
}
In the future, please don't come here with your homework before trying to do it yourself. Thanks! :)

Sum of the distincts Extended Description

I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.
Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}
From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.
There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}
Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124
When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);

Categories

Resources