Search Logic Blocks

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

Wednesday, February 12, 2020

Java: Let's Practice - Create different patterns with numbers - Diamond

Write a program to create a pattern like below - 

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9

Step1: Count the number of rows and columns needed.

Total no of columns - 9 and total no of rows - 9

Step2: Make a grid to see what character will fall in which row and which column. And notice if there is some pattern (repeating characters in some particular way).


1 2 3 4 5 6 7 8 9
1 1
2 1 2
3 1 2 3
4 1 2 3 4
5 1 2 3 4 5
6 1 2 3 4 5 6
7 1 2 3 4 5 6 7
8 1 2 3 4 5 6 7 8
9 1 2 3 4 5 6 7 8 9

Here, we notice that numbers are incremented in every row and it's a diagonal. So, here we can write one print statement for each row or we can have for loop to print the numbers diagonally. There might be other methods too, but I will show you only two methods.

Step3: Start writing a Java program by crating a class and main method.

public class CreatePattern {
    public static void main(String args[]) {
        
    }
}
Step4: In main method - 
Method1: write sout (System.out.println) statements equal to number of rows required. So, there are 9 rows means 9 println statements.
System.out.println("1");
System.out.println("1 2");
System.out.println("1 2 3");
System.out.println("1 2 3 4");
System.out.println("1 2 3 4 5");
System.out.println("1 2 3 4 5 6");
System.out.println("1 2 3 4 5 6 7");
System.out.println("1 2 3 4 5 6 7 8");
System.out.println("1 2 3 4 5 6 7 8 9");
Method2: write for loop - as you can see that there is a pattern. 1st row has only number 1, 2nd row has 2 numbers 1,2 and so on.... We need here nested for loops (one for loop in other for loop) - first for loop is for each row and inner loop is for each column.

for (int i = 1; i <= 9; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println("");
}
Here, notice that I am using print statement in the for loop to write the numbers in one row and after end of inner loop, I have a println statement to create next row. Outer loop is run for 9 times for 9 rows. Inner loop runs only i times (1st row - 1, 2nd row - 2 times, and so on....) and j is printed as j value starts from 1 and is increnmented till i.

Step5: Here is the final program with both methods -
Method1: 

Class CreatePattern1 (CreatePattern1.java)
public class CreatePattern1 {
    public static void main(String args[]) {
        System.out.println("1");
        System.out.println("1 2");
        System.out.println("1 2 3");
        System.out.println("1 2 3 4");
        System.out.println("1 2 3 4 5");
        System.out.println("1 2 3 4 5 6");
        System.out.println("1 2 3 4 5 6 7");
        System.out.println("1 2 3 4 5 6 7 8");
        System.out.println("1 2 3 4 5 6 7 8 9"); 
    }
}
Method2: 

Class CreatePattern2 (CreatePattern2.java)
public class CreatePattern2 {
    public static void main(String args[]) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    }
}
Let's try another pattern (Diamond) -

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

Step1: Let's count the number of rows and columns needed -

Total no of 9 columns and 9 rows required.

Step2: Make a grid of pattern -


1 2 3 4 5 6 7 8 9
1 1
2 2 1 2
3 3 2 1 2 3
4 4 3 2 1 2 3 4
5 5 4 3 2 1 2 3 4 5
6 4 3 2 1 2 3 4
7 3 2 1 2 3
8 2 1 2
9 1

Here, we notice that numbers form diamond, numbers are increasing in both directions and then decreasing in both directions. We need a lot of for loops going up and down.

Step3: Start writing the program by creating the class and main method.
public class CreateDiamondPattern {
    public static void main(String args[]) {
        
    }
}
Step4: In the main method - we require different loops for increasing numbers and decreasing numbers. Let's start with number of rows - for loop for 9 rows -
for (int i = 1; i <= 9; i++) {
    
}
This is the main outer loop which will run for 9 times for value of i from 1 to 9. As you notice that the numbers are increasing till row 5 and then the numbers are decreasing. So, we will create two separate inner for loops for rows 1 to 5 and 6 to 9. Here, we write an if statement to check row number, if it is less than or equal to 5 or not. If part and else parts will have separate for loops -
for (int i = 1; i <= 9; i++) {
    if(i <= 5) {
        
    } else {
        
    }
    System.out.println("");
}
Here, the in the outer loop, we have a condition for each row. First 5 rows there is a diffrferent pattern and remaining 4 rows there is a different pattern. When row is completed println statement goes to next row. 

First 5 rows (if part)
decreasing the number of spaces in first 4 columns - 
for (int j = i; j < 5; j++) {
    System.out.print("  ");
}
increasing number in each row but counting backwards for first 5 columns -
for (int j = i; j >= 1; j--) {
    System.out.print(j + " ");
}
increasing number in each row and counting forward for remaining 4 columns -
for (int j = 2; j <= i; j++) {
    System.out.print(j + " ");
}
so, integrated code for first rows is -
if(i <= 5) {
    for (int j = i; j < 5; j++) {
        System.out.print("  ");
    }
    for (int j = i; j >= 1; j--) {
        System.out.print(j + " ");
    }
    for (int j = 2; j <= i; j++) {
        System.out.print(j + " ");
    }
}
Last 4 rows (else part)
increasing the number of spaces in first 4 columns -
for (int j = i; j > 5; j--) {
    System.out.print("  ");
}
decreasing number in each row (6 to 9) but counting backwards for first 5 columns -
for (int j = (10-i); j >=1; j--) {
    System.out.print(j + " ");
}
decreasing number in each row and counting forward for remaining 4 columns -
for (int j = 2; j <= (10-i); j++) {
    System.out.print(j + " ");
}
so, integrated code for last 4 rows is -
else {
    for (int j = i; j > 5; j--) {
        System.out.print("  ");
    }
    for (int j = (10-i); j >=1; j--) {
        System.out.print(j + " ");
    }
    for (int j = 2; j <= (10-i); j++) {
        System.out.print(j + " ");
    }

}
Step5: Here is the full code to create the diamond pattern -

Class CreateDiamondPattern (CreateDiamondPattern.java)
public class CreateDiamondPattern {
    public static void main(String args[]) {
        for (int i = 1; i <= 9; i++) {
            if(i <= 5) {
                for (int j = i; j < 5; j++) {
                    System.out.print("  ");
                }
                for (int j = i; j >= 1; j--) {
                    System.out.print(j + " ");
                }
                for (int j = 2; j <= i; j++) {
                    System.out.print(j + " ");
                }
            } else {
                for (int j = i; j > 5; j--) {
                    System.out.print("  ");
                }
                for (int j = (10-i); j >=1; j--) {
                    System.out.print(j + " ");
                }
                for (int j = 2; j <= (10-i); j++) {
                    System.out.print(j + " ");
                }

            }
            System.out.println("");
        }
    }
}

Tuesday, February 4, 2020

Java: Let's Practice Series

So, I think we have a basic idea about how Java program works and how we can make use of classes, methods and variables, and also loops, conditional statements etc. to solve small problems. We will keep learning and exploring more deeper as Java is a vast language.

As you know I named this blog as Logic Blocks. I have written a separate post why I have named this blog as Logic Blocks. Today, I am going to start a Let's Practice Series, and in each post in this series I will solve problems logically (step by step) and then I will translate that logic into Java program. I will provide you test data and results, so you can try on your own.

NOTE: Why do I want to explain the logic in detail? As when I start learning programming in 1995, I started to learn C. I learnt the language as part of our course. But there was none to tell me how to write the logic to solve the problem. I learned it with my own experience. 

We will start with small examples. I will explain how can you break a problem into small-small steps. And how can you change those steps into a code. I will try to break program in every possible logical step.

When you solve a math problem, you find that there are more than one method to solve a problem. Similarly, to write a code to achieve some output, there is more than one way. So, it's not hard & fast rule that you follow my code. You should understand the process to create the logic behind the code. That will also help you to understand other developer's code.

Suppose there is a problem: Write a program to calculate factorial of 5. To get factorial I choose to have a for loop in two different ways.

1. For loop with variable increment

Class Factorial1 (Factorial1.java)
public class Factorial1 {
    public static void main(String args[]) {
        int val = 5;
        int fact = 1 ;
        for(int i = 1; i <= 5; i++) {
            fact = fact * i;
        }
        System.out.println("Factorial of 5 is: " + fact);
    }
}
And the output is:

Factorial of 5 is: 120

2. For loop with variable decrement

Class Factorial2 (Factorial2.java)
public class Factorial2 {
    public static void main(String args[]) {
        int val = 5;
        int fact = 1 ;
        for(int i = 5; i >= 1; i--) {
            fact = fact * i;
        }
        System.out.println("Factorial of 5 is: " + fact);
    }
}
And the output is:

Factorial of 5 is: 120

You might be solving the factorial using any other loop options - like while / do while loops or changing for loop options. So, there is no one way. Sometimes, you will find there are several options to solve the same problem. So, coming up our Let's Practice Series!!

Saturday, February 1, 2020

Java: Let's work on some problems

Problem: Using program in earlier post Classes and Objects, add two more class variables for name of dog and type of dog. Modify the constructor to set the values. Create one method to access all the details about the dog.
// Dog.Java

Class Dog (Dog.java)
import java.awt.*;

public class Dog {
    String name;
    String type;
    int age;
    int size;
    Color color;
    String colorName;

    Dog(String name, String type, int age, int size, Color color) {
        this.name = name;
        this.type = type;
        this.age = age;
        this.size = size;
        this.color = color;
    }

    public int getAge() {
        return this.age;
    }

    public void bark() {
        System.out.println("Bark - woof, woof");
    }

    public Color getColor() {
        return this.color;
    }

    public void getDogDetails() {
        System.out.println("Dog's Details:");
        System.out.println("Name: " + name);
        System.out.println("Type: " + type);
        System.out.println("Age : " + age);
        System.out.println("Size: " + size);
    }
}
// DogTest.java
Class DogTest (DogTest.java)
import java.awt.*;

public class DogTest {
    public static void main(String args[]) {
        Dog dog1 = new Dog("Tommy", "Bulldog",3, 4, Color.WHITE);

        dog1.getDogDetails();
        dog1.bark();
    }
}
Problem: In the example given in the post Static Variables, suppose we have to keep a counter how many kids have age greater than 8. Write a full program with an example output.
// Student.java
Class Student (Student.java)

public class Student {
    String name;
    int age;
    static int total = 0;
    static int gr8Total = 0;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
        total++;
        if(age >= 8) gr8Total++;
    }
}
// StudenTest.java
Class StudentTest (StudentTest.java)
public class StudentTest {
    public static void main(String args[]) {
        Student s1 = new Student("John", 6);
        Student s2 = new Student("Adam", 9);
        Student s3 = new Student("Alex", 7);
        System.out.println("Student1 -");
        System.out.print("Name  : " + s1.name + ", ");
        System.out.print("age   : " + s1.age + ", ");
        System.out.println("");

        System.out.println("Student2 -");
        System.out.print("Name  : " + s2.name + ", ");
        System.out.print("age   : " + s2.age + ", ");
        System.out.println("");

        System.out.println("Student3 -");
        System.out.print("Name  : " + s3.name + ", ");
        System.out.print("age   : " + s3.age + ", ");
        System.out.println("");

        System.out.print("Total Students Having Age Greater Than 8 - ");
        System.out.println(Student.gr8Total);
    }
}
// Output
Student1 -
Name  : John, age   : 6, 
Student2 -
Name  : Adam, age   : 9, 
Student3 -
Name  : Alex, age   : 7, 
Total Students Having Age Greater Than 8 - 1
Problem: When you try to call a non-static method from the static method, what kind of error do you get?

Solution: The program will give compilation error. - "java: non-static method <method> cannot be referenced from a static context"

Problem: Create an array of 6 double values and print them backwards.

Class ArrBack (ArrBack.java)
public class ArrBack {
    public static void main(String args[]) {
        double nums[] = {11.5, 3.2, 9.1, 11.80, 20.23, 70.76};

        for(int i = (nums.length-1); i >= 0; i--) {
            System.out.println("nums[" + i + "]: " + nums[i]);
        }
    }
}
// Output
nums[5]: 70.76
nums[4]: 20.23
nums[3]: 11.8
nums[2]: 9.1
nums[1]: 3.2
nums[0]: 11.5
Problem: Change the class ArrTest given in the post for-each loop to compute the average of the elements of the array. 

Class Average (Average.java)
public class Average {
    public static void main(String args[]) {
        int nums[] = {11, 3, 7, 8, 20, 16};
        int sum = 0;
        int size = nums.length;

        for(int num: nums) {
            sum = sum + num;
        }

        double avg = sum / size;
        System.out.println("Average is " + avg);
    }
}
// Output
Average is 10.0
Problem : Write a Java program to print all the numbers between 1 and 100, which are divisible by 3 or 7 or by both.

Solution :

Class DivBy3N7 (DivBy3N7.java)
public class DivBy3N7 {
    public static void main (String args[]) {
        for(int i = 1; i <= 100; i++) {
            if((i % 21) == 0) {
                System.out.print(i + " ");
            } else if((i % 3) == 0) {
                System.out.print(i + " ");
            }
            else if((i % 7) == 0) {
                System.out.print(i + " ");
            }
        }
    }
}
Output : 
3 6 7 9 12 14 15 18 21 24 27 28 30 33 35 36 39 42 45 48 49 51 54 56 57 60 63 66 69 70 72 75 77 78 81 84 87 90 91 93 96 98 99