control statements – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Wed, 13 Mar 2024 18:12:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg control statements – Programmerbay https://programmerbay.com 32 32 Difference between While and Do While loop in Tabular Form https://programmerbay.com/difference-between-while-and-do-while-loop/ https://programmerbay.com/difference-between-while-and-do-while-loop/#respond Mon, 11 Mar 2024 16:17:31 +0000 https://programmerbay.com/?p=6343 In this article we’ll be discussing the difference between while and do while loop and how they work.

Control statements provide an ability to execute a particular set of statements in a controlled manner. Basically, these statements are powerful statements that can mange the flow of a program.

Every programming language supports a basic form of Iteration statements that are known as loops, for example, While, Do-While and For loop.

 

While and do while loop

Iteration statements are categorised as the control statements. It allows us to iterate through a piece of code repeatedly.

The goal of all looping statements is to run a particular block of statements frequently until a specific condition is met. However, Do-While and While loop follows a completely different approach to looping around a statement. Both types of loops are different from each other when it comes to their order of execution and condition evaluation.

What is a loop?

A loop can be defined as a control statement that enables repetitive execution of a block of code until a given condition turns out to be false. It provides capability to write a block of code and execute it repeatedly for specific number of times. Suppose, if a block of code needs to be executed repeatedly, in such case, we must use loops, instead of writing the same code multiple times.

Normally a looping statement comprises of following components:

  • Control or counter variable initialization
  • Condition evaluation
  • Loop body execution
  • Counter variable updation

There are primarily three types of loops  :
1) while loop
2) do while loop
3) for loop

The main difference between While and Do-While loop is that one evaluates condition first and then executes the loop body, whereas, other one executes the loop body first and then checks for the condition.

Difference between While and Do While Loop in Tabular form

BasisWhile LoopDo-While Loop
DefinitionIn this, the given condition is evaluated first, and then loop body is executedIn this, the given loop body is executed first and then after the given condition is checked
Loop TypeIt is an entry-controlled loopIt is an exit-controlled loop
Loop ExecutionThe loop body would be executed, only if the given condition is trueThe loop body would be executed at least once, even if the given condition is evaluated as false
Counter Variable Intialization It allows initialization of counter variable before entering loop bodyIt allows initialization of counter variable before and after entering loop body
SemicolonNo semicolon is used as a part of syntax,
while(condition)
Semi-colon is used as a part of syntax,

while(condition);
UsageIt is used when condition evaluation is required to be evaluated first, before executing loop bodyDo-While is used when one needs to enter into the loop body before evaluating condition. For example, Menu driven programs
SyntaxSyntax:

while( condition )
{
// loop body
}
do
{
// loop body
}while( condition );

While Loop

While Loop can be defined as the loop where the condition is evaluated first and then after the loop body is executed. It is an entry controlled loop.

Syntax:

while(condition)
{
// body
}

How while loop works?

  • Counter or control variable initialization
  • Then, condition would be checked
  • If it is evaluated as true, then
  • loop body would be executed
  • Otherwise, the loop gets terminated

Entry Controlled Loop

A Program example for While loop:

Example 1. C program to demonstrate working of while loop

Program

#include <stdio.h>

int main ()
{

  int i = 1;
  while (i < 5)
    {
      printf ("Print :: %d \n", i);
      i++;
    }
  return 0;
}

Output:

Print :: 1 
Print :: 2 
Print :: 3 
Print :: 4 

Explanation:

In the above example, we are simply initializing counter variable i with 1. And iterating using while loop until the condition  having i is less than 5 becomes false. In loop body, we are printing a message and incrementing counter variable on very next line.

Example 2. C program to show the approach difference of while loop with do-while

#include<stdio.h>
void main()
{
int i=10;
while(i<10)
{
printf("I will not be executed as it is entry controlled loop");
i++;
}
getch();
}

Explanation:

Since, condition would be evaluated as false at very first place , no output would be printed. In this, counter variable ‘i’ was holding value 10. And at the entry point of while loop, when condition got evaluated for ‘i< 10’, it turned out to be false. As a result, the loop terminated.

Do-While Loop

Completely opposite to While loop, Do-While is a looping statement in which condition is checked after the execution of the loop body. It is a type of exit controlled loop.

Syntax:

do
{
// loop body

}whie(condition);

How do-While works?

  • Counter or control variable initialization
  • Loop body gets executed first and then-after the condition is evaluated
  • If the condition is evaluated as true, then loop would proceed to next iteration
  • Otherwise, it gets terminated

Exit Controlled Loop

A  Program example of Do-While loop

Example 1. C program to demonstrate working of do while loop

Program:

#include <stdio.h>

int main ()
{
  int i = 1;
  do
    {
      printf ("Print :: %d \n", i);
      i++;
    }while (i < 5);
  return 0;
}

Output:

Print :: 1 
Print :: 2 
Print :: 3 
Print :: 4 

Explanation:

In the above example, we are initializing counter variable i with 1. And iterating using do while loop until i is less than 5. In loop body, we are printing a message and incrementing counter variable on very next line. Lastly, we’re checking the condition and iterate accordingly.

Example 2. C program to show the approach difference of do-while loop with while

#include<stdio.h>
void main()
{
  int i=10;
  do
  {
  printf("I will be executed at once as it is exit controlled loop");
  i++;
  }while(i<10);
  getch();
}

Explanation:

Print statement would be executed at once, even though the condition is false. In this, counter variable ‘i’ was 10. In this, the loop body got executed first which resulted in print statement execution. And lastly, condition got evaluated for ‘i< 10’, it turned out to be false. As a result, the loop terminated.

Exit Controlled and Entry Controlled Loop

A loop that executes the loop body first and then checks for a condition is known as an exit controlled loop. For example Do-While loop.

On the other hand, a loop that checks for condition first and run the loop body can be categorized as entry controlled loop. For example, While loop, and For loop.

]]>
https://programmerbay.com/difference-between-while-and-do-while-loop/feed/ 0
What are Java Jump Statements With Program Example https://programmerbay.com/what-are-java-jump-statements-control-statements/ https://programmerbay.com/what-are-java-jump-statements-control-statements/#respond Wed, 14 Sep 2022 17:38:25 +0000 https://programmerbay.com/?p=5124 In Java, Jump Statements are control statements that shifts control from one part of the program to another part.  It is primarily used to escape from looping statements, skip certain statements based on conditions, exit from a method and so on. These can interrupt the execution of a loop, switch and methods right away, enabling us to change the flow of program execution.

image 2021 01 02 190721

Java supports break, continue, and return. However, Go To statement can be implemented using label and break statements.

However, Java uses label with break statement or continue statement to get some sort of functionality of go to statement. In this, label works as a target point and break statement considers the label to jump out of that particular target point. [Read brief about go to statement implementation and program example]

Break Statement

A break statement is used to terminates the execution of the loop abruptly and flow of cases in a switch statement. Java doesn’t have Go-to statement as C or C++ does. Interestingly, the Break statement can also work as Go-to using label. 

The break statement can be used:

  • Within a Loop to terminate the loop
  • In Switch Cases to terminate case sequence 
  • As Go-To Label
break statement
Figure: Working of Break Statement in a Loop

Syntax: 

if(condition)  
{  
   break;  
}  

Program:

public class ApplicationExample {
    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            if (i == 3) {
                System.out.println("Terminating or breaking the loop as i reaches to 3 ! ");
                break;
            }
            System.out.println("Executing " + i + " times. ");
        }
    }
}

Output:

Executing 1 times. 
Executing 2 times. 
Terminating or breaking the loop as i reaches to 3 ! \

Continue Statement

It skips the execution of codes of the loop that comes after it and starts the next iteration. Unlike the break statement, it doesn’t terminate a loop, instead, it ends the current iteration. 

It always comes with a conditional statement in order to avoid unreachable code error. It applies on the loop only.

continue statement 1
Figure : Working of Continue Statement

Syntax:

if(condition)  
{  
   continue;  
}

Program:

public class ApplicationExample {
    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            if (i <= 5) {
                continue;  //  skipping the line 8 and 9 until value of i is not greater than 5
            }
            System.out.println("Executing " + i + " times. ");
        }
    }
}

Output:

Executing 6 times. 
Executing 7 times. 
Executing 8 times. 
Executing 9 times. 

 

Return Statement

It returns a value from a function or method and transfers the control back to the calling function. In other words, it terminates a method in which it’s encountered and shifts the flow back to the calling function. 

return statement java

Syntax:

if(condition)  
{  
   return;  
} 

Program:

public class ApplicationExample {

    public static void main(String[] args) {
        ApplicationExample example = new ApplicationExample();
        example.printMessage(true);

    }
    private void printMessage(boolean controlVar){
        String message = getMessage(controlVar);
        System.out.println(message);
    }

    private String getMessage(boolean isTrue){
        if(isTrue){
            return "Hi I am true statement";
        }
        return "Hi I am false statement";

    }
}

Output:

Hi I am true statement

 

Java program to show working of break, continue and return statement

public class JumpStatement
{
  public static void main (String[]args)
  {
    int i = 0;
    boolean x = true;		// Simple break Statement 
    while (i < 5)
      {
  System.out.println ("Break will cause termination of while loop");
  i++;
  break;
      }				// break Statement acts as Go-to Statment 
    first:
    {
    second:{
      third:{
    System.out.println ("I am third block");
    if (x)
      break second;
  }
  System.out.println ("I am second block");
      }
      System.out.println ("I am first block");
    }				// Continue Statement acts as Go-to Statment 
    for (i = 0; i < 5; i++)
      {
  System.out.println ("This is before continue");
  if (i > 3)
    continue;
  System.out.println ("This is after continue");
      }				// Return Statement
    if (x)
      return;
    System.out.println ("I wouldn't be executed");
  }
}

Output:

Break will cause termination of while loop
I am third block
I am first block
This is before continue
This is after continue
This is before continue
This is after continue
This is before continue
This is after continue
This is before continue
This is after continue
This is before continue

 

]]>
https://programmerbay.com/what-are-java-jump-statements-control-statements/feed/ 0
Difference between For and For-each Loop in Java https://programmerbay.com/difference-between-for-and-for-each-loop/ https://programmerbay.com/difference-between-for-and-for-each-loop/#respond Sat, 06 Aug 2022 09:11:36 +0000 https://www.programmerbay.com/?p=4477 A loop is a control statement which executes a particular block of code repeatedly until a given condition becomes false. There are various types of loops such as while, do-while and for loop.

In this article, we will be focusing on for loop and its enhanced version.

for loop and for each loop in java

If you’re looking for forEach method introduced in Java 8: ForEach Method in Java 8

Difference between For and For-each Loop in Java

For LoopForeach Loop
It uses an index of an element to fetch data from an arrayIt uses an iteration variable to automatically fetch data from an array
Termination of this traditional loop is controlled by loop condition. Therefore, For loop executes repeatedly until the given condition turns out to be falseNo such provision is provided in foreach, instead break statement can be used to terminate the execution of the loop early, otherwise, it executes until the last element gets evaluated
It requires loop counter, initial and end values, in order to iterate through all the elements of an arrayIt automates the iteration by using the iteration variable which stores one element each time
When we iterate through using traditional for loop we can manipulate the actual data of an arrayThe iteration variable in foreach is read-only. It means changes made on iteration value would not affect the actual data of the collection or array
It was introduced in Java 1It was introduced back in Java 5
It has the flexibility of the iterating an array whether it is increasing order or decreasing orderIt can iterate only in a linear manner from initial to end element, but not vice versa
Syntax:
for( initialization; condition; iteration)
{
// body
}
Syntax:
for(type var_name: collection)
{
// body
}
It works only on indexable objects where random access of elements are allowed It works on all indexable objects even when random access of an individual element is not allowed

Traditional For loop in Java

It is generally known as a traditional for loop.
In Java, “for loop” is used to execute a particular block of code a fixed number of times. In other words, when the number of iterations are already known, then it is typically used.

It provides compact looping structure as initialization, condition and iteration are put together within a single statement.
Like C++, a simple for loop comprises three parts, initialization, condition and increment/decrement

1. Initialization: In this, a counter or control variable is assigned with some value and acts as a base for the loop counter
2. Condition: It is a relational or logical expression that returns a boolean value, true or false. It is evaluated after each iteration and continues execution until the condition turns out to be false.
3. Increment/ decrement: It updates with each iteration with incremented or decremented values

.

Syntax : 

for(initialization;condition; updatableExp){
//loop body
}

For each loop in Java

For each is the enhanced for loop which was introduced in Java 5. It is used to iterate through a collection of objects.

Unlike traditional for loop, the enhanced loop isn’t declared with control variable, condition, and increment/decrement, instead, an element of the same array or list type needs to be declared with a colon, is followed by the list or array name.

It executes until all the elements in the list are traversed.

Syntax:

for (type element : list/array)
{
// loop body
}

Java program to show the working of for loop

Program:

public class ForLoopExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(5);
        list.add(9);
        list.add(7);
        list.add(65);
        list.add(4);
        list.add(0);

        for(int i=0;i<list.size();i++)
        {
            System.out.println("List items : "+list.get(i));
        }
    }

}

Output:

List items : 5
List items : 9
List items : 7
List items : 65
List items : 4
List items : 0

Java program to show the working of for-each (enhanced for loop ) loop

public class ForLoopExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(5);
        list.add(9);
        list.add(7);
        list.add(65);
        list.add(4);
        list.add(0);

        for (Integer value: list
             ) {
            System.out.println("Items : "+value);
        }
    }

}

Output:

Items : 5
Items : 9
Items : 7
Items : 65
Items : 4
Items : 0

]]>
https://programmerbay.com/difference-between-for-and-for-each-loop/feed/ 0
What are Java Iteration Statements : Control Statements https://programmerbay.com/what-are-java-iteration-statements-control-statements/ https://programmerbay.com/what-are-java-iteration-statements-control-statements/#respond Sat, 14 Sep 2019 17:38:31 +0000 https://programmerbay.com/?p=5125 These are the statements that enable us to execute a particular block repeatedly until a given condition returns false. Java supports While, For and Do-While statements.

While

It runs a particular block until a control expression becomes false. As and when the condition gets false, control passes to the statement that is immediately after the loop.

Syntax:

while(condition)
{
//block
}

Do-while

In this, first loop body is executed and then after the condition is checked. It is a special loop in which control expression is checked after the execution of the block. The loop body runs at least once, no matter what condition is.

Syntax:

do{
//body
}while(condition)

For

It is a type of loop where the control variable, condition, and iteration are all put together at a single place.

A control variable acts as a counter and is executed once. After that, the condition is evaluated if it is true the loop body would be executed otherwise, it gets terminated. Lastly, the iteration portion is executed. In this  control variable is incremented or decremented. The incremented or decremented value is checked with the condition and if it returns true, the loop body would be executed. It keeps iterating until the condition returns false.

Syntax:

 for(control_variable;condition;increment or decrement)
{
//body
}

There is an advanced version of For which is referred to as For-each. However, it doesn’t require any keyword to declare this statement.

For-each is used to iterate through a collection of objects until all the elements are iterated.

for(type element_name:collection)
{
//body
}

Java program to demonstrate the working of the iteration statement

Program:

public class IterationStatement {

public static void main(String[] args) {

int i=0;
int control_variable;
int arr[] = {1,2,3,4};

while(i<5)
{
System.out.println("I am iterating using While Loop "+i+" time ");
i++;
}
// do while
i=0;
do{
System.out.println("I am iterating using Do-While Loop "+i+" time ");
i++;
}while(i<5);
// For loop

for(control_variable =0;control_variable<5;control_variable++)
{
System.out.println("I am iterating using For Loop "+control_variable+" time ");

}

// For-Each
for(int element:arr)
{
System.out.println("I am iterating using For-each Loop "+element+" time ");
}


}

}

Output:

iteration statement

]]>
https://programmerbay.com/what-are-java-iteration-statements-control-statements/feed/ 0
What are Java Selection Statements: Control Statements https://programmerbay.com/what-are-java-selection-statements-control-statements/ https://programmerbay.com/what-are-java-selection-statements-control-statements/#respond Sat, 14 Sep 2019 17:38:09 +0000 https://programmerbay.com/?p=5126 Control Statements

A control statement changes the flow of execution of a program. In Java, these statements are categorized in the selection, iteration and jump statements. A selection statement changes the flow by selecting different paths of execution based on the logical decision. Iteration statement runs a specific block repeatedly. Lastly, a jump statement forces a program execution to stop to follow the linear flow of the program.

Java Selection Statement

Java has If and Switch statement as selection statements. These statements control the execution of a program with the help of conditions which are evaluated at runtime.

If Statement

-If
It enables a program to execute a particular block if and only if the given condition is true.

Here’s the syntax:

if(expression)
{
//body
}

-If-else
If the condition of If-statement is true then its execution takes place, otherwise, the block of else-statement would be executed.

if(expression){
//body
}

else{

//body

}

-Nested if

It is said to be nested if when If-statement is followed with another If or else statement.

if(expression){
                    if(expression){
                                  //body
                          }
}

Program to Show the working of different type of If statements

public class IfStatement {

public static void main(String[] args) {
int value=5;

// If statement
if(value==5)
{
System.out.println(" This is the block of If Statement ");
}
// If-else statement
if(value>=10) /// 5>=10, which is false
{
System.out.println(" This is the block of Statement ");
}
else
{
System.out.println(" This is the block of else Statement ");
}
// nested-if statement
if(value==5)
{
if(value<=10)
{System.out.println(" This is the block of Nested-If Statement ");
}
}
}

}

Output:

if program

Switch Statement

Despite using Nested if which makes the code more complex and lengthy, we can use a switch statement. A switch statement allows the execution of different parts of code based on the value of an expression. It works by evaluating an expression and if it matches any of the cases then code paired with that case would be executed. Each and every case must be different and in addition, Java allows a switch statement to use the expression of the type of sting and an integer type. A break statement is put at the end of each of the case to break the statement sequence. Lastly, default is optional and executed when all the cases aren’t matched.

If break and default statement isn’t there in the program

public class SwitchStatement {

public static void main(String[] args) {
int i=2;
switch(i){
case 1:
System.out.println("I am one ");
case 2:
System.out.println("I am two ");
case 3:
System.out.println("I am three ");


}
}

}

Output:

without break switch

Since no break statement was declared in the above example. The value of “i ” was 2, which clearly matched with case 2. Resulting in, execution of 2nd case where break statement was missing, with successive execution of the 3rd case. If there were more cases then that would also be executed as sequence didn’t abrupt by any break statement.

Program to demonstrate the working of Switch Statment

public class SwitchStatement {

public static void main(String[] args) {
int i=2;
switch(i){
case 1:
System.out.println("I am one ");
break;
case 2:
System.out.println("I am two ");
break;
case 3:
System.out.println("I am three ");
break;
default:
System.out.println("nothing is matched ");


}
}

}

Output:

switch

]]>
https://programmerbay.com/what-are-java-selection-statements-control-statements/feed/ 0