Stopping a Loop

This is a discussion on Stopping a Loop within the C Programming forums, part of the General Programming Boards category; I have a function that takes the sum of 1/n/(n+1). I want my loop to keep adding the numbers together ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    1

    Stopping a Loop

    I have a function that takes the sum of 1/n/(n+1). I want my loop to keep adding the numbers together UNTIL the difference between consecutive numbers is less than or equal to 0.0000001. I have no idea how to tell the loop to look at only the difference between consecutive numbers, not just the number itself. Does anyone know how to tell a loop to stop in this case? Thanks!

  2. #2
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    A kind of fool proof method, but not very elegant way is to go

    Code:
    while(1){
    
    do something....
    
    if (difference<=0.0000001) break;
    }
    or better...

    Code:
    do {
    
    //do something....calculate sum and difference , increment n
    
    } while((difference<=0.0000001); // not sure is you need a semicolon here but the compiler will advise!!
    I bet they produce pretty much the same code anyway!!

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    18
    Quote Originally Posted by Catman188 View Post
    I have a function that takes the sum of 1/n/(n+1). I want my loop to keep adding the numbers together UNTIL the difference between consecutive numbers is less than or equal to 0.0000001. I have no idea how to tell the loop to look at only the difference between consecutive numbers, not just the number itself. Does anyone know how to tell a loop to stop in this case? Thanks!
    You can use while loop like this:
    Code:
    while(delta >threshold)
    {
        //update n
        //compute something
        //update delta
         
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 10:21 PM
  3. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 02:14 AM
  4. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 08:14 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21