Thread: Loop question

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    4

    Loop question

    Hi

    I'm new to this forum. I am currently a freshman at UCI and am in a beginning programming class-introduction to c.

    I need to know how to write a for loop within a for loop without one of the loops breaking. For example my program changes based on whether a number is even or odd, so if the number is odd it needs to add, but when its even to subtract. So how can I do this without one of the loops breaking when its condition is not met. For example if the number is odd I use the ++ to make it even but it breaks instead of continuing.

    Thanks in advance

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I don't really see why you want two for loops, based on the description. This sounds an awful lot like
    Code:
    int sum = 0;
    for (int i = 0; i < LARGE_NUMBER; i++) {
        if (isEven(i))
            sum -= i;
        else
            sum += i;
    }
    where of course you're doing whatever it is you do inside the if and the else.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    4
    This worked but only for one time. I need it to alternate back and forth between even and odd for n amount of times.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    What do you mean by only one time? The code (assuming you write isEven) will go back and forth, adding and subtracting.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    4
    does isEven need to be defined or is it already understood?

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It needs to be defined. (It's a simple enough function that you could just put the calculation right there in the if statement, if you want.)

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    4
    Thanks for the help, I really appreciate it!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. For loop question
    By JuzMe in forum C++ Programming
    Replies: 11
    Last Post: 04-20-2009, 08:39 AM
  2. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-06-2006, 11:43 PM
  3. Please don't laugh...SIMPLE loop question!
    By the_lumin8or in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2006, 01:08 PM
  4. while loop question
    By rayrayj52 in forum C++ Programming
    Replies: 2
    Last Post: 10-19-2004, 05:13 PM
  5. A question about while loop
    By Arooj in forum C++ Programming
    Replies: 5
    Last Post: 02-16-2003, 10:56 PM