Docsity

Loops for computer science, Schemes and Mind Maps of Computer Science

Toggle sidebar
bg1
C Loops: for and while | Page 1
C Programming
for and while Loops
10 Programs with Code and Step-by-Step Explanation
Contents of this Document
This document contains ten complete C programs. Each one includes the source code, the expected output,
and a step-by-step explanation of how the code works. Where useful, a dry-run table shows how the variables
change on every pass of the loop.
Common to every program:
•#include <stdio.h> loads the standard input/output library, so printf and scanf can be used.
•int main() is where execution starts.
•return 0; tells the operating system the program finished successfully.
Use for when... Use while when...
The number of iterations is known (Programs 1 to 5) It depends on data or user input (Programs 6 to 10)
You are counting or traversing arrays You loop until a condition changes
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Loops for computer science and more Schemes and Mind Maps Computer Science in PDF only on Docsity!

C Programming

for and while Loops

10 Programs with Code and Step-by-Step Explanation

Contents of this Document

This document contains ten complete C programs. Each one includes the source code, the expected output, and a step-by-step explanation of how the code works. Where useful, a dry-run table shows how the variables change on every pass of the loop. Common to every program:

  • #include loads the standard input/output library, so printf and scanf can be used.
  • int main() is where execution starts.
  • return 0; tells the operating system the program finished successfully. Use for when... Use while when... The number of iterations is known (Programs 1 to 5) It depends on data or user input (Programs 6 to 10) You are counting or traversing arrays You loop until a condition changes

Part A: for loop programs Program 1: Sum of the First N Natural Numbers Code #include int main() { int n = 10, sum = 0; for (int i = 1; i <= n; i++) { sum += i; } printf("Sum = %d\n", sum); return 0; } Output Sum = 55 Step-by-step explanation

  1. Create n = 10 (how far to count) and sum = 0 (the running total, which must start at 0).
  2. The loop starts with i = 1.
  3. Check i <= n. It is true, so enter the body.
  4. sum += i means sum = sum + i, so sum becomes 1.
  5. i++ makes i = 2. Go back to the condition check.
  6. This repeats, with sum growing 1, 3, 6, 10, 15, ... up to 55.
  7. When i becomes 11, 11 <= 10 is false and the loop stops.
  8. printf prints Sum = 55. Note: A for loop is the natural choice here because the loop runs exactly n times.

Program 3: Pyramid Pattern (Nested for Loops) Code #include int main() { int n = 4; for (int i = 1; i <= n; i++) { for (int s = 1; s <= n - i; s++) // leading spaces printf(" "); for (int j = 1; j <= 2 * i - 1; j++) // stars printf("*"); printf("\n"); } return 0; } Output

Step-by-step explanation

  1. n = 4 is the number of rows.
  2. The outer loop (i) picks the current row, from 1 to 4.
  3. The first inner loop prints n - i spaces so the stars are centred.
  4. The second inner loop prints 2i - 1 stars (the odd numbers 1, 3, 5, 7).
  5. printf("\n") ends the row. Without it, all rows would join on one line.
  6. For every single value of i, both inner loops run completely before i moves on. Dry run Row (i) Spaces (n - i) Stars (2i - 1) Result 1 3 1 * 2 2 3 *** 3 1 5 ***** 4 0 7 *******

Program 4: Fibonacci Series Code #include int main() { int n = 10, a = 0, b = 1, next; for (int i = 1; i <= n; i++) { printf("%d ", a); next = a + b; a = b; b = next; } return 0; } Output 0 1 1 2 3 5 8 13 21 34 Step-by-step explanation

  1. a and b hold the two current terms, starting with 0 and 1. next is a temporary variable.
  2. Each iteration does three things: print a, calculate next = a + b, then slide the pair forward (a = b; b = next).
  3. The order of the last two lines matters. If b were changed first, the old value of b would be lost.
  4. The loop prints exactly n terms. Dry run i prints next = a + b new a new b 1 0 1 1 1 2 1 2 1 2 3 1 3 2 3 4 2 5 3 5 5 3 8 5 8

Part B: while loop programs Program 6: Reverse a Number Code #include int main() { int n = 1234, rev = 0; while (n > 0) { int digit = n % 10; rev = rev * 10 + digit; n /= 10; } printf("Reversed = %d\n", rev); return 0; } Output Reversed = 4321 Step-by-step explanation

  1. rev starts at 0 and will be built digit by digit.
  2. While n > 0, there are still digits to process.
  3. n % 10 gives the last digit (1234 % 10 = 4).
  4. rev * 10 + digit shifts the existing reversed digits one place left and adds the new digit at the end.
  5. n /= 10 uses integer division to remove the last digit (1234 becomes 123).
  6. When n reaches 0, all digits are used up and the loop ends. Dry run Pass n digit rev calculation rev 1 1234 4 0 x 10 + 4 4 2 123 3 4 x 10 + 3 43 3 12 2 43 x 10 + 2 432 4 1 1 432 x 10 + 1 4321 Note: A while loop is used because the number of iterations depends on how many digits n has, not on a fixed count.

Program 7: Palindrome Number Check Code #include int main() { int n = 12321, original = n, rev = 0; while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } if (original == rev) printf("%d is a palindrome\n", original); else printf("%d is not a palindrome\n", original); return 0; } Output 12321 is a palindrome Step-by-step explanation

  1. Save the number in original first, because the loop will reduce n to 0.
  2. Run the same reversal loop as Program 6. The reverse of 12321 is 12321.
  3. Compare original == rev. Here they are equal, so the if branch prints "is a palindrome".
  4. For a number like 123, rev would be 321, the comparison would fail, and the else branch would run.

Program 9: Sum Numbers Until the User Enters 0 Code #include int main() { int num, sum = 0; printf("Enter numbers (0 to stop): "); scanf("%d", &num); while (num != 0) { sum += num; scanf("%d", &num); } printf("Total = %d\n", sum); return 0; } Output Sample input: 5 10 15 0 Total = 30 Step-by-step explanation

  1. Read the first number before the loop. This gives num a real value to test.
  2. If the first number is 0, the loop body never runs and the total is 0.
  3. Otherwise, add num to sum, then read the next number at the bottom of the loop.
  4. The condition is re-checked with the new value.
  5. The 0 is just a stop signal (a sentinel value), so it is never added. Dry run Read Condition num != 0 sum 5 true 5 10 true 15 15 true 30 0 false, stop 30 Note: This is the classic case where while beats for: we do not know how many numbers the user will enter.

Program 10: Decimal to Binary Conversion Code #include int main() { int n = 13, bin[32], i = 0; while (n > 0) { bin[i] = n % 2; n /= 2; i++; } printf("Binary = "); for (int j = i - 1; j >= 0; j--) printf("%d", bin[j]); printf("\n"); return 0; } Output Binary = 1101 Step-by-step explanation

  1. Part 1, collect the bits (while loop): bin[32] is the storage for bits, and i counts how many have been stored.
  2. n % 2 is the remainder (0 or 1), which is the next bit starting from the right.
  3. n /= 2 halves the number, and i++ moves to the next array slot.
  4. After the loop, the array holds {1, 0, 1, 1}, which is the binary number backwards.
  5. Part 2, print in reverse (for loop): start at j = i - 1 = 3, the last stored bit, and count down to 0.
  6. This prints bin[3], bin[2], bin[1], bin[0], which is 1 1 0 1.
  7. The output is 1101 , and indeed 8 + 4 + 0 + 1 = 13. Dry run Pass n before bin[i] = n % 2 n after i after 1 13 bin[0] = 1 6 1 2 6 bin[1] = 0 3 2 3 3 bin[2] = 1 1 3 4 1 bin[3] = 1 0 4 Note: This program shows both loops working together. For n = 0 the loop never runs and nothing is printed, so a real program should handle 0 separately.