How to display first column and row only? - java

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

Related

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

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

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

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

Printing a centered pyramid in Java with ascending and descending numbers

I'm trying to print a centered pyramid of 2^n, where 2^row# is the centered number of each row, the numbers to the left are ascending to 2^row# and the numbers to the right are descending. I'm pretty new to Java and it took me a really long time to get this much. But now I'm stuck. The last row is the only row that is correct. I don't know how to make it so 64 is not printed on every line. Can anyone please give me a hint?
I've tried messing with every single parameter - starting the last loop with the first row, the last row, changing the starting power, etc. and I just can't figure it out.
Thank you for any hints!
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
}
}
Your problem lies in the fact you always start the right side of the pyramid at 2^7, since you hard code the power2 = 7 decleration and assignment. If you start this value instead at the current row - 1, you get the behavior you're looking for. Code:
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = row - 1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
This part is not right.
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
On row 2 you get power2=6 so you display 2^6=64.
You should instead be doing something like
int power2 = power1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
You are assigning constant to power2 instead of depending value on row. Can you try this please.
int power2 = row-1;

Java multi-dimensional arrays - a question about system output

Would anyone please explain the output showm at the bottom for this code. I am somewhat confused about this part and understanding what is stored in doc after execution...
doc[a][b] = a + b;
public class doc
{
public static void main(String[] args)
{
int b = 0;
int [][] doc = new int [3][3];
int a;
while (b<3)
{
for(a=2; a >=0; a--)
doc[a][b] = a + b;
++b;
}
int j;
for (int i=0; i<doc.length; i++) {
for (j=0; j<doc[i].length; j++) {
System.out.println(" " + doc[i][j]); }
System.out.println("");
}
}
}
0
1
2
1
2
3
2
3
4
The output is above.
Thank you.
The array will look like the following
0 1 2
1 2 3
2 3 4
All it is doing is going through and printing out each row in succession. In the for loop
for (int i=0; i<doc.length; i++) {
for (j=0; j<doc[i].length; j++) {
System.out.println(" " + doc[i][j]); }
System.out.println("");
}
i represents the row number and j represents the column number so it says go to row 0 and print out column 1, the col 2, then col 3. Now go to row 1 and print col 1, col 2 and col 3 and so forth with row 2.

Categories

Resources