Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
You can have multiple variables and incrementers in a for loop.
for(int i = 10, j = 0; i >= 0; i--, j++) {
System.out.println(i);
System.out.println(j);
}
You want to decrease the loop values in incremental of 1 right? Here you need to update the code as below.
public class Loop {
public static void main(String[] args) {
int x=50, y= 1;
do {
System.out.println("X is = " + x);
if (x >= 0) {
x -=y++;
}
}while(x>=40);
}
}
In above example,
For decrement I've used x and for increment I've used y so loop will turn from 50 - 40 and y will helpfull to decrese values in Incremental form.
Updated answer
@Goion has suggested, you can use for-loop
public class Loop {
public static void main(String[] args) {
int y= 1; //To decrese 'x' in incremental order of `y`
for(int x=50; x>=40; x-=y++){
System.out.println("X: " + x);
}
}
}
I think that's what you need to do to decrease by 1 and 2
public class Loop {
public static void main(String[] args) {
int x = 0;
int y = 50;
do {
System.out.println("output is = " + y);
if (x % 2 == 0)
y -= 1;
else
y -= 2;
x++;
}
while (y >= 40);
}
java - Best idiom for a decrementing loop - Stack Overflow
java - Decrement on While loops - Stack Overflow
for loop - How to count from 10 to 1 in java - Stack Overflow
java - Why does decrement loop runs faster than increment loop? - Stack Overflow
Videos
I recommend the following because comparison against zero is optimized at the byte code level.
for(int idx=(len-1); idx>=0; idx--) {...}
This is a suggestion from Java Performance Tuning by Jack Shirazi
Another array-oriented variant you might see is this:
int n = foo.length;
while (n-- > 0) {
/* Do something with foo[n] */
}
Of the options you show, I prefer the first.
0is (arguably) more readable than-1.- Comparison to zero is usually faster than comparison to other constants. It is a single instruction that examines a single value on the stack. Other comparisons use one instruction to push a constant onto the stack and another instruction to compare the top two values.
e is the exponent and that while loop is doubling the value of the number until the exponent is less than or equal to 0.
It will remain the value of i unless it is decremented.
You could also convert it into a for loop like so
for (int e = i; e > 0; e--) {
result *= 2;
}
I understand if this is a learning exercise, but the Math.pow function could do the same thing.
You can also do the same with an other int j which takes incremental steps to calculate i-th powers of 2:
for(int i=0; i<10; i++){
result = 1;
for(int j=0; j<i; j++){
result *= 2;
}
}
Or, if you want to use while inner loop:
int j = 0;
while(j < i){
result *= 2;
j++;
}
change the for loop to:
for (int i=10; i>0; i-=2) {
System.out.println("i= "+i);
}
i-=2 is an abbreviation for i = i-2
It means that the new value of i will be the old value of i minus 2.
i-- is an abbreviation for i = i-1, which can be also written as i-=1
Just use this method and give it the number to decrement with in param:
public static void count(int counter) {
for(int i = 10; i > 0; i-=counter){
System.out.println("i = " + i);
}
}
For exmaple to decrement by 2 use:
count(2);
And your main will be like this:
public static void main(String[] args) {
count(2);// to decrement by 2
count(3);// to decrement by 3
count(4);// to decrement by 4
}
This is because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. Of course there will be no speed difference in most cases because of JVM optimizations. But we can try to make it visible by running the code with -Xint option (interpreted mode execution only).
Piyush Bhardwaj
I tested both the loops in online compiler but my increment loop is executing faster then decrement loop.
Program execution depends upon many factors. When sometimes we run the same program on same machine many times we gets different execution times. So it depends upon many factors.
See the results
for(int i = 1; i < 100001; i++) {
}
Increment loop -- http://ideone.com/irdY0e
for(int i = 100000; i > 0; i--) {
}
Decrement loop -- http://ideone.com/yDO9Jf
Sir Evgeniy Dorofeev has given an excellent explanation which an expert only can give.
Finally, you need to consider the performance of your CPU. When considering a benchmark to determine the overall performance of a Java application, bear in mind that bytecode execution, native code execution, and graphics each play a role. Their impact varies depending on the nature of the specific application.
I've been doing the MOOC Introduction to OOP course part 1 for a while, and I've been having a blast. I'm used to python, and no other language has got my attention like this, for some reason.
There is a thing, I don't quite understand. The increment operator in it self, raises the value of your variable by 1. However, in several excercises now, we have been doing something similar to this:
import java.util.Scanner;
public class ManyPrints {
// NOTE: do not change the method definition, e.g. add parameters to method
public static void printText() {
System.out.println("In the beginning there were the swamp, the hoe and Java");
// Write your code here
}
public static void main(String[] args) {
// ask the user how many times the text should be printed
// use the while structure to call the printText method several times
Scanner reader = new Scanner(System.in);
int num = 0;
System.out.println("How many? ");
int times = Integer.parseInt(reader.nextLine());
while(num <= times) {
printText();
num++;
}
}
}On the first try, I didn't even have the increment operator in my code, and it would just constantly print my code. Then I thought of this, because we have been doing it a lot, and it worked. However, I don't understand why. Why does the increment operator, make the program able to stop after the number in the user input? Why doesn't it just keep increasing the value by 1?
Sure while num is less or equal to times that part of the code runs, but if i remove the increment operator, it would be infinite.
Thank you.
I think you mean > instead of <:
for (int i = 10; i > 0; --i) {
If you want the values of i to be the same as in the original code except in reverse order (i.e. 9, 8, 7, ..., 1, 0) then you also need to change the boundaries:
for (int i = 9; i >= 0; --i) {
I just want to add to keep in mind that --i decrements first, then checks and i-- checks, then decrements.