Program Structure (Part - 2)

Program Structure (Part - 2)

ยท

7 min read

In the previous article, we learned about the expression and statements, bindings, and other concepts related to program structure.
Let's continue that article and learn other concepts related to it, more program-oriented.

Control Flow

When we write a program, it always contains more than one line. So, the flow is which our program executes is called control flow.
The simplest type of flow is top-to-bottom called straight control flow.

let sum = 6; 
sum = sum + 5;
console.log(sum);

So, what the above program is doing? First, it created a binding named as sum and assign value "6" using assignment operator(=).
Then, in the next line, "5" is being added to the previous sum binding and assigned to the binding "sum" again.
After that, it is displaying on the console. We can clearly see that the control flow is going from top to bottom.

Control Execution

Sometimes, what happens is the flow of the program depends on some condition and that condition decides which part of the program will execute. This is called conditional execution. Conditional Execution can happen in many ways:

  • Using if: In this case, the code will be executed if and only if the condition wrapped in the parentheses holds true. The syntax is :
if(/*condition*/){
    //actions
}

Let's understand more with the help of example:

let num = 8;
if(num > 10)
{
    console.log("larger");
}

In the above example, num > 10 is the condition wrapped in () and the statement after "if" should be wrapped in curly braces ({}). There can be any number of statements between braces and called a block.

  • Using if-else: Sometimes, we want some other block of code to be executed when a certain condition holds false. In these cases, we use if-else.
    The syntax is:
if(/*condition*/)
{
    /* if true
        this will execute */
}
else
{
    /*else
       this will execute */
}

Let's understand this with the help of an example:

let num = 8;
if( num > 10)
{
    console.log("larger");
}
else
{
    console.log("smaller");
}

In this case, the else block will execute because "8" is smaller than 10. So, the condition holds false.

  • Using if-else if-else: When there are multiple conditions in our program we use if-else if-else. Based on which condition holds true, the block executes.
    The syntax is:
if(/*condition*/)
{
    //some actions
}
else if(/*condition*/)
{
    //some actions
}
else if(/*condition*/)
{
    //some actions
}
...
...
...
...
else
{
   /*if no condition matches
      this will execute*/
}

Let's understand with the help of an example:

let num = 8;
if(num > 10)
{
    console.log("larger");
}
else if(num === 10)
{
   console.log("equal");
}
else
{
   console.log("smaller");
}

Some important points to remember while working with if-else if-else:

  1. There can be any number of else-if statements but there can one and only one else statement.
  2. We can use "if" independently but not else.
  3. We can use "if-else if" without else statement.

While and Do Loops:

The next type of control flow is loops. Now, what looping is?
Let's understand with the example:

Suppose we want to print numbers from 1 to 10. One way to do it is:

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log(6);
console.log(7);
console.log(8);
console.log(9);
console.log(10);

But the point of writing programs is to do less work. And suppose we want to print numbers from 1 to 100. Then it would be a tedious task.
This is where looping comes into the picture. So, how can we write the above program using looping?

let num = 1;   //initial value
while( num < 100)   //condition
{
    console.log(num);  //block of statements
    num=num+1;          //updating binding
}

This program will run automatically and print the numbers until the condition holds true. So what exactly this program is doing?
First, we create a binding called num to hold the initial value. Then, while keyword is creating a loop and we put conditions in parentheses.
So, the above program will run until the value of num will be less than 100 and then it will come out of the loop.
We put a set of statements that needs to be executed in the curly braces. There can be any number of statements.
Then we are updating the value of the binding num. So, it will run again and again until a certain condition.

Do loop is similar to while with a simple difference that it executes at least once and then the condition is checked whether it should do its next iteration or not.

let name;
do
{
   name=prompt("Enter your name:");
}while(!name);
console.log(name);

The above program will execute until you don't put an empty string "". So what exactly above program is doing?
First, we created a binding name. Then we use do keyword to start a loop. Since there is no condition it will run once and ask you to enter a name.
Then, for the next iterations, it will check the condition which is given after while keyword. That condition is converting the value to true every time you enter a name.
It will hold false when you enter an empty string and come out of the loop.
Then, the last name you entered gets printed on the console.

For Loop

It is a shorter form of looping in which the initialization, condition checking, and binding update done in one place. If you are not new to programming you obviously heard about it in other languages. The syntax for it is:

for(initialization; condition; increment/decrement)
{
    //set of actions
}

Let's understand this with the help of an example:

let num;
for(num=1; num<=100; num=num+1)
{
   console.log(num);
}

So, first, we are initializing num. Then checking the condition that it will run until the num is less than equal to 100. Then, we are incrementing the value of num binding.

Break and Continue

There is one more way to get out of the loop when certain conditions met with the special keyword break. Let's understand:

for(let i=3; ; i=i+1)
{
    if(i % 2 == 0)
   {
      console.log(i);
      break;
   }
}

As you can see we didn't put any condition in the "for" loop means that we need something to get out of the loop otherwise it will go in an infinite loop.
Infinite looping means that your program will never stop until you close the browser or stop the process somehow. It is bad for programs. So, what it is doing?
We have initialized loop from 3 with no condition and we are updating the value of i. Now, we put a condition that whenever we encounter any value of i whose remainder will be zero after dividing it with 2.
It will be breaking out of the loop and print the value of i in the console.

Continue is similar to break except when continue is encountered it jumps out of the loop body and continues with next iteration.

for(let i=0; i<5; i=i+1)
{
    if(i==3)
    {
       continue;
    }
    console.log(i);
}

Output: 0 1 2 4

So, what it is doing? we put the condition that whenever the value of i will be equal to 3. It will jump out of the loop and continues the next iteration.

Dispatching on a value with Switch

A switch case is just a more direct way of using a chain of "if" statements. Let's understand how:

switch (prompt("What is the weather like?")) {
  case "rainy":
    console.log("Remember to bring an umbrella.");
    break;
  case "sunny":
    console.log("Dress lightly.");
  case "cloudy":
    console.log("Go outside.");
    break;
  default:
    console.log("Unknown weather type!");
    break;
}

It is mandatory to put a break after every case otherwise it will show the results which you don't expect. It can contain any number of cases and a default condition in case no condition holds true.
So, it will ask for the user input and according to that input, it will display the result. For example, the user puts rainy then it will go in the rainy case and print Remember to bring an umbrella.
In case, a user enters something which doesn't match any case it will print the default statement. Now you can think of switch to be something similar like:

if(/*condition*/)
{
    //some actions
}
else if(/*condition*/)
{
    //some actions
}
else if(/*condition*/)
{
    //some actions
}
...
...
...
...
else
{
   /*if no condition matches
      this will execute*/
}

Bingo! We have successfully completed the second chapter i.e. program structure.

bingo.gif

Thanks for reading! ๐Ÿ˜Š

ย