Lecture 3
Lecture 3
Do-while loop
Do-while loop is similar to the while loop but
the only difference is that, in this the loop block is
guaranteed to run at least one time!!!!
do
{
//all codes here
}
While (condition)
//since condition appears at the end, therefore the
code block executes at least one
For loop
In for loop the initialization, condition checking and
updating of loop element is done in a single line.
For(initialization; condition; update)
{
// codes
}
The initialization step is executed first, and only once. This
step allows you to declare and initialize any loop control
variables.
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 does not execute.
After the body of the for loop executes, the flow of control
jumps back up to the update statement. This statement
allows you to update any loop control variables.
Nesting of loops
The placing of one loop inside the body of another
loop is known as Nesting of loops.
While working with nesting loops the outer loop will
change only when inner loop is completely finished.
For (int outer =0; outer<5 ; outer++)
{
For (int inner= 0; inner <3; inner++)
{
System.out.println(outer is + outer + inner is + inner);
}//inner loop ends
}//outer loop ends
Switch statement
Switch statement is the shorthand for multiple if-else statement,
which allow us to choose a single path from a number of execution
path.
Switch statement works with char, short, byte, int and String.
switch(x)
{
case 1:
System.out.println("case1");
break;
case 2:
System.out.println("case2");
break;
case 3:
System.out.println("case 3");
break;
Default
System.out.println(default case)
}
Multidimensional arrays
Multi-dimensional arrays are nothing but the
array of arrays where each element represents
a single dimensional array.
for(int i=0;i<myArray2.length;i++)
{
for (int j= 0; j<myArray2[i].length;j++ )
{
myArray2[i][j]= j;
}
}
for (int i=0; i<myArray2.length;i++)
{
for (int j=0 ; j<myArray2[i].length; j++)
{
System.out.print(myArray2[i][j] + "\t");
//System.out.print("\t");
}
System.out.println();
}
for(int[] x : myArray2)
{
for (int y : x)
{
System.out.print(y + "\t");
}
System.out.println();
}