9.Control Statements

Thursday, August 20, 2009 Posted by Sudarsan
Control Structures
In this chapter you are going to learn how to use if and if-else selection statements to choose among alternative actions, while repetition statements in a program and also how to use basic problem-solving techniques.


Java uses curly braces ({}) to group multiple statements together. The statements execute in order. More modern languages like Java and C++ allow you to declare variables on any line, which is handy.

Conditional Statements

Conditional statements allow selective execution of a set of statements depending on the value of expressions associated with them. Conditional statements are also known as decision-making statements.

We can control the flow of a program using conditional statements. We have two types of conditional statements are available in Java they are:

The if-else statement
The switch-case construct

If Statement

Both an if and an if-else are available in Java. The . The parentheses around the expression are required, even if it is just a single variable.

The if-else statement enables us to execute selectively. It is followed by a boolean expression.
It executes the set of statements depending upon the result of the boolean expression.


if (expression) // simple form with no {}'s or else clause

if (expression) { // simple form with {}'s to group statements
statement
statement
}

if (expression) { // full then/else form
statement
}
else {
statement
}


In the preceding syntax, if the boolean expression of the if construct evaluates to true, the Java compiler executes the statements following the if construct else executes the statements following the else construct.

We can replace a single if construct with multiple if-else statements to write a compound if statement.
The multiple if-else construct allows us to check multiple boolean expressions in a single compound if statement.

The syntax of the multiple if-else statements is:

if (Boolean_expression_1)
{
statements
}
else if (Boolean_expression_2)
{
statements
}
else (Boolean_expression_3)
{
Statements
}


Conditional Expression -or- The Ternary Operator

The conditional expression can be used as shorthand for some if-else statements. The general syntax of the conditional operator is:


expression1 ? expression2 : expression3


This is an expression, not a statement, so it represents a value. The operator works by evaluating expression1. If it is true (non-zero), it evaluates and returns expression2.Otherwise, it evaluates and returns expression3.

The classic example of the ternary operator is to return the smaller of two variables.
Every once in a while, the following form is just what you needed. Instead of...


if (x < y) {
min = x;
}
else {
min = y;
}


You just say...


min = (x < y) ? x : y;


Switch Statement

The switch statement is a sort of specialized form of if used to efficiently separate different blocks of code based on the value of an integer. The switch expression is evaluated, and then the flow of control jumps to the matching const-expression case. The case expressions are typically int or char constants. The statement is probably the single most syntactically awkward and error-prone features of the Java language.

When a match is found in one of the case labels, the statements associated with that case label get executed. The switch keyword in the switch-case construct contains the variable or the expression whose value is evaluated to select a case label. The case keyword is followed by a constant and a colon. The data type of case constant should match the switch variable.

Statements associated with the default keyword is executed if the value of the switch variable does not match any of the case constants.

The break statement used in the case label causes the program flow to exit from the body of the switch-case construct.

The break Statement causes the program flow to exit from the body of the switch construct.
Control goes to the first statement following the end of the switch-case construct. If not used inside a case construct, the control passes to the next case statement and the remaining statements in the switch-case construct are executed.


The syntax of the switch-case construct is:


switch(expression or variable name)
{
case Expr1:
statements;
break;
case Expr2:
statements;
break;
default:
statements;
}


Have a look at the fallowing examples to know more about if-else and switch statements.

If-Else Example


// Demonstartion of If-Else construct
import java.util.Scanner;
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int age;

System.out.print("Enter the Age of the Candidate :");
age=s.nextInt();

if(age>=18)
{
System.out.println("The Candidate is Eligible for Vote");
}
else
{
System.out.println("The Candidate is not Eligible for Vote");
}
}

}


Nested If Example


// Demonstartion of Nested-If construct

import java.util.Scanner;

/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int sub1,sub2,total;
double avg;

System.out.print("Enter Subject I Marks :");
sub1=s.nextInt();

System.out.print("Enter Subject II Marks :");
sub2=s.nextInt();

total=sub1+sub2;
avg=(double)total/2; // Type Conversion

System.out.print("Total Marks :"+total);
System.out.print("Average Marks :"+avg);

if(avg>=60)
System.out.print("First Division");
else if(avg>=55)
System.out.print("Second Division");
else if(avg>=35)
System.out.print("Third Division");
else
System.out.print("Student Failed");
}

}


Switch-Case Example


// Using Switch-Case-Break-Default

import java.util.Scanner;

/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int X;
System.out.println("What is the Capital City of Japan ?");
System.out.println();
System.out.printf("[1].Mumbai\t\t[2].Tokyo\n\n[3].Newyork\t\t[4].Islamabad\n\n\n");
System.out.print("Enter Your Choice (1..4) :");
X=s.nextInt();

switch(X)
{
case 1:
System.out.println("Your Answer is Wrong !" );
break;

case 3:
System.out.println("Your Answer is Wrong !" );
break;
case 4:
System.out.println("Your Answer is Wrong !" );
break;
case 2:
System.out.println("Your Answer is Correct !!");
break;
default:
System.out.print("Please Enter Valid Choice !!");
break;

}
}

}


Looping Statements

A looping statement causes a section of program to be executed a certain number of times.

The repetition continues while the condition set in the looping statement remains true.

When the condition becomes false, the loop ends and the control is passed to the statement following the loop.

While Loop

The while loop evaluates the test expression before every loop, so it can execute zero
times if the condition is initially false. It requires the parenthesis like the if.

While loop executes a statement or a block of statements as long as the evaluating condition remains true.The evaluating condition has to be a boolean expression and must return a boolean value that can be true or false.

The syntax of the while loop is:


while(Bool_Expr)
{
statements; //executed as long as Bool_Expr is true
}


In the preceding syntax, the statements in the while loop are executed as long as the Bool_Expr condition is true. When the condition returns false, the statement immediately following the while block is executed.

Do-While Loop

Like a while, but with the test condition at the bottom of the loop. The loop body will always execute at least once. The do-while is an unpopular area of the language, most everyone tries to use the straight
While if at all possible.

The syntax of the do-while loop is:


do
{
statements;
}while(Bool_Expr);


The for Loop

This is a looping statement iterating for a fixed number of times. It consists of the for keyword followed by parentheses containing three expressions, each separated by a semicolon.

The three expressions in the for loop are:

1. Initialization expression
2. Test expression
3. IterationExpr expression

It is used when the number of iterations is known in advance. For example, it can be used to determine the square of each of the first ten natural numbers.

The syntax of the for loop is:


for(InitializationExpr; TestExpr; IterationExpr)
{
statement_1
statement_2

}


In the preceding syntax, the initialization expression is executed only once, when the control is passed to the for loop for the first time.

The initialization expression gives the loop variable an initial value.

The test expression is executed each time the control passes to the beginning of the loop. If true, the body of the loop is executed, otherwise not.

The IterationExpr expression is always executed when the control returns to the beginning of the loop in each loop iteration.

The following figure shows the use of for loop:


Have a look at the fallowing examples to know more about loops.

While Loop Example

// Demonstartion of While Loop with Natural Numbers

import java.util.Scanner;
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int i=1,n;

System.out.print("Enter the Limit :");
n=s.nextInt();

while(i<=n)
{
System.out.printf("%d\t", i);

i=i+1;
}

}

}


Do-While Loop Example


// Demonstartion of Do-While Loop.
// To check wether a Number is Palindrome or Not

import java.util.Scanner;
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int n,sum=0,r,temp;

System.out.print("Enter any Number :");
n=s.nextInt();

temp=n;

do
{
r=n%10;
sum=sum*10+r;
n=n/10;
}while(n>0);

if(temp==sum)
{
System.out.println("The Number "+temp+ " is Palindrome");
}
else
{
System.out.print("The Number "+temp+ " is Not Palindrome");
}

}

}


For Loop Example


// Demonstartion of For Loop.
// Genaration of Multiplication Table for a Number

import java.util.Scanner;
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner s=new Scanner(System.in);

int n;

System.out.print("Enter any Number :");
n=s.nextInt();

for(int i=1;i<=10;i++)
{
System.out.printf("%d X %d = %d\n", i,n,i*n);
}

}

}


Although I am not going very deep into these concepts, if you people want any more regarding loops just post your problem, I will get back to you very soon.

Post a Comment