Decision Making Statements in Java.

Decision-making statements in any programming language help us in taking decisions base on certain conditions so we can execute a particular block of code and discard the remaining block of code to get our desired output. These are used to control the flow of the execution of the program. It works similarly like we take in real-life situations. 

Selection statements are available in Java. 

It might necessary to make a decision before arriving at a conclusion or to go on to the next step of processing, a selection statement is used in that case. 

  • Simple if: If is the most simple decision-making statement which is used to decide whether a statement or a block of code will be executed or not. If the condition is written inside if the statement is true then the block of code will be executed otherwise it will not be executed. 

if statement syntax

  • if statement only accepts the boolean value true or false and if the condition is written inside round brackets is true then the code inside the curly brackets will be executed. 

Here, Curly brackets are essential if there is more than one statement to execute. If you will write more than one statement inside if statement without curly brackets then only the first statement will execute when the condition is satisfied. 

Flowchart of if statement:

if statement flowchart

Example of if statement:

class AlgoLesson
{
  public static void main(String[] args)
  {
    int num = 4;
    if(num < 5)
    {
      int square = num * num;
      System.out.println(square);
    }
  }
}
Output:
16

  • if-else: In this statement, if the condition gets true then the code that is present in the if block will get executed, and if the condition gets false then the code that is present in the else block gets executed. It is different from simple if because here we know what to do when the condition will not satisfy. 
if-else syntax in java

 Flowchart for if-else statement:

if-else flowchart
Example of an if-else statement:

 
class AlgoLesson
{
  public static void main(String[] args)
  {
    int num = 6;
    if(num < 5)
    {
      int sum = num + num;
      System.out.println(sum);
    }
    else
    {
      int square = num * num;
      System.out.println(square);
    }
  }
}
Output:
36


  • nested if-else: It is used when one if statement triggers another if statement that is present inside the if block of code. We can check multiple conditions using nested if-else statements.

nested if-else syntax

Flowchart for nested if-else:

nested if-else Flowchart

Example of nested if-else:

class AlgoLesson
{
  public static void main(String[] args)
  {
    int a = 10;
    int b = 20;
    int c = 30;
    if(a > b)
    {
      if(a > c)
      {
        System.out.println("Biggest number: "+a);
      }
      else
      {
        System.out.println("Biggest number: "+b);
      }
    }
    else if(c > b)
    {
      System.out.println("Biggest number: "+c);
    }
    else
    {
      System.out.println("Biggest number: "+b);
    }
  }
}
Output:
Biggest number: 30

  • switch case: In the switch statement, we use a value of a variable or an expression to change the control flow of the program execution. Here we choose which block of code to execute base on the value we give as input and each block of code ends with a break statement. 

If non of the variable or expression matches with our desired value then the default block of code get executed. 

Some important points about switch case in Java:

  • We can have N number of switch-case statements in Java. 
  • Duplicate values are not allowed or we will get a compilation error. 
  • Data of the value which we provide to the switch case must be the same as the data type of the expression of the switch case. 
  • The datatype which is allowed for switch case expression is int, char, short, byte, and long.
  • Break statement in switch case is to control execution if we remove break then it will execute all the code until it reaches its end or meets new break statement. 
  • The default statement is optional, it gets execute when no expression matches the case. If we remove the default statement then noting will execute in that case. 

switch case syntax

Flowchart for switch case statement:

switch statement flowchart

Example of switch statement:

public class AlgoLesson
{
	public static void main(String[] args) {
		int day = 6;
		switch(day)
		{
		    case 1:
		        System.out.println("Today is Monday");
		        break;
		    case 2:
		        System.out.println("Today is Tuesday");
		        break;
		    case 3:
		        System.out.println("Today is Wednesday");
		        break;
		    case 4:
		        System.out.println("Today is Thursday");
		        break;
		    case 5: 
		        System.out.println("Today is Friday");
		        break;
		    case 6: 
		        System.out.println("Today is Saturday");
		        break;
		    case 7:
		        System.out.println("Today is Sunday");
		        break;
		    default:
		        System.out.println("Invalid Input");
		}
	}
}
Output:
Today is Saturday

  • break: break statement is mostly used to terminate the switch sequence or to exit a loop. But if you are using a break statement inside a nested loop then only it will only break out of the innermost loop. 
Flowchart for break statement:
break statement flowchart
Example break statement:


public class AlgoLesson
{
	public static void main(String[] args) {
		
		for(int i = 1; i<=10; i++)
		{
		    //terminate the loop when i is 6
		    if(i == 6)
		      break;
		    System.out.println(i);    
		}
		System.out.println("Loop get Terminated");
	}
}
Output:
1
2
3
4
5
Loop get Terminated


  • continue: continue statement skips the current iteration of the loop and begin the next iteration of the loop. It is useful for the early iteration of a loop when a certain condition is met. 

Flowchart for continue statement:

continue statement flowchart

Example of continue statement:

//program to print even numbers
public class AlgoLesson
{
  public static void main(String[] args)
  {
    for(int i = 0; i < 10; i++)
    {
        if(i == 6)
        {
           continue;
        }
        System.out.println(i);    
     }
   }
}

Output:
0
1
2
3
4
5
7
8
9

  • return: return statement basically uses to return from a method. It can also use to return a value and the type of value it returns depends on the method return type. 

Example of return statement:

public class AlgoLesson
{
	public static void main(String[] args) {
		
		int a = 10, b = 10;
		
		System.out.println("Before return statement");
		if(a == b)
		   return;
		   
		System.out.println("This will not execute!");   
	}
}

Output:
Before return statement
Example:

public class AlgoLesson
{
    public static boolean returnExample(int a, int b)
    {
        if(a == b)
          return true;
        else
          return false;
    }
	public static void main(String[] args) {
		
		boolean result = returnExample(10, 20);
		System.out.println(result);
	}
}
Output:
false

Related post:

(getButton) #text=(Switch case statement in Java) #icon=(link) #color=(#2339bd)

(getButton) #text=(Do While Loop in Java) #icon=(link) #color=(#2339bd)

(getButton) #text=(For Loop in Java) #icon=(link) #color=(#2339bd)


Flowchart and Pseudocode Introduction.

Before writing the code for an application pre-planning the code is important and we can do this with the help of Flowcharts and Pseudocode. It helps us in writing good and efficient programs.  


What is a Flowchart?

A Flowchart is a diagrammatic representation of an algorithm, workflow, or process. It represents a step-by-step approach to solving a problem. The lines and arrows in it show the sequence of steps and the relationship among them. 


It uses different shapes and arrows to depict the sequence of actions and decision points in a program. Each shape in a flowchart represents a specific action, and arrows indicate the flow of control from one step to another.


Below are the Flowchart symbols commonly used:

  • Oval: Represents the start or end of the program.
  • Rectangle: Represents a process or action to be performed.
  • Diamond: Represents a decision point where a condition is evaluated.
  • Parallelogram: Represents input or output operations.
  • Arrows: Indicate the direction of flow between different steps.


Shapes Use in Flowchart

What is Pseudocode?

Pseudocode is an informal way of describing algorithms. It gives the programmer an idea about how the problem is going to solve. It is easily readable and does not require any strict programming language syntax to follow. 

One simple rule for writing pseudocode is that all the "dependencies" are intended, including while, for, do-while, if, if-else, and switch.  

Where Can I Write My Code?

In the previous post, we discussed what computer programming is and how a computer understands code. In this post, we are going to learn how we write codes.  

It is not like we can simply type words into text documents and automatically assume that the computer can translate them into machine code, read it and carry out a task like opening up a browser or running software.  


To properly send instructions to the computer we need programming languages. But we also can’t type in a certain language and expect the computer to understand. So how are we supposed to write code then?

Well, the answer is with an IDE, which stands for Integrated Development Environment allows the facilitation of code by a computer.  

IDEs are used to write code.

An IDE provides a graphic interface on your computer in which the programmer can easily write, run, and debug the code without having to worry about problems with the compilation or interpretation of the program.  

An IDE is like any other program on your computer such as a game, a browser, or even the file explorer, except we’ll be using it to write code. IDEs are able to turn your code into machine code and run it through the computer to produce results.    

IDE Example: NetBeans, IntelliJ, Visual Studios.  

Advantages of Using an IDE.

In addition to providing a place for programmers to develop their code, IDE’s provide some extremely useful tools for programmers to ease the job of writing code, such as built-in error checking, auto-fill in for frequently used words or phrases, and project hierarchy which will help you organize and manipulate the files within your project.  

“Back in olden days, before IDE’s, code used to be written on punch cards and then fed into computers which would take hours and causes a lot of pain.”  

IDEs are extremely powerful and will be used in almost 100% of your programming projects. So, through these IDE we are finally able to write and compile code smoothly without worrying about the computer not being able to understand it.  

How To Write code in IDE?

Each language has its own set of rules you must follow within an IDE. This is where a programming language syntax comes into play.  

Syntax: Rules you must have followed if you want your program to run correctly.  

Learning a computer language is very similar to learning a real language. It also has a set of rules you must follow when writing code in that language, similar to grammar in real-life languages.  


Breaking programming rules will result in an error.  

For example:

  • In Java, we must specify which type of variable we are defining and we also have to add a semicolon at the end of the line.  
  • In python, we just type what we want to create, we don’t even need to define that we are trying to create a variable, and just have we just have to type what we want to create.
  • In JavaScript, we specify we are making a variable but don’t define what type of variable we want to make.  

All these languages require that you follow this syntax because computers are extremely dumb, if you forgot one semicolon or misplace a character, the entire program will not run and send you back a syntax error.  


The IDE will tell you where in your code the error is and it also won’t let you run your program until the error has been fixed.  

So, it is always recommended that you learn the rules and syntax of a language before beginning to write complex programs in that language. 

(getButton) #text=(Visual Studio Code Setup) #icon=(link) #color=(#2339bd)

What is Computer Programming?

Dictionary Definition: Programming is the process of preparing an instructional program for a device.

But that’s a really confusing definition, so in layman’s terms what exactly does that mean? Essentially, it is attempting to get a computer to complete a specific task without mistakes.

Just, for example, you instruct your less than intelligent friend to build a Lego set. He lost the instructions so now he can only build based on your commands. Your friend is far from competent on his own and so you must have to give him EXACT instructions on how to build, even if there is one piece wrong the entire Lego set will be ruined.

Giving instructions to your friend is very similar to how programmers code.

An important thing to note is that computers are actually very dumb. We build them up to be this super-sophisticated piece of technology when in actuality a computer’s main functionality comes from how we manipulate it to serve our needs.

{"Computers are only smart because we program them to be"};

The language that Computer Understand.


Programming isn’t a simple as giving instructions to your friend since, in the case of programming, the computer doesn’t speak the same language as you. The computer only understands machine code, which is a numerical language known as a binary that is designed so that the computer can quickly read it and carry out its instructions.

Every instruction fed to the computer is converted into a string of 1’s and 0’s and then interpreted by the computer to carry out a task. Therefore, in order to talk to the computer, you must first translate your English instruction to Binary.

Directly translating what you want the computer to do into machine code is extremely difficult, in fact almost impossible, and would take a very long time to do if you could. This is where programming languages come into play.

Programming languages are fundamentally a middle man for translating a program into machine code-the series of 0’s and 1’s that the computer can understand. These languages are much easier for humans to learn than machine code, and are thus very useful for programmers.

{"A programming language is not English and not machine code, it is somewhere in the middle"};

How is Programming Language Vary?

There are many different programming languages out there that each has its own unique uses.

  • Java and Python: General Purpose languages.
  • HTML/CSS: Designed for specific tasks like web page design.

Each language also varies in how powerful it is:

  • JavaScript is a scripting language and isn’t used for big problems.
  • Java and Python can carry out a much more computationally taxing process.

We measure a programming language’s power level by how similar it is to machine code. Low-level programming languages such as Assembly or C are closer to binary than a high-level programming language such as Java or Python.

The basic idea is that the lower the level of your programming language, the more your code will resemble what the machine can interpret as instructions.

So, try different languages and decide which one’s rules, interface, and level of specification you like the best.  

Tower of Hanoi using Recursion.

 Tower of Hanoi is one of the most popular recursive problems that everyone practices when they start learning the recursion concept. In this problem, we have three pillars and we have to move some disks from one pillar to another pillar. 

Let say, we have three pillars named A as source pillarB as a temporary pillar, and C as a destination pillar. Pillar A has a finite number of disks and these disks are arranged in decreasing order of their size. We have to move all the disks from source pillar A to destination pillar C using temporary pillar B but you have to follow two conditions while doing this-

  • You can move only one disk from one pillar to another at a time. 
  • A larger disk cannot be placed on a smaller disk.
Tower of Hanoi Picture

The approach of solving tower of Hanoi problem recursively, 
  1. Move upper (n-1) disks from A to B using C as the temporary pillar. 
  2. Move nth disk from A to C. 
  3. Move (n-1) disks from B to C using A as the temporary pillar. 
The base condition of our recursive approach is when we have to move only one disk from source to destination pillar and return. 

C++ Program to Tower of Hanoi Problem. 

#include <iostream>
using namespace std;

void tofh(int ndisk, char source, char temp, char dest)
{
    if(ndisk == 1)
    {
        cout<<"Move disk "<<ndisk<<" from "<<source<<" to "<<dest<<endl;
        return; 
    }
    tofh(ndisk-1, source, dest, temp);
    cout<<"Move disk "<<ndisk<<" from "<<source<<" to "<<dest<<endl;
    tofh(ndisk-1, temp, source, dest);
}
int main() {
    char source = 'A', temp = 'B', dest = 'C';
    int ndisk;
    cout<<"\nEnter the number of disks: ";
    cin>>ndisk;
    cout<<"\nSequence of steps: \n";
    tofh(ndisk, source, temp, dest);
    return 0;
}

Output: 
Enter the number of disks: 3

Sequence of steps: 
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Different Types of Machine Learning System.

Data Mining is a process of applying ML techniques to dig into large amounts of data can help to discover patterns that were not immediately apparent.


Types of Machine Learning System:

Machine Learning system can be classified according to the amount and type of supervision they get during training.


Supervised learning: In supervised learning, the training data you feed to the algorithm includes the desired solutions, called labels.

supervised learning

Spam Filter of your Gmail Inbox is a good example of this, as it is trained with many emails (spam & ham) and it must have to learn how to classify new emails.

A typical supervised learning task is classification.


Some important supervised learning algorithm:

  • K-Nearest Neighbors.
  • Linear Regression.
  • Logistic Regression.
  • Support Vector Machines(SVMs).
  • Decision Trees.
  • Random Forest.
  • Neural network.

Unsupervised Learning: In unsupervised learning, the training data unlabeled and the system try to learn without the teacher.


Some important unsupervised learning algorithm:

  • Clustering.
  • K-Means.
  • Hierarchical Cluster Analysis(HCA).
  • Expectation-Maximization.
  • Visualization and dimensionality reduction.
  • Principal component analysis(PCA).
  • Kernel PCA.
  • Logical Linear Embedding(LLE)
  • t-distributed Stochastic Neighbor Embedding(t-SNE).
  • Association rule learning.
  • Apriori.
  • Eclat.
unsupervised learning

For example Grouping the visitor of your blog into a different group like 40% of visitors are male who likes cricket and 20% of men like football. You don’t even have to tell which group visitors belongs to, the clustering algorithm finds those connections by themselves.

 

Semisupervised Learning: In this, the algorithm has to deal with lots of unlabeled data and a little bit of labeled data.


Google Photos are good examples of semisupervised learning. After uploading the photos, it automatically recognize if a person is present in many different photos now you just have to tell who these people are. One label per person and later it will help you search for photos.  


Most of the semisupervised learning algorithms are a combination of supervised and unsupervised algorithms.


Reinforcement Learning: The best example of a reinforcement learning algorithm is a robot learning how to walk. The robot observes the environment, select and perform an action and get rewards or penalties, and base on this the robot decide what to do and what not to do.  

reinforcement learning

Another criterion used to classify Machine Learning systems is whether or not the system can learn incrementally from a stream of incoming data.


Batch Learning: In batch learning, the system is not capable of learning incrementally with time. As it takes a lot of time and computing resources so the entire process is done offline. First, the system is trained, and then it is launched into production and runs without learning anymore. It is also known as offline learning.


Online Learning: In this algorithm, you train the system incrementally by feeding data continuously, either individually or by small groups called mini-batches. The best use of this learning is for stock prices where data change rapidly.


Machine Learning system is also categorized base on generalization:


Instance-based learning: In this learning, the system learns the old examples by heart then generalizes to new cases using a similarity measure.


Model-based learning: In model-based learning, we build a model of these examples then use that model to make predictions.  

Binary Tree Important Definition and Properties.

 Binary Tree


Tree: Non-Linear Data Structure in which data is organized in a hierarchical manner.  It is very fast for information retrieval and searching operations. 


Important Terminology of a Binary Tree.


Node: Each element in a tree is called a node.

Edges: Lines connecting two nodes, it is also known as branches. 

Parent Node: The immediate predecessor of a node (node that comes just before a node).

Child Node: The immediate successors of a node (node that comes just next in line).

Root Node: The node that doesn't have any parent node.

Leaf Node: The node that doesn't have any child node. The node other than the leaf node is known as a non-leaf or terminal node. 

Level: Distance of that node from the root.

Height: Total number of level, depth of the tree, Level+1=Height

Siblings: All nodes having the same parent. All siblings are at the same level but it is not necessary that nodes at the same level are siblings.

Path: It is a way to reach a node from any other node. In a tree, there is only one path possible between any two nodes. Path length = Number of Edges on the path.

Degree: The number of children or subtrees connected to a node.

Forest: The subtrees we get after removing the root of the main tree is collectively called as Forest (also known as a set of disjoint trees).  

Strictly Binary Tree: Each node in the tree is either a leaf node or has exactly two children. There is no node with one child. 

Extended Binary tree: Each Empty subtree is replaced by a special node then the resulting tree is extended binary tree or 2-tree.

Full Binary tree: All the levels have the maximum number of nodes.

**If the number of any node is k, then the number of the left child is 2k, the number of right children is 2k+1, and the number of its parent is k/2.

Complete Binary Tree: All the levels have the maximum number of nodes except possibly the last node.


Important Properties of a Binary Tree.

P1. The maximum number of nodes possible on any level i is 2^i where i>=0.

P2. The maximum number of nodes possible in a binary tree of height h is 2^h-1.

P3. The minimum number of nodes possible in a binary tree of height h is equal to h. A tree with a minimum number of nodes is called skew trees.

P4. If a binary tree contains n nodes, then its maximum height possible is n and the minimum height possible is log2(n+1).

P5. In a non-empty binary tree, if n is the total number of nodes and e is the total number of edges, then e = n-1.


P6. In a non-empty binary tree, if n is the number of nodes with no child and m is the number of nodes with 2 children, then n = m+1.

Traversal in Binary Tree
1. Breadth-First Traversal (Level Order Traversal)
2. Depth First Traversal
APreorder Traversal (Root, Left, Right)
BInorder Traversal (Left, Root, Right)
CPostorder Traversal (Left, Right, Root)

Edit your videos for free using VLC media player.

Edit using VLC Media Player

 

VLC is usually thought of as a media player and a very good one at that. However, there’s more to the software than meets the eye. Did you know you can use it to make simple edits to your videos as well as just watch them? This saves you needing to download a separate video-editing tool if you’re short on space or don’t use one often enough to justify the installation.

 

Trim a video clip using a VLC media player.

 

#Step 1:

First, we’ll look at how to trim video, so you can remove unwanted sections to create a clip. To do this, you need some extra tools. Open the View menu and choose Advanced Controls. This adds a Record button and a useful ‘Frame by frame’ button.

 

Video Trim using VLC

#Step 2:

Load the video and watch it through to make sure you’re familiar with where you want to start and endpoints to be. Use the slider to get the video near and immediately press the Record button when you get to the correct place.

 

trim video step 2

#Step 3:

You have to mark the end of your clip manually. When the video gets to the stop point, click the Record button again. The trimmed video file is saved to your Videos folder with ‘vlc_record’ at the front of its name. Do this as many times as required to collect the clips that you need.

 

Stick video clips together using a VLC media player.

While VLC is perfectly capable of sticking video clips together, the option was removed from the latest version of the graphical interface. However, the action can still be performed from the Command Prompt. Start by renaming the files you want to stitch together-use a simple, consecutive system, such as numbering them.

 

#Step 1:

Close any instances of VLC that you have open. Enter cmd in the search box to launch the Command Prompt, and navigate to the folder that contains your renamed video files. In our case, we used cd c:\Users\Praveen Kumar\Videos.

 

#Step 2:

Next, type a command with the path to the vlc.exe file, the names of all the files you want to join, and a couple of additional commands including the name of the final file. Our was “C:\Program Files\VideoLAN\VLC\vlc.exe” 1.mp4 2.mp4 --sout “#gather:std{access=file,dst=join.mp4}” --sout-keep

 

#Step 3:

VLC opens and joins the files together. The process is carried out discreetly, so you won’t see anything appear on the screen. You now have to shut VLC down again before the new file (in our case, called ‘join’) is properly finished. If you look at it before closing VLC, it will appear to be an empty file.

 

#Step 4:

The file’s thumbnail appears. You can reopen VLC and play the video as normal. If you want to watch any changes to the file, such as adding more clips, make sure you rename the output file in Step 2, so it doesn’t overwrite your existing file.

 

#Step 5:

You may feel your video is a bit boring and decide to spice it up with a few video effects. If you do this as you record your clips above, you can insert them into your finished product. Click the ‘Show extended settings’ button and click the Video Effects tab.

 

#Step 6:

There are plenty of effects to experiment with, such as changing the color of your video from the Colors tab. Here, we’ve chosen a Sepia tint. The Essential tab has subtler color changes, Geometry lets you rotate the video and Overlay can insert a logo or text.  

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo