Counting with loops
Author |
Message |
slider203
|
Posted: Sat Feb 27, 2010 11:24 pm Post subject: Counting with loops |
|
|
Hello I am having trouble with loops I understand that to count up the code would look somthing like this:
int MAX = 5
int countNum = 1
for (int counter = 0; counter <= Max; counter++)
System.out.println (countNum)
countNum++;
this will count from one to five. How would I use a counted loop to count backwards from 30 to 1? also how would I count but skip all odd numbers?
I am stuck nothing I do seems to work any help is greatly appreciated.
Thanks |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
TheGuardian001
|
Posted: Sat Feb 27, 2010 11:30 pm Post subject: Re: Counting with loops |
|
|
You can count in different ways by changing the last value in the for loop (as well as the others if you need to change the bounds).
counter++ says to increment the counter each time, but you're free to use whatever you want, IE:
code: |
for (int i = 0; i < 100; i += 10){} //Adds 10 each time
for (int i = 100; i > 90; i--){} //subtracts 1 each time
for (int i = 90; i > 60; i -= 15{} //subtracts 15 each time
|
There is also no need for the number countNum, as you can just output whatever value you are using in the for loop (in your case, "counter"), as long as you start counter at the value you want to start counting at instead of 0. |
|
|
|
|
![](images/spacer.gif) |
slider203
|
Posted: Sun Feb 28, 2010 8:15 am Post subject: Re: Counting with loops |
|
|
Thanks Guardian this was really helpful, and yes I do have to use the countNum variable thats the way that the my prof wants us to do it and if we dont follow the rule we loose marks I know its dumb
How would I skip odd numbers in a for loop though or count negative? |
|
|
|
|
![](images/spacer.gif) |
Euphoracle
![](http://compsci.ca/v3/uploads/user_avatars/11170373664bf5f25f636f1.png)
|
Posted: Sun Feb 28, 2010 1:19 pm Post subject: RE:Counting with loops |
|
|
How would you do it using the two basic operators + and x ?
Skip odd:
n += 2;
Negative:
n -= 1;
Make sure your 'exit conditions' can actually exit or you may hit an infinite loop. |
|
|
|
|
![](images/spacer.gif) |
|
|