Search Logic Blocks

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!!

No comments: