# Creating loops in Java

• 11-26-2010, 02:19 PM
Beck7223
Creating loops in Java
I am a java beginner and would like some help on creating loops

the mark is between 0 and 100 and loses 5 marks each day it is late
if it drops below 20 no marks are deducted and if the original mark was 20 or less it stays at the original mark

m= mark
d = days

so far i have

for ( int m=100 ; m <=100 ; m -=5 )
system.out.println ( " mark is " m)

i have no idea if this is right or how to incorporate the days into the loop
• 11-26-2010, 04:23 PM
Fou-Lu
The loop declaration itself is fine, but probably not for what you are intending to do.

I perceive this as follows: an assignment is first graded giving the value of 'mark'. After it is graded, it is reduced by 5 marks/day until it hits a minimum of 20 (to me this hardly seems fair; I would reduce until 0, but I'm not the one giving marks ;)). To do this with a for loop, use multiple conditions:
PHP Code:

``` for (int m = mark, d = daysLate; m >= 20 && d >= 0; m -= 5, ++d)  ```
So if 'mark' is 75, and it was late for fourteen days, logically:
PHP Code:

``` int mark = 75;int daysLate = 14;for (int m = mark, d = daysLate, m >= 20 && d >= 0; m -= 5, --d)  ```
m would be 20 and d would be 3 in the end (since only 11 days would be subtracted off).

This can also be calculated with just regular mathematics and conditions.
• 11-27-2010, 08:29 AM
corecase
This is how i would do it:

Code:

```int m = mark; int d = daysLate; if(m <= 20) {     System.out.println("Mark is: " + m); } else {     while(d >= 0 && m > 20)     {         m -= 5;         d--;     }     System.out.println("Mark is: " + m); }```
I think it's a bit easier to understand than using a for loop with two variables inside. Just my opinion though! Hope it helps! :thumbsup:
• 11-27-2010, 02:31 PM
Fou-Lu
Quote:

Originally Posted by corecase
This is how i would do it:

Code:

```int m = mark; int d = daysLate; if(m <= 20) {     System.out.println("Mark is: " + m); } else {     while(d >= 0 && m > 20)     {         m -= 5;         d--;     }     System.out.println("Mark is: " + m); }```
I think it's a bit easier to understand than using a for loop with two variables inside. Just my opinion though! Hope it helps! :thumbsup:

Your right, multiple variables and conditions in a for loop do tend to get complicated looking quite quickly, and neither approach has any additional overhead, so a simple if check followed by a while would be much easier to read than a single for loop.
• 11-27-2010, 07:57 PM
corecase
Yeah, that's exactly what i had in mind. Although a for loop does make the code look more tidy, logically the other way seems simpler, especially for beginners.