Java while loop and for loop

Source: Internet
Author: User

While loop and for loop two loops can be converted to one another

Let's take a look at it by example.

First example.??

1.//Output 1-10

public static void Main (string[] args) {

int i = 0;

while (true) {

if (I <= 10) {

System.out.println (i++);

} else {

Break

}

}

System.out.println ("----------------------");

for (int j=1;j<=10;j++) {

System.out.println (j);

}

System.out.println ("----------------------");

for (int j=1;j<=10;) {

System.out.println (j);

j + +;

}

}

? A simple example shows that while loops and for loops can be converted to each other, a problem replaced by a computer language can have different solutions, which is the pleasure of the computer.

Let's look at another problem.

Import Java.util.Scanner;

public class Problem2 {

public static void Main (string[] args) {

while (true) {

Scanner scan=new Scanner (system.in);

System.out.print ("Please enter the length of the Fibonacci sequence: (a positive integer greater than or equal to 3)");

int Len=scan.nextint ();

if (len<=2) {

SYSTEM.OUT.PRINTLN ("You entered the wrong, please re-enter");

}else{

int []array=new Int[len];

Array[0]=1;

Array[1]=1;

System.out.print (array[0]+ "\ T" + array[1]+ "\ t");

for (int i=2;i

ARRAY[I]=ARRAY[I-1]+ARRAY[I-2];

System.out.print (array[i]+ "\ t");

}

Break

}

}

}

}

? Here I use the while and for loop to achieve this problem, the idea is consistent, the solution is different.

Friends, is there a new understanding of the while loop and for loop today?

Java while loop and for loop

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.