Using of 2 while to get this - java

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.

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

number pattern programs in 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();
}

Java Pattern of 1 row odd and 1 row even

I want to print a pattern like :
Till now i have been able to achieve only for odd numbers like :
1
3 5 7
-
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
I am a beginner and new learner. please help
I'm not sure what's the expected result since that pattern is not clear, however this might be what you're looking for:
int evenCounter = 1;
int oddCounter = 2;
for (int i = 1; i <= 10; i++) {
boolean even = (i % 2 == 0);
for (int j = 1; j < i; j++) {
System.out.print((even ? evenCounter : oddCounter) + " ");
evenCounter += even ? 2 : 0;
oddCounter += even ? 0 : 2;
}
System.out.println();
}
Result:
1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
14 16 18 20 22 24
19 21 23 25 27 29 31
26 28 30 32 34 36 38 40
33 35 37 39 41 43 45 47 49
If the length of each row matters, then the second for loop should have a different exit condition I suppose
To get the pattern from 3 5 7, this code would do, where MAX_PATTERN_NUM is the first number of the last line of the pattern (in your example's case, MAX_PATTERN_NUM = 15)
for(int i = 3; i <= MAX_PATTERN_NUM ; i+=3)
for(int j = i; j <= (i + 4); j+=2)
System.out.print(j + " ");
System.out.println();
However, I see no logical way of getting the entire pattern using the same nested for loops, so I hope this helps
How about this:
public void printPattern(){
int evenCounter = 2;
int oddCounter = 1; //counters
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt(); //input
}
for(int i = 1; i <= num ; ++i){
if(i % 2 == 0)
evenCounter = addNumbers(i, evenCounter); //print line with evenCounter
else
oddCounter = addNumbers(i, oddCounter); //print line with oddCounter
}
}
private int addNumbers(int i, int counter){
for(int j = 0; j < i;){
if(getIntLength(counter) + j > i) //if the number to long
System.out.print(cut(counter, getIntLength(counter) + j - i) + " "); //output the cut version
else
System.out.print(counter + " ");
j += getIntLength(counter);
counter += 2;
}
System.out.println();
return counter;
}
private String cut(int i, int length){
return Integer.toString(i).substring(0,length); //get substring of int
}
private int getIntLength(int i){
return Integer.toString(i).length(); //get the length of int value
}
It's not so simple, but I don't see an easier way
My answer is based on the assumption that the last 2 is a cut off 21
int n,i,j,o=1,e=2;
System.out.println("enter n:");
n=sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
if(i%2!=0){
System.out.print(o);
o+=2;
}
if(i%2==0){
System.out.print(e);
e+=2;
}
}
System.out.println();
}

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

How can I print consecutive integers greater than 0, three per line?

How to loop this?
I'm trying to loop this:
0-> 1,2,3
1-> 4,5,6
2-> 7,8,9
3-> 10,11,12
4->.....
......
I don't know how to write this algorithm.
I tried below, it doesn't work.
public class gYie {
public static void main(String[] args) {
int current = 0;
int death = 0;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death+j +" ");
current += j;
}
death += current;
System.out.println("");
}
}
}
Its Output is:
run:
0 0 1 2
1 3 4 5
2 9 10 11
3 18 19 20
4 30 31 32
5 45 46 47
6 63 64 65
7 84 85 86
8 108 109 110
9 135 136 137
How to solve this? I can't think how to write it.
3 becomes 18,19,20 instead of 12,13,14.
Looks suspiciously like homework, so here's some pseudo-code (actually Python) that will do the trick for you:
for outer in range (10):
print "%d ->"%(outer),
for inner in range (3):
print "%2d"%(outer * 3 + inner + 1),
print
The basic idea is to simply have an inner loop of 0 through 2 inclusive and an outer loop that increases by one each time. Then the formula:
outer * 3 + inner + 1
gives you the values you want:
0 -> 1 2 3
1 -> 4 5 6
2 -> 7 8 9
3 -> 10 11 12
4 -> 13 14 15
5 -> 16 17 18
6 -> 19 20 21
7 -> 22 23 24
8 -> 25 26 27
9 -> 28 29 30
You're overthinking it. For the left-hand side, all you need to print is i. For the right-hand side , you just need a single variable current that gets incremented every time its printed:
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current + " ");
current ++;
}
System.out.println();
}
}
Try this
int loopCount = 1;
for(int a = 1; a < 21; a++){
System.out.println(a);
for(int b = 0; b < 3; b++){
System.out.print((loopCount++) + " ");
}
System.out.println();
}
Edit: But I guess I found a more efficient way by using a single loop
int x = 1;
for(int a = 0; a < 21; a++){
System.out.println(a + " -> " + (x) + " " + (x + 1) + " " + (x + 2));
x = x + 3;
}
now you can merge it with your variables and logic
Here is a solution with a single loop:
int n = 15;
for (int i = 0; i < n; i++) {
if (i % 3 == 0) {
System.out.println();
}
System.out.print(i + " ");
}
You need to do something like this. Just keep printing the current.
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current +" ");
current ++;
}
System.out.println();
}
this should do the job...
public class gYie {
public static void main(String[] args) {
for (int i = 0, j = 1; i < 10; i++) {
System.out.print(i + " ");
for (int h = 0; h < 3; h++, j++) {
System.out.print(j +" ");
}
System.out.println("");
}
}
}
You can just simplify your code as follows :
public static void main(String[] args) {
int death = 3;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
death = 3*i;
for (int j = 1; j <= 3; j++) {
System.out.print(death+j +" ");
}
System.out.println("");
}
}
}
You will now get the output as :-
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15
5 16 17 18
6 19 20 21
7 22 23 24
8 25 26 27
9 28 29 30
Use a simple counter:
int j = 0;
for (int i = 0; i < 10; i++)
System.out.println(i + " " + ++j + " " + ++j + " " + ++j + " ");
There is a lot of nested loops above. Here's a scalable solution within a single for loop.
public static void main(String[] args) {
int numbersPerLine = 3;
int finalNumber = 12;
int startingRowNumber = 0;
System.out.print(startingRowNumber + " -> ");
for(int i = 0; i < finalNumber; i++) {
if(i > 0 && (i % numbersPerLine) == 0) {
System.out.print("\n" + ((i / numbersPerLine) + startingRowNumber) + " -> ");
} else if(i > 0) {
System.out.print(",");
}
System.out.print((i + 1));
}
}
Change your code like this.
int death = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death++ +" ");
//current += j;
}
//death += current;
System.out.println("");
}
Got exact solution for it ...
class Alok{
public static void main(String[] args){
int i = 0,j=0;
for(i=0;i<10;i++){
System.out.print(""+i+"->");
for(j=(i*3)+1;j<(i*3)+4;j++){
System.out.print(""+j+" ");
}System.out.println();
}
}
}

Categories