Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Creating loops in Java

1. ## 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

2. 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.

3. 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!

4. 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!
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.

5. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•