For loop, multiple loop variables Session No. 18 Course Name: Programming for Problem Solving Course Code: E1UA102C Instructor Name: Anil Kumar Gankotiya Duration: 50 min Date of Conduction of Class: Galgotias University 1
Review of Previous Session: Galgotias University 2 Iteration and Loops : Use of While and Do-While
Opening Question: Galgotias University 3 "If you already know how many times a task needs to repeat, which loop would you choose — and why ?“ "Imagine two runners starting at opposite ends of a track — one moves forward, the other backward. How could you simulate their positions using a single loop?"
Learning Outcomes : Galgotias University 4
Session Outline Galgotias University 5
GSCALE full form and date 6 For Loop in C A for loop is a control structure used for repeated execution of a block of statements when the number of iterations is known in advance. for (initialization; condition; update) { // statements to execute } Components : Initialization : Sets the starting value of loop variables (executed once at the beginning). Condition: Checked before each iteration; if true, the loop body executes; if false, the loop ends. Update: Changes the loop variable(s) after each iteration. Syntax: for ( int i = 1; i <= 5; i ++) { printf ("%d ", i ); } Output: 1 2 3 4 5
Flowchart of for Loop Galgotias University 7
Working of For Loop Galgotias University 8 Step 1: Initialization is the basic step of for loop this step occurs only once during the start of the loop. During Initialization, variables are declared, or already existing variables are assigned some value. Step 2: During the Second Step condition statements are checked and only if the condition is the satisfied loop we can further process otherwise loop is broken. Step 3: All the statements inside the loop are executed. Step 4: Updating the values of variables has been done as defined in the loop . Continue to Step 2 till the loop breaks.
Infinite For Loop Galgotias University 9 This is a kind of for loop where the input parameters are not available or the condition that's always true due to which, the loop iterates/runs endlessly . #include < stdio.h > int main() { // for loop with no initalization , condition and updation for (;;) { printf (" GfG \n"); } return 0; }
Example: First N Natural Numbers Using For Loop Galgotias University 10 #include < stdio.h > int main() { int n = 5; // Initialization of loop variable int i ; for ( i = 1; i <= n; i ++) printf ("%d ", i ); return 0; }
Nested Loops Galgotias University 11 Nesting loops means placing one loop inside another. The inner loop runs fully for each iteration of the outer loop. This technique is helpful when you need to perform multiple iterations within each cycle of a larger loop, like when working with a two-dimensional array or performing tasks that require multiple levels of iteration. #include < stdio.h > int main() { // Outer loop runs 3 times for ( int i = 0; i < 3; i ++) { // Inner loop runs 2 times for each outer loop iteration for ( int j = 0; j < 2; j++) { printf (" i = %d, j = %d\n", i , j); } } return 0; }
Example: Print Table from 1 to 5 Using For Loop Galgotias University 12 #include < stdio.h > int main() { // Outer for loop to print a multiplication table for all numbers upto 5 for ( int i = 1; i <= 5; i ++) { // Inner loop to print each value in table for ( int j = 1; j <= 5; j++) { printf ("%d ", i * j); } printf ("\n"); } return 0; }
Loop Control Statements Galgotias University 13 Loop control statements in C programming are used to change execution from its normal sequence.
Loop Control Statements Galgotias University 14 #include < stdio.h > int main() { for ( int i = 0; i < 5; i ++) { if ( i = = 3) { // Exit the loop when i equals 3 break; } printf ("%d ", i ); } printf ("\n"); for ( int i = 0; i < 5; i ++) { if ( i = = 3) { // Skip the current iteration when i equals 3 continue; } printf ("%d ", i ); } printf ("\n"); for ( int i = 0; i < 5; i ++) { if ( i = = 3) { // Jump to the skip label when i equals 3 goto skip; } printf ("%d ", i ); } skip: printf ("\ nJumped to the 'skip' label %s ", " when i equals 3."); return 0; }
GSCALE full form and date 15 Multiple Loop Variables A for loop can control more than one variable at a time , allowing parallel iteration or coordinated updates . Multiple variables are separated by commas in initialization and update sections. The condition can involve both variables (typically combined with logical operators ). Key Points: All variables are updated in each iteration. The loop continues as long as the condition evaluates to true. Useful for tasks like simultaneous counting, reverse counting, or pairing elements. Syntax: for (initialization1, initialization2; condition; update1, update2) { // statements }
GSCALE full form and date 16 Example 1: Increasing and Decreasing Counters #include < stdio.h > int main() { for ( int i = 1, j = 10; i <= j; i ++, j--) { printf (" i = %d, j = %d\n", i , j); } return 0; } Output: i = 1, j = 10 i = 2, j = 9 i = 3, j = 8 i = 4, j = 7 i = 5, j = 6
GSCALE full form and date 17 Example 2: Printing Pairs of Numbers Output: (0, 5) (1, 4) (2, 3) (3, 2) (4, 1) (5, 0) #include < stdio.h > int main() { for ( int x = 0, y = 5; x <= 5 && y >= 0; x++, y--) { printf ("(%d, %d) ", x, y); } return 0; }
GSCALE full form and date 18 Advantages of Using Multiple Loop Variables Reduces the need for nested loops in some situations. Makes code compact and readable for simultaneous iteration. Useful in array manipulations, pairing elements, and solving mathematical patterns.
GSCALE full form and date 19 C Program: Display Sum of Two Loop Variables Syntax: # include < stdio.h > int main() { for ( int a = 0, b = 10; a <= 5; a++, b--) { printf ("a = %d, b = %d, sum = %d\n", a, b, a + b); } return 0; } Output: a = 0, b = 10, sum = 10 a = 1, b = 9, sum = 10 a = 2, b = 8, sum = 10 a = 3, b = 7, sum = 10 a = 4, b = 6, sum = 10 a = 5, b = 5, sum = 10
GSCALE full form and date 20 C Program: Factorial of a Number Using for Loop #include < stdio.h > int main() { int n; unsigned long long fact = 1; printf ("Enter a number: "); scanf ("%d", &n); for ( int i = 1; i <= n; i ++) { fact = fact * i ; } printf ("Factorial of %d = % llu \n", n, fact); return 0; } Enter a number: 5 Factorial of 5 = 120
GSCALE full form and date 21 C Program: Factorial of a Number Using for Loop Variable fact stores the factorial result (initialized to 1). The loop variable i runs from 1 to n. In each iteration, fact is multiplied by i . For n = 5: Iterations : fact = 1 × 1 = 1 fact = 1 × 2 = 2 fact = 2 × 3 = 6 fact = 6 × 4 = 24 fact = 24 × 5 = 120 Finally, fact = 120 is printed .
Summary Galgotias University 22 For Loops The for loop is an entry-controlled loop , meaning the condition is checked before each iteration. It consists of three main parts: initialization, condition, and update — all written in a single line for compactness. It is commonly used when the number of iterations is known beforehand. Initialization , condition, and update expressions can be left empty or combined depending on logic. The for loop improves readability and control for counter-based iteration compared to while and do-while loops. Nesting for loops allows performing operations like patterns, matrices, and table generation .
Summary (Continued) Galgotias University 23 Multiple Loop Variables A for loop can have multiple initialization and update expressions , separated by commas. Multiple loop variables allow simultaneous control over two or more counters within a single loop. They are useful for problems involving paired operations — e.g., forward and backward traversal , mirrored sequences, or two-pointer techniques. The condition part of the loop typically involves logical operators (&& or ||) to ensure all variables remain valid. Using multiple variables enhances code efficiency and compactness , reducing the need for nested loops in some cases. Helps in implementing algorithms like array reversal, matrix traversal, and parallel computations .
Ensure attainment of LOs in alignment to the learning activities: outcomes (1-2) Galgotias University 24
Post session activities (Practice Questions ) Galgotias University 25 For Loops: Display the squares of the first 10 natural numbers . Print even numbers between 1 and 50 using a for loop. Find the sum of numbers from 1 to N (user input). Count the number of digits in a given integer using a for loop. Reverse counting: Print numbers from 50 to 1 using a for loop. Multiple Loop Variable: Write a program to print two variables, one incrementing and one decrementing simultaneously. Write a program to generate the first N Fibonacci numbers using a for loop and multiple variables (a, b, next). Write a program to compute the cumulative sum and cumulative product of numbers using two loop variables. Write a program to print prime numbers between 1 and 100 using a for loop. Write a program using multiple loop variables to find the average of first N numbers while also tracking cumulative totals.
Information about the next lesson Galgotias University 26 In the next lecture we will study Programming Examples on loops
Review and Reflection from students Galgotias University 27