Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Loop is not doing what expected

I'm studying Obj-C and now I'm not understand why my loop isn't work how it should. I know a way i could achieve result with single while loop, but i want to do this through do while and can't figure out whats going wrong.

What i want is, to show integer called triangularNumber for integers 5,10,15.. and so on. There is what i've tried:

for (int i=1; i<51; i++){


            int triangularNumber;

            do {
                triangularNumber = i * (i+1)/2;


                NSLog(@"Trianglular number is %i", triangularNumber);

            }
            while (i%5 == 0);

        }

It produce odd results: 1) Condition of i%5==0 is not met, it output 1,3,6,10 then infinite numbers of 15 2) It create an infinite loop

Please tell me, what is wrong in that code and how to fix it. Thanks!

Upvotes: 0

Views: 27

Answers (1)

SMA
SMA

Reputation: 37023

Instead of do while loop within for loop, use if to check whether a number is divisible by 5 or not.

If you want to do it with do while loop, you could do the following:

int i = 5;
int triangularNumber;
do {
    triangularNumber = i * (i+1)/2;
    NSLog(@"Trianglular number is %i", triangularNumber);
    i += 5;
} while (i < 51);

Reason your code is not working:

  • Within your do while loop, if i say is 5, then you will end up running in infinite loop as you will satisfy your do while loop's condition which is i%5==0
  • You just need numbers like 5, 10, 15.. so it's just matter of one loop. Now loop starts with 1 till 50, and you are picky in the sense you just need one element of 5, hence to be picky you could use if condition which says print if and only if my i is multiple of 5.
  • Do while will always enter into loop and will execute it once. So for 1 it will enter and do calculation for triangularNumber as 1 * 2 /2 = 1 and hence your output 1 and checks condition post printing is 1 divisible by 5, no then it comes out and increments i to 2 and follows same routine as above.

Upvotes: 1

Related Questions