Code for Numerical Pyramid in Java Programming [closed] - java

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

Related

I want to print this pattern in Java

1
333
55555
7777777
999999999
Program to print number pyramid. I want to print this pattern in Java.
My code:
private static void pyramid() {
System.out.println("Please Enter any number less than 10 : ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int temp = num;
for (int row = 0; row <= num; row++) {
for (int column = 0; column < temp; column++) {
System.out.print(" ");
}
temp--;
for (int k = 0; k <= row-1; k++) {
if (row % 2 != 0) {
System.out.print(row);
}
System.out.println();
}
}
}
And I am getting following output:
Please Enter any number less than 10 :
9
1
3
3
3
5
5
5
5
5
7
7
7
7
7
7
7
9
9
9
9
9
9
9
9
9
System.out.println(" 1");
System.out.println(" 333");
System.out.println(" 55555");
System.out.println(" 7777777");
System.out.println("999999999");
Your teacher probably wants you to use loops.
So you should note that the bulk standard for loop which programmers can bang out with their eyes closed:
for (int i = 0; i < someNumber; i++) {
//..
}
Is fairly configurable. For instance the i++ at the end means to increment i, but we could increment by bigger amounts (or decrement, or do some other funky things like stepping through a list of objects and so on and so forth).
e.g.
i += 3;
Will increase i by three.
You can also nest loops inside one another, e.g.
for (int i = 1; i < 10; i+=2) {
String s = "";
for (int j = 0; j < i; j++) {
s += i;
}
System.out.println(s);
}
The padding at the front I leave as an exercise to the reader.
Note that this pattern (one loop inside another, and the inner loop being bounded by the outer loops counter) is actually quite common 'out in the wild', and so is worth investing the time to understand.

Transpose java error

I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).

Printing spaces to align numbers according to my pyramid pattern

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.

What can I do to get my program to not have a IndexOutOfBounds error? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
import java.util.Arrays;
public class Lab12st {
public static void main(String args[]) {
System.out.println("/nLab 12 80 Point Version \n");
final int MAX = 100;
boolean primes[];
primes = new boolean[MAX];
computePrimes(primes);
displayPrimes(primes);
}
public static void computePrimes(boolean listA[]) {
Arrays.fill(listA, true);
for (int j = 2; j < 100; j++) {
for (int k = 0; k <= 100; k += j) {
listA[k] = false;
System.out.println(listA[k + 1]);
}
}
}
}
I have tried using different relational operators, switching some numbers around, and I still get an IndexOutofBounds error. I think it is because I have 100 array elements that are listed 0-99, but I don't know how to fix this. Any help would be greatly appreciated.
In your inner loop the condition is causing issues
for (int k = 0; k <= 100; k += j)
At each iteration the index k is incremented of a value equal to j
Since the array size is 100 at some point you will get the index-out-of-bounds error.
My question is why are performing such increment? What is your code actually doing?
In addition to that you should keep an eye on this line of code and adjust the condition of your for loop accordingly
System.out.println(listA[k + 1]);
This line is your problem.
for (int j = 2; j < 100; j++)
for (int k = 0; k <= 100; k += j)
and
System.out.println(listA[k + 1]);
100 would give you the number of bool in the array. However, the largest legal index is always the length()-1.
Thus, you are trying to access a character that is outside of the array, resulting in the indexOutOfBounds, as indexes always count 0 as a place.
The fact that you are hardcoding the 100 values into the code is bad practice.
You should use
listA.length
Thus, your solution would be
for (int j = 2; j < listA.length; j++)
{
for (int k = 0; k <listA.length; k += j)
{
listA[k] = false;
if(k >= listA.length)
{
System.out.println("THERE ARE NO VALUES AT K+1");
//Add what you want to do here if there are no more values.
break; //this is a typical solution.
}
}
}
if you use the comparator "<=" then you must use
listA.length-1

How to make pattern of numbers in java using only two variables?

#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
..........

Categories