c
exercises
exercises.c🔧c
/**
* @file exercises.c
* @brief Loop Exercises (for, while, do-while)
*
* Practice all types of loops in C.
*
* Compile: gcc -Wall exercises.c -o exercises
* Run: ./exercises
*/
#include <stdio.h>
/* ============================================================
* EXERCISE 1: PRINT EVEN NUMBERS
* ============================================================
* Difficulty: Easy
*
* Task: Print all even numbers from 2 to 20 (inclusive).
* Use a for loop.
*/
void printEvenNumbers() {
printf("Even numbers 2-20: ");
// TODO: Print 2, 4, 6, ..., 20
// Your code here
printf("\n");
}
void exercise_1() {
printf("\n=== Exercise 1: Print Even Numbers ===\n");
printEvenNumbers();
}
/* ============================================================
* EXERCISE 2: SUM OF ARRAY
* ============================================================
* Difficulty: Easy
*
* Task: Calculate and return the sum of all elements in an array.
*/
int sumArray(int arr[], int size) {
// TODO: Return sum of all elements
// Your code here
return 0; // Replace this
}
void exercise_2() {
printf("\n=== Exercise 2: Sum of Array ===\n");
int arr[] = {5, 10, 15, 20, 25};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array: 5, 10, 15, 20, 25\n");
printf("Sum: %d\n", sumArray(arr, size));
}
/* ============================================================
* EXERCISE 3: FACTORIAL
* ============================================================
* Difficulty: Easy
*
* Task: Calculate n! (n factorial) using a loop.
* 5! = 5 × 4 × 3 × 2 × 1 = 120
*/
long factorial(int n) {
// TODO: Return n!
// Handle n < 0 by returning -1
// 0! = 1
// Your code here
return 0; // Replace this
}
void exercise_3() {
printf("\n=== Exercise 3: Factorial ===\n");
int values[] = {0, 1, 5, 10, -1};
int count = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < count; i++) {
printf("%d! = %ld\n", values[i], factorial(values[i]));
}
}
/* ============================================================
* EXERCISE 4: REVERSE STRING
* ============================================================
* Difficulty: Medium
*
* Task: Reverse a string in place using loops.
*/
void reverseString(char str[]) {
// TODO: Reverse the string in place
// Hint: Use two indices, one from start, one from end
// Your code here
}
void exercise_4() {
printf("\n=== Exercise 4: Reverse String ===\n");
char str1[] = "Hello";
char str2[] = "World!";
printf("Before: %s\n", str1);
reverseString(str1);
printf("After: %s\n", str1);
printf("Before: %s\n", str2);
reverseString(str2);
printf("After: %s\n", str2);
}
/* ============================================================
* EXERCISE 5: MULTIPLICATION TABLE
* ============================================================
* Difficulty: Easy
*
* Task: Print the multiplication table for a given number.
*/
void multiplicationTable(int n) {
// TODO: Print n x 1 = n, n x 2 = 2n, ..., n x 10 = 10n
// Your code here
}
void exercise_5() {
printf("\n=== Exercise 5: Multiplication Table ===\n");
multiplicationTable(7);
}
/* ============================================================
* EXERCISE 6: COUNT DIGITS
* ============================================================
* Difficulty: Medium
*
* Task: Count the number of digits in a positive integer.
* Use a while loop.
*/
int countDigits(int n) {
// TODO: Return number of digits
// Handle n = 0 specially (1 digit)
// Your code here
return 0; // Replace this
}
void exercise_6() {
printf("\n=== Exercise 6: Count Digits ===\n");
int numbers[] = {0, 5, 42, 123, 9999, 100000};
int count = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < count; i++) {
printf("%d has %d digit(s)\n", numbers[i], countDigits(numbers[i]));
}
}
/* ============================================================
* EXERCISE 7: SUM OF DIGITS
* ============================================================
* Difficulty: Medium
*
* Task: Calculate the sum of digits of a number.
* Example: 12345 -> 1+2+3+4+5 = 15
*/
int sumOfDigits(int n) {
// TODO: Return sum of all digits
// Handle negative numbers (use absolute value)
// Your code here
return 0; // Replace this
}
void exercise_7() {
printf("\n=== Exercise 7: Sum of Digits ===\n");
int numbers[] = {12345, 999, 10, 7, 0, -123};
int count = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < count; i++) {
printf("Sum of digits of %d = %d\n", numbers[i], sumOfDigits(numbers[i]));
}
}
/* ============================================================
* EXERCISE 8: POWER FUNCTION
* ============================================================
* Difficulty: Medium
*
* Task: Calculate base^exponent using a loop.
* Do not use math library.
*/
long power(int base, int exponent) {
// TODO: Return base^exponent
// Handle exponent = 0 (return 1)
// Handle negative exponent (return 0 for simplicity)
// Your code here
return 0; // Replace this
}
void exercise_8() {
printf("\n=== Exercise 8: Power Function ===\n");
printf("2^10 = %ld\n", power(2, 10));
printf("3^5 = %ld\n", power(3, 5));
printf("5^0 = %ld\n", power(5, 0));
printf("7^1 = %ld\n", power(7, 1));
printf("2^-1 = %ld\n", power(2, -1));
}
/* ============================================================
* EXERCISE 9: FIBONACCI SEQUENCE
* ============================================================
* Difficulty: Medium
*
* Task: Print the first n Fibonacci numbers.
* Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, ...
*/
void printFibonacci(int n) {
// TODO: Print first n Fibonacci numbers
// Your code here
}
void exercise_9() {
printf("\n=== Exercise 9: Fibonacci ===\n");
printf("First 10 Fibonacci: ");
printFibonacci(10);
printf("\n");
}
/* ============================================================
* EXERCISE 10: IS PALINDROME NUMBER
* ============================================================
* Difficulty: Medium
*
* Task: Check if a number is a palindrome.
* A palindrome reads the same forwards and backwards.
* Example: 12321 is palindrome, 12345 is not.
*/
int isPalindromeNumber(int n) {
// TODO: Return 1 if palindrome, 0 otherwise
// Hint: Reverse the number and compare
// Your code here
return 0; // Replace this
}
void exercise_10() {
printf("\n=== Exercise 10: Palindrome Number ===\n");
int numbers[] = {12321, 12345, 11, 1, 1221, 1234321};
int count = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < count; i++) {
printf("%d: %s\n", numbers[i],
isPalindromeNumber(numbers[i]) ? "Palindrome" : "Not palindrome");
}
}
/* ============================================================
* EXERCISE 11: PRINT PATTERN
* ============================================================
* Difficulty: Medium
*
* Task: Print a pyramid pattern of given height.
* *
* ***
* *****
* *******
*/
void printPyramid(int height) {
// TODO: Print pyramid of given height
// Your code here
}
void exercise_11() {
printf("\n=== Exercise 11: Pyramid Pattern ===\n");
printPyramid(5);
}
/* ============================================================
* EXERCISE 12: GCD (Greatest Common Divisor)
* ============================================================
* Difficulty: Medium
*
* Task: Find GCD using Euclidean algorithm.
* gcd(a, b) = gcd(b, a % b) until b = 0
*/
int gcd(int a, int b) {
// TODO: Return GCD of a and b
// Use Euclidean algorithm with a loop
// Your code here
return 0; // Replace this
}
void exercise_12() {
printf("\n=== Exercise 12: GCD ===\n");
printf("GCD(48, 18) = %d\n", gcd(48, 18));
printf("GCD(100, 25) = %d\n", gcd(100, 25));
printf("GCD(7, 13) = %d\n", gcd(7, 13));
printf("GCD(0, 5) = %d\n", gcd(0, 5));
}
/* ============================================================
* EXERCISE 13: PRIME NUMBERS IN RANGE
* ============================================================
* Difficulty: Hard
*
* Task: Print all prime numbers between start and end (inclusive).
*/
void printPrimesInRange(int start, int end) {
// TODO: Print all primes in range
// Your code here
}
void exercise_13() {
printf("\n=== Exercise 13: Primes in Range ===\n");
printf("Primes between 10 and 50: ");
printPrimesInRange(10, 50);
printf("\n");
}
/* ============================================================
* EXERCISE 14: BINARY REPRESENTATION
* ============================================================
* Difficulty: Hard
*
* Task: Print the binary representation of a positive integer.
*/
void printBinary(int n) {
// TODO: Print binary representation
// Hint: Use array or recursion to print in correct order
// Your code here
}
void exercise_14() {
printf("\n=== Exercise 14: Binary Representation ===\n");
int numbers[] = {0, 1, 5, 10, 255};
int count = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < count; i++) {
printf("%3d in binary: ", numbers[i]);
printBinary(numbers[i]);
printf("\n");
}
}
/* ============================================================
* EXERCISE 15: ARMSTRONG NUMBER
* ============================================================
* Difficulty: Hard
*
* Task: Check if a number is an Armstrong number.
* An Armstrong number equals the sum of its digits
* each raised to the power of the number of digits.
* Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
*/
int isArmstrong(int n) {
// TODO: Return 1 if Armstrong number, 0 otherwise
// Your code here
return 0; // Replace this
}
void exercise_15() {
printf("\n=== Exercise 15: Armstrong Numbers ===\n");
printf("Armstrong numbers up to 1000: ");
for (int i = 0; i <= 1000; i++) {
if (isArmstrong(i)) {
printf("%d ", i);
}
}
printf("\n");
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ LOOPS - EXERCISES ║\n");
printf("║ Practice iteration in C ║\n");
printf("╚════════════════════════════════════════════════╝\n");
// Uncomment exercises as you complete them:
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// exercise_10();
// exercise_11();
// exercise_12();
// exercise_13();
// exercise_14();
// exercise_15();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/* ============================================================
* ANSWER KEY
* ============================================================
*
* EXERCISE 1:
* void printEvenNumbers() {
* printf("Even numbers 2-20: ");
* for (int i = 2; i <= 20; i += 2) {
* printf("%d ", i);
* }
* printf("\n");
* }
*
* EXERCISE 2:
* int sumArray(int arr[], int size) {
* int sum = 0;
* for (int i = 0; i < size; i++) {
* sum += arr[i];
* }
* return sum;
* }
*
* EXERCISE 3:
* long factorial(int n) {
* if (n < 0) return -1;
* long result = 1;
* for (int i = 2; i <= n; i++) {
* result *= i;
* }
* return result;
* }
*
* EXERCISE 4:
* void reverseString(char str[]) {
* int len = 0;
* while (str[len] != '\0') len++;
*
* for (int i = 0, j = len - 1; i < j; i++, j--) {
* char temp = str[i];
* str[i] = str[j];
* str[j] = temp;
* }
* }
*
* EXERCISE 5:
* void multiplicationTable(int n) {
* for (int i = 1; i <= 10; i++) {
* printf("%d x %d = %d\n", n, i, n * i);
* }
* }
*
* EXERCISE 6:
* int countDigits(int n) {
* if (n == 0) return 1;
* int count = 0;
* while (n > 0) {
* count++;
* n /= 10;
* }
* return count;
* }
*
* EXERCISE 7:
* int sumOfDigits(int n) {
* if (n < 0) n = -n;
* int sum = 0;
* while (n > 0) {
* sum += n % 10;
* n /= 10;
* }
* return sum;
* }
*
* EXERCISE 8:
* long power(int base, int exponent) {
* if (exponent < 0) return 0;
* long result = 1;
* for (int i = 0; i < exponent; i++) {
* result *= base;
* }
* return result;
* }
*
* EXERCISE 9:
* void printFibonacci(int n) {
* int a = 0, b = 1;
* for (int i = 0; i < n; i++) {
* printf("%d ", a);
* int next = a + b;
* a = b;
* b = next;
* }
* }
*
* EXERCISE 10:
* int isPalindromeNumber(int n) {
* if (n < 0) return 0;
* int original = n, reversed = 0;
* while (n > 0) {
* reversed = reversed * 10 + n % 10;
* n /= 10;
* }
* return original == reversed;
* }
*
* EXERCISE 11:
* void printPyramid(int height) {
* for (int i = 1; i <= height; i++) {
* for (int j = 0; j < height - i; j++) printf(" ");
* for (int j = 0; j < 2 * i - 1; j++) printf("*");
* printf("\n");
* }
* }
*
* EXERCISE 12:
* int gcd(int a, int b) {
* while (b != 0) {
* int temp = b;
* b = a % b;
* a = temp;
* }
* return a;
* }
*
* EXERCISE 13:
* void printPrimesInRange(int start, int end) {
* for (int num = start; num <= end; num++) {
* if (num < 2) continue;
* int isPrime = 1;
* for (int i = 2; i * i <= num; i++) {
* if (num % i == 0) { isPrime = 0; break; }
* }
* if (isPrime) printf("%d ", num);
* }
* }
*
* EXERCISE 14:
* void printBinary(int n) {
* if (n == 0) { printf("0"); return; }
* int bits[32], count = 0;
* while (n > 0) {
* bits[count++] = n % 2;
* n /= 2;
* }
* for (int i = count - 1; i >= 0; i--) {
* printf("%d", bits[i]);
* }
* }
*
* EXERCISE 15:
* int isArmstrong(int n) {
* int original = n, digits = 0, sum = 0;
* int temp = n;
* while (temp > 0) { digits++; temp /= 10; }
* temp = n;
* while (temp > 0) {
* int digit = temp % 10;
* int power = 1;
* for (int i = 0; i < digits; i++) power *= digit;
* sum += power;
* temp /= 10;
* }
* return sum == original;
* }
*
* ============================================================
*/