Question

I'm trying to get the first 1000 numbers in this arithmetic sequence (1,4,7,10,...) I must do it using a while loop. I can't figure out how to set the counter so I get my 1000 numbers; I did something like this:

I'm new to programming and do not have much experience, thanks in advance.

public static void main(String[]args) /* main Method */
    {
      int s = 1;
        int sum = 3;
        while ( s < 1000 )

             {
               s = s + sum;
               System.out.println(s);
             }
}
Was it helpful?

Solution 2

Here is the corrected code snippet:

  int s = 0;
  int sum = 1;
  while ( s < 1000 )
  {
     s++;
     System.out.println(sum);
     sum += 3;
  }

In your original code, you were confusing your loop counter with your summation variable; the two should have been distinct.

OTHER TIPS

Your code will print the values as long as those values are less than 1000. Not quite what you want.

Try this instead:

int s = 1;
System.out.println(s);
for (int i = 0; i< 999; i++)
{
    s += 3;
    System.out.println(s);
}

Note that I am calling println outside the loop as well to ensure we output the initial value of s (1);

EDIT

You need to do it with a while loop? OK. Try this-

int s = 1;
int whileCounter = 0;
System.out.println(s);
while(whileCounter < 999)
{
    s += 3;
    System.out.println(s);
    whilecounter++;
}

Note also that siunce we outputted the value first time around, I've reduced the count variable by 1 to 999 so we only output 1000 lines in total.

An arithmetic progression or sequence is a sequence of numbers such that the difference between the consecutive terms (d) is constant. In your case, difference is 3, and the first in the sequence is 1, and you want the first 1000 sequence numbers. Now, fit the formula for the arithmetic progression:

a+(n-1)*d

For your problem, you have the following:

a = 1;
d = 3;

Code for your solution (in Java) would be as follows:

public class ArithProg {
public static void main(String[] args) {
    int a = 1;
    int n = 1;
    int d = 3;
    while ( n <= 1000 )  {
        System.out.println(a+(n-1)*d);
        n++;
    }
   }
}

The advantage with this is that, you can change the value of 'a' as well as 'd', and get a sequence of n numbers in the arithmetic progression. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top