Loops, Control Statements, Recursion and Iteration

Dictionary Deffinitions

    Iteration: To say or do again: repeat.

    Recursion: To occur or come up again.

They sound like the same thing, and truly the desired programming output is the same: a routine or program that repeats an operation. The internal coding differences are subtle, misunderstood and not explained well by text books or professors. I often remember getting marked down on assignments because I "used iteration instead of recursion" when I though I was just using a loop!

Often, even introductory sections concerning iteration and recursion will go into such depth that it only further confuses the student. This is the plainest definition that I have been able to come up with:

Iterative loops are statements that repeat themselves until a condition is met.
Recursive loops are statements that make calls to themselves until a condition is met.

I told you the difference was subtle!
Here are two examples to show the difference:
Iteration:
int i=0;
while(i<=5){
System.out.print("*");
i++;
}

Recursion:
printStar(0);
----------------------------

public static void printStar(int i){
i++;
System.out.print("*");
if(i<=5){
printStar(i);
}
}
Both have the same output, the difference is invisible to a user who only sees the end product, but internally they are different. From this example, recursion seems a little more complex, which makes it more powerful.


Loops and Control Statements

goto

if( )

Nested if( )

if( )...else

Nested if/else

ifels( )

for( )

nested for( ) loop
A C++ program with nested for loops

:?

for...in...do

while( )
A Perl program using while.

do...while( )
A do/while loop program in C
A do/while loop program in Java

Creating Counters

Increment and Decrement Operators

Postfix and Prefix Operators

switch( )

case:

break;

exit( )

return( )

Booleans and Conditionals

Endless Loops

The boolean value for true is "1"(or not zero). A while loop stops when the condition is false, so if it is always 1 it will continue to process.

while(1){
cout<<"Endless while Loop!\n";
}

for(;;){
cout<<"Endless for Loop!\n";
}


Breadth-First
Checks each node in the first level before moving to the next.

Depth-First
Follows each path to the end, one at a time.