Reputation: 6940
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
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:
i%5==0
Upvotes: 1