Nested loop means there should be an outer loop and one or more inner loop. We have seen the use of inner loop in different type of programs. Whenever we use any nested loop, inner loop plays the most vital part. In sorting programs inner loop does the sorting job. In pattern printing programs, it is the inner loop which displays the pattern. So for any type of the above jobs, students should understand the inner loop properly.
Use of inner loop in nested loop
For any type of pattern, the inner loop is the main architech to display the design or pattern. Job of outer loop is simply to maintain the rows but the major job is performed by inner loop. Take any program on printing pattern, you would find that the construction of inner loop, the logical statements used in the inner loop are the main points to stydy and understand. Any change in the statements of inner loop will change the shape of the pattern.
Here is a program to print a pattern like
55555
55554
55543
55432
54321
Simply observe the checking done in inner loop
class Pat
{
int i,n,j;
public void show()
{
for(i=0;i< 5;i++)
{
n=5;
for(j=0;j< 5;j++)
{
if(i+j >=5)
n--;
System.out.print(n);
}
System.out.println();
}
}
public static void main(String args[])throws Exception
{
Pat obj=new Pat();
obj.show();
}
}
Use of inner loop in sorting programs
In any type of sorting programs, inner loop performs the major job. In slection sort programs, the checking job is performed by inner loop and the necessary exchange of values is also performed within inner loop.
In Bubble sort , the accessing the values, cheking the values and exchanging the values on requirements are done by inner loop only. The outer loop determines the maximum number of passes required.
Other uses of inner loop
Inner loop has many other countless uses. One of the very common use of inner loopis to store unique values in an array. Inner loop is used in such program to search a particular values from the list. Although normal searching program do not need inner loop but to [ HREF]store unique values in an array, inner loop is used to search if the value is already in the array.
No comments:
Post a Comment