do-while loop using IF - java

I am using if condition statement with a do while loop. I want that everytime when the compiler runs the program it should print the statement in the" IF " till it reaches less then 15 what is happening is that the job is going quite well in do-while loop but the statement in" IF " only printed once? Where am i going wrong. If someone explains the flow it would be really appreciated as i am a beginner. Please see below for the code :
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
if(n<15)
System.out.println("print value of n is equal to"+ n);
do {
System.out.println(n);
n++;
}
while(n<10);
}
}
output--> print value of n is equal to1
1
2
3
4
5
6
7
8
9

Your if statement is outside your do while loop. Put it inside the do {} block
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
if(n<15) {
System.out.println("print value of n is equal to"+ n);
}
System.out.println(n);
n++;
}
while(n<10);
}
}

You're looking for something closer to this:
while(n<15) {
System.out.println("print value of n is equal to"+ n);
n++
}
The block of code within { and } will be run constantly until n reaches a value greater or equal to 15.
With your current code, the full print statement is only output once, as it isn't included in your while loop.

I explain the workflow, since you are a beginner:
int n = 1;
1 is assigned to n.
if(n<15)
System.out.println("print value of n is equal to"+ n);
The program check if n is less than 15. it is the case, so it execute the action: print "print value of n is equal to" + n. It only does that once. It's not a while or a for loop that execute a loop repeatedly.
do {
System.out.println(n);
n++;
}
while(n<10);
}
Here the program execute everything between the { and the } until n=10.
You are saying "it should print the statement in the" IF " till it reaches less then 15"
Then you need a similar do/while loop:
do {
System.out.println("print value of n is equal to"+ n);
n++
}
while (n<15);

I want that everytime when the compiler runs the program it should print the statement in the" IF " till it reaches less then 15
Since you are using n<10 condition in do while loop , the loop will not proceed beyond n=9 . So it won't reach n=15.

I guess this is what you want:
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
System.out.println("print value of n is equal to"+ n);
n++;
} while(n<10);
}
}
Code flow:
int n = 1; Assigns n to 1
do { Repeat code between braces from here until while.
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to1
n++; Increments n by 1, so n = 2
} while(n<10); Is n < 10? Yes so repeat from do
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to2
n++; Increments n by 1, so n = 3
} while(n<10); Is n < 10? n = 3 so yes, repeat from do
[ ...same thing repeats until... ]
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to9
n++; Increments n by 1, so n = 10
} while(n<10); Is n < 10? n = 10 so no, exit loop.
End of program.

The statement inside the IF is passed only once. Since it is not inside any loop.
The flow of the program is procedural. So the execution is from top to bottom. It first pass the IF block, executes it, procedes to the next line, finds the do-while block which is loop until the while condition is met. Loops only iterates on it's block and not on lines before it.

First off you need to put the if() statement INSIDE the do while loop. otherwise the program only sees the if once.
the next thing you're doing is in your statement:
do {
System.out.println(n);
n++;
}
while(n<10);
you have it only going until n is less then 10, you want it to be less then 15.
I assume you wan't it to print out 15 as well so you can change
while(n < 10)
to
while(n <= 15)
so all together your code would look like this:
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
if(n <= 15){
System.out.println("The value of n is equal to " + n);
n++;
} while(n <= 15);
}
}
note <= means "less then or equal to"

You can refer this any time...
It will be more helpful to you..
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html

Related

I can't get my java program to print result

I'm stuck on a program from mooc.fi course; wherein I can't get my program to print results.
The program should 'print all the numbers divisible by three in the given range. The numbers are to be printed in order from the smallest to the greatest.'
Thanks for the help.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = 0; i >= beginning && i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Welcome to stack overflow, Entropy!
The problem is this line:
for (int i = 0; i >= beginning && i <= end; i++) { ... }
Let's break up that for loop:
for says its a loop, with the first statement initializing the loop, the second giving the condition for executing the next iteration, and the third saying how to update after an interation. Inside the quotes is what to execute in an interation.
Loop initializing: int i = 0 defines the loop variable i and sets it to 0.
Loop condition: i >= beginning && i <= end. So we will execute the next iteration if i lies in the entered range.
Loop post update: i++ just increments the counter.
So effectively, you start with i being 0, and then execute the loop WHILE that number is within the entered range. But if i BEGINS outside your range, the loop is never executed, because the condition is false at the very beginning.
You can confirm that by entering making the range contain 0, i.e. enter a non-positive lower and a non-negative upper range (like -10 to 10). Then, the initial condition is fulfilled and your loop happily shows all the number divisable by 3.
So simply change the loop to
for (int i = beginning; i <= end; i++) { ... }
and it will work as intended: Start at the beginning of the range, and go the end of it -- done!
These for-loops can be tricky sometimes, don't they? :)
That's a great first post, by the way. Having a Minimal Reproducible Example (MRE, also called reprex or MCVE [Minimal, Complete, Verifiable Example]) always help others to quickly verify, debug and solve your problem.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = beginning ; i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}

understanding increment and decrement [duplicate]

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.
Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.
Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1
System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).
An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}
Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}
This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.
This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}
Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

iteration through a loop

Lets assume n=20
so after every 6 iterations I will do some processing
int i=0
for (t=6;t<20;t=t+6){
while(i<=t){
will do some processing
i++;
}
}
In the above code it will terminate when t=18, but I want to continue until 20.
How to do that ?
You are increasing the t variable 6 units... the last condition that satisfies the t<20 is when t = 18.
instead of doing t+=6 do a normal t++ and play with the modulo %6
example:
public static void main(String[] args) {
int n = 20;
for (int i = 0; i < n; i++) {
//TODDY
insert your while in here depending on when that must be executed
if (i % 6 == 0) {
System.out.println("am on a 6 modulo step..." + i);
} else {
System.out.println("foo#" + i);
}
}
System.out.println("done");
}
The behaviour is correct only.. Still if you want to perform any operation, do it after the condition is met, try below snippet:
int i = 0, n = 20;
do{
i += 6;
System.out.println(i);
} while (i < n);
System.out.println(i);
your code is not doing something every 6th iteration, but instead you are doing (n - n%6) times. your "will do some processing" is inside the while. If you add a print (or debug) there you will notice it; on the n=20 example the while will be executed 18 times; it will do something 18 times.
if you want to execute every 6th iterations, and include one extra for the cases that are not exactly divisible by 6, then you could do:
if (n == 0) {
return;
}
int number_iterations = n/6 + (n%6!=0 ? 1:0);
for (int i=0; i<number_iterations; i++) {
// do something
}
That covers what you requested; if not, pls edit question to be more clear on your exact needs.

Java: Prefix/postfix of increment/decrement operators

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.
Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.
Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1
System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).
An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}
Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}
This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.
This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}
Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

Help with understanding java 'for' loops

I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!
Example #1 (odd number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>
Example #2 (even number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>
a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:
for(counter=0;counter <= iterations;counter++){ }
the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.
if we want to loop from 1 - 10, we do the following:
for(counter=1;counter<=10;counter++){ System.out.println(counter); }
if we want to loop from 10 - 1, we do the following:
for(counter=10;counter>=1;counter--){ System.out.println(counter); }
if we want to loop through a 2 dimensional collection, like...
1 2 3
4 5 6
7 8 9
int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.
you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.
for(i=0;i<grid.length;i++){
//this will loop through all rows...
for(j=0;j<grid[i].length;j++){
//will go through all the columns in the first row, then all the cols in the 2nd row,etc
System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
}
}
In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.
We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.
Please feel free to ask any questions you may have regarding for loops!
EDIT: understanding the question.....
You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.
int lines = 10; //the number of lines
String carat = ">";
for(i=1;i<=lines;i++){
System.out.println(carat + "\n"); // last part for a newline
carat = carat + ">>";
}
The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.
.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.
Edit 3:
Class Test {
public static void main(String[] args) {
int lines = 7;
int half = lines/2;
boolean even = false;
String carat = ">";
int i;
if(lines%2==0){even = true;} //if it is an even number, remainder will be 0
for(i=1;i<=lines;i++){
System.out.println(carat + "\n");
if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
carat = carat.substring(0,carat.length()-2);
}else{
carat = carat + ">>"; //otherwise, going up
}
}
}
}
Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).
Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.
At the hump, if it is even, we have to repeat the string.
We have to then start taking off "<<" each time, since we are going down.
Please ask if you have questions.
I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.
There is a lot of commenting throughout the code that you can follow along to explain the logic.
class ArrowTip {
public void printFigure(int n) { //The user will be asked to pass an integer that will determine the length of the ArrowTip
int half = n/2; //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
String str = ">"; //The String to be printed that will ultimately create the ArrowTip
int endInd; //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip
for(int i = 1; i <= n; i++) { //Print this length (rows)
System.out.print(str + "\n"); //The first carat to be printed, then any following carats.
if (n%2==0) { //If n is even, then these loops will continue to loop as long as i is less than n.
if(i <= half) { //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
str = str + ">>"; //It will continue to add two carats to the string until i is greater than n.
}
endInd = str.length()-2; //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
if((endInd >= 0) && (i >= half)){ //Now, decrement the str while j is greater than half
str = str.substring(0, endInd); //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
}
}
else { //If integer n is odd, this else statement will be called.
if(i < half+1) { //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
}
endInd = str.length()-2; //Serves the same purpose as the above if-loop when n is even.
if((endInd >= 0) && (i > half)) { //This will create the bottom half of the ArrowTip by decrementing the carats.
str = str.substring(0, endInd); //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
}
}
}
}
}
Again, this was for a homework assignment. Happy coding.
Here is a simple answer for you hope it helps! Cheers Logan.
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
for (int i = 10; i > 0; i--) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
}
}
For making a 'for' loop:
public class Int {
public static void main(String[] args) {
for (Long num = 1000000L; num >= 9; num++) {
System.out.print("Number: " + num + " ");
}
}
}
Output:
Number: 1008304 Number: 1008305 Number: 1008306 Number: 1008307 ...

Categories

Resources