Example of nested loops

# Example of nested loops

##### Lesson Details:
June 29, 2020

I: Introduction

Programming languages are used to write programs and applications. They are just like natural language such as English, French, German and so on. Natural languages are spoken by man. Programming languages are written by man. Programs and applications are just like stories and novels written by man. If you know English, you can read a novel written in English and understand it. If you know Chinese, you can read a novel written in Chinese and understand it. If you know the C programming language, you can write a program in C and compile and run it.

II: Body

The following example shows the use of nested loops. Nested loop is a loop inside another loop. In this example, we have 2 loops: an outer loop and an inner loop. The outer loop iterates from 1 to 10; the inner loop iterates from 1 to 100. The inner loop has 5 iterations; each iteration outputs 1 character (i.e., ‘a’, ‘b’, ‘c’, ‘d’ and ‘e’).

# Program to demonstrate the use of nested loops # Set the output format to columns for easier reading OUTPUT_FORMAT = "columns" # Number of characters in each string # 10 x 5 = 50 chars in total N_CHARS_EACH_STRING = 10 * 5 # Outer loop variable i = 1 # Inner loop variable j = 1 # Counter variable k = 0 # ----------------------------------------------------- # Program starts here while i <= 10 : # Output the number of iterations if i == 1 : print ( "outer loop iteration:" , i ) else : print ( "inner loop iteration:" , i ) for k in range ( N_CHARS_EACH_STRING ): print ( str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) + "-" + str ( j ) ) for k in range ( N_CHARS_EACH_STRING ): print ( "" ) j += 1 i += 1

III: Conclusion

In conclusion, this example showed the use of nested loops.