17 Programming Exercise In C For Beginners With Solutions

Reading about C only gets you so far. The real learning starts when you sit down, write a program, and it does not work the way you expected. That is why exercises matter, and this page gives you 17 of them, with tested solutions.

You only really learn a programming language by writing code in it, again and again. C is one of the fundamental languages, and it needs a lot of hands-on practice before the concepts really click.

C has many concepts where students get stuck, like pointers, strings, and memory. In this article, we will solve 17 beginner-friendly C exercises, one step at a time, and then take a deep look at one of the most common assignments of all: the Fibonacci series.

We compiled every program on this page with GCC, with warnings turned on (-Wall -Wextra), and ran it. The sample runs below are copied from a real terminal, including what we typed.

Summary Of The Article:

  • C is a small but powerful language that works close to the hardware, which is why it is still taught in so many CS courses.
  • C exercises for beginners start with the basics, like input and output, conditions, and loops, and move on to arrays, strings, pointers, structs, and files.
  • Each exercise below has a difficulty level, a hint, a tested solution, a sample run, and an idea to try next.
  • The Fibonacci section compares 5 ways to write the program and shows where each one hits its limits.
  • The more C exercises you solve on your own, the better you get at the language.

Before You Start: How A C Program Is Put Together

If you are brand new to C, spend two minutes here first. Every exercise on this page follows the same basic shape:

#include <stdio.h>      // Lets us use printf() and scanf()

// Every C program starts running from main()
int main(void) {
    int age;                          // Declare a variable before you use it

    printf("How old are you? ");
    scanf("%d", &age);                // & gives scanf the address of age

    printf("Next year you will be %d.\n", age + 1);
    return 0;                         // 0 tells the system the program ended fine
}

Sample run:

How old are you? 19
Next year you will be 20.

Here are the syntax rules that trip up beginners most often:

  • Every program needs a main() function. That is where the program starts running.
  • #include lines bring in libraries. <stdio.h> gives you printf() and scanf(). <string.h>, <math.h>, and <stdlib.h> are others you will see below.
  • Every statement ends with a semicolon (;). A missing semicolon is one of the most common compile errors.
  • Curly braces { } group statements into a block, like the body of a function, a loop, or an if-statement.
  • C is case-sensitive. printf works, but Printf does not, and age and Age are two different variables.
  • Declare a variable, with its type, before you use it, for example int age;.
  • scanf() needs an & before normal variables, like &age. It does not need one before an array name, such as a string. A single element, like arr[i], is a normal variable, so it still needs the &.
  • Comments start with // for one line, or go between /* and */ for several lines. The compiler ignores them.

How to compile and run: Save the code as hello.c, then run these two commands in a terminal. On Windows, the second command is hello.exe (or .\hello.exe in PowerShell) instead.

gcc -Wall -Wextra hello.c -o hello
./hello

The -Wall -Wextra part turns on warnings, which catch many bugs before you even run the program. Always use it while practicing. If a program includes <math.h>, add -lm at the end of the gcc command on Linux.

Most exercises below use if-else statements and loops. If those still feel shaky, read our guide to control flow in C first, then come back.

17 C Programming Exercises For Beginners (With Solutions)

Let's get started. C is a big language with a lot of concepts, and the best way to understand each one is to use it in a real program.

C programming exercises for beginners

Here is how to get the most out of this list: read the problem, try to write the program yourself first, and open the hint only if you get stuck. Then compare your code with our solution and test it with the same inputs.

Basic C Programming Exercises For Beginners

These exercises cover the basics: input and output, conditions, loops, functions, and your first look at macros and pointers.

1. Write a C program to check if a triangle is a right-angle triangle

Easy Practices: functions, if-else, input

A triangle is right-angled if the sum of the squares of the two shorter sides equals the square of the longest side. This is the Pythagorean theorem, and we will use it to solve this problem.

Show a hint

First make sure the longest side ends up in one fixed variable, say s3. Then you only need one check: s1*s1 + s2*s2 == s3*s3.

#include <stdio.h>

int RightTriangle(int s1, int s2, int s3) {
    // Arrange sides so that s3 is the longest side
    if (s1 > s2) {
        int temp = s1;
        s1 = s2;
        s2 = temp;
    }
    if (s2 > s3) {
        int temp = s2;
        s2 = s3;
        s3 = temp;
    }

    // Check right triangle using the Pythagorean theorem
    if (s1 * s1 + s2 * s2 == s3 * s3)
        return 1;
    else
        return 0;
}

int main(void) {
    int s1, s2, s3;
    // Input the sides of the triangle
    printf("Enter the first side of the triangle: ");
    scanf("%d", &s1);
    printf("Enter the second side of the triangle: ");
    scanf("%d", &s2);
    printf("Enter the third side of the triangle: ");
    scanf("%d", &s3);

    // A side of a triangle must be longer than zero
    if (s1 <= 0 || s2 <= 0 || s3 <= 0) {
        printf("Sides must be positive numbers.\n");
        return 1;
    }

    // calling the function
    if (RightTriangle(s1, s2, s3))
        printf("It is a right-angled triangle.\n");
    else
        printf("It isn't a right-angled triangle.\n");

    return 0;
}

Sample runs:

Enter the first side of the triangle: 3
Enter the second side of the triangle: 4
Enter the third side of the triangle: 5
It is a right-angled triangle.
Enter the first side of the triangle: 5
Enter the second side of the triangle: 12
Enter the third side of the triangle: 14
It isn't a right-angled triangle.

In this code, the RightTriangle() function first moves the longest side into s3 with two swaps, and then checks the Pythagorean theorem. If the triangle is right-angled, the function returns 1. Otherwise, it returns 0. We also reject zero or negative sides, because no real triangle has them.

Try this next: Also check that the three sides can form a triangle at all. The two shorter sides must add up to more than the longest side.

2. Write a C program to convert a decimal number to its octal equivalent

Easy Practices: loops, arrays, number bases

Decimal numbers have base 10, while octal numbers have base 8. To convert decimal to octal, we keep dividing the number by 8 and saving the remainders until the number becomes 0. The remainders, read backwards, are the octal digits.

Show a hint

Store each n % 8 in an array, divide n by 8, and repeat. Then print the array from the last element to the first. Do not forget the special case where the input is 0.

#include <stdio.h>

void decimalToOctal(int n) {
    int octalNumber[32], i = 0;

    if (n == 0) {               // 0 is 0 in every base
        printf("0\n");
        return;
    }

    while (n != 0) {
        octalNumber[i] = n % 8; // Save the remainder
        n /= 8;                 // Divide by 8 for the next digit
        i++;
    }

    // The remainders come out backwards, so print them in reverse
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", octalNumber[j]);
    }
    printf("\n");
}

int main(void) {
    int n;
    printf("Enter a whole number (0 or more): ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Please enter 0 or a positive number.\n");
        return 1;
    }

    printf("Octal equivalent is: ");
    decimalToOctal(n);
    printf("Check with %%o:        %o\n", n); // printf can do it for you too
    return 0;
}

Sample runs:

Enter a whole number (0 or more): 100
Octal equivalent is: 144
Check with %o:        144
Enter a whole number (0 or more): 0
Octal equivalent is: 0
Check with %o:        0

In this code, we take a decimal number as input and pass it to the decimalToOctal() function. It uses a while loop to divide the number by 8 again and again, and then prints the saved remainders in reverse order. The input 0 needs its own check, because the loop would never run for it.

The last line uses printf("%o"), which prints a non-negative whole number in octal. It is a quick way to check your answer, but most assignments want you to write the conversion yourself, like we did.

Try this next: Change the program to convert decimal to binary (base 2). Change both 8s in decimalToOctal() to 2, and remove the %o check line.

3. Write a C program to swap two numbers using a macro

Easy Practices: macros, bitwise XOR

A macro, in C, is a piece of code defined with #define that the preprocessor replaces before compiling. For example, #define PI 3.14 replaces every PI in your code with 3.14. Here is how to swap two numbers with a macro.

Show a hint

XOR (^) has a neat property: a ^ b ^ b gives back a. Applying XOR three times, in the right order, swaps two numbers without a third variable.

#include <stdio.h>

// SWAP as a macro, using the XOR operator three times.
// do { ... } while (0) makes the macro behave like one normal statement.
#define SWAP(a, b) do { (a) ^= (b); (b) ^= (a); (a) ^= (b); } while (0)

int main(void) {
    int n1, n2;

    // Input two numbers
    printf("Enter two numbers: ");
    scanf("%d %d", &n1, &n2);

    printf("Before swapping: n1 = %d, n2 = %d\n", n1, n2);
    SWAP(n1, n2);
    printf("After swapping: n1 = %d, n2 = %d\n", n1, n2);
    return 0;
}

Sample run:

Enter two numbers: 12 45
Before swapping: n1 = 12, n2 = 45
After swapping: n1 = 45, n2 = 12

Here, SWAP() is defined as a macro. It uses the XOR operation three times to swap the two values without a temporary variable. We wrapped the macro body in do { ... } while (0), a common C habit that makes the macro act like a single statement, so it works safely inside an if-else.

One warning: the XOR trick breaks if both arguments are the same variable. SWAP(n1, n1) sets n1 to 0. In real code, a swap with a temporary variable, like the next exercise, is clearer and just as fast.

4. Write a C program to swap two numbers using pointers

Easy Practices: pointers, functions, call by reference

This is the classic first pointer exercise. A normal function gets copies of its arguments, so swapping them inside the function changes nothing in main(). To change the real variables, the function needs their addresses.

Show a hint

Make the function take int *a and int *b, and call it with swap(&x, &y). Inside, use *a and *b to reach the actual values.

#include <stdio.h>

// The function gets the ADDRESSES of the two variables
void swap(int *a, int *b) {
    int temp = *a;   // *a means "the value stored at address a"
    *a = *b;
    *b = temp;
}

int main(void) {
    int x, y;
    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    printf("Before swapping: x = %d, y = %d\n", x, y);
    swap(&x, &y);    // Pass the addresses with &
    printf("After swapping: x = %d, y = %d\n", x, y);
    return 0;
}

Sample run:

Enter two numbers: 7 20
Before swapping: x = 7, y = 20
After swapping: x = 20, y = 7

&x means "the address of x", and *a means "the value stored at address a". Because swap() works on the addresses, it changes x and y in main() directly. This is often called call by reference (C actually passes the address itself as a copy), and it is exactly why scanf() needs the & too.

Try this next: Write the same swap() without pointers, with int a, int b, and see for yourself that the values in main() do not change.

5. Write a C program to check whether a number is prime

Easy Practices: loops, functions, edge cases

A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself, like 2, 3, 5, 7, and 11. This is one of the most common beginner exercises in C.

Show a hint

You only need to test divisors up to the square root of the number. If n has a divisor bigger than its square root, it also has one smaller than it. So loop while i <= n / i, which means the same as i * i <= n but cannot overflow on very large numbers.

#include <stdio.h>

// Returns 1 if n is prime, 0 if it is not
int isPrime(int n) {
    if (n < 2) {
        return 0;               // 0, 1, and negative numbers are not prime
    }
    for (int i = 2; i <= n / i; i++) {   // Same as i * i <= n, but cannot overflow
        if (n % i == 0) {
            return 0;           // Found a divisor, so not prime
        }
    }
    return 1;
}

int main(void) {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);

    if (isPrime(num))
        printf("%d is a prime number.\n", num);
    else
        printf("%d is not a prime number.\n", num);
    return 0;
}

Sample runs:

Enter a number: 97
97 is a prime number.
Enter a number: 91
91 is not a prime number.
Enter a number: 1
1 is not a prime number.

The isPrime() function first rules out numbers below 2, which are not prime. Then it tries every divisor from 2 up to the square root of n. As soon as one divides evenly, it returns 0. The second run is a good test case: 91 looks prime, but it is 7 x 13.

Why i <= n / i instead of the more common i * i <= n? For a number close to the int limit, i * i can overflow. We tested it: with i * i, the program says 2,147,483,647 is not prime, even though it is.

Try this next: Print every prime number between 1 and 100 by calling isPrime() inside a loop.

6. Write a C program to reverse a number and check if it is a palindrome

Easy Practices: while loops, % and / operators

A palindrome number reads the same forwards and backwards, like 121 or 12321. To check it, we reverse the number digit by digit and compare the result with the original.

Show a hint

num % 10 gives you the last digit, and num / 10 removes it. Build the reversed number with reversed = reversed * 10 + digit.

#include <stdio.h>

int main(void) {
    int num, original;
    long long reversed = 0;             // long long, because the reversed number can be bigger

    printf("Enter a whole number (0 or more): ");
    scanf("%d", &num);
    if (num < 0) {
        printf("Please enter 0 or a positive number.\n");
        return 1;
    }

    original = num;
    while (num != 0) {
        int digit = num % 10;           // Take the last digit
        reversed = reversed * 10 + digit;
        num /= 10;                      // Drop the last digit
    }

    printf("Reversed number: %lld\n", reversed);
    if (original == reversed)
        printf("%d is a palindrome.\n", original);
    else
        printf("%d is not a palindrome.\n", original);
    return 0;
}

Sample runs:

Enter a whole number (0 or more): 12321
Reversed number: 12321
12321 is a palindrome.
Enter a whole number (0 or more): 1234
Reversed number: 4321
1234 is not a palindrome.

The loop takes the last digit off num and adds it to the end of reversed, until num becomes 0. We save a copy in original first, because the loop destroys num. Forgetting that copy is a very common bug, and the same idea comes back in Exercise 14. reversed is a long long, because reversing a big number like 1,000,000,009 gives 9,000,000,001, which is too big for an int.

Try this next: Count how many digits the number has, and find the sum of its digits, using the same loop.

Array and String C Exercises For Beginners

Arrays and strings (which in C are just arrays of characters ending in '\0') show up in almost every C assignment. Interviewers love them too, so let's practice.

7. Write a C program to concatenate two strings

Easy Practices: strings, string.h, buffer size

This is one of the most common C exercises for string manipulation. Concatenation means joining strings together. Here is how to do it in C.

Show a hint

strcat(dest, src) adds src to the end of dest. The catch: dest must have enough room for both strings plus the ending '\0'.

#include <stdio.h>
#include <string.h>

int main(void) {
    char str1[20] = "Coding"; // Room for 19 characters plus the ending '\0'
    char str2[] = "Zap";

    // Concatenate the strings: str2 is added to the end of str1
    strcat(str1, str2);

    printf("Concatenated string: %s\n", str1);
    return 0;
}

Sample run:

Concatenated string: CodingZap

In this program, the first string is "Coding" and the second is "Zap". To join them, we use strcat(), one of the built-in functions in the <string.h> library. It adds str2 to the end of str1, and then we print the result.

Notice the size [20] on str1. If you write char str1[] = "Coding"; instead, the array is only 7 bytes long (6 letters plus '\0'), and strcat() writes past the end of it. The program might still print the right answer, but it is a real bug called a buffer overflow. When we ran that version with AddressSanitizer turned on (-fsanitize=address), it stopped with a "stack-buffer-overflow" error.

Try this next: Join the two strings yourself with a loop, without using strcat().

8. Write a C program to count vowels and consonants in a string

Easy Practices: strings, fgets(), character checks

This exercise reads a whole line of text, including spaces, and counts how many letters are vowels and how many are consonants.

Show a hint

Use fgets() instead of scanf("%s"), because scanf stops at the first space. Convert each character to lowercase with tolower() so you only have to check five vowels.

#include <stdio.h>
#include <ctype.h>

int main(void) {
    char text[100];
    int vowels = 0, consonants = 0;

    printf("Enter a line of text: ");
    fgets(text, sizeof(text), stdin);   // Reads spaces too, unlike scanf("%s")

    for (int i = 0; text[i] != '\0'; i++) {
        char ch = tolower((unsigned char) text[i]);
        if (ch >= 'a' && ch <= 'z') {   // Only count letters
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                vowels++;
            else
                consonants++;
        }
    }

    printf("Vowels: %d\n", vowels);
    printf("Consonants: %d\n", consonants);
    return 0;
}

Sample run:

Enter a line of text: Learning C is fun!
Vowels: 5
Consonants: 9

The loop walks through the string until it reaches the ending '\0'. For each character, it first checks that it is a letter, so spaces, digits, and punctuation like "!" are not counted. Then it sorts the letter into vowels or consonants. In "Learning C is fun!", the vowels are e, a, i, i, u.

Try this next: Also count the words in the line. Hint: count every letter that is either the first character of the line or comes right after a space.

9. Write a C program to sort array elements in descending order using bubble sort

Medium Practices: arrays, nested loops, sorting

Bubble sort is one of the simplest sorting algorithms. It compares each element with the next one and swaps them if they are in the wrong order. After each full pass, one more element is in its final place. Since we want descending order, we swap when the first element is smaller than the next one.

Show a hint

Use two loops. The outer loop runs n - 1 passes. The inner loop compares arr[j] with arr[j + 1] and stops i places earlier each pass, because the end of the array is already sorted.

#include <stdio.h>

// Bubble sort function
void bubbleSortDesc(int arr[], int n) {
    int temp;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] < arr[j + 1]) {
                // Swap arr[j] and arr[j + 1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main(void) {
    int n;
    // n is the size of the array
    printf("Enter size of the array: ");
    scanf("%d", &n);
    if (n <= 0) {
        printf("Invalid input\n");
        return 1;
    }
    int arr[n];
    // Input elements using for loop
    printf("Enter %d elements of the array: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // call function
    bubbleSortDesc(arr, n);

    // Print the sorted array using for loop
    printf("Sorted array in descending order: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

Sample run:

Enter size of the array: 5
Enter 5 elements of the array: 12 45 7 89 23
Sorted array in descending order: 89 45 23 12 7

In this program, the bubbleSortDesc() function does the sorting, and main() handles the input and output. The only change needed to sort in ascending order is flipping < to > in the comparison. We also check that the size is positive, because an array of size 0 or less is not valid.

Try this next: Add a flag that stops the sort early if a whole pass makes no swaps. Then the sort finishes in one pass on an array that is already sorted.

10. Write a C program to calculate the average of all elements in an array

Easy Practices: arrays, loops, float division

The average, or mean, is one of the most basic calculations you can do on an array. Add up all the elements, then divide by how many there are.

Show a hint

Keep the sum in a float (or cast it) before dividing. If both the sum and the count are int, C does whole-number division and drops the decimal part.

#include <stdio.h>

// Function to calculate the average
float calculateAverage(int arr[], int n) {
    float sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum / n;
}

int main(void) {
    int n; //size of the array
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    if (n <= 0) {
        printf("Invalid input\n");
        return 1;
    }

    // Declare an array of the given size
    int arr[n];
    // Input values
    printf("Enter %d elements of the array: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // call function
    float avg = calculateAverage(arr, n);

    // Print the average
    printf("The average of elements is: %.2f\n", avg);

    return 0;
}

Sample run:

Enter the size of the array: 4
Enter 4 elements of the array: 10 20 35 42
The average of elements is: 26.75

Most of these programs put the main work in a function. That keeps main() short and makes the logic easy to reuse and test. Here, calculateAverage() adds up the elements into a float sum, so the division keeps the decimal part: 107 / 4 = 26.75, not 26.

Try this next: Also print how many elements are above the average.

11. Write a C program to find the minimum and maximum element in an array

Easy Practices: arrays, functions, comparisons

Next, we need to find the largest and smallest values in an array.

Show a hint

Start with the first element as both the current maximum and minimum, not with 0. Then compare every other element against them.

#include <stdio.h>

// Function to find the maximum element
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

// Function to find the minimum element
int findMin(int arr[], int size) {
    int min = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

int main(void) {
    int n;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    if (n <= 0) {
        printf("Invalid input\n");
        return 1;
    }
    int arr[n]; // declaring array
    // Input values
    printf("Enter %d elements of the array: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // calling functions
    int max = findMax(arr, n);
    int min = findMin(arr, n);

    // Print results
    printf("Maximum element in the array: %d\n", max);
    printf("Minimum element in the array: %d\n", min);

    return 0;
}

Sample run:

Enter the size of the array: 6
Enter 6 elements of the array: 14 -3 88 0 27 5
Maximum element in the array: 88
Minimum element in the array: -3

First, we define two functions, findMax() and findMin(). Each one uses a for loop to walk through the array and keep track of the largest or smallest element seen so far. Because we start from arr[0] instead of 0, the program works with negative numbers too, as the sample run shows.

Try this next: Find both values in a single loop, and also print the position (index) where each one was found.

Numerical And Mathematical C Exercises For Beginners

Math exercises are short and easy to check by hand, and they teach you to watch out for number limits.

12. Write a C program to find the factorial of a number using recursion

Easy Practices: recursion, data type limits

The factorial of n (written n!) is the product of all whole numbers from 1 to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. In this exercise, we use recursion, which means the function calls itself with a smaller number each time.

Show a hint

Every recursive function needs a base case that stops it. Here, 0! and 1! are both 1. For everything else, n! = n * (n - 1)!.

#include <stdio.h>

// recursive function
unsigned long long factorial(int n) {
    if (n == 0 || n == 1)
        return 1;                       // Base case: stops the recursion
    else
        return n * factorial(n - 1);    // Recursive case
}

int main(void) {
    int num;
    printf("Enter a number (0 to 20): ");
    scanf("%d", &num);
    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 1;
    }
    if (num > 20) {
        printf("20! is the largest factorial that fits in unsigned long long.\n");
        return 1;
    }
    printf("Factorial of %d is: %llu\n", num, factorial(num));
    return 0;
}

Sample runs:

Enter a number (0 to 20): 5
Factorial of 5 is: 120
Enter a number (0 to 20): 20
Factorial of 20 is: 2432902008176640000
Enter a number (0 to 20): 21
20! is the largest factorial that fits in unsigned long long.

In the above code, factorial() keeps calling itself with n - 1 until it reaches the base case, n == 0 or n == 1. Then all the waiting calls multiply their results on the way back.

Why unsigned long long and not int? Factorials grow very fast. A 32-bit int can only hold up to 12!, and for 13! it silently gives a wrong answer (we got 1932053504 instead of 6227020800). unsigned long long holds up to 20!, so the program refuses anything bigger instead of printing nonsense.

Try this next: Write the same program with a for loop instead of recursion. For a much deeper look at recursion, see our guide to recursive sorting algorithms.

13. Write a C program to print the Fibonacci series

Medium Practices: loops, functions, data type limits

The Fibonacci series is a sequence where each term is the sum of the two terms before it. It starts with 0 and 1 and goes on like 0, 1, 1, 2, 3, 5, 8, and so on. The task is to print the first n terms.

Show a hint

Keep two variables for the last two terms. In each step, print one, then work out the next term and shift both variables forward by one.

#include <stdio.h>

// Function to print the Fibonacci series up to n terms
void fibonacci(int n) {
    unsigned long long first = 0, second = 1, next;

    printf("Fibonacci series up to %d terms: ", n);
    for (int i = 1; i <= n; i++) {
        printf("%llu ", first);     // Print the current term
        next = first + second;      // The term that comes after second
        first = second;
        second = next;
    }
    printf("\n");
}

int main(void) {
    int n; // number of terms
    printf("Enter the number of terms for Fibonacci series: ");
    scanf("%d", &n);

    // Check if the number of terms is valid
    if (n <= 0) {
        printf("Invalid input\n");
        return 1;
    }
    if (n > 94) {
        printf("94 terms is the most that fits in unsigned long long.\n");
        return 1;
    }

    fibonacci(n);
    return 0;
}

Sample run:

Enter the number of terms for Fibonacci series: 10
Fibonacci series up to 10 terms: 0 1 1 2 3 5 8 13 21 34

In this code, the variables first and second start at the first two terms, 0 and 1. The for loop prints first, adds the two to get the next term, and moves both variables one step forward. Printing inside the loop means the program also works for 1 or 2 terms: if you enter 1, it prints just 0. We also stop at 94 terms, because the 95th term is too big for unsigned long long.

This is only one way to solve it. In the Fibonacci section below, we compare it with a while loop, recursion, memoization, and a direct formula, and show exactly when each one breaks.

14. Write a C program to check whether a given number is an Armstrong number

Medium Practices: functions, loops, digit math

An Armstrong number is a number that equals the sum of its digits, each raised to the power of the number of digits. For example, 153 has 3 digits, and 13 + 53 + 33 = 1 + 125 + 27 = 153. Here is a C program to check it.

Show a hint

Count the digits first. Then work on a copy of the number to pull out each digit, raise it to that power, and add it up. Compare the total with the original number, which you left untouched.

#include <stdio.h>

// Function to calculate the number of digits in a number
int countDigits(int num) {
    int count = 0;
    do {
        num /= 10;
        count++;
    } while (num != 0);
    return count;
}

// Whole-number power, so we avoid rounding problems with pow()
int power(int base, int exp) {
    int result = 1;
    for (int i = 0; i < exp; i++) {
        result *= base;
    }
    return result;
}

// Function to check whether a number is an Armstrong number or not
int isArmstrong(int num) {
    int n = countDigits(num);   // Number of digits
    int temp = num, result = 0;         // Work on a copy so num stays unchanged

    // Calculate the sum of the nth power of each digit
    while (temp != 0) {
        int remainder = temp % 10;
        result += power(remainder, n);
        temp /= 10;
    }

    // Compare with num, which we never changed
    return result == num;
}

int main(void) {
    int num;
    printf("Enter a whole number (0 or more): ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Please enter 0 or a positive number.\n");
        return 1;
    }

    if (isArmstrong(num))
        printf("%d is an Armstrong number.\n", num);
    else
        printf("%d is not an Armstrong number.\n", num);
    return 0;
}

Sample runs:

Enter a whole number (0 or more): 153
153 is an Armstrong number.
Enter a whole number (0 or more): 123
123 is not an Armstrong number.
Enter a whole number (0 or more): 9474
9474 is an Armstrong number.

The user enters a number, and isArmstrong() calls countDigits() to find how many digits it has. Then it adds up each digit raised to that power and compares the total with the original number.

Two details matter here. First, the check must compare against the unchanged number, which is why the loop works on temp, a copy. If you divide the input down to 0 while counting its digits and then compare with it, every input looks like an Armstrong number, because 0 equals 0. Second, we wrote a small whole-number power() function instead of using pow() from <math.h>. pow() works with decimals, and on some systems a result like 125 comes back as 124.99999, which turns into 124 when stored in an int.

Try this next: Print every Armstrong number between 1 and 10,000. You should get 1 to 9, 153, 370, 371, 407, 1634, 8208, and 9474.

Advanced C Exercises With Programming Examples

These last three exercises use the deeper parts of the language: dynamic memory, structs, and files.

15. Write a C program to create a dynamic array

Medium Practices: malloc(), free(), pointers

In Exercises 9 to 11, we used int arr[n], a variable-length array. That works in GCC, but Visual Studio does not support it, and a very large n can crash the program. malloc() is the standard way to make an array whose size you only know when the program runs.

Show a hint

malloc(size * sizeof(int)) asks for enough memory for size integers. Always check whether it returned NULL, and call free() when you are done.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int size;

    // Input the size of the dynamic array
    printf("Enter the size of the dynamic array: ");
    scanf("%d", &size);
    if (size <= 0) {
        printf("Size must be a positive number.\n");
        return 1;
    }

    // Allocate memory for the dynamic array
    int *dynamicArray = malloc(size * sizeof(int));
    // Check if memory allocation is successful
    if (dynamicArray == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Enter input values
    printf("Enter %d elements of the dynamic array: ", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &dynamicArray[i]);
    }

    // Print values
    printf("Dynamic array elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", dynamicArray[i]);
    }
    printf("\n");

    // Give the memory back with free()
    free(dynamicArray);

    return 0;
}

Sample run:

Enter the size of the dynamic array: 4
Enter 4 elements of the dynamic array: 5 10 15 20
Dynamic array elements: 5 10 15 20

In this program, we use the malloc() and free() functions from <stdlib.h>. malloc() reserves memory for the array while the program runs, and free() gives that memory back when we no longer need it. Forgetting free() in a long-running program causes a memory leak. Our guide to dynamic memory allocation in C covers malloc(), calloc(), realloc(), and free() in more detail.

Try this next: Ask the user for more elements after the first round, and grow the array with realloc().

16. Write a C program to store and print student records using a structure

Medium Practices: struct, arrays of structs, formatted output

A struct lets you group different types of data, like a name, a roll number, and marks, under one name. Student records are one of the most common struct assignments.

Show a hint

Define struct Student with three members, make an array of it, and fill it in a loop. Keep the index of the highest marks as you read the data.

#include <stdio.h>

// A struct groups related data under one name
struct Student {
    char name[50];
    int roll;
    float marks;
};

int main(void) {
    int n;
    printf("How many students? ");
    scanf("%d", &n);
    if (n <= 0 || n > 10) {
        printf("Please enter a number from 1 to 10.\n");
        return 1;
    }

    struct Student students[10];
    int top = 0;    // Index of the student with the highest marks

    for (int i = 0; i < n; i++) {
        printf("Enter name, roll number, and marks of student %d: ", i + 1);
        scanf("%49s %d %f", students[i].name, &students[i].roll, &students[i].marks);
        if (students[i].marks > students[top].marks) {
            top = i;
        }
    }

    printf("\nRoll  Name        Marks\n");
    for (int i = 0; i < n; i++) {
        printf("%-5d %-10s %6.1f\n", students[i].roll, students[i].name, students[i].marks);
    }
    printf("\nTop scorer: %s with %.1f marks\n", students[top].name, students[top].marks);
    return 0;
}

Sample run:

How many students? 3
Enter name, roll number, and marks of student 1: Ava 101 88.5
Enter name, roll number, and marks of student 2: Liam 102 92
Enter name, roll number, and marks of student 3: Noah 103 79.5

Roll  Name        Marks
101   Ava          88.5
102   Liam         92.0
103   Noah         79.5

Top scorer: Liam with 92.0 marks

Each students[i] is one record, and we reach its parts with a dot, like students[i].marks. The %49s in scanf() stops a long name from overflowing the 50-character array. In the table, %-10s left-aligns the name in a 10-character column and %6.1f prints the marks with one decimal place, so the columns line up.

Try this next: Sort the records by marks, highest first, using the bubble sort from Exercise 9.

17. Write a C program to copy one file's contents to another

Medium Practices: file handling, fgetc(), EOF

File handling is a big part of many C programming projects. Here is a small program that copies the contents of one file into another, one character at a time.

Show a hint

Open the source with "r" and the destination with "w", and check both for NULL. Read with fgetc() until it returns EOF, and store its result in an int, not a char.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *sourceFile, *destinationFile;
    char sourceFileName[100], destinationFileName[100];
    int ch;   // int, not char, so it can hold every byte AND the special EOF value
    long count = 0;

    // Input the source file name (%99s stops at 99 characters to avoid overflow)
    printf("Enter the name of the source file: ");
    scanf("%99s", sourceFileName);

    // Open the source file in read mode
    sourceFile = fopen(sourceFileName, "r");
    if (sourceFile == NULL) {
        printf("Error opening source file.\n");
        exit(1);
    }

    // Input the destination file name
    printf("Enter the name of the destination file: ");
    scanf("%99s", destinationFileName);

    // Open the destination file in write mode (creates it or empties it)
    destinationFile = fopen(destinationFileName, "w");
    if (destinationFile == NULL) {
        printf("Error opening destination file.\n");
        fclose(sourceFile);
        exit(1);
    }

    // Copy content from source file to destination file, one character at a time
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destinationFile);
        count++;
    }

    // Close files
    fclose(sourceFile);
    fclose(destinationFile);

    printf("File copied successfully. %ld characters copied.\n", count);

    return 0;
}

Sample run (notes.txt is a small two-line text file in the same folder):

Enter the name of the source file: notes.txt
Enter the name of the destination file: copy.txt
File copied successfully. 64 characters copied.

First, we ask for the source file name and open it in read mode. If it does not exist, fopen() returns NULL and we stop with an error message. Then we open the destination file in write mode, which creates it, or empties it if it already exists.

To copy the contents, we use a while loop with fgetc() to read the characters one by one and fputc() to write them to the destination file. When we are done, we close both files with fclose(). This makes sure everything is actually written to the file and frees it for other programs.

Notice that ch is an int. This is a classic bug: if you declare it as char, a byte with the value 255 looks the same as EOF on many systems. We tested this. With char ch, copying an 8-byte file that had a 255 byte in the middle stopped after 3 bytes, and the program still printed "File copied successfully."

Try this next: Count the lines and words in the file while copying it.

Fibonacci Series In C: 5 Methods Compared

The Fibonacci series program is one of the first problems most computer science students meet in C. The idea itself comes from mathematics, not computer science, but it is perfect for practicing loops, recursion, and data types. In this section, we go beyond Exercise 13 and compare five ways to write it and show where each one hits its limits.

What Is The Fibonacci Series?

In the Fibonacci series, each number is the sum of the two numbers before it. The first two terms are 0 and 1. The third term is 0 + 1 = 1, the fourth is 1 + 1 = 2, the fifth is 1 + 2 = 3, and so on.

Fibonacci series: each term is the sum of the two terms before it

In math, this rule is written as a formula:

F(n) = F(n-1) + F(n-2),  where F(0) = 0 and F(1) = 1

One thing that confuses students: some books count the terms from 1 (the "1st term" is 0), while others count from F(0). In this section, F(n) always means F(0) = 0, F(1) = 1, F(2) = 1, and so on. Check which one your assignment uses before you submit.

Method 1: Fibonacci Series Using A For Loop

The program in Exercise 13 uses a for loop, and it is the method you should use in most assignments. The whole idea is to keep only the last two terms and slide them forward, one step per loop. Here is the flow of the program:

Flowchart of the Fibonacci series program in C using a loop

And here is what the variables look like during the first five passes of the loop:

Pass (i)Prints firstnext = first + secondfirst becomessecond becomes
100 + 1 = 111
211 + 1 = 212
311 + 2 = 323
422 + 3 = 535
533 + 5 = 858

Only three variables are ever used, no matter how many terms you print. That makes this method fast and light on memory.

Method 2: Fibonacci Numbers Up To A Limit, Using A While Loop

A common twist in assignments is "print all Fibonacci numbers less than or equal to N" instead of "print N terms". Since we do not know in advance how many terms that is, a while loop is the natural choice:

#include <stdio.h>

int main(void) {
    long long limit;
    unsigned long long a = 0, b = 1;

    printf("Print Fibonacci numbers up to: ");
    scanf("%lld", &limit);
    if (limit < 0) {
        printf("The limit must be 0 or more.\n");
        return 1;
    }

    printf("Fibonacci numbers up to %lld: ", limit);
    // Stop once the next term is too big (and never go past F(93), the last one that fits)
    for (int k = 0; k <= 93 && a <= (unsigned long long) limit; k++) {
        printf("%llu ", a);
        unsigned long long next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}

Sample run:

Print Fibonacci numbers up to: 100
Fibonacci numbers up to 100: 0 1 1 2 3 5 8 13 21 34 55 89

The loop keeps going as long as the current term is still within the limit. The next term, 144, is bigger than 100, so the loop stops there.

Method 3: Fibonacci Using Recursion

In the recursive approach, a function calls itself. The Fibonacci formula is already recursive, F(n) = F(n-1) + F(n-2), so the code looks almost exactly like the math. This makes it a favorite teaching example. We also count how many times the function runs:

#include <stdio.h>

long long calls = 0;    // Counts how many times fib() runs

// Returns the nth Fibonacci number, where fib(0) = 0 and fib(1) = 1
long long fib(int n) {
    calls++;
    if (n <= 1) {
        return n;                       // Base cases: fib(0) = 0, fib(1) = 1
    }
    return fib(n - 1) + fib(n - 2);     // Recurrence: Fn = Fn-1 + Fn-2
}

int main(void) {
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    if (n < 0) {
        printf("n must be 0 or more.\n");
        return 1;
    }

    printf("F(%d) = %lld\n", n, fib(n));
    printf("fib() was called %lld times\n", calls);
    return 0;
}

Sample runs:

Enter n: 10
F(10) = 55
fib() was called 177 times
Enter n: 30
F(30) = 832040
fib() was called 2692537 times

The answer is right, but look at the call counts. To find F(10), the function ran 177 times. For F(30), it ran almost 2.7 million times. That is because each call makes two more calls, and the same values are worked out again and again. For example, F(30) calculates F(28) twice, F(27) three times, and so on.

This is why the recursive version is fine for small values of n but gets slow fast. On our machine, n = 40 took about a second, and every extra 5 made it roughly 10 times slower. If you need to print the whole series, calling this function in a loop is even worse, because every term starts the work from scratch.

Method 4: Recursion With Memoization

If your assignment requires recursion, you can still make it fast. Memoization means saving each answer the first time you work it out, and reusing it after that. This is the simplest form of dynamic programming:

#include <stdio.h>

#define MAX 94                   // F(93) is the largest that fits in unsigned long long

unsigned long long memo[MAX];    // memo[n] stores F(n) once we know it
int known[MAX];                  // known[n] is 1 after memo[n] is filled in
long long calls = 0;

unsigned long long fib(int n) {
    calls++;
    if (n <= 1) {
        return n;
    }
    if (known[n]) {
        return memo[n];          // Already worked out: reuse it
    }
    memo[n] = fib(n - 1) + fib(n - 2);
    known[n] = 1;
    return memo[n];
}

int main(void) {
    int n;
    printf("Enter n (0 to 93): ");
    scanf("%d", &n);
    if (n < 0 || n >= MAX) {
        printf("n must be from 0 to 93.\n");
        return 1;
    }

    printf("F(%d) = %llu\n", n, fib(n));
    printf("fib() was called %lld times\n", calls);
    return 0;
}

Sample runs:

Enter n (0 to 93): 30
F(30) = 832040
fib() was called 59 times
Enter n (0 to 93): 90
F(90) = 2880067194370816120
fib() was called 179 times

The same F(30) now takes 59 calls instead of about 2.7 million, and even F(90) needs only 179. Each F(k) is calculated once, stored in memo[k], and simply looked up after that.

Method 5: The Direct Formula (Binet's Formula)

What if you want one specific Fibonacci number without working out all the ones before it? There is a direct formula based on the golden ratio (about 1.618). It is a shortcut form of Binet's formula. Counting the terms from 1, where the 1st term is 0, the nth term is:

nth term = round( phi^(n-1) / sqrt(5) ),   where phi = (1 + sqrt(5)) / 2

Here it is in C:

#include <stdio.h>
#include <math.h>   // For sqrt(), pow(), and round()

#define PHI ((1 + sqrt(5)) / 2)   // The golden ratio, about 1.618

int main(void) {
    int n = 10;   // Which term we want (the 1st term is 0)

    // Binet's formula: the nth term is phi^(n-1) / sqrt(5), rounded
    double term = round(pow(PHI, n - 1) / sqrt(5));

    printf("The %dth term is: %.0f\n", n, term);
    return 0;
}

Output:

The 10th term is: 34

Steps Of The Program:

  • First, we include <math.h> for sqrt(), pow(), and round(). On Linux, compile with -lm at the end.
  • Next, we define PHI, the golden ratio, which is the main part of the formula.
  • Then we set which term we want. In this program, n is fixed at 10 instead of being read from the user.
  • Finally, we apply the formula, round the result to the nearest whole number, and print it. The 10th term is 34, which matches the series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

This program uses no loop and no recursion, so it is the fastest method on this page. But it has a catch: double only stores about 15 to 16 significant digits. We compared the formula with the exact values, and it first gives a wrong answer at F(71), where it returns 308061521170130 instead of 308061521170129. In this program, that is the 72nd term (n = 72), since the program counts from 1. So use the formula only for smaller terms, or when an approximate value is fine.

How Big Can Fibonacci Numbers Get In C?

Fibonacci numbers grow very fast, and every C data type has a limit. Here is what happens when you use a plain int for too many terms:

#include <stdio.h>
#include <limits.h>

int main(void) {
    int a = 0, b = 1;
    for (int k = 0; k < 48; k++) {    // Print F(44) to F(47) using int
        if (k >= 44) {
            printf("F(%d) = %d\n", k, a);
        }
        int next = a + b;             // Overflows once the sum passes INT_MAX
        a = b;
        b = next;
    }
    printf("INT_MAX = %d\n", INT_MAX);
    return 0;
}

Output on our machine:

F(44) = 701408733
F(45) = 1134903170
F(46) = 1836311903
F(47) = -1323752223
INT_MAX = 2147483647

F(47) is 2,971,215,073, which is bigger than the largest int, so the sum overflows and prints a negative number. In C, overflowing a signed integer is undefined behavior, so a different compiler or setting might print something else, but it will never be the right answer. Here is how far each type can go:

Data type (typical size)Largest valueLast Fibonacci number that fits
int (32-bit)2,147,483,647F(46) = 1,836,311,903
long long (64-bit)about 9.2 x 1018F(92) = 7,540,113,804,746,346,429
unsigned long long (64-bit)about 1.8 x 1019F(93) = 12,200,160,415,121,876,738

That is why most of the programs above use unsigned long long and %llu. Past F(93), you need a big-number library or your own code that adds numbers digit by digit.

Time And Space Complexity Of Each Method

Time and space complexity tell you how the work and the memory grow as n gets bigger. They help you decide which method to use:

MethodTimeExtra spaceUse it when
For loopO(n)O(1)You need the series, or one term. This is the default choice.
While loop up to a limitO(k), where k is the number of terms printedO(1)The assignment gives a maximum value, not a count.
Plain recursionExponential, often written as O(2n)O(n) for the call stackThe assignment asks for recursion and n is small.
Recursion with memoizationO(n)O(n)Recursion is required, but n can be large.
Binet's formulaO(1), a few math operationsO(1)You need one small term fast, or an estimate.

Because of that exponential growth, plain recursion is fine for small n but should be avoided for large n. (More precisely, it grows like 1.618n, the golden ratio again, but O(2n) is the upper bound most courses use.)

How To Practice C Exercises The Right Way

Solving exercises only helps if you actually struggle with them a little. Here is what works best, based on the bugs we found while testing the programs on this page:

  1. Try first, then look. Give each problem at least 15 minutes before opening the hint, and only read the solution after you have something that runs.
  2. Test the edge cases. Many C bugs only show up with special inputs, like the ones you saw above: 0 in the octal converter, 13! in an int, a huge prime in the prime checker, and a 255 byte in the file copier. Always try 0, 1, a negative number, and a very large number.
  3. Compile with warnings on. Use gcc -Wall -Wextra every time. While learning, also add -fsanitize=address,undefined. It catches buffer overflows and signed integer overflows as they happen, like the strcat() bug in Exercise 7 or 13! in an int. (It may not be available with every Windows compiler.)
  4. Read the error message. C error messages look scary, but they tell you the file, the line, and the problem. Our guide to common errors in C programming explains the ones beginners see most, with fixes.
  5. Predict before you run. Change one thing in a working program, guess the new output, then run it. If your guess was wrong, find out why.
  6. Come back later. A week after solving an exercise, write it again from a blank file without looking. That is when you find out whether you really learned it.

More C Programs To Try Next

Finished all 17? These step-by-step C programs on our blog are a good next challenge:

Conclusion

These 17 exercises go from the basics, like input, conditions, and loops, to harder topics like pointers, dynamic memory, structs, and files. Together, they cover the skills most intro C courses test.

Pick one you have not solved yet, close this page, and write it from scratch. Then come back and compare.

Takeaways:

  • Practice writing C code regularly. It is the only way the language really sticks.
  • Every exercise can be solved in more than one way. Once your program works, try to make it simpler or faster.
  • Always test with edge cases like 0, negative numbers, and very large values. That is where most C bugs hide.
  • Pick data types with their limits in mind. int overflows at 13! and at F(47).
  • For the Fibonacci series, use a loop by default, and add memoization if you must use recursion.

If you want one-on-one help while you practice, consider our live programming tutoring sessions, where a tutor works through problems like these with you. And if a graded assignment has you stuck, our team also offers C programming homework help.

Frequently Asked Questions

1. What are good C programming exercises for beginners?

Start with small programs that use input, if-else, and loops, like checking a prime number, reversing a number, or finding a factorial. Then move on to arrays and strings, such as sorting or counting vowels. After that, practice pointers, malloc(), structs, and files. The 17 exercises on this page follow roughly that order.

2. How do I compile and run a C program?

Save your code in a file ending in .c, then run gcc -Wall -Wextra program.c -o program in a terminal, followed by ./program (or program.exe on Windows). If your code uses <math.h>, add -lm at the end of the gcc command on Linux. If you do not have GCC installed, an online C compiler lets you run code in the browser.

3. Why does scanf() need an & in C?

scanf() has to store the value it reads in your variable, so it needs the variable's address, not a copy of its value. &age gives it the address of age. Array names, like a string char name[50], already act as addresses, so they do not need the &.

4. Why does my Fibonacci program in C print negative numbers?

Your variables are probably int. A 32-bit int can only hold values up to 2,147,483,647, so F(47) overflows and shows up as a negative number. Use unsigned long long with %llu in printf(), which works up to F(93).

5. Is recursion or a loop better for the Fibonacci series in C?

A loop is better. It takes O(n) time and constant memory. Plain recursion recalculates the same values again and again, so its running time grows exponentially: F(30) alone needs about 2.7 million function calls. If your assignment requires recursion, add memoization, which brings it down to O(n).

6. Does the Fibonacci series start with 0 or 1?

Most computer science courses and textbooks start with 0 and 1, so the series is 0, 1, 1, 2, 3, 5, 8, and so on. Some older books start with 1 and 1 instead. Both follow the same rule, so just check which starting point your assignment expects.