Number pyramid, can't get numbers to print out to the left - java

I need a full pyramid but I can only get the right side of it. It is suppose to look like this with a example output of 4:
1
212
32123
4321234
I'm still new to java for loops so I've tried doing negative increments but that didn't work is there a type of method to print it in reverse?
import java.util.Scanner;
public class Pyramid {
public static void main(String [] args) {
System.out.println("Enter a number 1 to 15");
Scanner input = new Scanner(System.in);
int input1 = input.nextInt();
if (input1 >= 1 && input1 <=15) {
for(int column =1; column <input1; column++) {
for(int row = 1; row < column; row++) {
System.out.print(row + " ");
}
System.out.print(column);
System.out.println();
}
}
}
}

You need more loops, and you work row by row, and not col by col so the outer loop should use row.
And the inner loops are for :
print the spaces
print the numbers is descending order until 1 (exlude)
print the numbers is ascending order from 1
for(int row = 1; row <= input1; row++) {
for(int space = 0; space < input1-row; space++) {
System.out.print(" ");
}
for(int desc = row; desc > 1; desc--) {
System.out.print(desc);
}
for(int asc = 1; asc <= row; asc++) {
System.out.print(asc);
}
System.out.println();
}

Related

Loop inside Loop in Java (simple)

I am doing an exercise where I have to print 'x' (is an input) rows of numbers incrementing from 0 to 10.
If I input 3, the output should look like this
012
345
678
012
345
678
012
345
678
but instead, I get 3 rows of a 0 to 10 count.
I know it might be easy to code, but I am stuck in that!
I think I am not undestanding well the nested loops :(
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
You don't need two loops for this. All you need is to print a newline after every 3rd letter and an extra newline after every 3rd line. Your code can be like:
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
int lines = 0;
int letters = 0;
while (lines < q) {
System.out.print(i);
if (letters && letters % q == 0) {
System.out.println();
lines++;
}
if (lines && lines % q == 0) {
System.out.println();
letters = 0;
continue;
}
letters++;
}
}
PS: I haven't tried this code myself. But concept would be the same.
The answer above should solve your problem so I will try to explain what your code does.
Let's start with code inside first for loop:
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
First we have a loop iterating through numbers from 0 to 10 and the output is:
012345678910
and a new line after that.
That means that output of your program will print above mentioned output q times.
012345678910
012345678910
012345678910
You can try with below code
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i < 9; i++) {
if(i%3 == 0)
System.out.println();
System.out.print(i);
}
System.out.println();
}
}
}
Print X quandrants of X rows and X columns each
Scanner in = new Scanner(System.in);
int q = in.nextInt();
// q quadrants
for (int iQuadrat = 0; iQuadrat < q; iQuadrat++) {
// count will keep track of the last number you print
int count = 0;
// q rows
for (int iRow = 0; iRow < q; iRow++) {
// q cols
for (int iCol = 0; iCol < q; iCol++) {
System.out.print(count);
// increment the count and take its modulo 10 so it stays between 0 and 9
count = (count+1)%10;
}
// line return at the end of the row
System.out.println();
}
// line return between quadrants
System.out.println();
}
For an input of 12, it will print 12 times this quadrant
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123

Creating 2 dimesional array with user input and find sum of specific columns

Please assist with my code.
There must be 3 rows and 4 columns in the array.
The user must be able to enter doubles for the first 2 columns.
Then I should be able to calculate the sum of each column in the array.
public class Main {
public static void main(String[] args)
{
// Implement scanner
Scanner input = new Scanner(System.in);
// Create loop for accepting matrix input
// Determine row size
System.out.println("Please enter the number 3 for the number of rows in the array:");
int row = input.nextInt();
//Rule for row not being 3
while (row != 3)
{
System.out.println("Sorry, there must be 3 rows.");
row = input.nextInt();
}
// Determine column size
System.out.println("Please enter the number 4 for the number of columns in the array:");
int column = input.nextInt();
//Rule for column not being 4
while (column != 4)
{
System.out.println("Sorry, there must be 4 columns.");
column = input.nextInt();
}
// Declare array with row and columns the user gave
int[][] userArray = new int[row][column];
//Informing user how data is inputted and saved
System.out.print("Note that the following inputs saves the numbers from left to right. So after entering 4 digits it moves onto the next row.");
System.out.println("\n");
for(int i=0;i < row ; i++)
{
for(int j=0; j< column; j++)
{
System.out.print("Please enter a value for the array:["+i+"]["+j+"]");
int val = input.nextInt();
userArray[i][j] = val;
}
}
printMatrix(userArray, row, column);
}
public static void printMatrix(int[][] array, int row, int column)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
The printed output should be, depending on user input:
1.9 2.3 5 1
5.0 7.3 6 8
2.4 3.1 3 2
The sum of column 1 is: 9.3
The sum of column 2 is: 12.7
The sum of column 3 is: 14
The sum of column 4 is: 11
You now need to add the array values by column. It can be as easy as:
private void printSumForColumn(int[][] array, int col)
{
int sum = 0;
for (int i = 0; i < row; i++)
{
sum += array[i][col];
}
System.out.println("The sum of column " + col + " is " + sum);
}
First of all, you cannot use int array to store floating-point numbers. So printMatrix method signature should be changed to double[][].
And here is a method to calculate column sums
public static void calColSum(double[][] matrix){
// number of columns
int col = matrix[0].length;
// array to hold column sum
double[] colSums = new double[col];
for (double[] row : matrix) {
for (int y = 0; y < col; y++) {
colSums[y] += row[y];
}
}
for(int x = 0; x< colSums.length; x++){
System.out.println("The sum of column " + x +" is: " + colSums[x]);
}
}

How to display first column and row only?

I have created a multiplication table. However, it cannot display the first row and column with my code. Is this even achievable via loop? Herr is my code:
int a;
int b;
for (a=1; a<=3; a++)
{
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
System.out.println();
}
The output of this code is:
1 2 3
2 4 6
3 6 9
However, i want the 123 on a row and column to display only. Is this achievable?
Desired output:
1 2 3
2
3
A basic approach is to know where your outer loop is at and print accordingly to your desired result.
public class StackOverflow {
public static void main(String[] args) {
int a;
int b;
for (a=1; a<=3; a++)
{
// Only print the first row
if (a == 1) {
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
// Ends the first row
System.out.println("");
} else {
// Prints the rest of the first column
System.out.println(a);
}
}
}
}
Result:
1 2 3
2
3
UPDATE
If I understand your comment, here's an approach with just one loop. It assumes that the size of the row will equal the size of the column. This means that the number of digits you'll display will be an odd number (rowColLength * 2 - 1) which makes the first digit a pivot point.
public class StackOverflow {
public static void main(String[] args) {
int a = 0;
int rowColLength = 3;
int numberOfDigits = rowColLength * 2 - 1;
for (int i = 0; i < numberOfDigits; i++) {
if (i < rowColLength) {
// Prints the first row
System.out.print(++a + " ");
} else if (i == rowColLength){
// Decrements the last number from the first row
// to continue the column count for printing
System.out.print("\r\n" + --a);
} else {
// Prints the rest of the column
System.out.print("\r\n" + ++a);
}
}
}
}
Result:
1 2 3
2
3
I think you want the upper bounds to be limited.
Better readable would be:
int rows = 3; // 1?
int columns = 10; // 1?
for (int row = 1; row <= rows; ++row) {
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
The printf prints digits, padded to the left upto 3 positions with spaces.
If you want a header row and column à la Excel:
// Header row:
System.out.print("AxB ");
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", column);
}
System.out.println();
System.out.print("---|");
for (int column = 1; column <= columns; ++column) {
System.out.print("---");
}
System.out.println();
// Data rows
for (int row = 1; row <= rows; ++row) {
System.out.printf("%3d|", row); // Column header
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
Print header and columns labels in 2 different loops:
int a;
int b;
// Print header label
for (b=1; b<=3; b++) {
System.out.print(b + " ");
}
System.out.println();
// Print column label
for (b=2; b<=3; b++) {
System.out.println(b);
}
The output:
1 2 3
2
3
Several possibilities, you could for example save the result to a variable and not print it if bigger than 3.
int temp = a*b
if (temp < 4){
System.out.print(temp);
else {
System.out.print(" ");
}

2D Array with Number Averages

Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;

Printing specified alphabet in pyramid format

I have some problem when trying to print out alphabet XXYY in half pyramid format using Java. Here is the expected output when user entered height of 7:
XX
YYXX
XXYYXX
YYXXYYXX
XXYYXXYYXX
YYXXYYXXYYXX
XXYYXXYYXXYYXX
And here is my code:
public static void main(String[] args){
int height = 0;
String display = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
height = sc.nextInt();
for(int i = 1; i <= height; i++){
for(int j = 1; j <= i; j++){
if(j %2 == 0){
display = "YY" + display;
}else{
if(j == 1){
display = "XX";
}
}
System.out.print(display);
}
System.out.println();
}
}
What my logic is I thinking to check for even/odd row first then add the XX or YY to the display string. First I check for first row, then I add XX to the display string. Then, if even row, I append YY to the front of the display string.
But my problem is I not sure how to count the amount of XX and YY for each row. Here is my output:
XX
XXYYXX
XXYYXXYYXX
XXYYXXYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXXYYYYYYXX
IMHO, you're over-complicating things. In each row you have the same number of pairs of letters as the row number (one pair on the first row, two on the second, etc). The first row starts with "XX" and then the beginnings alternate between "XX" and "YY". In a similar fashion, within the row, after determining what you started with, you alternate between the two pairs of letters:
for (int row = 0; row < height; ++row) {
for (int col = 0; col <= row; ++col) {
if ((col + row) % 2 == 0) {
System.out.print("XX");
} else {
System.out.print("YY");
}
}
System.out.println();
}
This should do it:
public static void main (String[] args) throws java.lang.Exception
{
int ht = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
ht = sc.nextInt();
String text = "";
for(int i=0; i<ht; i++)
{
if (i%2!=0)
text = "YY" + text;
else
text = "XX" + text;
System.out.println(text);
}
}
And works with single for loop too!

Categories

Resources