javaBegginer - how to counts from 10 to 0 using while/do while - java

I started learning Java and I can't solve this:
I want to code program which will be counting from 10 to 0 using "do while" and show numbers from 9 to 1.
I did this:
public class exWhile {
public static void main(String[] args) {
int a = 10;
do {
--a;
System.out.println(a);
} while (a==1);
}
}
Why this wont working?

The loop exits almost immediately after the first iteration since the exit condition has been met. Use
...
} while (a != 1);

Your loop is saying "while a equals 1" do stuff. Since a isn't initialized to 1, it's only going through the do-while loop once.
What you want to do is
while(a != 0)
or you can also do
while (a > 0)
to print 10 thru 0.

What your code is saying is to continue looping through prints while the value of a is one. You stay a at ten, so this is not true, and the loop exits.
You want to do something like this
While(a!=0){
System.out.println(a);
a--}

Related

Code written after infinite loop executes

The following code shows an empty infinite loop and code written after the loop prints "Hello, World".
In this example, the println statement to print the statement synchronously and thus theoretically, after the infinite loop nothing should be printed, but still when on running the code, it prints "Hello, World".
So, why is the code written after an infinite loop executing?
public class Main{
public static void main(String[] args){
for(int i=0; i>=0; i++){}
System.out.println("Hello, World"); // This is printed on the console
}
}
I tried searching goole and stackoverflow for it, but could not find an answer for the problem.
Thank you.
When i becomes greater than max value(2147483648 - that can be represented in 32 bits), it overflows to its min value.
It runs exaclty Integer.MAX_VALUE times, because Integer.MAX_VALUE + 1 is Integer.MIN_VALUE, a negative number.
You can visualize your code like this :
class Main {
public static void main(String[] args) {
int i = 0;
for(i=0; i>=0; i++){}
System.out.println("Hello, World : "+ i);
}
}
This loop is not an infinite loop. It goes until the i reaches Integer.MAX_VALUE. Then i becomes Integer.MIN_VALUE which is a negative value. Run the code below and check the output.
int x = Integer.MAX_VALUE;
x++;
System.out.println(x);
If you want the loop to be infinite use,
for ( ; ; ){
}
Either the compiler smartened up and knew that nothing was done in that loop (which shouldn't matter, because even the for conditions can edit stuff)
or i looped 2 million something times and overflowed into negative numbers, making it less than 0.

java - why is this recursive method exceeding what I expected

Doing a very simple program to test out recursion. The program prints something until the number is not greater than 0.
public class TestIt {
public static void print(int f){
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
}
}
the code above is called from the main program like this.
public static void main(String[] args) {
TestIt.print(2);
}
Maybe I'm finally losing my mind, but the amount of times the program prints is exceeding what I expected. If I send 3 to the method then the program prints 7 times. Any ideas as to why?
Because you did wrong
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
you are calling the method print f in the loop times
and as it is recursive it will be called f-1 times recursivelly
so it will b f fatorial times
remove the while loop and will work as you want
This is because everytime the call comes off the stack, f is still what it was originally, and then it continues with the while loop. So for 2:
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
First run, subtracts from 2, results in one. (Print count = 1) Resursive call:
Subtracts again, 0, recursive call: (Print count 2)
While loop is never entered. returns:
0, while loop is not executed, reuturns:
While loop is run again, recursive call: (print count = 3)
Passes zero, while loop not entered, return
While loop terminated, exit method
For 2 it prints three times, but this grows for every number passed in. To fix this do:
if(f>0){
System.out.println("Not today");
f--;
print(f);
}
Remember recursion usually is to avoid loops, so if you find yourself using both, this is usually a red flag

Recursive call has finish in a function but continue printing integers

I tried to investigate what will happen if I write some code after the recursive call and here is the code. I tried to trace the code but I didn't get what was going on. I thought the function will be terminated once my program prints the last value for x since the value for x doesn't satisfy the if loop condition. I executed this code, the result wasn't understandable. Any help would be appreciated.
public class Recursive {
public static void main(String []args){
int a=5;
call(a);
}
public static void call(int x) {
System.out.print(x+"\n");
if(x>0) {
x--;
call(x);
}
System.out.print(x);
}
}
Expected output:5 4 3 2 1 0 0
My output: 5 4 3 2 1 0 0 0 1 2 3 4
instead of while, you can try If condition and remove the last print.
public static void call(int x) {
System.out.print(x+"\n");
if (x>0) {
x--;
call(x--);
}
}
You forgot to say what was surprising or confusing, which indicates that you don't understand the problem (hence two downvotes). Here is what I think may be confusing. The decrement operator x-- first returns the value of a variable and then lowers it's value. So if you run
z= 25
dothedoo(z--)
the value inside dothedoo will be 25, not 24. The alternative --x will lower the value first and then return the value.
This is your code.
public static void call(int x) {
System.out.print(x + "\n");
while (x > 0) {
x--;
call(x);
}
}
Lets consider this call stack with an input of x=2
1) call(2)
2) print x // 2
2) x-- (becomes 1)
3) recursive call to call(1) // remember the call(2) is suspended right now.
4) print x //1
5) x -- (becomes 0)
6) recursive call to call(0)// remember the call(2) and call(1) is suspended right now.
7) print x //0
8) x-- (becomes -1)
9) recursive call to call(-1) // breaks the loop since it doesnt match the condition, resumes flow to the suspended call(1) function.
10) refer step 5 for the value of x.
11) breaks the loop for the call(1) function. // resumes call(2) which was suspended.
12) refer step 2 where x is still 1.
13) moves on with another call(1)
14) this results in printing an extra 0; from the call in step 13
Your while loop is messing up the program.
Your variable in the recursion is passed by value, hence your actual
value of x which is caller's value isnt decremented globally in the caller when you do this call(x) the x which is used after
decrementing in your recursive call is a copy of the x that you have
decremented in the caller.
Please refer to this article to understand more on it.
Also, the while loop is notorious here based on the explaination provided in this answer and what you actuall need is an if loop

While and do while loops

I'm new to this site and also very new to Java and I'm trying to understand the do while loops
Question: What is the output and why?
public class DoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i is : " + i);
i++;
} while(i < 1);
}
}
I get that the output is "i is : 1" but I'm trying to understand why. It stops once it hits while because i isn't less that 1, right?
Just trying to get my head around it so any help will be appreciated.
Yes. Correct.
do { } while (condition);
This will perform the code at least once, regardless of the condition. After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop.
Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once.
After the do block is executed the i value becomes 2 and the while block is not executed.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
Yes, the output is
i is : 1
The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; it's only evaluated at the end of each iteration. This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration.
i is 1 at the start, then print occurs, then i is incremented to 2. Then the condition is evaluated -- it's false, so the loop terminates.
The output is just 1 becuase the do causes the loop to execute at least once, but the condition in the while doesn't aloow the loop to reiterate, because i is never less than 1
It is no more 1
public class DoWhile {
public static void main(String[] args) {
int i = 1; // i is 1
do {
System.out.println("i is : " + i); //still i is 1
i++; // this makes i = 2;
} while(i < 1);
}
}
if you notice the comments it is no more 1 after the first iteration

What is the "continue" keyword and how does it work in Java?

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.
What is the continue keyword?
How does it work?
When is it used?
continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:
break terminates the loop (jumps to the code below it).
continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next.
This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:
for(int i=0; i < 10; ++i) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This will print out only the odd numbers.
Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.
As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration
Example: This is a code to print the odd numbers from 1 to 10
the compiler will ignore the print code whenever it sees continue moving into the next iteration
for (int i = 0; i < 10; i++) {
if (i%2 == 0) continue;
System.out.println(i+"");
}
As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet will contain odd numbers only 100%... you are wrong!
Continue is a keyword in Java & it is used to skip the current iteration.
Suppose you want to print all odd numbers from 1 to 100
public class Main {
public static void main(String args[]) {
//Program to print all odd numbers from 1 to 100
for(int i=1 ; i<=100 ; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.
Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.
Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '
public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}
}
It will print: aa cc Out of the loop.
If you use break in place of continue(After if.), it will just print aa and out of the loop.
If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
I'm a bit late to the party, but...
It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:
while ((buffer[i++] = readChar()) >= 0)
continue;
In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.
It's a little more obvious than the equivalent:
while (...)
{ }
and definitely better (and safer) coding style than using an empty statement like:
while (...)
;
continue must be inside a loop Otherwise it showsThe error below:
Continue outside the loop

Categories

Resources