简体   繁体   中英

for loop that produces series of different numbers

I have found a few similar topics to my issue, but couldn't figure out the task still, so I thought it'd be best to create my own topic.

I need to write a for loop that produces the following output:

289 256 225 196 169 144 121 100 81

For added challenge, try to modify your code so that it does not need to use the * multiplication operator.

This is my code below, I'm stuck here so please help.

public class Exercises2{
   public static void main(String[] args){
      int start = 19;
      int increment = 2;
      for(int count = 81; count <= 289; count++){


         System.out.println(count + start);
         start = increment + start;         

      }
   }
}

Below is what you need. Notice the count+=start increment within the for loop and the start+=increment adding from the base of 17 so you increase count by 19 the first time, 21 the second, etc.

Remember a for loop doesn't require a count++ it can be any valid command in the last portion or can be left out completely

int start = 17;
int increment = 2;
for(int count = 81; count <= 289; count+=start){
    System.out.println(count);
    start+=increment;
}

Have you figured out the pattern for generating the numbers in the series? If not, the multiplication "challenge" is actually a big hint at how it's generated.

After that try to figure out how to write a loop that does multiplication manually and that should give you the answer you're looking for.

Your main problem is that you're not incrementing count enough. If you're going to have count go from 81 to 289 then you need to be doing more to count than just ++; Just a couple changes fixes your own code. Change the start value to 17 and change how count is incremented to count += start.

int start = 17;
int increment = 2;
for(int count = 81; count <= 289; count += start){      
    System.out.println(count);
    start += increment;
}

I think there is value in doing your homework yourself and figuring it out can bring a lot of benefit and gain as a programmer. But here is your answer without multiplication:

 int start = 2;

int increment = 19;

int value = 81;

int _max = 289;

while(value <= _max)
{
    System.out.println(value);
    value += increment;
    increment += start;
}

Try this.

    int start=17;  
    int end=9;     
    for(int i=17;i>=9;i--)
    {
        System.out.println (i*i);

    }   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM