Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Counting with loops
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
slider203




PostPosted: 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
Sponsor
Sponsor
Sponsor
sponsor
TheGuardian001




PostPosted: 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.
slider203




PostPosted: 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 Sad I know its dumb


How would I skip odd numbers in a for loop though or count negative?
Euphoracle




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: