Hi,
Below i have pasted the code, now i understand that this is a recursive algorithm however when i step through this im really confused .
I understand that the Scale (5) line states the starting number for the value of 'n' once this is found the program then enters the first if statement, checks to see if its greater than 1 if it is it then minuses 1 from n's value and repeats this until n is not greater than 1 or is equal to 1.
From that point it then moves forward to the if n ==1 line where it prints a single dash and line space. After that it then enters the FOR loop. - This is where i get confused
the counter within the FOR loop is set to 0 if the counter is less than the value of N it then increments the counter by 1 and again prints a single dash followed by a line space.
it then steps onto the scale (n - 1) line this then minuses 1 from the value of n making it zero.
N = 0 at this point the program returns to the first if statement to check it n > 1 which is isnt and moves into the n == 1 statement and prints a single dashed line.
the counter and n are both equal to zero this stage are they or arent they? shouldnt the program stop there?
i know the actual outcome but cant get my head round why its like that?
the output is beneath the code :S please help
Code:void scale( int n ) { int counter; if ( n > 1 ) { scale( n - 1 ); for ( counter = 0; counter < n; counter++ ) printf( "-" ); printf( "\n" ); scale( n - 1 ); } else { if ( n == 1 ) printf( "-\n" ); } } int main( void ) { printf( "\n" ); scale( 5 ); }
-
--
-
---
-
--
-
----
-
--
-
---
-
--
-
-----
-
--
-
---
-
--
-
----
-
--
-
---
-
--
-