C Loops - Comprehensive Study Notes

Looping in C: Comprehensive Study Notes

  • Looping is used to repeat a task multiple times.

    • A loop executes a sequence of statements many times until a stated condition becomes false.
    • A loop consists of two parts: a body of the loop and a control statement.
    • The control statement is a condition (or set of conditions) that directs the body to execute until the condition becomes false.
    • Purpose: to repeat the same code a number of times efficiently.
  • Kinds of loops by position of the control statement:

    • Entry controlled
    • Exit controlled
  • Entry vs Exit Controlled Loops (C context):

    • Entry controlled loop: condition is checked before the loop body executes. If the condition is false initially, the loop body may not execute at all.
    • Exit controlled loop: condition is checked after the loop body has executed. If the condition is false initially, the loop body will still execute once.
  • Types of loops in C:

    1. The for loop (entry controlled)
    2. The while loop (entry controlled)
    3. The do-while loop (exit controlled)

The for Loop

  • General format:
    for(initialization;condition;increment/decrement)  statement-block;\text{for}(\text{initialization}; \text{condition}; \text{increment/decrement}){\;\text{statement-block};}
  • Key formatting rules:
    • There are two semicolons inside the parentheses: one after initialization and one after the condition.
    • You can have multiple initializations or increments/decrements separated by the comma operator, e.g. a=0, b=1; a<b; a++, but there can be only one condition.
  • How it executes (step-by-step):
    1. Evaluate the initialization code.
    2. Check the condition expression.
    3. If true, execute the loop body.
    4. Evaluate the increment/decrement, then go back to step 2.
    5. When the condition becomes false, exit the loop.
  • Example: Display numbers from 1 to 10 using a for loop
#include<stdio.h>
#include<conio.h>
void main()
{
  int i;
  clrscr();
  for(i=1; i<=10; i++)
  {
    printf("%d ", i);
  }
  getch();
}
  • Explanation of the example:
    • i is initialized to 1.
    • Condition i <= 10 is checked; if true, print i.
    • i is incremented by 1 after each iteration until i becomes 11 and the condition fails.
  • Another typical use: display numbers up to a user-specified limit n
#include<stdio.h>
#include<conio.h>
void main()
{
  int i, n;
  clrscr();
  printf("Enter the limit:");
  scanf("%d", &n);
  printf("The numbers are:\n");
  for(i=1; i<=n; i++)
  {
    printf("%d ", i);
  }
  getch();
}

The while Loop

  • Syntax:
    while(test condition)  statements inside the body  \text{while}(\text{test condition}){\;\text{statements inside the body}}\;

  • How it works:

    • The test condition is evaluated before each iteration.
    • If true, the body executes, then the test condition is evaluated again.
    • If false, the loop terminates.
  • Important note: when a loop needs a repeated increment/decrement, that update must typically occur inside the loop body for a while-loop.

  • Common exercise: sum of the first n natural numbers using a while loop

#include<stdio.h>
#include<conio.h>
void main()
{
  int i, n, s = 0;
  clrscr();
  printf("Enter limit:");
  scanf("%d", &n);
  i = 1;
  while(i <= n)
  {
    s = s + i;
    i++;
  }
  printf("Sum=%d", s);
  getch();
}
  • How the loop progresses in this example:
    • i starts at 1; as long as i <= n, add i to s and increment i.
    • When i becomes n+1, the condition fails and the loop ends.

The do-While Loop

  • Syntax:
    do  statements inside the body while(test condition);\text{do}{\;\text{statements inside the body}}\text{ while}(\text{test condition});
  • Key characteristic: the body is executed at least once, even if the condition is false on the first check.
  • Flow: execute body, then test condition; if true, repeat; otherwise exit.
  • Example: display numbers from 1 to 5 using do-while
#include<stdio.h>
#include<conio.h>
void main()
{
  int i = 1, n = 5;
  clrscr();
  do
  {
    printf("%d ", i);
    i++;
  } while(i <= n);
  getch();
}
  • Note on a later variant: the do-while can also be used to demonstrate a loop that executes once even if the condition is false, e.g., with a different terminating condition.

The break Statement

  • Purpose: immediately terminate the nearest enclosing loop (or switch) and resume execution after it.
  • In nested loops, break ends the innermost loop only.
  • Syntax:
    break;\text{break;}
  • Demonstration: stop the loop when a specific value is reached
#include<stdio.h>
#include<conio.h>
void main()
{
  int i = 1, n = 10;
  clrscr();
  while(i <= n)
  {
    if(i == 5)
    {
      break;
    }
    printf("%d ", i);
    i++;
  }
  getch();
}
  • Output: prints 1 2 3 4 and then stops when i becomes 5.

The continue Statement

  • Purpose: skip the rest of the current iteration and begin the next iteration of the loop.
  • It is useful to skip certain iterations based on a condition.
  • Syntax:
    continue;\text{continue;}
  • Behavior: control jumps to the beginning of the loop for the next iteration.
  • Examples:
// Print numbers 1 to 10, excluding 5
#include<stdio.h>
#include<conio.h>
void main()
{
  int i;
  clrscr();
  for(i = 1; i <= 10; i++)
  {
    if(i == 5)
      continue;
    printf("%d ", i);
  }
  getch();
}
  • Another example: read n numbers and display only odd numbers using continue
#include<stdio.h>
#include<conio.h>
void main()
{
  int n, i, a;
  clrscr();
  printf("Enter n:");
  scanf("%d", &n);
  for(i = 1; i <= n; i++)
  {
    printf("\nEnter no%d:", i);
    scanf("%d", &a);
    if(a % 2 == 0)
    {
      continue; // skip printing even numbers
    }
    printf("\nNumber is: %d", a);
  }
  getch();
}

Nested Loops

  • A loop inside another loop.
  • Outer loop controls the execution of the inner loop; the inner loop completes for every iteration of the outer loop.
  • Example: nested for loops
#include<stdio.h>
#include<conio.h>
void main()
{
  int i, j;
  clrscr();
  for(i = 1; i <= 5; i++)
  {
    for(j = 1; j <= i; j++)
    {
      printf("%d ", j);
    }
    printf("\n");
  }
  getch();
}
  • Output pattern:

    • 1
    • 1 2
    • 1 2 3
    • 1 2 3 4
    • 1 2 3 4 5
  • Nested while loop (concept): a while loop inside another while loop.

  • Nested do-while loop (concept): a do-while loop inside another do-while loop.


Nested Do-While Loop Pattern Examples

  • Do-while inside a do-while to print patterns; example structure is shown in the notes.
  • Example pattern (5 rows):
    1
    2 1
    3 2 1
    4 3 2 1
    5 4 3 2 1
  • The exact code structure for the nested do-while pattern is similar to the nested do-while slide, adjusted to print decreasing sequences.

Goto Statement (Goto) – A Note

  • The goto statement provides an unconditional jump to a labeled statement.
  • Typical usage in old code examples for error handling or simple flow control is shown here for educational purposes.
  • Example outline (not recommended for clean code):
#include<stdio.h>
#include<stdlib.h>
void main()
{
  int num;
  printf("Enter a number\n");
  scanf("%d", &num);
  if(num % 2 == 0)
    goto even;
  else
    goto odd;
  even:
  printf("%d is even\n", num);
  exit(0);
  odd:
  printf("%d is odd\n", num);
}
  • Important: goto can lead to spaghetti code and is generally discouraged in modern practice.

  • Note: Several slides reference Turbo C specific headers and functions (e.g., conio.h, clrscr(), getch()). Modern compilers (like GCC on Windows/Linux/macOS) may not provide these; use standard headers and functions when possible.


Prime Numbers and Loop-Based Checks

  • Definition: A prime number is a whole number greater than 1 that has only two factors: 1 and itself.
    • In other words, a prime is divisible only by 1 and itself.
    • First few primes: 2, 3, 5, 7, 11, …
  • Common algorithm to test primality using a for loop (as shown in the transcript):
    • Check divisors from 2 to floor(n/2).
    • If any divisor n%d == 0, n is not prime; break out of the loop.
    • If no divisor found (i is greater than n/2 after the loop), then n is prime.
  • Example (prime check for a single number n):
#include<stdio.h>
#include<conio.h>
void main()
{
  int i, n;
  clrscr();
  printf("Enter the number:");
  scanf("%d", &n);
  for(i = 2; i <= n/2; i++)
  {
    if(n % i == 0)
    {
      printf("%d is not prime....", n);
      break;
    }
  }
  if(i > n/2)
  {
    printf("%d is prime....", n);
  }
  getch();
}
  • Explanation of the prime test flow:

    • Test divisors from 2 up to n/2 (inclusive).
    • If a divisor is found (n % i == 0), break to stop further checks.
    • After the loop, if i > n/2, it means no divisor was found and n is prime.
  • More broadly, mathematical statement for prime testing:
    n>1 \,\land\, \nexists d\in{2,3,\dots,\lfloor \tfrac{n}{2} \rfloor}\text{ such that } d \mid n.
    (This captures the same logic as the loop-based check.)

  • Additional prime-related code: print all primes up to n using a nested loop structure:

#include<stdio.h>
#include<conio.h>
void main()
{
  int i, j, n;
  clrscr();
  printf("Enter the limit:");
  scanf("%d", &n);
  for(i = 2; i <= n; i++)
  {
    for(j = 2; j <= i/2; j++)
    {
      if(i % j == 0) break;
    }
    if(j > i/2) printf("%d ", i);
  }
  getch();
}

Fibonacci Series up to n

  • Concept: Fibonacci sequence is defined by x = 0, y = 1; z = x + y; next terms shift as x <- y, y <- z.
  • Loop form shown uses a while loop:
#include<stdio.h>
#include<conio.h>
void main()
{
  int x=0, y=1, z=0, n;
  clrscr();
  printf("Enter the limit:");
  scanf("%d", &n);
  printf("The series is:\n");
  while(z <= n)
  {
    printf("%d ", z);
    x = y;
    y = z;
    z = x + y;
  }
  getch();
}
  • The loop continues until the next Fibonacci term exceeds n.

Factorial of a Number (Using for Loop)

  • Factorial definition: n!=1×2××n=k=1nkn! = 1 \times 2 \times \cdots \times n = \prod_{k=1}^{n} k
  • Example implementation (n! for input n):
#include<stdio.h>
#include<conio.h>
void main()
{
  int i, n, f = 1;
  clrscr();
  printf("Enter a number:");
  scanf("%d", &n);
  for(i = 1; i <= n; i++)
  {
    f = f * i;
  }
  printf("Factorial=%d", f);
  getch();
}

Sum of Digits and Reversing a Number

  • Sum of digits: iterative extraction of digits using remainder and division
  • Common pattern:
    • While n > 0:
    • r = n % 10
    • s = s + r
    • n = n / 10
  • Example: sum of digits program
#include<stdio.h>
#include<conio.h>
void main()
{
  int n, s = 0, r;
  clrscr();
  printf("Enter a number:");
  scanf("%d", &n);
  while(n > 0)
  {
    r = n % 10;
    s = s + r;
    n = n / 10;
  }
  printf("Sum=%d", s);
  getch();
}
  • Reversing a number:
#include<conio.h>
#include<stdio.h>
void main()
{
  int n, r, rev = 0;
  clrscr();
  printf("Enter a num:");
  scanf("%d", &n);
  while(n > 0)
  {
    r = n % 10;
    rev = rev * 10 + r;
    n = n / 10;
  }
  printf("Rev=%d", rev);
  getch();
}
  • These patterns illustrate how a simple loop can convert between representations of a number and compute digit-based aggregates.

Pattern Printing with Nested Loops (Nested for example)

  • Pattern: 1; 1 2; 1 2 3; 1 2 3 4; 1 2 3 4 5
  • Code:
#include<stdio.h>
#include<conio.h>
void main()
{
  int i, j;
  clrscr();
  for(i = 1; i <= 5; i++)
  {
    for(j = 1; j <= i; j++)
    {
      printf("%d ", j);
    }
    printf("\n");
  }
  getch();
}
  • This demonstrates how outer and inner loops interact to generate triangular patterns.

Do-While Pattern Demonstrations (Nested do-while)

  • Do-while can also be nested to create patterns; the outer do-while controls how many lines, the inner controls the contents of each line.
  • Example patterns printed in the slides show decreasing sequences such as:
    5 4 3 2 1
    4 3 2 1
    3 2 1
    2 1
    1
  • The structure mirrors the do-while pattern described earlier, but with nested blocks.

Break and Continue: Quick Revisit with Examples

  • Break in loops:

    • Stops the current loop immediately and continues with the next statement after the loop.
    • In nested loops, breaks affect only the innermost loop.
    • Example snippet shown earlier demonstrates breaking when a condition is met.
  • Continue in loops:

    • Skips the remaining statements in the current iteration and starts the next iteration.
    • Useful for skipping specific values or conditions without exiting the loop entirely.

Quick References: Common Algorithms with Loops

  • Sum of first n natural numbers (while loop): see the sample above.
  • Sum of digits of a number: see the sample above.
  • Reverse a number: see the sample above.
  • Fibonacci series: see the sample above.
  • Factorial: see the sample above.
  • Prime checking and listing primes up to n: see the samples above.

Implementation Notes and Practical Tips

  • C loop variations:

    • for: best for counting with a known number of iterations.
    • while: best when the number of iterations is not known beforehand.
    • do-while: ensures at least one execution of the loop body.
  • The comma operator in for loops allows multiple initializations or updates in a single for statement, e.g.:
    \text{for}(i = 0, j = 10; i < j; i++, j--)

  • Be mindful of language specifics:

    • The slides use #include , clrscr(), getch() which are from Turbo C. These are not standard C and may not compile on modern compilers. Prefer standard input/output without conio.h for portability.
  • Practice patterns to gain familiarity:

    • Printing patterns with nested loops
    • Controlling flow with break and continue in various scenarios
  • For mathematical expressions in notes, see the LaTeX snippets embedded in sections above:

    • For loop signature: for(init;cond;incr)\text{for}(init; cond; incr)
    • Prime test condition: n>1 \land \nexists d \in {2,\dots, \lfloor n/2 \rfloor}\text{ such that } d \mid n
    • Factorial: n!=k=1nkn! = \prod_{k=1}^{n} k
    • Fibonacci relation: z=x+y,xy,yzz = x + y,\quad x\leftarrow y,\quad y\leftarrow z
    • Sum of digits: s=s+r,n=n/10,r=nmod10s = s + r,\quad n = \lfloor n/10 \rfloor,\quad r = n \bmod 10
  • Endnotes:

    • The materials presented here are adapted from a lecture transcript that uses Turbo C-era conventions. For modern practice, port code to standard C and use modern compilers.

Quick Reference List

  • Entry vs Exit controlled:
    • Entry: condition checked before first execution.
    • Exit: condition checked after body execution.
  • Loop types in C: for, while, do-while.
  • Key statements: break, continue, and (briefly) goto.
  • Core numeric examples include: sum of numbers, sum of digits, reverse digits, factorial, Fibonacci, primes.