I'm trying to grasp the relation between iteration and recursion by trying to model a simplified execution of a body of statements within a scope { } on an old homework assignment I had. Let's say I have two statement types: while statement, and an assignment statement.
For now, I'm assuming the while statement's condition is always true. EDIT: Also, assume the while statement only executes once (i.e, I should have called it an if statement)
In recursion, this would be simple:
executeBody( body )
{
for each stmt in body
{
switch (stmt)
{
case ASSIGNMENT:
// work
break;
case WHILE-STMT:
executeBody(whileStmt->body)
break;
}
}
}
But, I'm having trouble doing this for iteration. I know I need to simulate a stack, but I just can't conceptualize how to execute all the statements in a while statement before I go to the next statement. Here's a model of what I have:
executeBody( body )
{
for each stmt in body
{
case ASSIGNMENT:
// work
break;
case WHILE-STMT:
{
stack< body > stack;
stack.push(whileStmt->body);
while (stack isNotEmpty)
{
for each stmt (in each body) in stack
{
case ASSIGNMENT:
// work;
break;
case WHILE-STMT:
//stack.push(this_whileStmt->body);
// ????
break;
}
}
}
}
}
EDIT: Changed the recursion example to show that the body is a sequence of statements.