Solved

# For loop

Posted on 2006-11-01
281 Views
Hi,

How is the following loop interpreted?

Thank you.

for (i=56;i>0;){
0
Question by:IAJWDDIY
• 5
• 3
• 2
• +1

LVL 16

Expert Comment

ID: 17850729
Set i to 56.

Then, as long as i is greater than 0
execute the following compound statement.
0

LVL 86

Expert Comment

ID: 17850730
'i' is initialized to 56 and the loop is executed as long as 'i' does not drop below '1'. However, since the 'loop expression' (as in "for( [init-expr]; [cond-expr]; [loop-expr] )") does not change 'i', it has to be altered inside the loop body to meet that criteria.
0

LVL 30

Expert Comment

ID: 17850733
Loop starts with i equal to 56
Continues to loop while i is greater than 0
0

LVL 30

Expert Comment

ID: 17850751
0

LVL 30

Expert Comment

ID: 17850856
Need to reduce i, else you have infinite loop. This will reduce it by one on each iteration of the loop:

for (i=56;i>0;i--){
0

LVL 86

Expert Comment

ID: 17850877
>>Need to reduce i

What was unclear about "However, since the 'loop expression' [...] does not change 'i', it has to be altered inside the loop body to meet that criteria."?
0

Author Comment

ID: 17850985
So if there is a statement like:

a=z[i-] ; b=z[i-].....

inside the loop would this reduce?

Thanks
0

LVL 86

Accepted Solution

jkr earned 500 total points
ID: 17851056
Well, if they were like

a=z[i--] ; b=z[i--];

Yes, they would, e.g.

for (i=56;i>0;){

a=z[i--];
}
0

Author Comment

ID: 17851079
Thank you.
0

LVL 30

Expert Comment

ID: 17851128
>>What was unclear

Nothing wrong with more clarity, adding the words "infinite loop', and giving an i--  option.   : )
0

LVL 30

Expert Comment

ID: 17851173

IAJWDDIY, it's almost hidden away, but there's a "Split points" link in open questions at the bottom ;)
0

## Featured Post

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.