Very basic Java nested for loop issue - java

I'm having a hard time trying to get this code to start at 5 spaces and reduce to 0 spaces, subtracting a space every line.
public class Prob3 {
public static void main(String[]args) {
for (int x=1; x<=5; x++)
{
for (int y=5; y>=1; y--)
{
System.out.print(" ");
}
System.out.println(x);
}
}
}
Current output is (should be 5 spaces):
5
4
3
2
1
I'm happy with the progress so far but I need to get something closer to this:
1
2
3
4
5
I feel like I'm pretty close

Change your inner loop to:
for (int y=5; y > x; y--)
You would notice a pattern in the number of whitespaces on each row:
Row 1 = 4 whitespaces
Row 2 = 3 whitespaces
Row 3 = 2 whitespaces
so on..
So, the pattern is, the number of whitespaces is 5 - rowNumber. In your code the outer loop denotes the rowNumber. And the inner loop should run 5 - rowNumber of times. That is why the condition should be y > rowNumber, i.e. y > x.

Change your inner loop to this:
for (int y=5; y>x; y--)
Full Code:
for (int x=1; x<=5; x++)
{
for (int y=5; y>x; y--)
System.out.print(" ");
System.out.println(x);
}

Inner for loop expression should be:
public class Prob3 {
public static void main(String[]args) {
for (int x = 0; x < 5; x++) {
for (int y = (4 - x); y > 0; y--) {
System.out.print(" ");
}
System.out.println(x + 1);
}
}
}
The problem was that you were starting at 5 each time. The (4-x) in the inner loop is so that the last number (5) has 0 leading spaces.

Related

how do i get rid of the zero that shows up after all my elements in my array are listed?

i have to make a program that prints out the elements of an array filled with random numbers backwards but it also prints out a zero after my variables? i think it has something to do with my for-loops but i get a java.lang.ArrayIndexOutOfBoundsExceptionerror any time i try to change them.
edit: i also noticed that the first printed element is always zero. i don't really see it as a problem but what could be causing that?
import java.util.*;
public class EZD_printBackwards
{
static int vars[] = new int[10];
static int backwards()
{
Random rand = new Random();
int bkwds = vars[0];
for (int a = 0; a < 10; a++)
{
vars[a] = rand.nextInt(100)+1;
}
for (int x = 10; x > 0; x--)
{
System.out.println("Element " + x + " is " + vars[x] );
}
return bkwds;
}
public static void main(String Args[])
{
int option;
Scanner kbReader = new Scanner(System.in);
do
{
System.out.println(backwards());
System.out.print("Type 1 to run again. Type 0 to end the program.");
option = kbReader.nextInt();
while(option !=1 && option !=0)
{
if (option != 1 && option != 0)
{
System.out.print("Please enter 1 to run again or 0 to end the program.");
option = kbReader.nextInt();
}
}
}while(option==1);
System.out.println("");
}
}
In your example, vars is size 10. The second for loop starts at index x = 10 which is greater than the last index of vars because array index starts at zero. To fix the issue, you should use this condition in your for loop:
for (int x = vars.length -1; x >= 0; x--)
{
System.out.println("Element " + x + " is " + vars[x] );
}
You have two problems:
FIRST => For loop out of bounds
you want to go through 10 elements, therefore your
for (int x = 10; x > 0; x--)
should be
for (int x = 9; x >= 0; x--)
0..9 is 10 elements and the same things goes for
for (int a = 0; a < 10; a++)
to
for (int a = 0; a < 9; a++)
SECOND ==> 0 at the end
That's because you do
System.out.println(backwards());
instead of
backwards();
you are returning the value of "bkwds", and you are initializing "bkwds" with vars[0] , and i guess in java the compiler initialize all the values of an array with 0 ,
in other words your probleme is in System.out.println(backwards());
remove it with
backwards();
and it should work !
EDIT
your look is out of bound either replace it with this
for (int a = 0; a < 10; a++)
or
do this
for (int a = 9; a > 0; a--)
The range of your Array is from 0 up to and including 9. Your for loop, however, is starting from 10 and coming down to index 1. It should start from 9 and comes down to index zero. This, however, does not explain printing random 0! The reason for these zeros is you have an int bkwds which youb set to vars[0] at the beginning of your function. But, since it is not initialized, it will be set to 0 (the default for int) In your main, you call the function in a print statement, which I suppose keeps printing that falsely, useless initialized variable that you return :)
As arrays are indexed from zero, change to
System.out.println("Element " + x + " is " + vars[x-1] );
output
Element 10 is 31
Element 9 is 63
Element 8 is 82
Element 7 is 46
Element 6 is 67
Element 5 is 24
Element 4 is 3
Element 3 is 27
Element 2 is 37
Element 1 is 13
edit
And change this
System.out.println(backwards());
to
backwards();
As the return value of this method is useless and not used, change this method to return void

Java For Loop Practice

Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}

Understanding the for loop in Java

I'm new to Java.
I can't seem to understand why these two codes produce different outputs.
Please explain this to me.
What is the difference of y<=x; and y<=5;. As you can see the x is 5 too, I don't understand why I get different outputs.
for (int x = 0; x < 5; x++) {
for (int y = 1; y <=x ; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
*****
x****
xx***
xxx**
xxxx*
Code:
for (int x = 0; x < 5; x++) {
for (int y = 1; y <= 5; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
xxxxx*****
xxxxx****
xxxxx***
xxxxx**
xxxxx*
Basically the main difference is this line:
for(int y=1; y<=x; y++)
resp.
for(int y=1; y<=5; y++)
The number of times the loop is executed is different. Namely in the first case it is variable (so the number of 'x' increases), in the second case it is fixed (5 'x' printed each time).
(edit: typo)
xstarts at 0 so the first iteration has the condition y<=0, the second will have y<=1 and so on .. till y<=5
While the second one will have y<=5in every iteration, thats why you get xxxxx in every line.
In the first code you print x times the "x" String in each row.
for(int y=1; y<=x; y++) {
System.out.print("x");
}
BTW, it prints the following (which is different than what you claim in the question):
*****
x****
xx***
xxx**
xxxx*
In the second code you print 5 times the "x" String in each row.
for(int y=1; y<=5; y++) {
System.out.print("x");
}
As you can see the x is = 5 too
No, x iterates from 0 to 4, so in each iteration of the outer for loop, it has a different value.
In your first code your for(int y=1; y<=x; y++) for iterations of outer for loop is -
for(int y=1;y<=0;++y) (for first iteration of outer loop)
for(int y=1;y<=1;++y) (for second iteration of outer loop)
for(int y=1;y<=2;++y) (for third iteration of outer loop)
for(int y=1;y<=3;++y) (for fourth iteration of outer loop)
for(int y=1;y<=4;++y) (for fifth iteration of outer loop)
But in your second code its always -
for(int y=1; y<=5; ++y)
for all iterations of outer for loop.
It is very simple the will run for 5 time times and every itreation its value will be increamented by 1 i.e. from 0 to 4.
So in first loop inner loop will have the condition like this:
for (int y = 1; y <= x; y++) {
System.out.print("x");
}
But since in first loop the value of x is 0 hence it literally means:
for (int y = 1; y <= 0; y++) {
System.out.print("x");
}
But in the last iteartion of outer loop the value of x is 4 hence this is equivalent to:
for (int y = 1; y <= 4; y++) {
System.out.print("x");
}
So it iterates 4 times.
In your first example y is first less than x = 1 and during the next iteration it will be less x= 2 ... Because x values changes with your first for loop.
For the second example however you state that y have to be less than 5 which doesn't change at all.
They are different because in the first case your x varies from 0 to 4 based on :
for(int x=0; x<5; x++)
In the case second case x is fixed at 5.
I have replaced your two inner for loops with a new stringRepeat function. It might be easier to understand this way.
public class ForLoopStarsAndCrosses {
public static void main(String[] args) {
/// the total length ot the x's and stars
final int length = 5;
// start with 1 x until one less than the length (in this case 4)
for(int x = 1; x < length; x++) {
// the number of stars equals the total length minus the number of x's
final int nbStars = length - x;
// add the x's and the stars
final String output = stringRepeat("x", x) + stringRepeat("*", nbStars);
System.out.println(output);
}
System.out.println();
}
/** Repeat the string s n times */
private static String stringRepeat(String s, int n) {
String result = "";
for (int i = 0; i < n; i += 1) {
result += s;
}
return result;
}
}
Firstly, you should understand the difference between value and variable. Value is a constant as you write 5 but variable can be changeable.
For your question, first code and first round:
x = 1, y<= 1 and output: x
for(int y=1; y<=x; y++){
System.out.print("x");
}
but for the second code and first round:
y<=5 so output is: xxxxx
for(int y=1; y<=5; y++){
System.out.print("x");
}
it is very simple.
The purpose of loops (can be for, while, do-while) is that, how many number of times the same set of statements to be executed under a specific condition. "for" is a definite loop where there will be an index starting with an integer, keep increment it until the condition is achieved. "while" is a indefinite loop where there is no index and it will be executed until the condition is achieved. "do-while" is a loop similar to "while", which will be executed atleast once and then validates the condition for the next iteration.
Based on the above details,
for(int x=0; x<5; x++){
for(int y=1; y<=x; y++){
for(int x=0; x<5; x++){
for(int y=1; y<=5; y++){
The diff between these two conditions is that,
First condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with x which is 0 and 1<=0 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x.
Second condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with 5, 1<=5 which is true, this condition is valid and the statements under Y will be executed and the control will go back control of x until y becomes 6 and condition checked is 6<=5 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x
Note: Due to low reputation, I can't add comments and had to contribute this as an answer. Don't downvote this, instead suggest corrections by comment on the same.

how to print a number triangle in java

I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)  
{          
System.out.print(i); 
}      
System.out.print("\n");        
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){

Explaining output in a for loop

I'm a novice in Java programming and I'm trying to guess why the output of the following code:
public class ForLoop {
public static void main(String[] args) {
int x;
for (x=1; x<=2; x++) {
x += 3;
}
System.out.print(x);
}
}
is 5 and not 7! For the first iteration, 1 is added to 3 (result: 4) and it is stored in the variable x so x is 4. In the second iteration, we add 3 to 4 and we must obtain 7. The error might be easy to find but I can't catch it. Please help and thanks.
This part:
for (x=1; x<=2; x++)
means that x will be incremented at the end of each iteration. So, in the first iteration, 3 is added to x because of this:
x += 3;
which results in a value of 4. Then, at the end of that iteration, x is incremented by 1, which comes to 5. Since 5 is greater than 2, the loop is then closed.
Big problem here using x as your iterator and your variable to update. This is what the computer is evaulating.
When you are inside the for loop, x is initially 1, then you add three to it, and then your iterator on the for loop adds 1 to it afterwards (making it five). At that point, your condition, (x<=2) is false for the for loop is complete.
change it to this and you will get your desired result:
public class ForLoop {
public static void main(String[] args) {
int x = 1;
for (int y = 0; y <= 1; y++) {
x += 3;
}
System.out.print(x);
}
}
In first pass the body is carried out, there x becomes 4. Then the incrementation is carried out. (The 3rd parameter of for loop) which results x to be 5.
In the second pass the condition is unmet as x is already 5 there but less than or equals to 2 is required to run the loop. So instead the loop will discontinue and x will be printed 5.
The code
int x;
for (x=1; x<=2; x++) {
x += 3;
}
works as follows:
int x;
x = 1; // for-initialization
while (x <= 2) { // for-condition
x += 3; // for-body
x++ // for-increment
}
Particularly:
the condition is tested before the loop body, and in your case
the loop body has an effect on the condition.
After the first iteration x is 4 as you say, but then x++ is executed, so x becomes 5. 5 is bigger than 2 (x<=2), so iteration stops.

Categories

Resources