130 likes | 149 Views
Re-writing the for -statement using a while -statement and vice versa. Relationship between the while -statement and the for -statement. The for -statement and the while -statement have many aspects in common They can often replace each other.
E N D
Re-writing the for-statement using a while-statement and vice versa
Relationship between the while-statement and the for-statement • The for-statement and the while-statement have many aspects in common They can often replace each other.
Relationship between the while-statement and the for-statement (cont.) • Facts: • A while-statement can always be re-written using a for-statement • A for-statement that does not contain any continue-statement in its body, can be re-written using a while-statement.
Re-writing a while-statement using a for-statement • While-statement:
Re-writing a while-statement using a for-statement (cont.) can be written as follows using a for-statement: (We simply use an empty statement as the INIT-STATEMENT and as the INCR-STATEMENT)
Re-writing a while-statement using a for-statement (cont.) • Example: While-statement Equivalent for-statement a = 1; while ( a <= 10 ) { System.out.println(a); a++; } a = 1; for ( ; a <= 10 ; ) { System.out.println(a); a++; }
Re-writing a for-statement using a while-statement • For-statement:
Re-writing a for-statement using a while-statement (cont.) that does not contain a continue-statement, can be written as follows using a while-statement: (We move the INIT-STATEMENTbefore the while-statement and put the INCR-STATEMENT as the last statement in the body)
Re-writing a for-statement using a while-statement (cont.) • Example: For-statement Equivalent while-statement a = 1; while ( a <= 10 ) { System.out.println(a); a++; } for ( a = 1 ; a <= 10 ; a++ ) { System.out.println(a); }
Re-writing a for-statement using a while-statement (cont.) • Note: • A for-statement containing a continue-statement may jump to the INCR-STATEMENT • Because a while-statement does not have an INCR-STATEMENT, it can never jump to it.... Thus: a for-statement containing a continue-statementcannot be re-written as a while-statement
Abusing the Java for-statement • If a for-statement does not contain any continue statements, you can re-write the for-statement as follows:
Abusing the Java for-statement (cont.) • Example: Original for-statement Abused for-statement a = 1; for ( ; a <= 10 ; ) { System.out.println(a); a++; } for ( a = 1 ; a <= 10 ; a++ ) { System.out.println(a); }
Abusing the Java for-statement (cont.) • Example Program: (Shows the abused for-loop) • Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/07/Progs/For02.java • How to run the program: • Right click on link and save in a scratch directory • To compile: javac For02.java • To run: java For02