"while" loop not iterating correctly - java

I am supposed to print the following output by using loops:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
The highest number in this pattern (in this example, 7) is determined by user input. Here is the applicable code for the pattern:
index=patternLength+1; n=1; //These values are all previously intitialized
while (index!=1) {
index--;
printSpaces((index*2)-2); //A static method that prints a certain number of spaces
while(n!=1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
n=patternLength+1-index;
}
And here is the incorrect output for the user input "7":
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
There are two blank lines preceding the incorrect output; these lines have the correct number of spaces necessary for the complete/correct pattern, but for some reason, the actual numbers start printing too "late" in the loop. In other words, the spaces that appear before the "1, 2 1" in the correct example are in the incorrect output. It's some of the numbers that are missing and make the incorrect example incorrect.

OK, I got it.
index=patternLength+1; n=1;int nSetter=1;
//Loop C
System.out.println("Pattern C:");
while (index!=1) {
index--;
printSpaces((index*2)-2);
while(n!=0) {
System.out.print(n + " ");
n--;
}
System.out.print("\n");
nSetter++;
n = nSetter;
}
My problem was that my "n" needed to go both up and down, so the extra variable "nSetter" seems to have solved that, although this may be a round-about solution. Whatever. Thanks to #Andreas for pointing me in the correct direction and #JohnKugelman for the helpful edit.

Please try this code your second while loop is not correct.
int index = patternLength + 1;
int n = 2; //These values are all previously intitialized
int i = 1;
while (index != 1) {
index--;
printSpaces((index * 2) - 2); //A static method that prints a certain number of spaces
while (n != 1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
i++;
n = i+1;
}

Related

How do I print this specific pyramid in Java?

I desire a code output that looks like this:
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Keep in mind that my code takes in the size of the pyramid through input before
My code now looks like:
for(int numRows=sizePyr;numRows>=1;numRows--){
for(int i=sizePyr;i>=numRows;i--){
System.out.print(i + " ");
}
System.out.println();
}
Changing the nested for loop to for (int i = numRows; i >= 1; i--) fixed the issue
You want to start printing i with the current numRows value, then work the way down to 1.
Your current code start printing i with sizePyr (which is a constant 6 throughout the function), then work the way down to numRows.
for(int numRows=sizePyr;numRows>=1;numRows--){
for(int i=numRows; i >= 1; i--){
System.out.print(i + " ");
}
System.out.println();
}
For the first line, you want to start with sizePyr (as your inner loop does), but want to end with 1 (which your loop decidedly does not). In fact, every line should end with 1. Change your loop to reflect this.

What is the difference between multiple ifs and if-else in this case?

The program is supposed to stop looping at 1 but with multiple ifs, it continues to loop. I was able to complete the exercise using if-else but I am having trouble tracking and understanding the differences between multiple ifs and if-else here.
I am new here so thank you all in advance for the help.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a starting value: ");
int input = keyboard.nextInt();
System.out.print(input + ",");
System.out.print(" ");
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
keyboard.close();
}
Expected: the program should stop at 1 (while check)
Actual: it continues to loop infinitely: 4 2 1 4 2 1 ....
Because the starting value is 4, the first if-statement reduces it to 2. On the next iteration of the loop, the first if-statement reduces it to 1, but then the second if-statement sees that it's an odd number and multiplies it by 3 and adds 1.
To fix this issue, your second if-statement needs to be replaced with else, as there are only two possible conditions:
if (input % 2 == 0) {
input = input / 2;
} else {
input = 3 * input + 1;
}
System.out.print(input + ", ");
This will make it so that, if the first if-statement is executed, then the second one won't be.
When input enters the while loop with the value 2, it enters the first if and when leaving the block its value is 1. Then it enters the 2 if and its value is set to 4. Then there is a new loop with values 4 2 1...
Think of the situation when input is 2
case 1. with 2 ifs first if will make the input 1 and 2nd if will be executed and will make it again 4.
case 2 . with if else , once the input becomes 1 after first if it will come out of loop , and hence the result.
Not an answer, but relevant for the Collatz sequence.
(The error being entering the first if changes input causing to enter
the second if if there would be no else.)
1 -> 1
odd n -> 3n+1 (even!)
even n -> n/2
As you can see odd n's could short cut taking two steps:
odd n ->-> (3n+1)/2
For math research this is a better sequence.
Then you can do without else entirely.
while (input != 1) {
if (input % 2 == 1) {
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
/*if (input % 2 == 0)*/ {
input /= 2;
System.out.print(input + ",");
System.out.print(" ");
}
}
The while loop will continue iterating until value of the variable, input is 1. In your sample example, when you enter input = 4, there will be infinite iterations (the loop will execute infinitely as per the conditions)
Before while loop it prints 4 (the input)
Iteration 1: input is 4. Enters while loop -> Enters 1st if as 4%2=0 and reassigns input to 4/2=2 -> Prints 2 -> Doesn't enter 2nd if as 2%2=0
Iteration 2: input is 2. Enters while loop -> Enters 1st if as 2%2=0 and reassigns input to 2/2=1. Prints 1 -> Enters 2nd if as input=1 now and 1%2=1. -> Reassigns input = 3*1 + 1 = 4. Prints 4
Then it again stats with 4. It continues infinitely printing 4 2 1 4 2 1 4 2 1 ...
while (input != 1) {
//1st if
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
//2nd if
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
Else statement executes only when the if condition fails. When you replace the 2nd if condition with a else statement, the program will not assign the input value to 4 again. Hence it will stop at 1, printing 4 2 1
Each and every if condition is checked even though previous condition is passed or failed in multiple if statements. But in case of if-else block, if any one is passed others are skipped.
Try this:
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
else { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
In your code:
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
In your code if input is 2, then input = input / 2; this statement will make input 1. Next as input % 2 == 1 will become true it will make input equal to 4(input = 3 * input + 1;) and the loop will not end. You should use else instead. Even the code is commented as // replace with else

Creating a sliding number puzzle board using arrays in Java

So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. Here's what I have :
int[] puz = {1,2,3,
4,5,6,
7,8,9}
for(int i=0; i<puz.length; i++){
System.out.println(puz[i]);
}
The 1 is supposed to be the blank spot but I'll figure that out later. My problem is that the code prints:
1
2
3
4
5
6
7
8
9
when I want it to print:
1 2 3
4 5 6
7 8 9
I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was.
Would I try using a 2d array instead?
I guess you could try...
int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}
Try creating a variable counter and increment it every time you iterate through the loop. Using a modulus operator, divide it by 3 and when remainder is 0, create a new line.
int puz = {1,2,3,4,5,6,7,8,9};
int counter = 1;
for(int i=0; i<puz.length; i++){
System.out.print(puz[i]);
if (counter % 3 == 0){
System.out.println("");
}
counter++;
}
The trick here is to use the modulus operator. This operator divides one number by another, and returns the remainder. In java (and everywhere else as far as I know), % is the modulus operator. If you want every third number to have a line break after it, simply divide by three using modulus division, like so:
int[] puz = {1,2,3,4,5,6,7,8,9};
//For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
System.out.print(puz[i] + " ");
if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
System.out.println("");
}
}
This code, when executed, prints the following, which is what you wanted:
1 2 3
4 5 6
7 8 9

Java - Understanding Recursion

Can someone please explain to me why this prints out 1 2 3 4 5? I figured it would print out 4 3 2 1 0 but my book and eclipse both say I'm wrong.
public class whatever {
/**
* #param args
*/
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int n){
if (n>0){
xMethod(n-1);
System.out.print(n + " ");
}
}
}
It is pretty simple, these are the calls
main
xMethod(5)
xMethod(4)
xMethod(3)
xMethod(2)
xMethod(1)
xMethod(0)
print 1
print 2
print 3
print 4
print 5
So you see the prints are 1,2,3,4,5
It's the result of the call stack. Here's what it would look like after a call with n = 5. Rotate your head about 180 degrees, since the bottom of this call chain is actually the top of the stack.
xMethod(5)
xMethod(4)
xMethod(3)
xMethod(2)
xMethod(1)
xMethod(0)
In a recursive call, you have two cases - a base case and a recursive case. The base case here is when n == 0, and no further recursion occurs.
Now, what happens when we start coming back from those calls? That is, what takes place after the recursive step? We start doing System.out.print(). Since there's a condition which prevents both recursion and printing when n == 0, we neither recurse nor print.
So, the reason that you get 1 2 3 4 5 as output is due to the way the calls are being popped from the stack.
It first call itself recursively and only when the recursive call finishes it prints.
So think about which call finishes first - it's when n = 0.
Then n = 1, etc.
It's a stack and you print after taking from the stack (after the recursion call), so the order is reversed.
If you printed before putting on the stack, then the order is preserved.
System.out.print(n + " ");
xMethod(n-1);
It will print 5 4 3 2 1. Because It will first print then call xMethod.
And in your case
xMethod(n-1);
System.out.print(n + " ");
Here it will reach to end condition then poped up and print. so 1 2 3 4 5
To explain how recursion works, let's see the sample of factorial calculation:
int factorial(int i) {
if (i == 0) {
return 1;
}
return i * factorial(i - 1);
}
For example let's get factorial value of 5:
int result = factorial(5);
Remember that exit value:
if (i == 0) {
return 1;
}
and return value:
i * factorial(i - 1)
Just look at iterations (according to return value):
5*factorial(4) -> 4*factorial(3) -> 3*factorial(2) -> 2*factorial(1) -> 1*factorial(0)
In fact it is:
5*(4*(3*(2*(1*factorial(0)))))
cause factorial(4) == 4*factorial(3), factorial(3) == 3*factorial(2), etc.
last iteration is factorial(0) that equals 1 (look at exit value).
In result:
5*(4*(3*(2*(1*1)))) = 120
xMethod is called until n is 0. The stack will then be xMethod(5)->xMethod(4)->xMethod(3)->xMethod(2)->xMethod(1)->xMethod(0). As it finishes xMethod(0), it will pop into the next line in xMethod(1), printing 1. This will then repeat until xMethod(5) is exited.
If you went and expanded each xMethod as it was called, the code would look something like this:
{
nA = 5 // What n was set at first
if (nA>0){
{
// Instead of xMethod(n-1),
// we're setting nB to nA - 1 and
// running through it again.
nB = nA - 1 // nB is 4
if (nB>0){
{
nC = nB - 1 // nC is 3
if (nC>0){
{
nD = nC - 1 // nD is 2
if (nD>0){
{
nE = nD - 1 // nE is 1
if (nE>0){
{
nF = nE - 1 // nF is 0.
if (nF>0){
// This will never execute b/c nF is 0.
}
}
System.out.print(nE + " "); // prints 1
}
}
System.out.print(nD + " "); // prints 2
}
}
System.out.print(nC + " "); // prints 3
}
}
System.out.print(nB + " "); //prints 4
}
}
System.out.print(nA + " "); //prints 5
}
}
1 public static void xMethod(int n){
2 if (n>0){ //the base condition
3 xMethod(n-1); //function is again called with one value less than previous
4 System.out.print(n + " "); //now print
5 }
6 }
Now look at line#3, As nothing is printed but the function is again called, so from line#3, the call reaches to line#1 again. which means, n was 5, but the new call takes n = 4 and it keeps going till line#2 tells that n is now less than 0.
When if condition fails at line#2, it reaches at line#5 and then line#6 which means the function has ended execution, and n = 1 at this time.
Now where should the call be returned? at line#3 where the last function was called and it will be popped out from stack executing line#4 which prints the value of n i.e. 1 2 3 4 5.
this
xMethod(n-1);
System.out.print(n + " ");
should be:
System.out.print(n + " ");
xMethod(n-1);
this is the right code
System.out.print(n + " ");
xMethod(n-1);

How to display a 2D table in java

I try do disply a 2 D table but for some reason I can't, I don't see what i wrote wrong.
This is my code (I am working in vim):
int [][] tab = new int [5][5];
for (int i= 0; i<tab.length ; i++){
for (int j =0; j<tab[i].length; j++){
tab[j][i]=i;
System.out.println("" + tab[j][i]);
}
System.out.println("");
}
}
The result of this code is:
0
0
0
0
1
1
1
1
2
2
2
2
3
3
3
3
4
4
4
4
And i want:
0
0
0
0
1
1
1
1
2
2
2
2
3
3
3
3
4
4
4
4
Can someone help me with this?
Thank you
In the inner loop, replace: -
System.out.println("" + tab[j][i]);
with: -
System.out.print(" " + tab[j][i]);
since you want to continue printing in the same row.
The problem is that System.out.println("" + tab[j][i]);
print a whole line in your output, if you change the
System.out.println("" + tab[j][i]);
with
System.out.print(tab[j][i] + " ");
adding a blank space, you will print the String in the line but it wont break and
start in a new line. Try what #Rohit Jain post, this is a correct solution...
You need to change the code
int [][] tab = new int [5][5];
for (int i= 0; i<tab.length ; i++){
for (int j =0; j<tab[i].length; j++){
tab[i][j]=i;
System.out.print( tab[i][j]+" ");
}
System.out.println("");
}
Cause your outer loop run for every row and the inner for every column. So you must use tab[i][j] (the convention is tab[row][col]) to make the code error free. And here in your case you have equal rows & columns. But problem may arise when they are different.

Categories

Resources