Search Logic Blocks

Showing posts with label Java Programs. Show all posts
Showing posts with label Java Programs. Show all posts

Monday, October 19, 2020

Java: Let's Practice - How to create Fibonacci sequence through recursion

What is the Fibonacci sequence?
Fibonacci sequence is a sequence of numbers generating new number by adding two previous numbers. It starts with 0 and 1.

SequenceLast two nos.
0
1
10+1
21+1
31+2
52+3

0, 1, 1, 2, 3, 5, 8, 13.......

So, to create recursive method to get next number in the sequence, program should use the same method which calculates the previous numbers of the sequence -

fib(0) = 0
fib(1) = 1
fib(2) = fib(1) + fib(0)
fib(3) = fib(2) + fib(1)
........
fib(n) = fib(n-1) + fib(n-2)

Here is the code -
import java.util.Scanner;

public class FibonacciDemo {
static int[] fibnos;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
fibnos = new int[n+1];
int fib = fibonacci(n);
System.out.println(n + "th number in the Fibonacci Sequence (0, 1, 2, ...) is : " + fib);

for(int i = 0; i < fibnos.length; i++) {
System.out.print(fibnos[i] + ", ");
}
}

public static int fibonacci(int n) {
int result = 0;

if(n == 0) {
fibnos[0] = 0;
return 0;
}
if(n == 1) {
fibnos[1] = 1;
return 1;
}
result = fibonacci(n-1) + fibonacci(n-2);
fibnos[n] = result;
return result;
}
}
And here is the output -

Enter the number: 6
6th number in the Fibonacci Sequence (0, 1, 2, ...) is : 8
0, 1, 1, 2, 3, 5, 8, 

And here is the explanation -

The program asks user to enter any number n. It passes the number to calculate the nth number of the sequence. The method calculates the next number recursively and returns the result back. The numbers are added into an array to display the sequence.

Code can be found on the Github.

Sunday, October 11, 2020

Java: Let's Practice - How to calculate factorial through recursion

I have already explained about recursion in earlier post and shown the example Reverse the string. In this post, we will use recursion method to calculate the factorial of a number.

What is factorial of a number?
Factorial of a number is the product of all numbers counting backwards from the given number till number 1. Suppose number is 5, so factorial of number 5 is equal to 5 * 4 * 3 * 2 * 1

f(5) = 5 * 4 * 3 * 2 * 1
f(4) = 4 * 3 * 2 * 1
f(3) = 3 * 2 * 1

We can notice the pattern to calculate the factorial.

f(n) = n * f(n-1)

We will use this pattern for recursion. The program will call the same method recursively till the number is 1 and then it will calculate the backwards and return the result.

Here is the program -
import java.util.Scanner;

public class FactorialDemo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
int fact = factorial(n);
System.out.println("Factorial of the number " + n + " is: " + fact);
}

public static int factorial(int n) {
int result = n;
if(n != 1)
result = result * factorial(n-1);
return result;
}

}
Here is the output - 

Enter the number: 5
Factorial of the number 5 is: 120

The program asks user to enter any number. It passes the number to a method factorial() which calculates the factorial of the number. 
  • The method factorial() method calls itself recursively by decreasing the number by 1 till the number is 1. It returns 1 when the number is 1. 
  • Then it multiplies by 2 and then returns result back to the calling method. 
  • Multiplies by 3 and then returns result back to the calling method.
  • And so on till it reaches the original number
  • When it reaches the original number, multiplies and it returns the final result back to main method.
Code can be found here on Github.

Friday, July 31, 2020

Java: Let's Practice - Convert Binary Numbers to Decimal Numbers and Decimal Numbers to Binary Numbers

We already know what are the bits, bytes and binary values. And we also know how to convert binary numbers to decimal numbers and decimal numbers to binary numbers. Let's write a program to convert user entered binary number into decimal number and  decimal number into binary number.

Convert Binary Number To Decimal Number
Here is the example for the conversion from binary number to decimal number -

10100101
1 x 270 x 261 x 250 x 240 x 231 x 220 x 211 x 20
12803200401

Decimal Value for 1010 0101 is = 128 + 32 + 4 + 1 = 165.

Let's establish the logic behind this conversion. 
  1. First, we need to have binary number as a long data type to have enough bits in the binary value. Long binaryVal = 10100101
  2. The program will read every bit of the binary value from right to left in while loop. We can get each bit by using the remainder operator (binaryVal % 10) and convert it to integer as the data type is Long
  3. The remainder will be multiplied by 2 to the power of bit position from right to left. The product will be added to the old product.
  4. New binary value will be (binaryVal / 10) and go back to while loop. Loop will terminate when binaryVal is 0.
Loop Logic -
10100101 % 10 => 1 => 1x2=> 1 and 10100101 / 10 => 1010010
1010010 % 10 => 0 => 0x2=> 0 and 1010010 / 10 => 101001
101001 % 10 => 1 => 1x22 => 4 and 101001 / 10 => 10100
10100 % 10 => 0 => 0x23 => 0 and 10100 / 10 => 1010
1010 % 10 => 0 => 0x2 => 0 and 1010 / 10 => 101
101 % 10 => 1 => 1x2 => 32 and 101 / 10 => 10 
10 % 10 => 0 => 0x2 => 0 and 10 / 10 => 1 
1 % 10 => 1 => 1x2 => 128 and 1 / 10 => 0

1 + 0 + 4 + 0 + 0 + 32 + 0 + 128 = 165

Here is the program for conversion binary number to decimal number. The program has an extra method to calculate the power of number. Java has a built-in method Java.lang.Math.pow() but only for parameters as double data type. So, I wrote a method for int data type - int calcPower(int no1, int no2)
import java.util.Scanner;

public class BinaryToDecimal {
public static void main(String args[]) {
System.out.println("Enter the binary value");
Scanner sc = new Scanner(System.in);
Long binaryVal = sc.nextLong();

int decVal = 0;
int rem, pow = 0;
Long origBinaryVal = binaryVal;

while(binaryVal != 0) {
rem = (int)(binaryVal % 10);
decVal = decVal + rem * calcPower(2, pow);
binaryVal = binaryVal / 10;
pow++;
}
System.out.println("Binary Value: " + origBinaryVal);
System.out.println("Decimal Value: " + decVal);
}

// Calculates no1 To The Power no2
static int calcPower(int no1, int no2) {
int powVal = 1;
for(int i = 0; i < no2; i++) {
powVal = powVal * no1;
}
return powVal;
}
}
And the output is:

Enter the binary value
10100101
Binary Value: 10100101
Decimal Value: 165

Convert Decimal Number To Binary Number
Here is the example for the conversion from decimal number to binary number -

Divide by 2QuotientRemainder2 to the power
165 / 282120
82 / 241021
41 / 220122
20 / 210023
10 / 25024
5 / 22125
2 / 21026
1 / 20127

Binary Number for 165 is = 10100101

Let's establish the logic behind this conversion. 
  1. Divide decimal value by 2 and get quotient and remainder values. Multiply the remainder by 10 to the power of bit's position. Result is the leftmost bit for the binary number. New decimal value is equal to quotient.
  2. Repeat step 1 for new decimal value. Add the result to the earlier result.
  3. Repeat the steps till decimal value is 0. The total result is the converted binary number.
Loop Logic -
165 % 2 => 1 => 1x10=> 1 and 165 / 2 => 82
82 % 2 => 0 => 0x10=> 0 and 82 / 2 => 41
41 % 2 => 1 => 1x102 => 100 and 41 / 2 => 20
20 % 2 => 0 => 0x103 => 0 and 20 / 2 => 10
10 % 2 => 0 => 0x10 => 0 and 10 / 2 => 5
5 % 2 => 1 => 1x10 => 100000 and 5 / 2 => 2 
2 % 2 => 0 => 0x10 => 0 and 2 / 2 => 1 
1 % 2 => 1 => 1x10 => 10000000 and 1 / 2 => 0

1 + 0 + 100 + 0 + 0 + 100000 + 0 + 10000000 = 10100101

Here is the program for conversion binary number to decimal number.
import java.util.Scanner;

public class DecimalToBinary {
public static void main(String args[]) {
System.out.println("Enter the decimal value");
Scanner sc = new Scanner(System.in);
int decVal = sc.nextInt();

Long binaryVal = 0L;
int rem, pow = 0;
int origDecVal = decVal;

while(decVal != 0) {
rem = (int)(decVal % 2);
decVal = decVal / 2;
binaryVal = binaryVal + rem * calcPower(10, pow);
pow++;
}

System.out.println("Decimal Value: " + origDecVal);
System.out.println("Binary Value: " + binaryVal);
}

// Calculates no1 To The Power no2
static int calcPower(int no1, int no2) {
int powVal = 1;
for(int i = 0; i < no2; i++) {
powVal = powVal * no1;
}
return powVal;
}
}
And the output is:

Enter the decimal value
165
Decimal Value: 165
Binary Value: 10100101

Code can be accessed here: Github Link

Wednesday, July 1, 2020

Java: Let's Practice - Prime Numbers

Let's write a program to find all the prime numbers between two numbers - 

I have already explained in my earlier post - Why Logic Blocks?, that logic thinking is very important for problem solving and writing programs. So, we will build the logic to examine how we can find all the prime numbers between two numbers.

What are the prime numbers?
Prime numbers are which can be wholly divided by 1 or itself, but not any other number. Or in other words, you can say that the number is a prime number if it has only two factors - 1 and itself.

Create a logic
Suppose, we have two numbers 2 and 50, and we have to find prime numbers between these two numbers. 
  1. We need to check each and every number to find all the prime numbers, but logic will be the same for each number. So, we need a for loop to repeat the logic for each number between 2 and 50. This loop will be iterate between numbers 2 and 50. For Loop and For-each Loop
  2. But we know, that all even numbers can be divided by 2, and they can't be the prime numbers. We will avoid checking even numbers. So, for loop will run for only odd numbers starting from 3 to 49.
  3. If they are not even numbers, we should not check the odd numbers dividing by even numbers. We will avoid by dividing only by odd numbers. So, there will be another inner for loop which will run between 3 and till the number we are checking for in outer (step 2) for loop.
  4. We need a Boolean variable to set, if the number is prime - set it true, and if number is not prime - set it false. We will use remainder operator (%) (Arithmetic Operators) to determine if the number can be divisible by another number. Initially set prime boolean value as true, if remainder is 0 then set prime boolean value as false. And once it is proved that the number is not prime number, you come out from the inner loop, no need to continue for more checking. We use break statement to come out from the loop. Break Statement
  5. Print only the numbers which have prime boolean value as true, when come out from the inner loop.
Program to find the prime numbers between 2 and 50

Class PrimeNumber (PrimeNumber.java)
public class PrimeNumber {
public static void main(String args[]) {
// Find prime numbers between n1 and n2
int n1 = 2, n2 = 50;

// Set as the number is prime
boolean prime = true;
// Check only odd numbers
for(int i = 3; i < n2; i = i + 2) { // Outer Loop
// Divide by only odd numbers and till outer loop number
for(int j = 3; j < i; j = j + 2) { // Inner Loop
// If remainder is 0 then number is not prime
if((i % j) == 0) {
prime = false;
break;
}
}
if(prime) System.out.print(i + " ");
prime = true;
}
System.out.println(" ");
}
}
Let's analyze above program using the logic steps above -
for(int i = 3; i < n2; i = i + 2) {}
Outer for loop in above statement, starts with initializing a local variable i with value 3 and runs the loop till i's value as n2 (50). And in the increment part, the value of i is incremented by 2 to avoid even numbers. The loop will run for possible values of i => 3, 5, 7, 9, 11, .......... , 49
for(int j = 3; j < i; j = j + 2) {}
Inner for loop in above statement, starts with initializing a local variable j with value 3 and runs the loop till j's value as i's value in outer loop. And also in the increment part, the value of j is incremented by 2 to avoid division by even numbers. The loop will run for possible values of j -
  • if i = 3 then no inner loop. 
  • if i = 5 then j => 3
  • if i = 7 then j => 3, 5
  • if i = 13 then j => 3, 5, 7, 9, 11
if((i % j) == 0) {
prime = false;
break;
}
As soon as program finds that number is not the prime number, it comes out from the inner loop and continues the outer loop.
if(prime) System.out.print(i + " ");
If the number is prime, it will continue the inner loop till all the possible values of j and then print the number. Output will be like -

3 5 7 11 13 17 19 23 29 31 37 41 43 47

Note: Here in the above program, I tried to simplify the logic and convert into the program instructions. In reality, the problems are very complex. You just have break them down to simple steps and then create the logic. I hope this post is helpful for the brginners who are learning how to program.

Saturday, June 13, 2020

Java: How to reverse any string backwards using recursive method

What is recursive method?
Recursive method is a method which calls itself. There should always be a condition on which the recursion stops, else it will keep running indefinitely. Suppose we have to add numbers consecutively for particular start and end numbers.

Suppose start number is 2 and end number is 8, then consecutively you will add like below -
total = start + ..................... + end 
= 2 + 3 + 4 + 5 + 6 + 7 + 8
= 5 + 4 + 5 + 6 + 7 + 8
= 9 + 5 + 6 + 7 + 8
= 14 + 6 + 7 + 8
= 20 + 7 + 8
= 27 + 8
= 35

We use the same concept for writing recursive method to add consecutive numbers.

Class SumRecursive (SumRecursive.java)
public class SumRecursive {
public static void main(String args[]) {
int start = 2, end = 8;
int next = start + 1;
int total = sum(start, next, end);
System.out.println("Total is: " + total);
}

public static int sum(int total, int next, int end) {
int tot = total + next;
if(next != end) {
next++;
tot = sum(tot, next, end);
}
return tot;
}
}
Here is the output:

Total is: 35

Reverse the string using recursive method
To reverse a string, we have created two methods - revStr() and swapChars(). In the main method, user is asked to enter any string. String is converted to a char array. The converted array is passed to the method revStr() as the parameter. revStr() method calls method swapChars() and pass the char array and the first and last character positions to swap. Here is the logic -

Suppose user enters the string: "Logic Blocks" -

Converted char array will be like this.
ch[] = {'L', 'o', 'g', 'i', 'c', ' ', 'B', 'l', 'o', 'c', 'k', 's'}

Characters will be swapped like this
'L' = > 's'
'o' = > 'k'
'g' = > 'c'
'i' = > 'o'
'c' = > 'l'
' ' = > 'B'

Reversed String will be like this 
"skcolB cigoL"

Class Reverse (Reverse.java)
import java.util.Scanner;

public class Reverse {
public static void main(String args[]) {
String s1, s2;
char ch[];

System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();

ch = s1.toCharArray();
s2 = revStr(ch);

System.out.println();

System.out.println("String backwards:");
System.out.println(s2);
}

public static String revStr(char[] ch) {
swapChars(ch, 0, ch.length-1);

String str = String.valueOf(ch);
return str;
}

public static void swapChars(char[] ch, int left, int right) {
if(left < right) {
char tch = ch[left];
ch[left] = ch[right];
ch[right] = tch;
swapChars(ch, left+1, right-1);
}
}
}
Here is the output:

Enter the string:
Logic Blocks

String backwards:
skcolB cigoL

Friday, June 12, 2020

Java: Example of passing object reference as the parameter

When a method is called in a program, parameters can be passed two ways -

Call by Value
When a variable is passed as a parameter to a method, the method can use the value of the variable or manipulate the value in the method and can return the new value. But any changes in the variable value doesn't reflect after returning from the method. Method doesn't change the value of original variable. Here is the example -

Class CallByVal (CallByVal.java)
public class CallByVal {
    public static void main(String args[]) {
        int i = 5;

        System.out.println("Original Value: " + i);

        int y = doubleVal(i);

        System.out.println("After Method Called: " + i);
        System.out.println("Doubled Value: " + y);

    }

    public static int doubleVal(int x) {
        x = x * 2;
        return x;
    }
}
A class CallByVal is created and an int variable i is declared and initialized to 5. There is one static* method defined in the class which returns the double of the passed value - doubleVal(). In the method, the parameter value is doubled. It returns the doubled value in different variable. After method, still the original variable i has the same value.

*Why static method? - static methods can call only static methods, main method is static method so called method is also static method.

Call by Reference
When a object is passed as a parameter to a method, then the reference of the object is passed to the method, and any changes to the object in the method, reflects after returning from the method. The method has still the reference to the original object and changes the value in the original object.

So, here is the example of passing object reference as the parameter -

Suppose there are two players and they throw the dice turn by turn and whoever has more, gets scored. They play 15 times. A class Score is created for to keep a track of scores. A constructor sets the initial value of score as 0. There are two methods in the class - setScore() and getScore().

Class Score (Score.java)
public class Score {
    private int val;
    Score(int i) { val = i; }

    static void setScore(Score sc) {
        sc.val++;
    }

    int getScore() {
        return val;
    }
}
setScore() is a static method so it can be accessed by class itself. It takes one parameter - Score  class object. The method increases the score value by 1.

getScore() method is regular method which can only be accessed through the object of the Score class. It returns the score value for the particular player.

Class ScoreDemo (ScoreDemo.java)
import java.lang.Math;

public class ScoreDemo {
    public static void main(String args[]) {
        int max = 6;
        int min = 1;
        int range = max - min + 1;

        Score s1 = new Score(0);
        Score s2 = new Score(0);

        System.out.println("Initial Score: ");
        System.out.println("Player1 " + s1.getScore());
        System.out.println("Player2 " + s2.getScore());

        for(int i = 0; i < 15; i++) {
            int dice1 = (int)(Math.random() * range) + min;
            int dice2 = (int)(Math.random() * range) + min;
            if(dice1 > dice2) Score.setScore(s1);
            else Score.setScore(s2);
        }

        System.out.println();
        System.out.println("Final Score: ");
        System.out.println("Player1 " + s1.getScore());
        System.out.println("Player2 " + s2.getScore());

    }
}
A class ScoreDemo initializes two variables max and min as 6 and 1, like a dice can have. A range is also set as total possible values. Two objects of class Score created. There is a for loop for 15 iterations - players throw dice turn by turn (number is generated randomly between 1 to 6 like dice). If player1 has more than player2, score1 value is increased. else score2 value is increased. Here is the sample output -

Initial Score:
Player1 0
Player2 0

Final Score:
Player1 7
Player2 8

Notice that how the method setScore() is declared in the class Score, and how it is called in class ScoreDemo using the class name itself: Score. This is a good example of passing object reference to a method.

Thursday, June 11, 2020

Java: How to create a class Stack

What is Stack? 

It is basically pile of anything kept in such way that things are accessed in LIFO (Last In First Out) order. A very good example is when we stack the plates. And we pick up the last plate first, and when we put more plates, we stack them up.

Stack in computer language is an array of any data type elements / class objects where the data is pushed or stacked one on top of another and always the last element is popped or retrieved first. Here is the implementation of Stack class.

In the following example, two classes are created - Stack and StackDemo.

Class Stack is a simple representation of a stack. Here stack is in the form of a character array. There is a constructor for the class Stack, which creates a character array for the given size and set pointer to start of the array. All the data members of the class Stack are kept private to avoid direct access from other classes.

There are two methods push and pop - push method checks if the stack is full, if not puts the element into last available index and increases index value by 1. pop method checks if the stack is empty, if not pops the last index element from the stack and then decreases the index value by 1.

Class StackDemo simply shows how to use the push and pop method from the class Stack.

Class Stack (Stack.java)
public class Stack {

    private char ch[];
    private int size, lastIndex;

    Stack(int size) {
        this.size = size;
        ch = new char[size];
        lastIndex = 0;
    }

    void push(char c) {
        if(lastIndex == size) {
            System.out.println("Stack is full");
            return;
        }

        ch[lastIndex] = c;
        System.out.print(c + " ");
        lastIndex++;
    }

    void pop() {
        if(lastIndex == 0) {
            System.out.println("Stack is empty");
            return;
        }

        System.out.print(ch[lastIndex-1] + " ");
        lastIndex--;
    }
}
Class StackDemo (StackDemo.java)
public class StackDemo {
    public static void main(String args[]) {
        Stack s1 = new Stack(10);

        System.out.println("Push to stack:");
        s1.push('j');
        s1.push('a');
        s1.push('v');
        s1.push('a');

        System.out.println("");
        System.out.println("Pop from stack:");

        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();

        System.out.println("");
        System.out.println("Push to stack:");

        s1.push('s');
        s1.push('t');
        s1.push('a');
        s1.push('c');
        s1.push('k');

        System.out.println("");
        System.out.println("Pop from stack:");

        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
    }
}
Output
Push to stack:
j a v a
Pop from stack:
a v a j Stack is empty

Push to stack:
s t a c k
Pop from stack:
k c a t s Stack is empty

Wednesday, February 19, 2020

Java: Let's Practice - Create Patterns with numbers - Heart

Exercise: Let's create Heart pattern -

12345678910111213141516171819
15555
24444
33333
42222
5111
611
722
833
944
1055
1155
1244
1333
1422
151

Solution: 

Step 1: Count the rows and columns needed - 15 rows and 19 columns.

Step 2: There will be a for loop for 15 rows. See the pattern of numbers how they are ordered. There are 3 different patterns - row 1 - 5, row 6 - 10 and row 11 - 15. Using if conditions, separate code for each pattern.

Step 3: Start declaring 4 variables having column numbers in first row, which are not empty and one variable having value for that row. In first row, we have four cells - 5, 6, 14, 15 which are having number 5 as value and other cells have spaces.
int cell1 = 5, cell2 = 6, cell3 = 14, cell4 = 15, val = 5;
Step 4: Start writing a for loop which will run 15 times, one loop is equivalent to one row. Last statement in the loop should be println() statement, so next iteration will start for next row. Divide the loop in 3 sections for three patterns using if condition with row number. The code will look like this -
for (int i = 1; i <= 15; i++) {
    if(i <= 5) {
    
    } else if(i >=6 && i <=10){
    
    }
    else if(i >=11 && i <=15){
    
    }
    System.out.println("");
}
Step 5: For row numbers 1 to 5, there should be a for loop for 19 columns (19 cells) and for each iteration, there are few if conditions -
if cell number is less than cell1, then spaces - 
if(j < cell1) System.out.print("  ");
if cell number is greater than cell2 and cell number is less than cell3, then spaces -
if(j > cell2 && j < cell3) System.out.print("  ");
if cell number isequal to cell1 or cell2 or cell3 or cell4, then print value as val -
if(j == cell1 || j == cell2 || j == cell3 || j == cell4) System.out.print(val + " ");
if cell number is greater than cell1 and cell number is less than cell2, then spaces -
if(j > cell1 && j < cell2) System.out.print("  ");
if cell number is greater than cell3 and cell number is less than cell4, then spaces -
if(j > cell3 && j < cell4) System.out.print("  ");
After finishing the for loop, decrease cell1 and cell3 by 1 and increase cell2 and cell4 by 1, and decrease value by 1 -
cell1--; cell2++; cell3--; cell4++;
val--;
When you integrate the code, it will look like this -
if(i <= 5) {
    for (int j = 1; j <= 19; j++) {
        if(j < cell1) System.out.print("  ");
        if(j > cell2 && j < cell3) System.out.print("  ");
        if(j == cell1 || j == cell2 || j == cell3 || j == cell4) System.out.print(val + " ");
        if(j > cell1 && j < cell2) System.out.print("  ");
        if(j > cell3 && j < cell4) System.out.print("  ");
    }
    cell1--; cell2++; cell3--; cell4++;
    val--;
}
Step 6: For row numbers 6 to 10, there should be a for loop for 19 columns (19 cells) and for each iteration, in these rows we use only two cells - cell1 and cell4 there are few if conditions -
Before loop starts, increase cell1 and decrease cell4 by 1, and val increase by 1 -
cell1++;cell4--;val++;
In the for loop -
if cell number is less than cell1, then spaces - 
if(j < cell1) System.out.print("  ");
if cell number is equal to cell1 or cell4, then print value as val -
if(j == cell1 || j == cell4) System.out.print(val + " ");
if cell number is greater than cell1 and cell number is less than cell4, then spaces -
if(j > cell1 && j < cell4) System.out.print("  ");
When you integrate the code, it will look like this -
else if(i >=6 && i <=10){
    cell1++;cell4--;val++;
    for (int j = 1; j <= 19; j++) {
        if(j < cell1) System.out.print("  ");
        if(j == cell1 || j == cell4) System.out.print(val + " ");
        if(j > cell1 && j < cell4) System.out.print("  ");
    }
}
Step 7: For row numbers 11 to 15, there should be a for loop for 19 columns (19 cells) and for each iteration, there are few if conditions -
Before loop starts, increase cell1 and decrease cell4 by 1,
cell1++;cell4--;
In the for loop -
if cell number is less than cell1, then spaces - 
if(j < cell1) System.out.print("  ");
if cell number is equal to cell1 or cell4, then print value as val -
if(j == cell1 || j == cell4) System.out.print(val + " ");
if cell number is greater than cell1 and cell number is less than cell4, then spaces -
if(j > cell1 && j < cell4) System.out.print("  ");
When you integrate the code, it will look like this -
else if(i >=11 && i <=15){
    cell1++;cell4--;
    for (int j = 1; j <= 19; j++) {
        if(j < cell1) System.out.print("  ");
        if(j == cell1 || j == cell4) System.out.print(val + " ");
        if(j > cell1 && j < cell4) System.out.print("  ");
    }
    val--;
}
After each for loop, decrease val by 1 -
val--;
Step 8: The whole integrated code will look like as follows. Save the program file as CreateHeartPattern.java file.

Class CreateHeartPattern (CreateHeartPattern.java)
public class CreateHeartPattern {
    public static void main(String args[]) {
        int cell1 = 5, cell2 = 6, cell3 = 14, cell4 = 15, val = 5;
        for (int i = 1; i <= 15; i++) {
            if(i <= 5) {
                for (int j = 1; j <= 19; j++) {
                    if(j < cell1) System.out.print("  ");
                    if(j > cell2 && j < cell3) System.out.print("  ");
                    if(j == cell1 || j == cell2 || j == cell3 || j == cell4) System.out.print(val + " ");
                    if(j > cell1 && j < cell2) System.out.print("  ");
                    if(j > cell3 && j < cell4) System.out.print("  ");
                }
                cell1--; cell2++; cell3--; cell4++;
                val--;
            } else if(i >=6 && i <=10){
                cell1++;cell4--;val++;
                for (int j = 1; j <= 19; j++) {
                    if(j < cell1) System.out.print("  ");
                    if(j == cell1 || j == cell4) System.out.print(val + " ");
                    if(j > cell1 && j < cell4) System.out.print("  ");
                }
            }
            else if(i >=11 && i <=15){
                cell1++;cell4--;
                for (int j = 1; j <= 19; j++) {
                    if(j < cell1) System.out.print("  ");
                    if(j == cell1 || j == cell4) System.out.print(val + " ");
                    if(j > cell1 && j < cell4) System.out.print("  ");
                }
                val--;
            }
            System.out.println("");
        }
    }
}
The result will look like as follows -  

5 5 5 5
4 4 4 4
3 3 3 3
2 2 2 2
1 1 1
1 1
2 2
3 3
4 4
5 5
5 5
4 4
3 3
2 2
1