Nested for loop for a triangle - java

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();
}
}

Related

Java - my while loop works, but my for loop doesn't - having trouble converting it

I assume that if I can't convert my while loop into a for loop, then I don't fully understand the concepts here. Here's my working while loop:
(I am trying to implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = Integer.valueOf(scanner.nextLine());
int sum = 0;
int i = 0;
while (i < number) {
i++;
sum += i;
}
System.out.println(sum);
I was looking at this user's answer here: https://stackoverflow.com/a/36023451/11522261
and tried to implement it, but it's not working.
.....
for (i = 0; i < number; i++){
sum += i;
}
System.out.println(sum);
It looks like the conditions of For Init expression statement and ForUpdate are set right, but I'm having trouble understanding the differences here.
Also, it looks like this exercise is trying to teach loops to solve iterative problems. But I suspect that this isn't helping me practice recursion. Perhaps there is a recursive solution to this problem which would be better. Just thinking out loud here. Thanks!
The difference is that in your while loop, you're incrementing i before adding it to sum, but in your for loop, it's after.
If the while is producing the right result, you can adjust your for by starting at 1 instead of 0 and continuing while <= number instead of < number.
For completeness, here's how your current for loop works:
i = 0
If i < number is not true, exit the loop; otherwise, continue to Step 3
sum += i (i is still 0)
i++
Goto Step 2
On the second pass, i < number is 1 < number so still true if number is greater than 1, so you go to Step 3, do sum += i while i is 1, then continue.
Eventually i < number isn't true anymore, and the loop exits.
For problems like this, the best approach is usually to use the debugger built into your IDE to step through the code statement by statement, looking at the values of variables as you go. That can reveal how things work really well. This article may be helpful: How to debug small programs
Since you are incrementing the value of i before adding it to sum in the while loop, the same thing needs to be done in case of for loop as well. Given below is the implementation using the for loop:
for (i = 0; i++ < number; ){
sum += i;
}
System.out.println(sum);
Use <= instead of <. This will solve Your problem, and make sure you understand why will the following code would work. I would recommand you to use a paper and pencil and start writing down the values of i and sum after every iteration.
for (i = 1; i <= number; i++) {
sum += i;
}

Java - For loop seems to execute past it's termination condition

I have debugged this code and it appears to run a for loop even though the termination condition is met.
This program takes two types of input:
Line 1 - How many data points there are following (N)
Lines 2 to N - The data points
The program should then print the smallest difference between all of the data points.
So, for instance, a sample input would be (on separate lines): 3 5 8 9
There are 3 data points (5 8 9), and the smallest difference is between 8 and 9, so the program should return 1.
I am trying to build the program in a way in which the data points are populated into an array at the same time as the comparisons are made. Obviously I could separate those concerns, but I am experimenting. Here it is:
package com.m3c.vks.test;
import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); //How many data points there will be
int strengthArray[] = new int[N]; //Initialise the array to be of length = N, the first input line
int tempStrengthDifference=99999; //junk difference set arbitrarily high - bad practice I know
int lowestStrengthDifference=99999;
for (int i = 0; i < N; i++) //Go through all elements of array
{
strengthArray[i] = in.nextInt(); //read a value for the ith element
System.out.println("i: " + i); //test
if (i > 0) //do not execute the next for loop if i = 0 as cannot evaluate sA[-1]
{
for (int j = i - 1; j < 1; j--) // **this is line 20** from wherever the array has populated up to, work backwards to compare the numbers which have been fed in thus far
{
System.out.println("j: " + j); //test
tempStrengthDifference = Math.abs(strengthArray[i] - strengthArray[j]); //finding the difference between two values
if (tempStrengthDifference < lowestStrengthDifference) //store the lowest found thus far in lowestSD
{
lowestStrengthDifference = tempStrengthDifference;
}
}
}
}
System.out.println(lowestStrengthDifference);
}
}
Everything is fine up until when i = 1 on line 20. At this point, j is set to i - 1 = 0 and the difference is found. However, when the for loop comes back around again, the termination condition of j < 1 is not met, and instead the loop continues to set j = -1, at which point it throws an out of bounds error as it clearly cannot evaluate strengthArray[-1]
Any ideas? Thanks
Have a look at your loop: for (int j = i - 1; j < 1; j--)
You start with j = 0 when i == 1 and thus j < 1 is ok.
The next iteration has j = -1 (0-1) and hence you get the problem.
Do you mean to use j >= 0 as your loop condition instead? Note that the second parameter is not a termination condition but a continuation condition, i.e. as long as that condition is met the loop will execute.
The reason behind your failure is the inner loop variable change.
When i=1, j=0 and after executing the loop once, J is decremented, and thus j becomes - 1. The condition j<1 is satisfied since you have written j--, change it to j++ and you should be fine.

What is this Nested For Loop doing? (Asterisk Right Triangle)

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();

two loops in a function?

Is it possible to have two loops in a function?
public static void reduce(Rational fraction){
int divisorNum = 0;
int n = 2;
while(n < fraction.num){
if(fraction.num % n == 0){
divisorNum = n;
System.out.println("n: " + divisorNum);
n++;
}
}
int divisorDenom = 1;
int m = 2;
while(m<fraction.denom){
if(fraction.denom % m == 0){
divisorDenom = m;
System.out.println("m: " + divisorDenom);
m++;
}
}
}
I'm trying to get the greatest common denominator. I know this is the very long way about doing this problem but I just wanted to try having two loops. When I call this function, only the first loop gets printed and not the second. I originally had an if statement, but seeing that the second loop doesn't execute I figured that I fix this part first.
Here's my other part of the code:
public static void main(String[] args){
Rational fraction = new Rational();
fraction.num = 36;
fraction.denom = 20;
reduce(fraction);
}
Absolutely. There are no limitations
Watch your conditional test = is not quite ==
Based on your edit I suspect fraction.denom is initialized at 1 or 0
Hence you will never get in the second loop
You can have any number of loops in your function :-
1.You can have nested loops;
2.Two loops side by side.
SO,your piece of code is fine enough considering the value of n, until the conditions for loop execution are met :-
public static void ....
while(n<x){
do this
add to counter
}
while(m<x){
do this
add to counter
}
if(y==z){ // NOTE :- Here you have committed mistake, compare using ==, not by =(it will be always true else and your condition will always be met else)
print this
}
Yup. You even can have 3 if you try hard enough.
EDIT: The didactic version:
Loops, as the name suggest, are constructs that allow you to repeat blocks of code several times (post conditional loops -> until certain condition is met keep running, pre conditional loops -> if certain condition is met, keep running). This is often called "iteration". So in a typical for-loop:
for ( int i = 0; i < 10; ++i )
print(array[i]);
You can say you're "iterating" over the array 10 times.
This has nothing to do with functions. You can have several loops inside a function, or functions being called inside loops. As long as you define your "blocks" of code (with begining and ending braces) you do what you think its best.
Yes, there are no limitations when it comes to looping. You could do 1000 while loops if you wanted.
An example here could be doing something like making a square out of *...
Here's an example
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("*");
}
System.out.println();
}
It would look like:
****
****
****
****

Nest Loops, Cannot figure out how to code this

Hey I have a question I have been trying to figure out for a couple hours now, I need to use nested loops to print the following
-----1-----
----333----
---55555---
--7777777--
-999999999-
This is what I have so far.
public static void Problem6 () {
System.out.println("Problem 6:");
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= 9; j += 2) {
System.out.print(j);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
This is what it prints
-----13579-----
----13579----
---13579---
--13579--
-13579-
You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:
Which loop prints out the numbers?
The 2nd nested for loop.
What does it do?
It prints out j where j ranges from 1 to 9 and j is incremented by 2 each iteration of the loop. In other words, 1, 3, 5, 7, 9, which is confirmed in your output
What do you want it to do?
Well let's look at the desired output. You want 1 to be printed once on the first first line. You want 3 to be printed three times on the third next line. You want 5 to be printed five times on the fifth next line after that. And so on.
Do you notice a pattern? You want that loop we mentioned above to print the same number (1, 3, 5, ... i) as the number of times (1, 3, 5, ... i).
edit Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still 3 three times, 5 five times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.
Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.
These for loops
for(int i=1;i<=9;i+=2)
{
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
System.out.println();
}
print
-----1-----
----333----
---55555---
--7777777--
-999999999-
public class pattern
{
public static void main ( )
{
for (int i = 1;i<=9;i+=2)
{
for(int b = 9;b>=i;b-=2)
{
System.out.print(" ");
}
for(int j =1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}

Categories

Resources