JAVA, for Loop Classic example

Source: Internet
Author: User

Two applications of loops: exhaustive and iterative.

One, the poor lift: will all the possible situation go through, with if filter out to meet the conditions.

Hundred Chicken Hundred Money: A Rooster 1 text money, a hen 2 text money, a chicken half wen Qian, need to buy 100 chickens, just spend, how can buy? How many kinds of buying methods are there?

        intFF = 0;  for(intg=0;g<=100;g++)        {             for(intm=0;m<=50;m++)            {                 for(intx=0;x<=200;x++)                {                    if(g+m+x==100 && g+2*m+0.5*x==100) {FF++; System.out.println ("Can buy Rooster" +g+ "only, hen" +m+ "only, Chick" +x+ "only"); } }}} System.out.print ("Total" +ff+ "method of purchase"); 

As follows:

Add + or-make a formula in the following parentheses

123 () () () () 8 () 9=100

                for(inta=-1;a<=1;a+=2)        {             for(intb=-1;b<=1;b+=2)            {                 for(intc=-1;c<=1;c+=2)                {                     for(intd=-1;d<=1;d+=2)                    {                        if(123+a*45+b*67+c*8+d*9==100) {System.out.print (a+ "\ t" +b+ "\ T" +c+ "\ T" +d); }                    }                }            }        }        

As follows:

Positive 1 is the minus 1 for the plus sign, so the order added in parentheses is 123 (+) (-) (-) (+) 8 ( -) 9=100

two , iteration: Find the law, from the known conditions, the introduction of results

Basketball Bounce: Basketball from a 10-meter position down, each drop is the previous one-third, asked to bounce 10 times after the height of basketball basketball

float h=10;for (int g=0;g<10;g++) {H=H/2;} System.out.print ("The height of the tenth time is" +h+ "M");

  

JAVA, for Loop Classic example

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.