Sign in to follow this  

For loop

Recommended Posts

bs819    0

I should have just added this in my topic yesterday :P 

 

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)

Share this post


Link to post
Share on other sites
+Andre S.    1,892

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.

Share this post


Link to post
Share on other sites
+Majesticmerc    871

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.

Share this post


Link to post
Share on other sites
+Andre S.    1,892

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.

  • Like 1

Share this post


Link to post
Share on other sites
bs819    0

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.