Printing rows of increasing amounts of even numbers - java

I'm trying to print the following:
2
2 4
2 4 6 ..etc
The code I have written (below) prints the following:
2
4 6
8 10 12 ...etc
Can anyone spot where I'm going wrong? The n variable comes from the main method which I am not including.
public static void printEvenTable(int n) {
int i;
int j;
int k = 0;
for (i = 1; i <= n; i++) {
for (j = 0; j < i; j++)
System.out.print(" " + (k += 2));
System.out.println(" ");
}
}

You need to prevent the variable k from using its old value by reassigning 0 to it right after the second for loop. Placing k = 0; before the second for loop makes redundant reassigning because it has already been assigned right before the loop. Ensure program optimization. If you are using a good editor, it show you some warning if placed before the second for loop.
for (i = 1; i <= n; i++) {
for (j = 0; j < i; j++) {
System.out.print(" " + (k += 2));
}
k=0;
System.out.println(" ");
}

Here, the inner loop is increasing the variable k by 2 in each steps after the first execution of the inner loop k becomes 2 from the initial value 0. In the second iteration of the outer loop k starts as 2. After k+=2, k becomes 4 so second line of output starts from 4. That's why we need to re-initialize k to 0 before each inner loop.
public static void printEvenTable(int n) {
int i;
int j;
int k = 0;
for (i = 1; i <= n; i++) {
k = 0;
for (j = 0; j < i; j++)
System.out.print(" " + (k += 2));
System.out.println(" ");
}
}

Related

Why does the inner loop range make a difference in the way this problem is solved?

Write a static method printNumbers that takes an integer max as an argument and prints out all perfect numbers that are less than or equal to max.
At first, I kept getting the wrong answer because the inner loop was set to j < max before I changed it to j < i. However, I don't understand why that range would matter, because wouldn't i % j != 0 anyway, even if the range of j were to be larger?
for (int i = 1; i <= max; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.print(sum + " ");
}
}
If I changed the inner loop j < max, then printNumbers(6) gives both 1 and 6, but printNumbers(500) gives only 1 and no other number.
If you set j < max in the inner loop, then when j = i, i % j == 0 returns true and skews your result.
This is a good example of a mathematical error to watch out for in coding.

Magic Square gives ArrayIndexOutOfBoundException

I have been working on Magic Square formation, after reading through the algo, I found out there are certain set of rules to be followed while forming the MagicSquare.
The algo which I'm following is :
The magic constant will always be equal to n(n^2 + 1)/2, where n is the dimension given.
Numbers which magicSquare consists will always be equals 1 to n*n.
For the first element that is 1, will always be in the position (n/2, n-1).
Other elements will be placed like (i--,j++)
The condition to be put through for placing an elements are :
a) If i < 0, then i = n-1.
b) If j == n, then j = 0.
c) This is a special case, if i < 0 and j=n happens at the same time, then i = 0, j = n-2.
d) If the position is already occupied by some other element, then i++, j = j-2.
Then input the element inside the magicSquare based upon the conditions.
Based upon the above algo, I have written down a code, and due to some reason I'm getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.generateMagicSquare(Main.java:25)
at Main.main(Main.java:58)
This is weird. I have checked, and feels like it is safe to use the code to get the desired result, but I don't know where I'm going wrong.
Code
static void generateMagicSquare(int n){
int[][] magicSquare = new int[n][n];
//initialising for pos of the elem 1
int i = n/2, j = n-1;
magicSquare[i][j] = 1;
//the element consist by the magic square will always be equal to 1 to n*n
for(int num=2; num <= n*n; num++){
//it must go like this, for any other element
i--; j++;
// if the element is already present
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
if(i < 0)
i = n-1;
if(j == n)
j = 0;
if(i < 0 && j == n){
i = 0;
j = n-2;
}
}
magicSquare[i][j] = num;
}
for(int k=0; k<n; k++){
for(int l=0; l<n; l++){
System.out.print(magicSquare[k][l] + " ");
}
System.out.println();
}
}
Any help would be appreciated. Thanks. Since I could have copied and pasted the code from internet, but I want to learn it in my way, and your help would help me achieve what I want. :)
EDITS
After reading through the exception, I made some amendments in my code, but still some of the result didn't come upto the mark.
Here is my updated code =======>
static void generateMagicSquare(int n){
int[][] magicSquare = new int[n][n];
//initialising for pos of the elem 1
int i = n/2, j = n-1;
magicSquare[i][j] = 1;
//the element consist by the magic square will always be equal to 1 to n*n
for(int num=2; num <= n*n; num++){
//it must go like this, for any other element
i--; j++;
if(i < 0){
i = n-1;
}
if(j == n){
j = 0;
}
if(i < 0 && j == n){
i = 0;
j = n-2;
}
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
magicSquare[i][j] = num;
}
}
for(int k=0; k<n; k++){
for(int l=0; l<n; l++){
System.out.print(magicSquare[k][l] + " ");
}
System.out.println();
}
}
I get this output :
2 0 6
9 5 1
7 3 0
Still not the right answer to follow.
This line throws the error:
if(magicSquare[i][j] != 0)
and the problem is that the array magicSquare is initialized as:
int[][] magicSquare = new int[n][n];
meaning that it has n columns with indexes from 0 to n - 1 (indexes are zero based).
The variable j is initialized as
j = n-1;
and later this line:
j++;
makes j equal to n
so when you access magicSquare[i][j] you are trying to access magicSquare[i][n] which does not exist.
The index of an array is an integer value that has value in interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. You have to check the value of i and j before using it in array. You can use the below code :
for(int num=2; num <= n*n; num++){
i--; j++;
//Here We have to check the value of i and j i.e. it should less than or equal to the length of array.
if((i <= magicSquare[0].length-1 && j <= magicSquare[0].length-1))
{
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
if(i < 0)
i = n-1;
if(j == n)
j = 0;
if(i < 0 && j == n){
i = 0;
j = n-2;
}
}
magicSquare[i][j] = num;
}
}
For understanding ArrayIndexOutOfBoundsException, Please visit :
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/

Making a pattern with java using nested loops

I have to make a pattern that is of a diamond shape such as this:
1
1 2
1 2 3
1 2 3 4 5
1 2 3
1 2
1
I wrote this ( sorry if for the variable name, this is just a small part of my program and I'm trying to get the pattern right so I didn't mind my variables at the moment):
public class NewFile{
public static void main(String []args){
int k = 0;
for (int i=1 ; i<=5 ; i++)
{
{ for (int h=2 ; h >= i ; h--)
System.out.print(" ");
for (int j=1 ; j<= i + k ; j++)
System.out.print(j);
for (int w=2 ; w>= i; w--)
System.out.print(" ");
}
k++;
System.out.println();}
}
}
My output is the following:
1
123
12345
1234567
123456789
I realize I should divide the code into a lower and upper triangle using two loops. However, I don't know how to break the first part. I did find the "trend" but I don't see how to implement it.
The following code will display a diamond shape that is made up of asterisks:
int i = 0, j, k, n;
n = 7; // 7 characters high. Change as needed.
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
The integer n represents the height of the diamond in characters and can be changed as needed.

Asterisk in Nested loops, Java

I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}

How to print 1 to 10 with following format first line 1 2nd line 2 & 3 3rd line 4,5 & 6 4th line 7,8,9,10?

I tried like this,
for (int j = 1; j <= 4; j++) {
for (int k = 1; k < 10; k++) {
if (k <= j) {
System.out.print(k + " ");
} else
break;
}
System.out.println();
}
but it prints like
1
1 2
1 2 3
1 2 3 4
This question is asked in one interview i had attended, my mind is breaking to find solution.. i can't think..
init a variable before
int printed = 1;
and change your
System.out.print(k+" ");
with
System.out.print(printed+" ");
printed++;
This will do it :
public static void main(String[] args)
{
int i, j, k;
for (i = 1, j = 1; i < 11; j++)
{
for (k = 0; k < j; k++)
{
System.out.print(i++ + " ");
}
System.out.println();
}
}
This code will do that:
int i, j, k;
for (i = 1, j = 1; i < 11; j++) {
for (k = 0; k < j; k++)
System.out.print(i++ + " ");
System.out.print("\n");
}
Basically, i controls the next number to print, and j controls how many numbers you will print in the current line. k is just a counter for j.
You can also try this with some mathematic magic (sequences).
for (int j = 1; j <= 4; j++) {
for (int k=(int) (0.5*(Math.pow(j,2)-j+2));k<=(int) (0.5*j*(j+1));k++) {
System.out.print(k + " ");
}
System.out.println();
}

Categories

Resources