I just started learning about "nested for loops". But my question what is the nested for loop exactly doing every time it loops? I'm still confused as to what is variable "i" is doing and what is variable "j" is doing. If you can explain what is happening after every loop, it would make nested for loops much clearer.
import java.util.Scanner;
public class LoopStatement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numStar;
System.out.print("Number of stars: ");
numStar = input.nextInt();
while (numStar < 1 && numStar > 20) {
System.out.println("Enter a valid number ");
numStar = input.nextInt();
}
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
So this is the output I get if I input 4 for numStar
*
**
***
****
There is actually nothing special about nested loops, they behave exactly the same like regular loop.
Specifically here the outer loop loops from i being 1 to numStar and therefore prints numStar rows.
The nested loop loops from j being 1 to i where i is the number of current row being printed. In each iteration it prints one star and therefore altogether it prints i stars.
Therefore here it prints 1 star on row number 1, 2 stars on row number 2, etc.
Try writing down in a paper like this :
i=1 j=1 => *
i=1 j=2 => (j<=i) is false
.
.
i=2 j=1 => *
*
i=2 j=2 => *
**
.
.
You'll get the output if you try to write it in a paper.
In order to understand the nested loop you must understand the for structure. It sounds like you did not get it.
from the basics:
for (int i = 1; i <= numStar; i++) {
System.out.println(i);
}
the code above iterate exactly numStart following the steps:
a-Starts with i=1: int i = 1
b-Test condition: i <= numStar
c-Print the value of i in the screen: System.out.println(i)
d-increments i value: i++
It execute while the conditions is satisfied: i <= numStar. The steps c and d are executed only the condition is satisfied.
the tested loop follows the same logic:
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
when i=1 -> j iterates from 1 to 1. So it prints "*"
when i=2 -> j iterates from 1 to 2. So it prints "**"
when i=3 -> j iterates from 1 to 3. So it prints "***"
and so on...
After the nested iteration finish there is line break: System.out.println();
Related
I am trying to print an array in reverse order.
Here is the code:
import java.util.Scanner;
public class Main {
public static void main(String []argh) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
for (int j = n-1 ; j == 0; j--) {
System.out.print(arr[j] + " ");
}
in.close();
}
}
In this code nothing happened, but when I changed the second condition in the 2nd for loop from j == 0 to j >=0 it worked. I don't understand why . In j==0, isn't that supposed to decrement j until it becomes equal to 0?
for (int j = n-1 ; j == 0; j--) means that the loop will execute as long as j is equal to 0. Since j is initialized to n-1, the loop is never executed (assuming n != 1).
The second argument to a for loop is the loop condition: it specifies the condition under which the loop body will execute. The body will execute while the condition is true, not until it is true.
Note how your first for loop works: i starts at 0, and it loops while i < n. It's the same principle in your second loop, only your loop variable moves in the opposite direction: j starts at n - 1, and should loop while j >= 0.
All conditional loops in Java (while, for, and do-while) work in this way: they loop only as long as the condition holds, then they terminate, and execution picks up after the loop.
In j==0 the condition will be false, because j is given a value which is equal to n-1, j=n-1.
Suppose the value of n is 3, so j will be equal to 2 then it'll come to condition checking part in for loop, in that part you've written like this j==0, since j isn't equal to 2 so the condition will be false and it'll come out of the for loop.
for (int i = 1; i < 5; i++) {
int j = 0;
while (j < i) {
System.out.println("i = " + i + "\tj = " + j);
j++;
}
}
The output is:
i = 1 j = 0
i = 2 j = 0
i = 2 j = 1
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 4 j = 0
i = 4 j = 1
i = 4 j = 2
i = 4 j = 3
My question is, why is the value of j=0 in the second line, even though we increment it after the first line was displayed?
Also, why is the value of i=2 twice, and i=3 thrice?
you declared int j=0; within the first loop so whenever the outer loop runs value of j set to be 0.
And reason of repeated value of i is the inner loop.For every time the loop runs the value of i is same for it.
Because you said that "until j is < than i" you increment j but the increment stops when j is = i so you have that i repeats for each increment of j.
I'm a bit confused about what your program should do but if I understood you should resolve your code like this:
for (i = 0; i < 5; i++) {
int j;
for (j = 0; j < i; j++) {
System.out.println("i = "+i+"\tj = "+j);
}
}
Outer for loop re-initialzes j to 0 in second iteration of the outer loop as it does in every iteration of the outer loop. Hence second line shows j as 0.
Since in second and third iteration of outer for loop, inner loop gets executed twice and thrice respectively, but outer loop variable value remains the same during the iteration of the outer loop. Hence, i=2 and i=3 is shown twice and thrice.
The j-variable and the i-variable in your code are going like this:
i=2:j=0->1: prints 2 times
i=3:j=0->1->2 prints 3 times
...
This concept is called nested loops. The for-loop is the outer loop, which has value of i from 1 to 4. In the inner while-loop, the value of j is initialized to 0 and it goes till j = i-1 (since the condition mentioned in while-loop is j < i).
You enter the first iteration of for-loop (i = 1). Now you enter the first iteration of while-loop (j = 0). Condition is true (0 < 1). i = 1 j = 0 is printed. In next iteration of while loop, j = 1, condition is false (1 not < 1). Hence while-loop is now exited.
Now in the second iteration of for-loop, i value is incremented (i = 2). Now you enter the first iteration of while-loop (j = 0). Condition is true (0 < 2). i = 2 j = 0 is printed. In next iteration of while loop, j = 1, condition is true (1 < 2). i = 2 j = 1 is printed. In next iteration of while loop, j = 2 , condition is false (2 not< 2). Hence while loop is exited.
As you can see, in the first iteration of for-loop print is executed only once. And in the second iteration of for-loop print is executed twice. This is because execution of print is dependent on the value of j being lesser than i (i increases by 1 every time). This pattern will repeat and for i = 3 print statement will be executed thrice and so on.
Hope you understood. If not, feel free to clear your doubts in the comments.
I'm learning about Java loops and struggling to understand how an output was produced for a question regarding nested-for loops.
The code is:
for(int count = 0; count <=3; count++)
for(int count2 = 0; count2 < count; count2++)
System.out.println(count2);
The output produced was:
0
0
1
0
1
2
Can anyone please explain this as there isn't an explanation in the book like there usually is, thanks.
First loop variable: Count is looping to 3.
second loop variable: count2 is looping to count.
then you are printing the count 2. so first time you print nothing because 0 is not less then 0, and therefore stop right away because in that iteration count2 is not less then count. then count becomes 1, and at the time you are printing. Therefore you print 0. You follow this logic until count is <= 3, and count2 < count.
Here is a table that iterates through the loop: Hope this helped.
It is simple,Read this as
for(int count = 0; count <=3; count++) {
for(int count2 = 0; count2 < count; count2++) {
System.out.println(count2);
}
}
So when outer loop is 0,
inner loop will run 0 times as count2
So when outer loop is 1,
inner loop will run 1 times as count2<1 and hence it will run one time then count2 is incremented and so will fail and hence 0 as output
and similarly output continues till count is 3
Looking at
for (int count = 0; count <= 3; count++)
{
for (int count2 = 0; count2 < count; count2++)
{
System.out.println (count2);
}
}
You first enter the loop with count = 0;. Then the inner loop will not execute, since the initial condition is wrong (count2 < count is false since 0 < 0 = false). Then countincreases by one. The inner loop will then print all values which are strictly smaller than the outer loop variable (count). So if count = 1 the inner loop will print all numbers starting from 0 which are strictly smaller than 0, i.e. only 0 in that case. For count = 2, it will print 0,1 since these numbers are all strictly smaller than count. Same for count = 3, it prints the numbers 0,1,2. And that produces the output.
<No output from count = 0>
0 <from count = 1>
0
1 <from count = 2>
0
1
2 <from count = 3>
To understand this code change your code to following -
for (int count = 0; count <= 3; count++) {
for (int count2 = 0; count2 < count; count2++) {
System.out.print(count2 + " ");
}
System.out.println();
}
This will produce output as -
0
0 1
0 1 2
First of all your code would be clearer with curly braces and indentation :
for (int count = 0; count <=3; count++) {
for (int count2 = 0; count2 < count; count2++) {
System.out.println (count2);
}
}
Now the outer for loop will iterate 4 times with count getting values 0,1,2,3
the inner loop won't iterate for count == 0 so nothing is printed. For the values of count, count2 will be :
which explains the result you are getting
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++){
I'm a beginner in java & I really need this answer.
I have been trying to create a triangle in this sequence:
1
21
321
4321
54321
Even though my syntax is correct, I have been going through logical errors with non-terminating loops.
This is the program which I'm trying to fix:
for(i=1;i>=1;i++)
{
for(j=i;j<=i;j=j-1)
{
System.out.print(j);
}
System.out.println();
}
Help would really be appreciated for this.
You get non-terminating loop because of this
for(i=1;i>=1;i++)
The code means, you want to loop the body if i greater or equal than 1 (i>=1), and this i value are always incremented by 1 (i++) for each loop, so it always have value greater than 1 and this condition is always correct for the loop code. So you must correct the loop statement.
I am not sure I fully understood your problem but
the following code created a nice triangle for me.
int i,j;
for(i = 1; i>= 1 && i < 10; i++)
{
for(j = i; j <= i && j > 0; j = j - 1)
{
System.out.print(j);
}
System.out.println();
}
for(i=1;i>=1;i++) is not correct in this since increment on 1 will always result in number greater than 1 so the loop will end only after i = (2^31 -1) iterations. So for given output your loop should look like this:
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
Running through the loop
for(j=i;j<=i;j=j-1) (assume i is 2 for the example)
j=2, is 2<=2, yes:run loop
j=j-1 (j=2-1=1)
j=1, is 1<=2, yes:run loop
j=j-1 (j=1-1=0)
j=0, is 0<=2, yes:run loop
j=j-1 (j=0-1=-1)
j=-1, is -1<=2, yes:run loop
j=j-1 (j=-1-1=-2)
etc
j is getting smaller and smaller so it will always be less than 2.
i has exactly the reverse problem, its always getting bigger so it will always be greater than 1.
public static void main(String[] args)
{
for(int x=1;x<=5;x++)
{
for(int j=x;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}