number pattern programs in java - java

How to print the triangle below:
2 3 5 8 3 8
4 6 9 4 9
7 1 5 1
2 6 2
7 3
4
First you need to start with number 2 and add one to the next one vertically
My code:
int d = 2, n = 6;
for (int line=1; line <= n; line++ ) {
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}
Result:
2 3 5 8 3 8
5 7 1 5 1
7 1 5 1
7 2 7
4 9
6

The pattern is that the value of d has to be calculated initially on every new line based on the value of d in the first instance of the previous line. That is the part that's missed here. You can do that by having a temp variable store the initial value of d on every line and print based on that. I have used a variable tempD here, which can help print the pattern that you require.
int d = 2, n = 6;
int tempD = d - 1;
for (int line = 1; line <= n; line++) {
tempD = tempD + line;
if (tempD > 9) {
tempD = tempD - 9;
}
d = tempD;
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}

Related

Invert incrementing triangle pattern

I am writing some code that creates a incrementing number right angle triangle that looks something like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
I am unsure on how to make my code output a triangle to that shape as my code outputs the same thing except inverted.
This is the code I have:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
My speculation is that instead of incrementing some of the values I would decrement them however the code would run infinite garbage values and not what I wanted.
It is needed to print some spaces before printing the numbers in each row, and the number of spaces should be decreasing depending on the row:
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = rows - i; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
This prefix may be build using String::join + Collections::nCopies:
System.out.print(String.join("", Collections.nCopies(rows - i, " ")));
Or since Java 11, this prefix may be replaced using String::repeat:
System.out.print(" ".repeat(rows - i));
Instead of two nested for loops, you can use a single while loop with two incrementing variables. The number of iterations stays the same.
int n = 7, i = 0, j = 0;
while (i < n) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
j++;
} else {
// print a new line
System.out.println();
j = 0;
i++;
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
See also: Optimized Bubble Sort
Your approach is almost correct - use two nested for loops, all that remains is to add one if else statement and calculate the sum of coordinates i and j.
Try it online!
public static void main(String[] args) {
int n = 6;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(" ");
int sum = i + j;
if (sum > n)
System.out.print(sum - n);
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: Printing a squares triangle. How to mirror numbers?
You can print an inverted triangle using two nested for-loops as follows:
// the number of rows and the
// number of elements in each row
int n = 6;
// iterating over rows with elements
for (int i = 0; i < n; i++) {
// iterating over elements in a row
for (int j = 0; j < n; j++) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
} else {
// print a new line
System.out.println();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: How to draw a staircase with Java?
You have to print spaces before printing the numbers to make the triangle look inverted, the number of spaces depends on the amount of numbers you skip which are rows-i, so you can loop from i to rows and print space in each iteration.
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
You can use the property that for the row containing i as the greatest number of the row the number of the spaces can be calculated as 2*(rows-i). You can rewrite your program like below:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int nspaces = 0; nspaces < 2 * (rows - i); ++nspaces) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1

Nested loop Confusion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
public class Exon303 {
public static void main(String[] args) {
int k = 109;
do {
for(int i = 3; i < 9; i = i * 2) {
if(k % i ==3) {
k = k / 3;
} else {
k = k / 2;
}
}
System.out.println(k);
} while(k > 0);
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int m = 0; m < i * 2; m++) {
if(m == j && m == i) {
System.out.println("i: " + i);
System.out.println("j: " + j);
System.out.println("m: " + m);
}
}
}
}
}
}
Can someone explain to me the output of these loops I created I've hand traced it twice now and for some reason, I am getting a different output when I trace it.
Expected output:
27
6
1
0
i: 1
j: 1
m: 1
Here is my handtraced output below
Handtraced output:
54
27
9
4
2
0
i: 0
j: 0
m: 0
i: 1
j: 1
m: 1
You was wrong in tracing your code by hand. Let me explain.
Separate your code to 2 parts. 1st part:
int k = 109;
do {
for(int i = 3; i < 9; i = i * 2) {
if(k % i ==3) {
k = k / 3;
} else {
k = k / 2;
}
}
System.out.println(k);
} while(k > 0);
You printed k outside of for loop, then k / 2 twice each for loop (i = 3, 6), after 1st while loop, k = (k / 2) / 2 = 27. It is the same with next while loops when k does not have any value that make k % i == 3. So next values of k in each while loop is 27/4 = 6 and 6/4 = 1. This is k, i values at beginning of each for loop:
---- while loop ----
k = 109, i = 3
k = 54, i = 6 => print k / 2 = 27
---- while loop ----
k = 27, i = 3
k = 13, i = 6 => print k / 2 = 6
---- while loop ----
k = 6, i = 3
k = 3, i = 6 => print k / 2 = 1
---- while loop ----
k = 1, i = 3
k = 0, i = 6 => print k / 2 = 0
----> k == 0, break while loop
2nd part:
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int m = 0; m < i * 2; m++) {
if(m == j && m == i) {
System.out.println("i: " + i);
System.out.println("j: " + j);
System.out.println("m: " + m);
}
}
}
}
The condition to print i, j, m values is m == j == i and i, j only have 2 values 0, 1, but the condition m < i*2 make for loop of m is ignored when i = 0 and m = 0. So the only output: i = j = m = 1.

Outer Loop isn't working (java)

I'm trying read a set of numbers from a file and then isolate the lines in between the first line (which lets us know how many lines will need to be worked on, in this case, 5) and the seventh line (mind you that this is just an example, the range of the lines will is subject to change) so that I can populate a list in the format of (0 1 98, 0 2 5, ...,4 3 15). Right now my code manages to get (0 1 98, 0 2 5, 0 3 16, 0 4 16) added into the list but not the rest. I'm not sure what I've done wrong. Any help would be much appreciated.
Example input:
5
0 1 98 2 5 3 16 4 16
1 0 13 2 47 3 3 4 40
2 0 71 1 51 3 43 4 30
3 0 20 1 94 4 46
4 0 1 1 10 2 28 3 15
2
2 3
2
0 1
public static void t() {
List<String> L = new ArrayList();
try {
BufferedReader f = new BufferedReader(new FileReader("graph.txt"));
String s = f.readLine();
int nodes = Integer.parseInt(s);
int c = -1;
int c1 = 2;
int c2 = 3;
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
for (int i = 0; i < L.size(); i++) {
System.out.println(L.get(i));
}
} catch (Exception ex) {
System.out.println(ex);
}
}
You just need to reset your C variables within the outer loop.
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
// Declare the variables here, otherwise code is the same
int c = -1;
int c1 = 2;
int c2 = 3;
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}

Using of 2 while to get this

I have 2 questions:
1: How can get the result below using two while loops?
2
4 2
6 4 2
8 6 4 2
10 8 6 4 2
12 10 8 6 4 2
14 12 10 8 6 4 2
16 14 12 10 8 6 4 2
2: How would I do it using two for loops?
It's basic algorithm, you should find some tutorials if you don't know loops in Java
With while:
int i = 2;
while (i <= 16) {
int j = i;
while (j > 0) {
System.out.print(j + " ");
j -= 2;
}
System.out.println();
i += 2;
}
With for:
for (int i = 2; i <= 16; i += 2) {
for (int j = i; j > 0; j -= 2) {
System.out.print(j + " ");
}
System.out.println();
}
I would use code (two for loops example):
for(int i = 0; i < 8; i++) {
for(int k = (i+1); k > 0; --k) {
System.out.print(k*2+" ");
}
System.out.println();
}
and two while loops:
int i = 0, j;
while(i < 8) {
j = (i+1);
while(j > 0) {
System.out.print(j*2+" ");
j--;
}
System.out.println();
i++;
}
for and while loops are similar, they are differ only by construction.

Pascal's triangle positioning

I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Categories