nested loops and increment user input - java

I'm trying to print user input numbers and indent them by that number of spaces. I can't seem to get the numbers to indent, however, I am able to print them all vertically. Any help? Here is my code.
for (i = 0; i <= userNum; i++) {
for (j = 0; j < i; j++) {
System.out.println(i);
break;
If a user entered the number 3, my output would currently look like this:
1
2
3
When it should look like this:
1
2
3

This should do it
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}

You can try to add another for loop within that for loop. The print statement would be after this nested for loop. The inner loop would start from zero to i+1. In this for loop, you can print the spaces or tabs. Then after the for loop you can print the number. Make sure you do not include a new line inside the print statement in the inner for loop.

You haven't added the code yet to add the indenting. Try this:
public static void printNum(int userNum) {
for (int i = 0; i < userNum; i++) {
System.out.print(" ");
}
System.out.print(userNum+ "\n");
}
Calling it with:
printNum(10);
printNum(1);
printNum(2);
printNum(3);
Gives the following:
run:
10
1
2
3
BUILD SUCCESSFUL (total time: 0 seconds)

I hope this solves your problem :
for (i = 1; i <= userNum; i++)
System.out.format("%+(i-1)+s]%n", i);

public class Program {
public static void main(String[] args) {
int i = 3; // or your userNum
// this loop will iterates through 1 to i (or 1 to userNum for you)
for (int j = 1; j <= i; j++) {
// this loop iterates until j2 equals j (e.g. if j = 5, this loop will iterates 4 times)
for (int j2 = 1; j2 < j; j2++) {
// prints the space(s)
System.out.print(" ");
}
// prints the current number (in the first loop) and line break
System.out.println(j);
}
}
}

Related

Numerical triangle using java

How do I stop the loop if the number reaches the n? i tried the break; but the loop still doesn't stop.
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
for(i = 1; i <= n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
if(number >= n){
break;
}
}
System.out.println();
}
input: 9
expected output:
1
23
456
789
or
input: 12
expected output:
1
23
456
78910
1112
Break and Labeled break should be avoided in code. So you can use loops as below:
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter input number:");
int n = in.nextInt();
System.out.println("You have entered : " + n);
for (int i = 1, k = 1; k <= n; i++) {
for (int j = 0; j < i && k <= n; j++, k++) {
System.out.print(k);
}
System.out.println();
}
}
Printing k variable which is initialized in outer and updated in inner loop.
Putting condition to break inner and outer loop to check k with input variable
EDITED : To understand it better:
i variable is used to maintain the number of rows we need to print.
j variable is used to maintain the number to elements to print in each row.
In most of placed the value which is being print is in context with either row number or element number in row, but here print value is not in sync with it, so we are maintaining it in 2rd variable k.
Use the labeled break statement and you can break from the nested loop:
loop:
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
System.out.print(number);
++number;
if (number > n) //not (number >= n)
{
break loop;
}
}
System.out.println();
}
There are many ways of doing this. The most straightforward one is to use a label to break out of several loops at once:
outer: for(i = 1; i <= n; ++i) { // a label is a word followed by :
inner: for(j = 1; j <= i; ++j) { // you can declare labels without using them
System.out.print(number);
++number;
if(number >= n){
break outer; // break inner would be equivalent to what you had
}
}
System.out.println();
}
However, these break statements with labels look suspiciously similar to gotos, and gotos are frowned upon. A more teacher-friendly version would be to use a boolean flag, and check the flag in each loop:
boolean finished = false;
for(i = 1; i <= n && ! finished; ++i) {
for(j = 1; j <= i && ! finished; ++j) {
System.out.print(number);
++number;
if (number >= n) {
finished = true; // no need to break - loops condition will now be false
}
}
System.out.println();
}
Note that this introduces an extra newline, which you generally want to make sure that whatever you print next appears on a different line.
Another option is to simply complicate your initial condition, without any flags:
for(i = 1; i <= n && number < n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
}
System.out.println();
}
I would recommend, for readability purposes, version 2. Additionally, I would write it as follows:
boolean finished = false;
for(int i = 0; i < n && ! finished; ++i) {
for(j = 0; j < i && ! finished; ++j) {
System.out.print(number++);
if (number >= n) {
finished = true;
}
}
System.out.println();
}
The key differences are using 0 to n-1 counting to repeat something n times (most programmers are very accustomed to that, instead of counting from 1 to n), and defining loop variables within the for, so that trying to use them outside of their loops is an error. This helps to avoid accidental reuse of variables.
import java.util.Scanner;
public class Tester{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
loop:
for ( i = 1; i <= n; ++i){
for ( j = 1; j <= i; ++j){
System.out.print(number);
++number;
if (number > n)
{
break loop;
}
}
System.out.println();
}
}
}
by using a for loop with a nested one you can achieve it like this:
you have a row which is incremented by 1 on each row (line)
you have a column variable which is increasing by one on each line or row
you have a number with start to print from 1 till the inputed number for example it was entered 12.
in inner loop you need to check the column be less or equal to row and the incremented number be less the entered number.
Scanner in = new Scanner(System.in);
System.out.print("Enter a Number: ");
int n = in.nextInt();
int number = 1;
for (int row = 1; row <= n && number <= n; row++) {
for (int column = 1; column <= row && number <= n; column++) {
System.out.print((number++) + " ");
}
System.out.println();
}

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

Can't figure out For Loop

I have recently started java, so I unfortunately am terrible at this. I have an question about a for loop question that was asked in my class today, but I can't figure out a part of it.
We were supposed to print out:
__1__
_333_
55555
with only for loops.
I have started the code but can't figure out what to do to print out the numbers, though I figured out the spaces.
public class Question{
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=?; k<=?; k??){
System.out.print(???);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
The question mark are the place where I don't know what goes in there.
Thanks.
You can do something like this,
class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 1; i <= 3; i++) {
for (j = 2; j >= i; j--) {
System.out.print("_");
}
for (k = 1; k <= (2 * i - 1); k++) {
System.out.print(i * 2 - 1);
}
for (j = 2; j >= i; j--) {
System.out.print("_");
}
System.out.println();
}
}
}
The first for loop will print the _ before the number, second one will print the number and 3rd one will print the _ after the number
The values are changing by two each time j increments, that leads to the formula 1 + (2 * (j - 1)) which is how you can finish your loops. Like,
for (int j = 1; j <= 3; j++) {
for (int i = 1; i <= 3 - j; i++) {
System.out.print(" ");
}
int n = 1 + (2 * (j - 1));
for (int k = 1; k <= n; k++) {
System.out.print(n);
}
for (int m = 1; m <= 3 - j; m++) {
System.out.print(" ");
}
System.out.println();
}
Outputs
1
333
55555
Thanks everyone for helping. I figured out the answer.
public class Welcome {
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=1; k<=(2*j-1); k++){
System.out.print(2*j-1);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
}
}
This can also be achieved as below
public class ForLoopPrinter {
public static void main(String[] args) {
int number = 1;
int row = 3;
int column = 5;
char space = '_';
for(int i = 1; i <= row; i++){
for(int j = 1; j <=column;j++){
int offset = (column - number)/2;
if( j <= offset ||
j > (number + offset)){
System.out.print(space);
}else{
System.out.print(number);
}
}
System.out.println();
number += 2;
}
}
}
Here number of For loops are limited to 2 (one for row and one for column).
Logic goes like this -
offset provides you number of spaces to be printed at both sides of number.
first if condition checks if j (position) is below or above offset and if true it prints underscore and if false it prints number
I know that right answer has been given for this question and it will work like charm. I just tried to optimise code by reducing number of For Loops in answers provided before. Reduction of For loop will improve performance.
Apart from reduction of For loops, this code has following advantage
- This code is more scalable. Just change row, column values (e.g. 5,9) or space char to '*' and check output. You can play with it.
I would suggest you to go with answer given by #Sand to understand For loop and then check this answer to understand how you can optimise it.

Nested for loops 0123

I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}

Upside-down triangle of numbers

I'm a beginner to Java and can't figure out how to print an upside down triangle of numbers. The numbers should decrease in value by 1 for each row. Ex. Number of rows: 6;
Print:
666666
55555
4444
333
22
1
So far this is what I came up with; (int nr is scanned input from user)
for (int i = 1; i <= nr; i++) {
for (int j = 1; j <= nr; j++) {
System.out.print(nr);
}
nr--;
System.out.println();
}
By having nr--; the loop gets shorter and I cant figure out how to keep the loop going for nr-times, yet still decreasing the amount of numbers printed out.
You are right in that you need to write a loop to print a line for each number, starting at nr and decreasing by 1 until you get to 0. But you also have to print a variable number of numbers at each line. To do that, a nested loop could be used to print the number the amount of times necessary.
Since you start printing at nr and decrease until you reach 1, you could try writing an outer loop that decrements rather than increments. Then use a nested loop to print the number the required number of times. For example:
for (int i = nr; i > 0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
In this case, you can use a single while loop and two decreasing variables:
i - number of the row - from 6 to 1
j - number of repetitions in the row - from i to 1:
int i = 6, j = i;
while (i > 0) {
if (j > 0) {
// print 'i' element 'j' times
System.out.print(i);
--j;
} else {
// start new line
System.out.println();
j = --i;
}
}
Output:
666666
55555
4444
333
22
1
See also: Printing a squares triangle. How to mirror numbers?
You can't decrease nr and still use it as upper limit in the loops. You should in fact consider nr to be immutable.
Instead, change outer loop to count from nr down to 1, and inner loop to count from 1 to i, and print value of i.
for (int i = nr; i > 0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
Your problem is that you are changing nr, try:
int original_nr = nr;
for (int i = 1; i <= original_nr; i++) {
for (int j = 1; j <= nr; j++) {
System.out.print(nr);
}
nr--;
System.out.println();
}

Categories