Control Flow, Arrays - Doc
Control Flow, Arrays - Doc
Definition
Control flow statements, however, break up the flow of execution by employing decision
making, looping, and branching, enabling your program to conditionally execute particular blocks
of code.
In Java, program is a set of statements and which are executed sequentially in order in
which they appear. In that statements, some calculation have need of executing with some
conditions and for that a control to that statements has been provided.
In other words, Control statements are used to provide the flow of execution with
condition.
Selection Statement
Selection statement is also called as Decision-making statements because it provides the
decision-making capabilities to the statements.
These two statements are allows the user to control the flow of a program with their conditions.
if statements:
There are various types of if statement in Java.
● if statement
● if-else statement
● if-else-if ladder
● nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Flow Diagram
Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}}
Output:
Age is greater than 18
if else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
}
The “if statement” is a commanding decision making statement and is used to manage the flow
of execution of statements.
The “if statement” is the simplest one in decision statements. Above syntax is shows two ways
decision statement and is used in combination with statements.
Following figure shows the “if statement”
Example:1
Program to check whether the number is positive or negative.
import java.util.*;
class NumTest
{
public static void main (String[] args)
{
int Result;
Scanner s = new Scanner(System.in);
Result = s.nextInt();
System.out.println("Number is"+Result);
if ( Result < 0 )
System.out.println("The number "+ Result +" is negative");
else
System.out.println("The number "+ Result +" is positive");
}
}
Example:2
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
If the condition1 is true then it will be goes for condition2. If the condition2 is
true then statement block1 will be executed otherwise statement2 will be executed. If the
condition1 is false then statement block3 will be executed. In both cases the statement4 will
always executed.
Flow Diagram
Example:1
Program to find largest number of three given numbers using if else.
class Test
{
public static void main(String args[])
{
int x = 20;
int y = 15;
int z = 30;
if (x > y)
{
if (x > z)
System.out.println("Largest number is: "+x);
else
System.out.println("Largest number is: "+z);
}
else
{
if (y > z)
System.out.println("Largest number is: "+y);
else
System.out.println("Largest number is: "+z);
}
}
}
Example:2
//Java Program to demonstrate the use of If else-if ladder.
//program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail"); }
else if(marks>=50 && marks<60){
System.out.println("D grade"); }
else if(marks>=60 && marks<70){
System.out.println("C grade"); }
else if(marks>=70 && marks<80){
System.out.println("B grade"); }
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!"); }
}
}
Output:
C grade
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output:
You are eligible to donate blood
Points to Remember
● There can be one or N number of case values for a switch expression.
● The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
● The case values must be unique. In case of duplicate value, it renders compile-time error.
● The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
● Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression. If a break
statement is not found, it executes the next case.
● The case value can have a default label which is optional.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Flow Diagram
Example:1
class Test {
public static void main(String args[]){
char grade;
Scanner s = new Scanner(System.in);
grade = s.next();
switch(grade)
{
case ‘S’ : System.out.println(“>90”);
break;
case 'A' : System.out.println(">80 and <=90");
break;
case 'B' :System.out.println(“>70 and <=80”);
break;
case 'C' : System.out.println(“>60 and <=70”);
break;
case 'D' : System.out.println(“>55 and <=60”);
break;
case 'E' : System.out.println(“>50 and <=55”);
break;
case ‘U’: System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Example:2
//Java Program to demonstrate the example of Switch statement
//where we are printing month name for the given number
public class SwitchMonthExample {
public static void main(String[] args) {
int month=7; //Specifying month number
String monthString="";
switch(month){
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
......
.....
default:System.out.println("Invalid Month!");
}
System.out.println(monthString);
} }
Output: 7 - July
Loop Statements
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. The statements may be executed multiple times
(from zero to infinite number). If a loop executing continuous then it is called as Infinite loop.
Looping is also called as iterations.
There are three types of loops in Java.
● while loop
● do-while loop
● for loop
while loop
A while loop statement in java programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
while(Boolean_expression)
{
//Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any non zero value. When executing, if the boolean_expression
result is true, then the actions inside the loop will be executed. This will continue as long as the
expression result is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram:
Program
class Test {
public static void main(String args[]) {
int x = 1;
while( x < 10 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
do-while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do
{
//Statements
}while(Boolean_expression);
The Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.
If the Boolean expression is true, the control jumps back up to do statement, and the statements
in the loop execute again.
Example
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
for loop
for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. A for loop is useful when the user knows how many
times a task is to be repeated.
Syntax
for(initialization; Boolean_expression; update)
{
//Statements
}
● The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. and this step ends with a semi colon (;)
● Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop will not be executed and control jumps to the next
statement past the for loop.
● After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
● The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Flow Diagram
Example:1
class Loop {
public static void main(String[] args) {
Output:
Number 1
Number 2
Number 3
Number 4
Number 5
Example:2
public class Demo {
public static void main(String[] args) {
int num = 10, count, total = 0;
Example:
/Java Program to demonstrate the use of break statement
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break; //breaking the loop
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Continue
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
● In for loop, the continue keyword causes control to immediately jump to the update
statement.
● In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax
continue;
Flow Diagram
Example:1
/Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=5;i++){
if(i==3){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
4
5
Example:2
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output:
10
20
40
50
Return statement
● return is a reserved keyword in Java i.e, we can’t use it as an identifier.
● It is used to exit from a method, with or without a value.
Syntax
return;
Example : Program for return statement
public class MyClass
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{
System.out.println(myMethod(3));
}
}
Output:
8
Arrays are objects which store multiple variables of the same type. It can hold primitive types as well
as object references. In fact most of the collection types in Java which are the part of java.util package use
arrays internally in their functioning. Since Arrays are objects, they are created during runtime .The array
length is fixed.
Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store one or more
values of a specific data type and provide indexed access to store the same. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.
● First, you must declare a variable of the desired array type
● Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable
Arrays can be initialized when they are declared. The array will automatically be created large enough to hold the
number of elements you specify in the array initializer. There is no need to use new.
Features of Array
Array Declaration
First let us get into the declaration of arrays which hold primitive types. The declaration of array
states the type of the element that the array holds followed by the identifier and square braces which indicates
the identifier is array type.
int MyArray[];
Declaring Array
int []aiMyArray;
int aiMyArray[];
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
● It creates an array using new dataType[arraySize].
● t assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from
0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double type
and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
Example
The following code displays all the elements in the array myList –
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
}}}
Output
1.9
2.9
3.4
3.5
Example
public static void printArray(int[] array)
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray
method to display 3, 1, 2, 6, 4, and 2 −
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
Example
class TwodimensionalStandard
{
public static void main(String args[])
{
int[][] a={{10,20},{30,40}};//declaration and initialization
System.out.println("Two dimensional array elements are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
}
}
Output:
10
20
30
40