Answer to Question #255785 in Java | JSP | JSF for Sayem

Question #255785

Hey, I hope you are well.

Can you explain me the conversion from for loop to while loop vice versa in Python and Java? (As well as giving the examples of Recursive Function or Fruitful Functions)


1
Expert's answer
2021-10-26T15:09:47-0400


public class ForAndWhile {


	public static void main(String[] args) {


		int n = 10;
		while (n > 0) {
			System.out.println("Tic " + n--);
		}
//		For loop consist of four parts: loop control variable, loop condition, increment/decrement and the loop body. The first three are separated by semicolon.
//
//		for ( variable ; condition ; Increment/Decrement ){
//
//		Body
//
//		}
//
//		In order to convert for loop to while loop in C just move the loop control variable above the while and Increment/decrement expression inside the loop.


//		Loop control variable initialization;
		for (int i = 0; i >= n; i++) {
			System.out.println("Toe " + n--);
		}
	}
}



Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration.

Following is a simple for loop that traverses over a range

for x in range(5):
     print (x)



To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in every iteration as long as it is less than 5

x=0
while x<5:
     x=x+1
     print (x)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS