Number Pattern Printing in Java - java

I'm newbie to programming. So as an exercise, I'm trying to print a number pattern like below
4
34
234
1234
I tried the below code
public static void main(String[] args) {
// TODO Auto-generated method stub
int n =4;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
System.out.print(" ");
}
int num = 4;
for (int j = 1; j <= i; j++) {
System.out.print(num);
num--;
}
System.out.println("");
}
}
but it is printing in this way.
4
43
432
4321
I think, I have to decrement the value before printing. Please correct me if i'm wrong. But I'm stuck here. Can anyone please help me?

This is the pattern you want to get:
4
34
234
1234
When you describe the pattern in words, it could look like this:
line 1 has 3 spaces, and then the digit 4
line 2 has 2 spaces, and then the digits 3 and 4
line 3 has 1 space, and then the digits 2 to 4
line 4 has 0 spaces, and then the digits 1 to 4
There is already some kind of pattern here. The last two lines look remarkably similar. Let's see whether the first two lines can be brought into the same form:
line 1 has 3 space(s), and then the digits 4 to 4
line 2 has 2 space(s), and then the digits 3 to 4
line 3 has 1 space(s), and then the digits 2 to 4
line 4 has 0 space(s), and then the digits 1 to 4
Now that looks good. The next step is to change the wording to depend on the given line:
line i has (4 - i) space(s), and then the digits (4 - i + 1) to 4
I took care not to say 5 instead of the 4 + 1, so that the 4 is still visible. Let's give this 4 another name:
line i has (max - i) space(s), and then the digits (max - i + 1) to max
Now you should be able to translate this instruction into Java code.

You only need one inner for-loop.
I use the ternary operator (also called elvis-operator because ?:) to decide whether to print the number or a blank space:
int n = 7;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(j > n-i ? j : " ");
}
System.out.println();
}
It prints
7
67
567
4567
34567
234567
1234567

You actually only need one nested loop in this situation:
int n = 4;
for (int i = n; i > 0; i--) {
for (int j = 1; j <= n; j++) {
if (j < i) {
System.out.print(" ");
} else {
System.out.print(j);
}
}
System.out.println();
}
So loop from 0 to n and either print a space, or print the number if the inner counter is less than i.
Output:
4
34
234
1234

Related

Printing a squares triangle. How to mirror numbers?

So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern

Decreasing number pyramid, nested for loop, user input, java

Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}

Java Looping Arrays

How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);

pascal triangle starting and ending with 1

Pasted below is a program to print Pascal's triangle. The way to compute any given position's value is to add up the numbers to the position's right and left in the preceding row. For instance, to compute the middle number in the third row, you add 1 and 1. the sides of the triangle are always 1 because you only add the number to the upper left or the upper right (there being no second number on the other side).
int pascal[][]=new int[50][50]; int j;
for(int i=0;i<m;i++)
{
pascal[i][i]=1;
for(j=1;j<i;j++)
{
pascal[i][j]=pascal[i-1][j-1]+pascal[i-1][j];
}
for(int n=1;n<=m-i;n++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(pascal[i][k]);
System.out.print(" ");
}
System.out.println(" ");
}
Is there any way to accomplish this without using arrays?
I'm trying this combination without arrays:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
You can easily compute it using Combination.
You can compute combination as:
|n| = (n!) / ((n-k)!*k!)
|k|
So if you want to print the image above you would start as:
int size = 5;
for(int i = 0; i < size; i++){
for(int k = 0; k < (size - i)/2; k++)
System.out.print(" "); // print the intendation
for(int j = 0; j <= i; j++){
System.out.print(combination(i,j));
}
System.out.println("");
}

java - looping through values

I am trying to create a nested for loops that will generate all the pairs in a range specified by the user, ranging from negative values to positive values. It is a little tough to explain, but here is the code I have:
public class test method {
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = 3;
int d = 4;
for (int i = -a; i <= a; i++)
for (int j = -b; j <= b; j++) {
System.out.println(a+" and "+b+" vs "+c+" and "+d+"\n");
}
}
}
Given command line arguments 1 and 2, my desired output would be something like:
-1 and -2 vs 3 and 4
-1 and -1 vs 3 and 4
-1 and 0 vs 3 and 4
-1 and 1 vs 3 and 4
-1 and 2 vs 3 and 4
0 and -2 vs 3 and 4
0 and -1 vs 3 and 4
0 and 0 vs 3 and 4
0 and 1 vs 3 and 4
0 and 2 vs 3 and 4
1 and -2 vs 3 and 4
1 and -1 vs 3 and 4
1 and 0 vs 3 and 4
1 and 1 vs 3 and 4
1 and 2 vs 3 and 4
I assume the lack of brackets in the first for is a problem in the copy & paste, but if that's your real code you've got a problem there.
a = Math.abs(a);
b = Math.abs(b);
for (int i = -a; i <= a; i++) {
for (int j = -b; j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");
}
}
Two things. First of all you should be printing i and j and second you should also consider negative values. Your for's will fail since -a if a = -1 will result in
for (int i = 1; i <= -1; i++)
The condition will not be met and the iteration won't take place. By doing Math.abs you get the absolute value of the inputs and you can do the iteration from that negative value to the positive one. If both a and b are positive the abs method will return the same values (assigning a and b with the same values they already have).
Whatever should be done with c and d remains to be seen. Your desired output says you leave them as they are so I won't touch them by now.
looks reasonable, exception for the '-a' business (and printing the wrong variables)
Assuming a/b are always positive, try
for (int i = (0-a); i <= a; i++)
for (int j = (0-b); j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");

Categories

Resources