How do you subtract a value from a counter in Java? - java

Say that length=11 and that I want to subtract 2 from it on every cycle until it reaches 1. Is my code for the for method correct? And what would it be for a while loop?
for(int i =length ; i!=1; i-=2)
EDIT: This was the question. To solve it I made an if statement that if the length%2==1 I would use the for loop listed above. Then I am going to write an else stating modifying the code above to stop at 0. Does this make sense?
The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.)

For is not a method. It's a language construct. Just a nitpick.
Almost. If i starts out even you'll never end. Use:
for(int i =length ; i>1; i-=2)

If the 1 is inclusive, you could try:
for(int i = length; i >= 1; i -= 2){ ... }
Or
for(int i = length; i > 0; i -= 2){ ... }
If the 1 is exclusive, you could try:
for(int i = length; i > 1; i -= 2){ ... }

Related

How can I print out a series of number starting at 1 less than x and ending at 0?

When I run this, I don't get any input at all? What's wrong?
int x = inp.nextInt();
//write your code below
for(int reverse = x - 1 ; reverse >= x ; reverse--) {
System.out.print(reverse);
}
It should decrease the value reverse until it reaches 0. If you chose reverse >= x the loop will never complete.
for(int reverse = x - 1; reverse >= 0; reverse--) {
System.out.print(reverse);
}
In your for loop
for (int reverse = x - 1 ; reverse >= x ; reverse--) {...}
You start with reverse being x - 1. Therefore, the second condition is by default false. So nothing happens.

Trying to properly print an array in Java

I am new to Programming so bear with me if I do not properly present my issue. I have an assignment to create a program to assign integer values 1-25 to a 25 element integer array. I need to print the array as five separate lines with each line containing 5 elements separated by commas. The last element does not have a comma following it. The final output should be as follows:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
The code that I came up with comes close, but it's not quite right. The code that I came up with is:
public class Test2 {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
int[] numbers = new int[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
System.out.print(numbers[i] + ",");
if (i % 5 == 0 && i > 0)
System.out.println();
}
}
}
The printout that I get from my code is as follows:
1,2,3,4,5,6,
7,8,9,10,11,
12,13,14,15,16,
17,18,19,20,21,
22,23,24,25,
I am not sure why I am getting 1-6 on the first line as well as how to remove the comma at the end of each line. Any help pointing out my errors would be appreciated.
The error is that you are checking if int i is divisible by 5 (i % 5), not numbers[i] (numbers[i] % 5). This way, your code prints:
number 1 when i = 0,
number 2 when i = 1,
number 3 when i = 2,
number 4 when i = 3,
number 5 when i = 4,
number 6 when i = 5
and finally prints line break.
The correct code is:
int[] numbers = new int[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i]=i+1;
System.out.print(numbers[i]);
if (numbers[i] % 5 == 0 && i > 0) {
System.out.println();
} else {
System.out.print(",");
}
}
The above code will print (as intended):
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
You're getting 6 numbers on the first line, because you start counting at i=0, and only print the newline once i=5; at which point the number you've just printed is 6, not 5 - you're printing i+1 in each iteration.
If you made your logic such that it printed EITHER a comma OR a newline but not both, you'd get rid of the commas at the ends of the lines.
You're close. Very close.
Consider what your condition is checking - you want to inspect a value i, and want to stop when that particular value is divisible by 5 but is nonzero.
The problem is that you have the wrong value - i isn't what you want, but numbers[i]. The reason: each number in numbers[i] is offset of i by 1.
What you want to do is check if numbers[i] is divisible by 5. You still need to check for a nonzero i, though.
if(numbers[i] % 5 == 0 && i > 0) {
System.out.println(numbers[i]);
} else {
System.out.print(numbers[i] + ",");
}
Replace
if (i % 5 == 0 && i > 0)
with
if (i % 5 == 4)

Sum of factorials

So I need to output a sum of factorials like 1!+2!...+n!=sum I found a way to get a single factorial but I don't know how to sum them together. This is my attempt at doing so:
System.out.println("Ievadiet ciparu");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Ciparam jabut pozitivam.");
else
{
while (x>2){
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
sum=sum+fact;
n=n-1;
if (n==0) break;
}
System.out.println("Faktorialu summa "+sum);
Rather than have a loop 1-n and calculate each factorial elsewhere, I would accumulate the sum as you calculate the factorials - ie have two local variables; one for factorial and one for the sum:
long factorial = 1, sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
When tested with n = 5, sum is 153, which is correct: 1 + 2 + 6 + 24 + 120
Your problem was that the sum was outside the loop - you just needed braces like here.
Also, your while loop condition x < 2 will never change, so either the loop will never execute (if x > 1) or the loop will never terminate, because x is not changed within the loop.
hmmm my search for finding a recursive(via recursive method calling) version of these code still getting nowhere
`public static long factorialSum(long n){
long x = n;
for(int i = 1; i < n; i++){
x = (n-i)*(1+x);
}
return x;
}`
if you just look at the problem more closely you'll see you can do it in linear time, the trick is in (n-1)! + n! = (n-1)!*(1 + n), to understand this more deeply i recommend add (n-2)! just to see how it grows.

Java integer maths to loop from 0-4 continuously

Is there a nicer way to do the count I'm doing below?
I'm sure this must be possible with modulus or something. I'm looking for someway to manipulate i instead of using the extra variable x. (to beautify this).
Here is the long way round:
int MAX = 4;
int x = 0;
for (int i = 0; i < 50; i++) {
System.out.print(x);
if(x++; == MAX)
x = 0;
}
Expected outcome:
// 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 .. etc
for (int i = 0; i < 50; i++) { System.out.print(i % MAX); }
Yes, you can just do x = i % MAX;
Your code is pretty clear as is. While modulus % might save you a few keystrokes, it's not necessary. Natural human expression is generally preferred, especially if your coding at 4am or coming back to your code 6 months later.

For Loop Doesn't Work Right

Why doesn't this for loop count the right number of times? If I set the variable runs to 3, the loops runs 4 times. (One extra case.)
Thanks in advance!
for (int i = runs; i >= 0; i--)
{
System.out.println("Input Duration of Trip");
Scanner timeCalc = new Scanner(System.in);
System.out.print("Hours ==> ");
int hour = timeCalc.nextInt();
System.out.print("Minutes ==> ");
int minute = timeCalc.nextInt();
System.out.println("You entered: " + hour + " hour(s) and " + minute + " minutes");
System.out.println();
time = convertHoursMinutesToDouble(hour, minute);
totalTime += time;
}
The loop runs for values:
3
2
1
0
That's 4 times.
If you want it to run for values 3, 2 and 1, you can change your for loop to:
for (int i = runs; i > 0; i--)
or
for (int i = runs; i >= 1; i--)
Your mistake is in
i>=0
What the code is doing is going "Ok, i is going to be equal to three. Now, let's see, ok, back up again, subtract one, i =2... subtract one i=1... Now tricky tricky it SKIPS the termination part of the code because it looks at it first BEFORE substracting one so i=0, ok WAIT i=0 so STOP."
Solution?
for (int i = runs; **i >= 1**; i--)
This mistake always messes me up.
Hope the whole "through the mind of the computer thing" doesn't bother you. That's how I tend to think.
Happy coding!
i == 3
i >= 0
println
i--
i == 2
i >= 0
println
i--
i == 1
i >= 0
println
i--
i == 0
i >= 0
println
That was 4 times. You need your condition to be: i > 0
Because you have set greater than or equal to...
So starts at 3 and goes, 2,1,0.

Categories

Resources