






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







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:
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
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
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
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
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
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
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