Saturday, June 16, 2007

Forn loop- executing the for loop n times

The for loop is a useful control statement.But if you want to execute the for loop "n" number of times, just nesting it will work fine. The following java program will do that job well.


classforn {public static void main(String args[]){int i,j,n=Integer.parseInt(args[0]);
for(i=0;i<n;i++)
{ for(j=0;j<5;j++){
System.out.println(j); }

}

}
}

The output for

C:\javaprogs>java forn 3
would be
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
The problem arises when the for loop has to be executed different number of times during the "n" executions.Hope that makes sense. The number of times the for loop has to be executed has to be stored in a array of size n. So the modified program to execute the for loop as per the value stored in the array would be-


classforn {public static void main(String args[]){int i,j,n=Integer.parseInt(args[0]);
for(i=0;i<n;i++){
for(j=0;j<(Integer.parseInt(args[i+1]));j++){

System.out.println(j); }

}

}
}

The output for

C:\javaprogs>java forn 3 2 4 3
would be
0
1
0
1
2
3
0
1
2

The point is "Do we need a forn loop" or can this be done better using a "while" or "until". The extra overhead in storing the array and checking individual conditions can be avoided. If anybody has program that cant be solved using the while or until and requires a forn loop pls let me know.

No comments: