1 of 30

Structured Iterations�& Recursion in C

Nested Loops · Matrices · Recursion · Control Flow

Slide 1

2 of 30

Learning Objectives

Slide 2

1. Trace nested loops and predict output

2. Count iterations and estimate time

3. Generate patterns with nested loops

4. Traverse 2-D arrays (matrices)

5. Compare recursion with iteration

6. Analyze stack usage and call overhead

7. Apply break and continue in loops

3 of 30

Nested Loops – Basic Concept

Slide 3

A loop inside another loop.

for (int i = 1; i <= 3; i++) { // Outer

for (int j = 1; j <= 3; j++) { // Inner

printf("(%d,%d) ", i, j);

}

printf("\n");

}

Output:

(1,1) (1,2) (1,3)

(2,1) (2,2) (2,3)

(3,1) (3,2) (3,3)

Key Formula

Total iterations = 3 × 3 = 9

4 of 30

Tracing Nested Loops

Slide 4

int count = 0;

for (int i = 1; i <= 4; i++) {

for (int j = 1; j <= i; j++) {

printf("* "); count++;

}

printf("\n");

}

printf("Total: %d\n", count);

i

j values

inner

cumulative

1

1

1

1

2

1,2

2

3

3

1,2,3

3

6

4

1,2,3,4

4

10

Total

1+2+3+4

= 4(5)/2

= 10

5 of 30

Guided Practice – Bubble Sort (Code)

Slide 5

#include <stdio.h>

void bubbleSort(int a[], int n) {

int temp, swaps = 0, passes = 0;

for (int i = 0; i < n - 1; i++) {

passes++;

for (int j = 0; j < n - i - 1; j++) {

if (a[j] > a[j + 1]) {

temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

swaps++;

}

}

}

printf("Passes: %d, Swaps: %d\n", passes, swaps);

}

int main() {

int arr[] = {5, 1, 4, 2, 8};

bubbleSort(arr, 5);

return 0;

}

6 of 30

Bubble Sort – Trace

Input: [5, 1, 4, 2, 8]

Slide 6

• Pass 1: (5,1) swap, (5,4) swap, (5,2) swap, (5,8) ok → [1,4,2,5,8]

• Pass 2: (1,4) ok, (4,2) swap, (4,5) ok → [1,2,4,5,8]

• Pass 3: no swaps

• Pass 4: no swaps

Complexity

Inner iterations = 4+3+2+1 = 10 | Time = O(n²)

7 of 30

Practice – Hollow Square

Slide 7

#include <stdio.h>

int main() {

int n = 5;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

if (i == 1 || i == n ||

j == 1 || j == n)

printf("* ");

else

printf(" ");

}

printf("\n");

}

return 0;

}

Output:

* * * * *

* *

* *

* *

* * * * *

8 of 30

Practice – 3×3 Matrix (Code)

Slide 8

#include <stdio.h>

int main() {

int a[3][3], i, j;

int rowSum[3] = {0}, colSum[3] = {0};

int diag1 = 0, diag2 = 0;

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

scanf("%d", &a[i][j]);

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++) {

rowSum[i] += a[i][j];

colSum[j] += a[i][j];

if (i == j) diag1 += a[i][j];

if (i + j == 2) diag2 += a[i][j];

}

/* print results ... */

return 0;

}

9 of 30

Matrix – Sample Run

Slide 9

Input:

1 2 3

4 5 6

7 8 9

Output:

Row 1 = 6 Row 2 = 15 Row 3 = 24

Col 1 = 12 Col 2 = 15 Col 3 = 18

Main Diagonal = 15

Anti Diagonal = 15

Insight

One nested loop handles all computations – 9 iterations.

10 of 30

Sparse Matrix Detection

Slide 10

#include <stdio.h>

int main() {

int a[3][3] = {{1,0,0},{0,0,4},{0,7,0}};

int zeroCount = 0, total = 9;

float threshold = 0.66;

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

if (a[i][j] == 0) zeroCount++;

float ratio = (float)zeroCount / total;

if (ratio >= threshold)

printf("Sparse Matrix\n");

else

printf("Not sparse\n");

return 0;

}

Output

Zero count = 6, Ratio = 0.67 → Sparse Matrix

11 of 30

Recursion vs Iteration

Slide 11

Iteration

Loops (for/while)

Constant stack memory

Faster

Recursion

Function calls itself

Needs a base case

Uses stack frames

Aspect

Iteration

Recursion

Memory

O(1)

O(n)

Speed

Faster

Call overhead

Risk

Infinite loop

Stack overflow

Best for

Simple repeat

Trees / D&C

12 of 30

Factorial – Both Ways

Slide 12

Iterative

long fact_iter(int n) {

long r = 1;

for (int i = 2; i <= n; i++)

r *= i;

return r;

}

Recursive

long fact_rec(int n) {

if (n <= 1) return 1;

return n * fact_rec(n - 1);

}

Memory for n = 5

Iterative: 1 variable → O(1) memory

Recursive: 5 stack frames → O(n) memory

13 of 30

Fibonacci – Both Ways

Slide 13

Iterative (fast)

int fib_iter(int n) {

if (n <= 1) return n;

int a = 0, b = 1, c;

for (int i = 2; i <= n; i++) {

c = a + b; a = b; b = c;

}

return b;

}

Recursive (slow!)

int fib_rec(int n) {

if (n <= 1) return n;

return fib_rec(n - 1)

+ fib_rec(n - 2);

}

Method

Calls (n=30)

Speed

Iterative

30

instant

Recursive

2,692,537

very slow

14 of 30

Binary Search – Code

Slide 14

Recursive

int recCalls = 0;

int bsRec(int a[], int lo,

int hi, int key) {

recCalls++;

if (lo > hi) return -1;

int m = (lo + hi) / 2;

if (a[m] == key) return m;

if (a[m] > key)

return bsRec(a, lo, m-1, key);

return bsRec(a, m+1, hi, key);

}

Iterative

int iterLoops = 0;

int bsIter(int a[], int n, int key) {

int lo = 0, hi = n - 1;

while (lo <= hi) {

iterLoops++;

int m = (lo + hi) / 2;

if (a[m] == key) return m;

if (a[m] > key) hi = m - 1;

else lo = m + 1;

}

return -1;

}

15 of 30

Binary Search – Output

Slide 15

int arr[] = {2,4,6,8,10,12,14,16};

int p1 = bsRec(arr, 0, 7, 14);

printf("Recursive: pos=%d, calls=%d\n", p1, recCalls);

int p2 = bsIter(arr, 8, 14);

printf("Iterative: pos=%d, loops=%d\n", p2, iterLoops);

Output:

Recursive: pos=6, calls=3

Iterative: pos=6, loops=3

Observation

Both O(log n)

Recursive uses 3 stack frames

Iterative uses 0

16 of 30

Palindrome – Both Ways

Slide 16

Iterative

int isPal_iter(char s[]) {

int n = strlen(s);

for (int i = 0; i < n/2; i++)

if (s[i] != s[n-1-i])

return 0;

return 1;

}

Recursive

int isPal_rec(char s[],

int lo, int hi) {

if (lo >= hi) return 1;

if (s[lo] != s[hi]) return 0;

return isPal_rec(s, lo+1, hi-1);

}

Test & Memory

"madam" → both return 1 (palindrome)

Iterative: O(1) memory

Recursive: ⌊n/2⌋ stack frames

17 of 30

Power – Both Ways

Slide 17

Recursive

long pow_rec(long a, int n) {

if (n == 0) return 1;

return a * pow_rec(a, n - 1);

}

Iterative

long pow_iter(long a, int n) {

long r = 1;

for (int i = 0; i < n; i++)

r *= a;

return r;

}

For power(2, 5)

Recursive: 6 stack frames, 5 multiplications

Iterative: 1 variable, 5 multiplications

Both O(n) time; recursion costs O(n) memory

18 of 30

break vs continue

Slide 18

break – exit loop

for (int i = 1; i <= 10; i++) {

if (i == 5) break;

printf("%d ", i);

}

// 1 2 3 4

continue – skip

for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) continue;

printf("%d ", i);

}

// 1 3 5 7 9

break

continue

Exits loop entirely

Skips to next iteration

Stops early

Filters values

19 of 30

Practice – Skip Multiples of 4

Slide 19

#include <stdio.h>

int main() {

for (int i = 1; i <= 20; i++) {

if (i % 4 == 0) continue;

printf("%d ", i);

}

return 0;

}

Output:

1 2 3 5 6 7 9 10 11 13 14 15 17 18 19

20 iterations | 15 printed | 5 skipped

20 of 30

Practice – Break on Negative

Slide 20

#include <stdio.h>

int main() {

int num, count = 0, sum = 0;

while (1) {

scanf("%d", &num);

if (num < 0) break;

sum += num; count++;

}

printf("count=%d, sum=%d\n", count, sum);

return 0;

}

Sample run:

Input: 10 20 30 -1

Output: count=3, sum=60

21 of 30

Sum of Digits – Both Ways

Slide 21

Iterative

int sumD_iter(int n) {

int s = 0;

while (n > 0) {

s += n % 10;

n /= 10;

}

return s;

}

Recursive

int sumD_rec(int n) {

if (n == 0) return 0;

return (n % 10)

+ sumD_rec(n / 10);

}

Step

Iterative

Recursive

1

n=1234, s=4

rec(123)

2

n=123, s=7

rec(12)

3

n=12, s=9

rec(1)

4

n=1, s=10

rec(0)

5

n=0, s=10

return 0

22 of 30

Stack Usage – fact(4)

Slide 22

fact(4)

fact(3)

fact(2)

fact(1) base

returns 1→2→6→24

Each frame stores

Return address + n + locals (~16–32 bytes)

For n=1000: 16–32 KB → stack overflow risk

23 of 30

When to Use Which?

Slide 23

Use Iteration

Many repetitions

Simple linear tasks

Limited stack

Performance critical

Use Recursion

Naturally recursive problem

Divide & conquer

Code clarity matters

Small depth

Memory Cost

Iteration: O(1) extra space

Recursion: O(depth) stack frames

Stack overflow if depth ≳ 10,000

24 of 30

Complete Program Structure

Slide 24

#include <stdio.h>

#include <string.h>

void printPattern(int n) { /* ... */ }

int isSparse(int a[3][3]) { /* ... */ }

long factIter(int n) { /* ... */ }

long factRec (int n) { /* ... */ }

int bsIter(int a[], int n, int key) { /* ... */ }

int bsRec (int a[], int lo, int hi, int k) { /* ... */ }

int main() {

// Call and test each function above

return 0;

}

25 of 30

Key Takeaways

Slide 25

Nested Loops

Total iterations = product of loop counts

Ideal for patterns and 2-D arrays

Always trace manually to verify

Criterion

Winner

Memory

Iteration

Speed

Iteration

Trees / D&C

Recursion

Deep depth

Iteration

Golden Rule

Use recursion when the problem is

naturally recursive; otherwise

use iteration.

26 of 30

Practice Exercises

Slide 26

1. Print a right-angled triangle of height n.

2. Find the largest element in a 4×4 matrix.

3. Count * printed by nested loop with (j % 2 == 0).

4. Write gcd(a, b) recursively (Euclidean).

5. Find first array element divisible by 7 (break).

6. Count steps in sumDigits(99999) both ways.

27 of 30

Complexity Cheat Sheet

Slide 27

Algorithm

Time

Iter Space

Rec Space

Factorial

O(n)

O(1)

O(n)

Fibonacci (naive)

O(2ⁿ)

O(1)

O(n)

Fibonacci (iter)

O(n)

O(1)

—

Binary Search

O(log n)

O(1)

O(log n)

Bubble Sort

O(n²)

O(1)

—

Sum of Digits

O(d)

O(1)

O(d)

Palindrome

O(n)

O(1)

O(n)

d = digits, n = input size

28 of 30

Summary

Slide 28

✓ Nested loops – tracing, patterns, matrices

✓ Bubble sort – iteration analysis

✓ 2-D arrays – row/col/diagonal sums

✓ Recursion vs iteration – factorial, Fibonacci

✓ Binary search – both approaches

✓ Palindrome & power – side-by-side

✓ break & continue – control flow

✓ Memory & performance – stack analysis

Next Steps

Implement, modify, add counters, test edge cases

29 of 30

References

Slide 29

• K&R – The C Programming Language (Ch. 3)

• CLRS – Introduction to Algorithms

• GeeksforGeeks – Recursion vs Iteration

• CPPReference – C standard library

Compile & debug:

gcc -Wall -Wextra -std=c11 program.c -o program

./program

printf("[DEBUG] i=%d, j=%d\n", i, j);

30 of 30

Thank You

Questions?

Lab Exercise:

1. Hollow triangle pattern

2. Convert binary search (rec ↔ iter)

3. Bubble sort iteration counter on sorted input

Slide 30