Upside-down triangle of numbers - java

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

Related

The iteration variable is +1 outside the for-loop?

I have an array of size 4 and I want to check if the array contains the number 8 (which it obviously does not, the code is just for testing).
In the for-loop j goes from 0 to 3, so the final value of j in the loop is 3. However I don't follow why the value of j after the loop has been changed to 4, why is it still not 3?
public class Test {
public static void main (String[] args) {
int[] a = new int[4];
a[0] = 2;
a[1] = 3;
a[2] = 4;
a[3] = 5;
int n = a.length; // n = 4
int number = 8;
int j;
for (j = 0; j < n; j++) {
if (a[j] == number) {
System.out.println("The number is at place " + j);
break;
}
// Last value of j is 3:
System.out.println("Value of j after each iteration " + j);
}
// But here j is 4?
System.out.println("Value of j after the for-loop: " + j);
}
}
The output:
Value of j after each iteration 0
Value of j after each iteration 1
Value of j after each iteration 2
Value of j after each iteration 3
Value of j after the for-loop: 4
Yes because at the end of a for loop there is an increment to the variable. A for loop can be rewritten as:
int j = 0;
while(j < n) {
//code
j++;
}
So on the last iteration j will be incremented, it will go to the condition, and it will be false so the body of the for loop will not be entered. In order for the loop to end, j has to be more than or equal to the condition.
Think about it...
This is your for loop:
for (j = 0; j < n; j++){
//your code here
}
You start your for loop with j = 0 and every time you iterate through it, you have to check if the value is less than n ( j < n ).
To achieve that you have to increment it on every iteration.
So this is what happens for n = 4:
1st iteration:
j = 0;
0 < 4 == true;
// you execute your code
j++; //As you can see you increment before you continue to the next iteration
2nd iteration:
j = 1; // j now equals 1 because you incremented it on the previous iteration
1 < 4 == true;
// you execute your code
j++;
3rd iteration:
j = 2;
2 < 4 == true;
// you execute your code
j++;
4th iteration:
j = 3;
3 < 4 == true;
// you execute your code
j++;
5th iteration:
j = 4;
4 < 4 == false;
// loop ends
As you can see, when your code is about to start the fifth iteration, the j variable now equals 4 so it doesn't pass the j < n criteria.
However, it still incremented in the 4th iteration so you get j = 4.
This was how my teacher explained it to me when I was just starting my coding education, I hope it helps you as it helped me!
New to programming?
for(initialization; booleanExpression; updateStatement) {
; // Body
}
The steps is,
Initialization statement executes
If booleanExpression is true continue, else exit loop
Body executes
Execute updateStatements
Return to Step 2
So the end value should be 4

triangle of square numbers java

So i'll be as specific as I can here. My lab requires a java console app where the user can enter any number between 1 and 9. The computer will then print a triangle of each number squared, and the triangle has to be aligned on the right side of the screen. Here is the example:
1
4 1
9 4 1
16 9 4 1.
Here is my code thus far:
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = input.nextInt();
for (int i = 1 ; i <=n; i++) {
for (int j = n-i; j >=1; j--) {
System.out.print(" ");
}
for (int k = i; k <=i; k++ ) {
System.out.print(" " + i * i);
}
System.out.println(" ");
}
}
}
And here is my output:
1
4
9
16
My problem here is that I can repeat each number on each line and fully fill the triangle, but I cant figure out how to print the sqrt of each previous count without writing a million nested loops.
Any help I can get would be greatly appreciated.
Only the second inner loop needs to be adjusted a little bit (changes in bold):
for (int k = i; k >= 1; k--) {
System.out.printf(" %2d", k * k);
}
The first inner loop for indention runs n-i times, so the second inner loop have to do the rest: i..1.
And you have to print the square of the inner loop variable k instead of the outer loop variable i (which does not change in the inner loop).
The problem is in the loop limits for the second loop
for (int k = i; k <=i; k++ ) {
You initialize k to i, and then stop the loop when k > i. This can execute only once under a "standard" increment. You need to run k to the end of the line:
for (int k = i; k <=n; k++ ) {
I had to adjust and add a few more increment variable before the outer loop, and in the outer loop as well to subtract from the overall count and increment for each cycle of the inner loop.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = input.nextInt();
int num = 0, temp = 0;
for (int i = 1 ; i <=n; i++) {
int l = 0;
num++;
temp = num * num;
for (int j = n-i; j >=1; j--) {
System.out.print(" ");
}
for (int k = 1; k <=i; k++ ) {
System.out.print(" " + temp);
l++;
temp = i -l;
temp = (int)Math.pow(temp, 2);
}
System.out.println(" ");
}
}
}

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

nested loops and increment user input

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

Loop through a 2d array backwards

I need to loop through a 2d array backwards for a little map project I'm doing. I tried doing so based off of what I've read online, but my 2d array is different. How can I loop through this backwards?
for(int i = 0; i < map.length; i++){
for(int j = 0; j < map[i].length; j++) {
switch (nmap[j][i]) {
map[i][j] = new Tile();
}
}
}
To go the other way, you need to start the index at the highest value and decrease it for each iteration. Like this:
for (int i = map.length - 1; i >= 0; i--)
for (int j = map[i].length - 1; j >= 0; j--) {
switch (map[i][j]) {
map[i][j] = new Title();
}
}
Note that in both loops, we are starting from the highest index, map.length - 1 in the first and map[i].length in the second, and going down by one for each iteration until we reach the lowest index, 0 for both loops.
With for(int i = 0; i < length; i++), you're starting at the start (0), and going to the end (length).
To go the other way, just reverse everything:
for(int i = length - 1; i >= 0; i--)
Few things to note:
We have to do length - 1, or we'll start 1 past the end
We're using >= to include 0
We're decrementing i instead of incrementing it.
If you need it for a 2D array, just add a second of the above for the second dimension.
To go backwards , you need to read from the highest index to 0 . Highest index is typically length-1 since indices start from 0. Same goes for the inner j loop. Start from the highest index of map[i] i.e length -1.
eg. Array = [2 ,3,4,5,6]
Length =5 .Indices to iterate = 4 to 0 if backwards.
for(int i = map.length-1; i >= 0; i--) {
for(int j = map[i].length-1; j >= 0; j--) {
//your operation
}
}
Here you go.
for(int i = map.length-1; i >= 0; i--){
for(int j = map[i].length-1; j >= 0; j--) {
switch (nmap[j][i]) {
map[i][j] = new Tile()
}
}
}
Rather then going from 0 to map.length and 0 to map[i].length, this program starts at map.length-1 (so you don't ever get an index out of bounds error) and continues until it hits zero.

Categories