Welcome Guest! To access all forums & features, please register an account or sign-in. → Why register?

# For loop

4 replies to this topic

### #1 bs819

bs819

Neowinian

• Joined: 16-September 13

Posted 18 September 2013 - 12:37

I should have just added this in my topic yesterday

I'm trying create a for loop that calculates a series of fractions, ranging from 1/30 to 30/1.

So far I have that I need to increment the numerator counter and decrement the denominator counter. I'm just confused about how to write the code that adds the fractions together!

Does this look right at all? This is my first programming class so it's still confusing to me!

For num = 1 To 30 Step 1

For den = 30 To 1 Step -1

Set sum = sum + (num/den)

(Once again, I'm not learning a specific language at the moment, so I'm sorry if it seems so basic haha)

### #2 Andre S.

Andre S.

Asik

• Tech Issues Solved: 5
• Joined: 26-October 05

Posted 18 September 2013 - 14:21

You'll need to initialize sum to zero before the loop:

```Set sum = 0
For num = 1 To 30 Step 1
For den = 30 To 1 Step -1
sum = sum + (num/den)```

After the outer loop exits, sum will contain the sum of all fractions 1/30, 1/29, 1/28... 2/30, 2/29, ... 30/1. Keep in mind that in most programming languages, number literals without a fractional part like "30" are integers, so you'll be performing integer division instead of real number division, which won't give you the result you want. Make sure you're using real (floating-point) numbers.

### #3 +Majesticmerc

Majesticmerc

Resident Idealist

• Tech Issues Solved: 2
• Joined: 24-August 05
• Location: United Kingdom
• OS: Arch Linux / Win 7
• Phone: HTC One X

Posted 18 September 2013 - 20:02

Keep in mind that in most programming languages, number literals without a fractional part like "30" are integers, so you'll be performing integer division instead of real number division, which won't give you the result you want. Make sure you're using real (floating-point) numbers.

This is good advice, but it's not relevant for pseudocode IMO as it's an implementation detail.

### #4 Andre S.

Andre S.

Asik

• Tech Issues Solved: 5
• Joined: 26-October 05

Posted 18 September 2013 - 20:26

This is good advice, but it's not relevant for pseudocode IMO as it's an implementation detail.

Indeed, I was just pointing that out in case he ends up implementing it.

### #5 OP bs819

bs819

Neowinian

• Joined: 16-September 13

Posted 20 September 2013 - 13:38

Indeed, I was just pointing that out in case he ends up implementing it.

Thanks for the help! I will make sure to remember that