\r\n
\n What is a For Loop?\n
\r\n
\r\n The for loop is a common construct in computer programming. A for loop is simply used to iterate\r\n repeat an action a given number of times. For example, it is a common scenario in computer programming\r\n to execute a block of code over and over for multiple times — each time with a different value of the control parameter.\r\n
\r\n
\n Structure of a For Loop\n
\r\n
\r\n A for loop has four essential components: initialization, conditional, incrementation and an action statement.\r\n
\r\n - \n
Initialization
\r\n This statement is used to declare and/or initialize the loop control variable, e.g., i=0.\r\n \r\n - \n
Conditional
\r\n This is a Boolean statement used to evaluate the condition for execution of the body of the loop, e.g., i<=5.\r\n \r\n - \n
incrementation
\r\n This statement is used to increment the counter variable, e.g., i++\r\n \r\n - \n
Action Statement
\r\n This represents the block of code that is iteratively executed as long as the condition checked remains true.\r\n \r\n
\r\n\r\n Shown below is the generic structure of a for loop.\r\n
\r\n
\r\nfor (initialization; conditional; incrementation)\r\n{\r\naction_statement;\r\n}\r\nend\r\n
\r\n \r\n
Example of For Loop
\r\n
\r\n The syntax used to write the for loop varies from language to language. Examples of\r\n for loops from Python, C and others are given below. The examples print out\r\n the numbers 0-9 (inclusive of 0 and 9).\r\n
\n Syntax of a for loop in Python3 Programming Language\n
\r\n
\r\nfor i in range(0, 10):\r\n print(i)\r\n
\r\n \r\n
\n Syntax of a for loop in C Programming Language:\n
\r\n
\r\n
\r\nfor (int i = 0; i < 10; ++i) {\r\n printf(\"%d\\n\", i);\r\n}\r\n
\r\n \r\n
\n MagicGraph | For Loop Explained\n
\r\n
\n This MagicGraph offers a visually interactive demonstration of how a for loop works.\r\n This simple computer program uses the for loop to incrementally move the rabbit from one point to another in N = 10 number of steps.\r\n
\r\n - \n
Initialization
\r\n The loop control variable i is initialized to a value of 1 (the yellow light is on).\r\n \r\n - \n
Conditional
\r\n Boolean statement to evaluate if i is less than or equal to N. If it is, the Boolean statement returns True (green light). Otherwise, it returns False (the red light is on).\r\n \r\n - \n
Incrementation
\r\n Then, i is updated in increments of 1 as long as its value is smaller than or equal to N (the default value is 10 but it can be modified).\r\n \r\n - \n
Action Statement
\r\n For each increment (while the green light is on), the x and y positions of the rabbit are updated by specified increments (defaults are 1 but they can be modified).\r\n \r\n
\r\n \r\n
\r\n \r\n \r\n \r\n \r\n
\r\n