Java Multiplication - java

How will do a program that displays a multiplication table based on the size that the user inputs? And will add each row and each column? Something like this:
Enter a number: 4
1 2 3 4 10
2 4 6 8 20
3 6 9 12 30
4 8 12 16 40
10 20 30 40
I tried this:
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = s.nextInt();
for(int i = 1; i <= x; i++)
{
for (int j = 1; j <=x; j++)
{
System.out.print((i*j) + "\t");
}
System.out.println();
}
Sample Output:
Enter a number: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
How I will do to add each row and each column?

Since this seems like homework, I wouldn't feel comfortable writing your code for you. However, keep the following things in mind.
Your matrix will always be a square, as the user only enters a single number, of n x n numbers.
Since these numbers increment by one along the row and column, the sum of each row and column pair will be the same. In other words, the total of row[n] will equal the total of column[n].
Using that, you can create a single array of size n to store the sum of each row. For example:
Enter a number: 3
1 2 3 x
2 4 6 y
3 6 9 z
x y z
When you're looping through each row, you can store the row total in the array.
Row 0: Add 1 + 2 + 3 and store in array[0]
Row 1: Add 2 + 4 + 6 and store in array[1]
Row 2: Add 3 + 6 + 9 and store in array[2]
At the end of each row you can simply display the total in array[row]. When you finish drawing all rows, you'd simply loop through array and display each total value.
Hope this points you in the right direction!

public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter size of table: ");
int x = s.nextInt();
int r = 0;
int l = 0;
int f = 0;
for(int i=1;i<=x;i++){
for (int j=1; j <=x; j++)
{
r = r + j;
System.out.print(i*j+"\t");
}
System.out.print(r);
System.out.println();
System.out.println();
l=l+i;
}
for(int k = 1; k<=x;k++)
{
f=f+l;
System.out.print(f + "\t");
}

Related

Print integer in 4 rows and 4 column Java without Array

I am supposed to create a program that prints out the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Here's my current code:
int n = 1,
cols = 4,
rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n+" ");
n++;
}
System.out.println();
}
But the output is as below:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Can someone please help to figure out the solution for this one? I've tried many ways but just can't get the output right. Thanks anyway.
Java can only print in lines and not in columns. So the first line you need to print is:
1 5 9 13
In other words, every successive number is 4 greater than the number preceding it. So start your outer loop with the first number of the first row, i.e. 1 (one). Now each row contains 4 numbers, so your inner loop needs to iterate four times. See the below code:
int rows = 4;
int cols = 4;
for (int row = 1; row <= rows; row++) {
for (int col = 0; col < cols; col++) {
int number = row + (col * cols);
System.out.print(number + "\t");
}
System.out.println();
}
Running the above code produces the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Change inner loop to go from 0 to cols-1 rather than 1 to cols, and make it print outer loop variable + (inner loop variable * 4).
This will surely work:
for(int row=1, num; row<=4; row++)
{
num = row;
for(int col=1; col<=4; col++, num+=4)
{
System.out.print(num + " ");
}
System.out.println();
}

Printing a squares triangle. How to mirror numbers?

So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern

How can i determine the formula for determining the first number in Java's loop array for floyd's triangle?

Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;

Determine factors of a number (n), then return possible pairs of positive integers that when multiplied together are less than (n)?

Basically, the directions go as such:
Enter positive integer greater than 3 (n)
Program should print all possible pairs of positive integers greater than one whose product is <= to number entered (n)
Here is a sample output:
Enter an integer: 24
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8
18 = 2 x 9
22 = 2 x 11
24 = 2 x 12
9 = 3 x 3
12 = 3 x 4
15 = 3 x 5
18 = 3 x 6
21 = 3 x 7
24 = 3 x 8
16 = 4 x 4
20 = 4 x 5
24 = 4 x 6
(Note: Products can appear more than once, but pairs should not)
For my solution, I started by determining the factors of n like so:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int factors = 0;
System.out.println("Enter integer:");
int n = keyboard.nextInt();
for(int i = 2; i <=n ; i++) {
if(n % i == 0) {
System.out.println(i);
}
}
From there, it seems I should pull each factor and multiply it by an incremented variable starting at 2 until it is equal to or exceeds (n). I started to thing maybe this was incorrect, so I tried something like this instead:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter integer:");
int n = keyboard.nextInt();
int index = 2;
int multiplier = 2;
int result = 0;
while(result < n) {
result = multiplier * index;
System.out.println(result);
index++;
}
Which works, but only for result 4 - 24, as multiplier never increments two 3. Is the actual solution just a hybrid of these possible solutions? Guidance in the correct direction would be appreciated, thank you!
I think your current approach is off, and in particular is missing one critical element to solving this: a double loop. I think the easiest way to handle this is to loop twice and generate all pairs meeting the requirements.
int number = 24;
for (int i=2; i < (int)Math.ceil(Math.sqrt(number)); ++i) {
for (int j=i; j <= number / 2; ++j) {
int pair = i * j;
if (pair <= number) {
System.out.println(pair + " = " + i + " x " + j);
}
}
}
The tricky part here was in determining the bounds for the two for loops. The second loop variable starts with the value of the first, and can get as large as half the input number. This is because the widest pair would occur when the first number be 2, forcing the second number to be the input halved. The bounds on the first loop are a bit more complex. We used the ceiling of the square root as the bounds, because the largest it can ever be would occur when both numbers are the same.
Try something like this.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter integer: ");
int n = keyboard.nextInt();
for (int i = 2; i <= n / 2; i++) {
for (int j = 2; i * j <= n; j++) {
System.out.println(i + " x " + j + " = " + (i * j));
}
}
The result as follows.
Enter integer: 24
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
2 x 11 = 22
2 x 12 = 24
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
7 x 2 = 14
7 x 3 = 21
8 x 2 = 16
8 x 3 = 24
9 x 2 = 18
10 x 2 = 20
11 x 2 = 22
12 x 2 = 24

Java Looping Arrays

How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);

Categories

Resources