#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required pattern and the code which i used is
public class Test{
public static void main(String[] args) {
int k = 1;
for (int i = 0; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print(k + " ");
k++;
}
System.out.println();
}
}
}
as you can see i used the variable k to print the numbers.
My question is that is there a way to print the exact same pattern without using the third variable k?
I want to print the pattern using only i and j.
Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:
Could you print the sequence if you knew the last number from the prior line? - the answer is trivial: you would need to print priorLine + j
Given i, how would you find the value of the last number printed on i-1 lines? - to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.
You can use this:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
}
}
}
Or you can the find the nth term and subtract it each time:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
// k++;
}
System.out.println(" ");
}
}
You can use
System.out.println((i+j) + " ");
e.g.
i j (i+j)
0 1 1
1 1 2
2 1 3
2 2 4
..........
Related
It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.
I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.
j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.
A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}
I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.
This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
System.out.println();
}
}
I'm a total beginner to java and need help writing this nested for loop. This is the desired output.
2 3 5
5 10 26
11 31 131
23 94 656
I understand that the increment is 2 times the first number + 1, but I don't understand how to create the loop for it.
public static void main(String[] args) {
for(int i = 2; i <= 5; i++) {
for(int j = i; j <= i; j++) {
System.out.print(j+(i*j));
}
System.out.println();
}
}
Question is so simple it consists of two things read the pattern and use the appropriate loop statements in java to achieve this. Printing them is another task which is not difficult.
#Jonathan your pattern is right but your algorithm is incorrect.
I'm not giving you perfect solution but you have to use proper loop statement to make it efficient. I'm here giving you a thought so that you can think in this way..hope you get it.
public static void main(String[] args) {
/* 2 3 5
5 10 26
11 31 131
23 94 656
*/
int two = 2;
int three = 3;
int five = 5;
int i=0;
//use do-while to print 2 3 5
do{
System.out.println(two +" "+ three +" "+five);
two=two*2+1; // apply math pattern
three= three*3+1;
five= five*5+1;
i++;
}while(i<4);;
}
Please try the following code (I have tested the code, the output is exactly the same as yours):
public static void main(String args[]) {
int[][] results = new int[4][3];
results[0][0] = 2;
results[0][1] = 3;
results[0][2] = 5;
for (int i = 1; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
results[i][j] = results[i - 1][j] * results[0][j] + 1;
}
}
for (int i = 0; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
System.out.print(results[i][j] + "\t");
}
System.out.println();
}
}
I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Create a java code that display the following figure:
1
2 3 4
3 4 5 6 7
4 5 6 7 8 9 10
Hey guys! New on here. We have an exercise to do involving java programming and for some reason It seems to get my head blows out in solving this problem. There's what I have done so far but the output is incorrect.
public class Pyramid {
public static void main(String[] args) {
int size = 10;
for (int row = 1; row <= size; row++) {
int j = 1;
int i = 1;
int counter1 = 1;
int counter2 = 1;
// print space
while (j++ <= size - row) {
System.out.print(" ");
}
// count up
j = size - (size - row);
if (j == 10) j = 0;
counter1 = 1;
while (counter1 <= row) {
System.out.print(j);
if (j == 9 && counter1 != row) j = -1;
j++;
counter1++;
}
j = j - 2;
counter2 = 1;
// count down
while (counter2 < row) {
System.out.print(j--);
if (j < 0) j = 9;
counter2++;
}
System.out.print("\n");
}
}
}
I can see two major mistakes in what you posted.
10 is the highest number in the pyramid but it has only 4 rows. So size should be equal to 4 (unless it is just an example and the number of rows isn't important).
I don't see any reason why you make a countdown. You can see that the numbers are always increasing in the same row.
In addition to that:
You should separate the numbers by a blank. The numbers in your example were stuck to each other. This imply that you have to change the number of spaces before each row. (In your example you can simply double the spaces)
Really not important: you can use System.out.println() when you want an new line.
Here you are doing counting down after the mid point of each raw. So instead of increasing number, you are decreasing in the count down part (j is decreasing).
And here you need 4 numbers of raws. but u have programmed for 10 numbers of raws with some conditions (here you don't need to specify the highest number. You just input the number of raws is enough. Please find the Logic below).
And even though you need to increase the number of raws, the logic should not be changed.
Logic:
For each raw the number of elements should be the raw's odd number and the 1st element of each raw should be started with the raw's number.
for example,
if we consider 3rd raw, then 3rd odd number is = (3*2) - 1 = 5. So number of elements in the raw is 5.
And the start element of 3rd raw is 3.
So raw will be:
3,4,5,6,7
Please try below code:
int n = 5;
for (int i = 1; i < n; i++) {
int odd = (i*2) - 1;
for (int j = 1; j <= odd; j++) {
if (j==1) {
for (int x = n; x >=i; x--)
System.out.print(" ");
}
System.out.print(((j + i)-1) + " ");
}
System.out.println();
}
Output is:
1
2 3 4
3 4 5 6 7
4 5 6 7 8 9 10
Try this
class Pyramid {
public static void main(String[] args) {
int myLevel;
int i, j, k;
int x = 1;
myLevel = 6;
for (i = 1; i <= myLevel; i++) {
for (k = 1; k <= myLevel - i; k++) {
System.out.print(" ");
}
for (j = k + 1; j <= myLevel; j++) {
System.out.print(x);
}
for (int l = myLevel; l > k - 1; l--) {
System.out.print(x);
}
x++;
System.out.println("");
}
}
}