1.Create a square 2D array of a size that is decided by user input - the first number being the number of rows.
2.Allow the user to fill the array with integers of their choice.
3. Print to the screen the sum of the diagonals. For example see below
Example 2D Array:
| 1 2 3 4 |
| 5 4 6 9 |
| 11 13 16 6 |
| 2 4 18 20 |
Diagonal 1 = 1, 4, 16, 20. Diagonal 2 = 4, 6, 13, 2. The sum of Diagonal 1 is 41. (1 + 4 + 16 + 20) The sum of Diagonal 2 is 25. (4 + 6 + 13 + 2) The sum of both diagonals is 66. You would return 66, the sum of both diagonals only.
The code I have written is as follows but it is missing the following :
I know I need to fill the array somewhere - but not sure where ???
when I run the sum diagonals it doesn't let me fill array properly ??
import java.util.Scanner;
public class SumOfDiagonals{
public static void main(String [] args){
Scanner input = new Scanner (System.in);
int [][] matrix;
System.out.print ("Enter row number:");
int row = input.nextInt();
int col = row;
matrix = new int [row][col];
for (int i=0; i<matrix.length; i++){
for (int j = 0; i<matrix[0].length; j++){
System.out.print ("Enter a number for ( "+i+", "+j+")");
matrix[i][j]=input.nextInt();
}
}
int sum1=0;
int sum2=0;
for (int i=0;i<matrix.length;i++){
sum1 += matrix[i][i];
sum2 += matrix[i][matrix.length-1-i];
}
System.out.println ("Diagonal 1: "+sum1);
System.out.println ("Diagonal 2: "+sum2);
System.out.println ("Sum of two diagonals: " + (sum2+sum1));
}
}
My error when the test code is as follows:
Your program tested with:
5 5 4 3 2 1 1 2 3 7 5 1 1 1 1 1 11 12 13 14 15 15 14 13 12 11
Your answer:
Enter row number:Enter a number for ( 0, 0)
Enter a number for ( 0, 1)
Enter a number for ( 0, 2)
Enter a number for ( 0, 3)
Enter a number for ( 0, 4)
Enter a number for ( 0, 5)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at SumOfDiagonals.main(SumOfDiagonals.java:13)
Expected answer:
Sum of diagonals = 69
You got a grade of 52
You have a typo in your second for-loop.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; *HERE* i < matrix[0].length; j++) {
System.out.print("Enter a number for ( " + i + ", " + j + ")");
matrix[i][j] = input.nextInt();
}
}
should be
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter a number for ( " + i + ", " + j + ")");
matrix[i][j] = input.nextInt();
}
}
Related
So, right now I managed to output the Histogram like this:
The code for this picture is as following:
int max = getBiggest(arr);
int min = getSmallest(arr);
int n = max / 50 + 1;
for (int i = 0; i < arr.length; i++) {
for (int j = min; j < arr[i]; j += n) {
System.out.print(i + 1);
}
System.out.println("(" + arr[i] + ")");
}
But my task is to output the Histogram like this:
Can someone explain me please how to write this code?
Try this.
public static void main(String[] args) {
int[] arr = {12, 28, 11, 16, 21, 12};
int length = arr.length;
int max = IntStream.of(arr).max().getAsInt();
int min = IntStream.of(arr).min().getAsInt();
System.out.println("Histgramm:");
for (int h = min; h <= max; ++h) {
for (int i = 0; i < length; i++)
System.out.print(arr[i] >= h ? (i + 1) + " " : " ");
System.out.println("(" + h + ")");
}
}
output:
Histgramm:
1 2 3 4 5 6 (11)
1 2 4 5 6 (12)
2 4 5 (13)
2 4 5 (14)
2 4 5 (15)
2 4 5 (16)
2 5 (17)
2 5 (18)
2 5 (19)
2 5 (20)
2 5 (21)
2 (22)
2 (23)
2 (24)
2 (25)
2 (26)
2 (27)
2 (28)
I have been trying to find a way to print an inverted pyramid that has a certain number sequence. The sequence needed is as follows as well as what I currently have.
The prompt asked to write a method that takes two numbers and create an inverted pyramid with the first row having a length of the first integer and starting with the number entered second. Then only have the sequence start at 1 after 9 is reached.
Needed: Currently Have:
1 2 4 7 2 7 4 1 2 3 4 5 6 7
3 5 8 3 8 5 8 9 1 2 3 4
6 9 4 9 6 5 6 7 8 9
1 5 1 7 1 2 3 4
6 2 8 5 6 7
3 9 8 9
1 1
static int plotTriangle(int a, int b){
int num = b;
for (int row = a; row >= 0; row--){
for (int i = a; i - row >= 0; i--){
System.out.print(" ");
num += (num+a-row);
num -= 2;
}
for (int i = 0; i <= row; i++){
num++;
while (num >= 10){
num -= 9;
}
System.out.print(num + " ");
}
System.out.println();
}
return 0;
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter length: ");
int l = in.nextInt();
System.out.print("Enter Start: ");
int s = in.nextInt();
int triangle = plotTriangle(l, s);
}
Try this:
public static void main(String[] args) {
int length = 7;
int[][] numbers = new int[length][length];
int count = 1;
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < (i+1); ++j) {
numbers[i][j] = count++;
if(count > 9)
count = 1;
}
}
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < numbers.length; ++j) {
if(numbers[j][i] == 0)
System.out.print(" ");
else
System.out.print(numbers[j][i]);
System.out.print(" ");
}
System.out.println();
}
}
This will give you your result. Note that I didn't include the dynamic part with the scanner. I used the length and the start-number as constants.
Explanation:
In the first loop I am basically just storing the numbers in an array. And in the second loop this array is printed in a different order.
i need to print out a numeric pyramid using java. that counts in multiples of 2 along with the spaces like how it is below. but the code i have it only bring up multiples of 1 of no spaces.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
this is my code.
import java.util.Scanner;
public class NumericPyramid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Taking noOfRows value from the user
System.out.println("How Many Rows You Want In Your Pyramid?");
int noOfRows = sc.nextInt();
//Initializing rowCount with 1
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = noOfRows; i > 0; i--) {
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++) {
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 1; j <= rowCount; j++) {
System.out.print(j+" ");
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--) {
System.out.print(j+" ");
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}
}
}
Output:
How Many Rows You Want In Your Pyramid?
7
Here Is Your Pyramid
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
For each j from 1 to n you need write 2^j. Currently you are writting only j.
So write function which for given k returns 2^k.
EDIT: For bigger n you need to use BigInteger:
import java.math.BigInteger;
public class NumericPyramid {
private static BigInteger pow(int exponent) {
BigInteger result = new BigInteger("1");
BigInteger two = new BigInteger("2");
for (int i = 0; i < exponent; i++) {
result = result.multiply(two);
}
return result;
}
and use it in both for loops. Replace
System.out.print(j+" ");
with
System.out.print(pow(j)+" ");
the pyramid goes 1 2 4 8 16, that's a sequence of 1 * 2 = 2, 2 * 2 = 4, 4 * 2 = 8 and so on, and then goes inverse, 8 / 2 = 4, 4 / 2 = 2, 2 / 2 = 1, you only need to multiply by 2 and divide by 2 when the center
for (int i = 0; i < noOfRows; i++) {
int cont = 1;
for (int j = 0; j <= i; j++) {
System.out.print(cont + " ");
cont = cont * 2;
}
cont = cont / 2;
for (int j = 0; j < i; j++) {
cont = cont / 2;
System.out.print(cont + " ");
}
System.out.println();
}
So, I'm trying to create a program that captures 9 numbers in a 2D array, being of size 3 x 3. After capturing all the numbers, they are re-arranged, reversed, and displayed.
So if a user entered:
1 2 3
4 5 6
7 8 9
It should be reversed as this:
9 8 7
6 5 4
3 2 1
So far I have this:
public class Reversenumber {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int val1 = 0;
int val2 = 0;
int[][] array2 = new int[3][3];
int val3 = 0;
int val4 = 0;
for (val1 = 0;val1<3; val1++){
for (val2 = 0;val2<3; val2++){
System.out.println("Please type number for column "+(val1+1)+" and row "+(val2+1));
array1[val1][val2] = kb.nextInt();
}
}
System.out.println("\nThe inverse of this array is:");
for(val1 = 0;val1<3; val1+=1){
for (val2 = 0;val2<3; val2+=1){
System.out.print(array1[val1][val2]+" ");
}
System.out.println("");
}
}
}
The problem I'm having is outputing the inverse of the array. The first for loop captures the information perfectly, but the second set of for loop displays that same information in a 3x3 array, but not inverted. Help anyone?
I hope you don't mind, I changed the variables around completely since they are confusing. also changed the way you input stuff.
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int[][] array2 = new int[3][3];
for (int y = 0; y < array1.length; y++) {
System.out.println("input 3 numbers for row " + (y + 1));
for (int x = 0; x < array1[y].length; x++) {
array1[y][x] = kb.nextInt();
}
}
System.out.println("\nThe inverse of this array is:");
for (int y = array1.length; --y >= 0;) {
for (int x = array1[y].length; --x >= 0;) {
System.out.printf("%3d", array1[y][x]);
}
System.out.println();
}
output
input 3 numbers for row 1
1 2 3
input 3 numbers for row 2
4 5 6
input 3 numbers for row 3
7 8 9
The inverse of this array is:
9 8 7
6 5 4
3 2 1
So instead of inputting each separately you put 3 on the same line and put a space between them.
Assuming you mean invert like so:
1 2 3
4 5 6
7 8 9
to
1 4 7
2 5 8
3 6 9
It's as simple as keeping the loop the same, but swapping the coordinates between the arrays:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int val1 = 0;
int val2 = 0;
int[][] array2 = new int[3][3];
int val3 = 0;
int val4 = 0;
for (val1 = 0; val1 < 3; val1++) {
for (val2 = 0; val2 < 3; val2++) {
System.out.println("Please type number for column " + (val1 + 1) + " and row " + (val2 + 1));
array1[val1][val2] = kb.nextInt();
}
}
System.out.println("\nOriginal array is:");
for (val1 = 0; val1 < 3; val1 += 1) {
for (val2 = 0; val2 < 3; val2 += 1) {
System.out.print(array1[val1][val2] + " ");
}
System.out.println("");
}
System.out.println("\nInverted array is:");
for (int x = 0; x < 3; x += 1) {
for (int y = 0; y < 3; y += 1) {
System.out.print(array1[y][x] + " ");
}
System.out.println("");
}
System.out.println("\nThe Reversed array is:");
for (int x = 2; x >= 0; x -= 1) {
for (int y = 2; y >= 0; y -= 1) {
System.out.print(array1[x][y] + " ");
}
System.out.println("");
}
}
Edit: I added the reversed scenario you asked about in the comment below. You actually expected output like this:
9 8 7
6 5 4
3 2 1
There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> System.out.println());
Output:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}