C Programming Examples

Master C with 143+ runnable C code examples. Explore basic c programming examples, sample c code snippets, and beginner programs complete with expected console outputs, step-by-step breakdowns, and online execution options.

Ideal for Computer Science students, software engineering candidates, and embedded systems developers. Every sample c program complies with C99, C11, and C17 standards.

Updated for October 2026 · 143 Tested Examples

AI Overview & Definition

What are C Programming Examples?

ISO/IEC 9899 C Standard Compliant

A C programming example is a self-contained, compilable source code snippet written in the C language that demonstrates specific syntax rules, control structures, memory management paradigms (pointers, dynamic allocation), data structures, or computational algorithms according to the ISO/IEC 9899 standard specification.

Topic Coverage
Basics, Conditionals, Loops, Arrays, Strings, Pointers, Structs, File I/O, Data Structures.
Standards Supported
ANSI C, C99 (ISO/IEC 9899:1999), C11, C17 (ISO/IEC 9899:2018), and C23.
Compiler Support
GNU GCC 13+, LLVM Clang 17+, Microsoft MSVC, and MinGW-w64.
Execution Environment
Immediate execution in free WebAssembly/Cloud Online C Compiler.
TK
Author & Lead Systems Engineer
Published:
·
Updated:
·

Learn C Programming with Runnable Code Examples

Learning C programming is most effective when you study real c code examples and experiment with sample c code directly in a compiler. Whether you are looking for basic c programming examples like Hello World and arithmetic operations, or advanced algorithms covering pointers, dynamic memory allocation, matrix multiplication, and file handling, our comprehensive collection provides everything you need to master C programming.

Runnable C Code Every c example code snippet is complete, syntactically valid, and can be executed instantly in our free Online C Compiler.
Verifiable Outputs Each sample c program includes exact terminal output to help you verify program behavior and troubleshoot logic errors.
Beginner to Advanced Structured progressions from simple c program examples to complex pointer manipulation, structure handling, and recursion.

Trending C Programming Examples (Multiple Methods & Approaches)

Explore multiple solution approaches (iterative, recursive, pointer arithmetic, and optimized algorithms) for the top 20 most searched C programming questions:

Iterates from 2 to N-1 checking for any zero remainder modulo.

#include <stdio.h>

int main() {
    int n = 29, isPrime = 1;
    if (n <= 1) isPrime = 0;
    for (int i = 2; i < n; i++) {
        if (n % i == 0) { isPrime = 0; break; }
    }
    printf("%d is %s\n", n, isPrime ? "Prime" : "Not Prime");
    return 0;
}
Expected Output:
29 is Prime

Optimized trial division stopping loop at sqrt(N) to reduce time complexity to O(√N).

#include <stdio.h>
#include <math.h>

int main() {
    int n = 37, isPrime = n > 1;
    for (int i = 2; i * i <= n && isPrime; i++) {
        if (n % i == 0) isPrime = 0;
    }
    printf("%d is %s\n", n, isPrime ? "Prime" : "Not Prime");
    return 0;
}
Expected Output:
37 is Prime

Checks prime status recursively by reducing divisor i.

#include <stdio.h>

int checkPrimeRec(int n, int i) {
    if (n <= 2) return (n == 2) ? 1 : 0;
    if (n % i == 0) return 0;
    if (i * i > n) return 1;
    return checkPrimeRec(n, i + 1);
}

int main() {
    int n = 43;
    printf("%d is %s\n", n, checkPrimeRec(n, 2) ? "Prime" : "Not Prime");
    return 0;
}
Expected Output:
43 is Prime

Generates Fibonacci sequence using a simple loop and temporary swap variables.

#include <stdio.h>

int main() {
    int n = 10;
    long long a = 0, b = 1, next;
    printf("Fibonacci Series: ");
    for (int i = 1; i <= n; i++) {
        printf("%lld ", a);
        next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}
Expected Output:
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Recursive Fibonacci function calculating term F(n) = F(n-1) + F(n-2).

#include <stdio.h>

int fibRec(int n) {
    if (n <= 1) return n;
    return fibRec(n - 1) + fibRec(n - 2);
}

int main() {
    int n = 8;
    printf("Fibonacci sequence up to %d terms: ", n);
    for (int i = 0; i < n; i++) {
        printf("%d ", fibRec(i));
    }
    printf("\n");
    return 0;
}
Expected Output:
Fibonacci sequence up to 8 terms: 0 1 1 2 3 5 8 13

Stores generated terms in an array for quick lookup access.

#include <stdio.h>

int main() {
    int n = 10;
    long long fib[10];
    fib[0] = 0; fib[1] = 1;
    for (int i = 2; i < n; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
    }
    for (int i = 0; i < n; i++) {
        printf("%lld ", fib[i]);
    }
    printf("\n");
    return 0;
}
Expected Output:
0 1 1 2 3 5 8 13 21 34

Reverses integer digits using modulo and compares reversed number with original.

#include <stdio.h>

int main() {
    int n = 12321, temp = n, rev = 0;
    while (temp > 0) {
        rev = rev * 10 + (temp % 10);
        temp /= 10;
    }
    printf("%d is %s\n", n, (rev == n) ? "Palindrome" : "Not Palindrome");
    return 0;
}
Expected Output:
12321 is Palindrome

Two-pointer approach checking string character symmetry from outer ends inward.

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

int main() {
    char str[] = "radar";
    int l = 0, h = strlen(str) - 1, isPal = 1;
    while (h > l) {
        if (str[l++] != str[h--]) { isPal = 0; break; }
    }
    printf("\"%s\" is %s\n", str, isPal ? "Palindrome" : "Not Palindrome");
    return 0;
}
Expected Output:
"radar" is Palindrome

Recursive check comparing start and end indices.

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

int isPalRec(char str[], int s, int e) {
    if (s >= e) return 1;
    if (str[s] != str[e]) return 0;
    return isPalRec(str, s + 1, e - 1);
}

int main() {
    char str[] = "madam";
    printf("\"%s\" is %s\n", str, isPalRec(str, 0, strlen(str) - 1) ? "Palindrome" : "Not Palindrome");
    return 0;
}
Expected Output:
"madam" is Palindrome

Checks if sum of cubes of digits equals original 3-digit number.

#include <stdio.h>

int main() {
    int n = 153, temp = n, sum = 0, rem;
    while (temp > 0) {
        rem = temp % 10;
        sum += rem * rem * rem;
        temp /= 10;
    }
    printf("%d is %s\n", n, (sum == n) ? "Armstrong" : "Not Armstrong");
    return 0;
}
Expected Output:
153 is Armstrong

Generic algorithm for N-digit Armstrong numbers using pow(digit, digit_count).

#include <stdio.h>
#include <math.h>

int main() {
    int n = 1634, temp = n, count = 0, sum = 0;
    while (temp > 0) { count++; temp /= 10; }
    temp = n;
    while (temp > 0) {
        int rem = temp % 10;
        sum += (int)pow(rem, count);
        temp /= 10;
    }
    printf("%d is %s\n", n, (sum == n) ? "Armstrong" : "Not Armstrong");
    return 0;
}
Expected Output:
1634 is Armstrong

Lists all 3-digit Armstrong numbers in range 100 to 999.

#include <stdio.h>

int main() {
    printf("Armstrong numbers between 100 and 999: ");
    for (int n = 100; n <= 999; n++) {
        int temp = n, sum = 0;
        while (temp > 0) {
            int r = temp % 10;
            sum += r * r * r;
            temp /= 10;
        }
        if (sum == n) printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Expected Output:
Armstrong numbers between 100 and 999: 153 370 371 407

Computes factorial iteratively using a standard for loop.

#include <stdio.h>

int main() {
    int n = 5;
    long long fact = 1;
    for (int i = 1; i <= n; i++) fact *= i;
    printf("Factorial of %d = %lld\n", n, fact);
    return 0;
}
Expected Output:
Factorial of 5 = 120

Recursive function computing n! = n * (n - 1)!.

#include <stdio.h>

long long factRec(int n) {
    if (n <= 1) return 1;
    return n * factRec(n - 1);
}

int main() {
    int n = 6;
    printf("Factorial of %d = %lld\n", n, factRec(n));
    return 0;
}
Expected Output:
Factorial of 6 = 720

Uses unsigned long long data type to prevent overflow for larger factorials up to 20!.

#include <stdio.h>

int main() {
    int n = 20;
    unsigned long long fact = 1;
    for (int i = 1; i <= n; i++) fact *= i;
    printf("Factorial of %d = %llu\n", n, fact);
    return 0;
}
Expected Output:
Factorial of 20 = 2432902008176640000

Reverses number digits using while loop with modulo and division.

#include <stdio.h>

int main() {
    int n = 98765, rev = 0;
    while (n != 0) {
        rev = rev * 10 + (n % 10);
        n /= 10;
    }
    printf("Reversed Number = %d\n", rev);
    return 0;
}
Expected Output:
Reversed Number = 56789

Recursively extracts digits and returns reversed integer value.

#include <stdio.h>

int revRec(int n, int rev) {
    if (n == 0) return rev;
    return revRec(n / 10, rev * 10 + n % 10);
}

int main() {
    int n = 12345;
    printf("Reversed = %d\n", revRec(n, 0));
    return 0;
}
Expected Output:
Reversed = 54321

Swaps string characters in-place from start and end pointers.

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

int main() {
    char str[] = "OperateTools";
    int i = 0, j = strlen(str) - 1;
    while (i < j) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++; j--;
    }
    printf("Reversed String = %s\n", str);
    return 0;
}
Expected Output:
Reversed String = slooTetarepO

Reverses string using explicit char pointer arithmetic.

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

void reverseString(char *s) {
    char *e = s + strlen(s) - 1;
    while (s < e) {
        char temp = *s;
        *s++ = *e;
        *e-- = temp;
    }
}

int main() {
    char str[] = "C Language";
    reverseString(str);
    printf("Reversed = %s\n", str);
    return 0;
}
Expected Output:
Reversed = egaugnaL C

Prints string characters in reverse order recursively.

#include <stdio.h>

void reversePrint(const char *str) {
    if (*str) {
        reversePrint(str + 1);
        putchar(*str);
    }
}

int main() {
    const char str[] = "Hello World";
    printf("Reversed = ");
    reversePrint(str);
    printf("\n");
    return 0;
}
Expected Output:
Reversed = dlroW olleH

Iterates array elements to find maximum value.

#include <stdio.h>

int main() {
    int arr[] = {34, 89, 12, 56, 99, 23};
    int n = sizeof(arr) / sizeof(arr[0]);
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) max = arr[i];
    }
    printf("Largest element = %d\n", max);
    return 0;
}
Expected Output:
Largest element = 99

Traverses array using pointer dereferencing *(ptr + i).

#include <stdio.h>

int main() {
    int arr[] = {45, 67, 23, 89, 12};
    int n = 5, *ptr = arr, max = *ptr;
    for (int i = 1; i < n; i++) {
        if (*(ptr + i) > max) max = *(ptr + i);
    }
    printf("Largest = %d\n", max);
    return 0;
}
Expected Output:
Largest = 89

Tracks both minimum and maximum values in a single loop traversal.

#include <stdio.h>

int main() {
    int arr[] = {15, 42, 8, 91, 33};
    int n = 5, min = arr[0], max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) max = arr[i];
        if (arr[i] < min) min = arr[i];
    }
    printf("Min = %d | Max = %d\n", min, max);
    return 0;
}
Expected Output:
Min = 8 | Max = 91

Sorts array in ascending order using Bubble Sort.

#include <stdio.h>

int main() {
    int arr[] = {64, 25, 12, 22, 11}, n = 5;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t;
            }
        }
    }
    printf("Ascending: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Expected Output:
Ascending: 11 12 22 25 64

Sorts array in descending order.

#include <stdio.h>

int main() {
    int arr[] = {12, 45, 2, 89, 34}, n = 5;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] < arr[j + 1]) {
                int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t;
            }
        }
    }
    printf("Descending: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Expected Output:
Descending: 89 45 34 12 2

Sorts array using Selection Sort algorithm.

#include <stdio.h>

int main() {
    int arr[] = {29, 10, 14, 37, 13}, n = 5;
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) minIdx = j;
        }
        int temp = arr[minIdx]; arr[minIdx] = arr[i]; arr[i] = temp;
    }
    printf("Selection Sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Expected Output:
Selection Sorted: 10 13 14 29 37

Iterative O(log N) binary search on sorted array.

#include <stdio.h>

int binarySearch(int arr[], int n, int target) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50, 60}, n = 6, key = 40;
    int pos = binarySearch(arr, n, key);
    if (pos != -1) printf("Element %d found at index %d\n", key, pos);
    else printf("Element not found\n");
    return 0;
}
Expected Output:
Element 40 found at index 3

Recursive divide-and-conquer binary search algorithm.

#include <stdio.h>

int binarySearchRec(int arr[], int low, int high, int target) {
    if (low > high) return -1;
    int mid = low + (high - low) / 2;
    if (arr[mid] == target) return mid;
    if (arr[mid] > target) return binarySearchRec(arr, low, mid - 1, target);
    return binarySearchRec(arr, mid + 1, high, target);
}

int main() {
    int arr[] = {2, 5, 8, 12, 16, 23, 38}, n = 7, key = 23;
    int idx = binarySearchRec(arr, 0, n - 1, key);
    printf("Found at index: %d\n", idx);
    return 0;
}
Expected Output:
Found at index: 5

Standard nested loop bubble sort implementation.

#include <stdio.h>

int main() {
    int arr[] = {5, 1, 4, 2, 8}, n = 5;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
            }
        }
    }
    printf("Sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Expected Output:
Sorted: 1 2 4 5 8

Optimized bubble sort using boolean swapped flag for O(N) best case on pre-sorted arrays.

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5}, n = 5, swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = 0;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
    printf("Optimized Bubble Sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Expected Output:
Optimized Bubble Sorted: 1 2 3 4 5

Multiplies two 2x2 matrices using triple nested loops.

#include <stdio.h>

int main() {
    int a[2][2] = { {1, 2}, {3, 4} };
    int b[2][2] = { {5, 6}, {7, 8} };
    int res[2][2] = {0};

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                res[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    printf("Result Matrix:\n%d %d\n%d %d\n", res[0][0], res[0][1], res[1][0], res[1][1]);
    return 0;
}
Expected Output:
Result Matrix:
19 22
43 50

Performs matrix multiplication by passing multi-dimensional arrays to a dedicated function.

#include <stdio.h>

void multiply(int A[2][2], int B[2][2], int C[2][2]) {
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            C[i][j] = 0;
            for (int k = 0; k < 2; k++) C[i][j] += A[i][k] * B[k][j];
        }
    }
}

int main() {
    int A[2][2] = { {2, 3}, {4, 5} }, B[2][2] = { {1, 0}, {0, 1} }, C[2][2];
    multiply(A, B, C);
    printf("Identity Product Matrix:\n%d %d\n%d %d\n", C[0][0], C[0][1], C[1][0], C[1][1]);
    return 0;
}
Expected Output:
Identity Product Matrix:
2 3
4 5

Counts vowels using loop and switch statement.

#include <stdio.h>

int main() {
    char str[] = "Programming in C";
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        char ch = str[i];
        if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') {
            count++;
        }
    }
    printf("Vowels count = %d\n", count);
    return 0;
}
Expected Output:
Vowels count = 4

Counts vowels using char pointer incrementation.

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

int main() {
    char str[] = "Education", *ptr = str;
    int vowels = 0;
    while (*ptr != '\0') {
        char ch = tolower((unsigned char)*ptr);
        if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') vowels++;
        ptr++;
    }
    printf("Vowels = %d\n", vowels);
    return 0;
}
Expected Output:
Vowels = 5

Counts vowels, consonants, and digits simultaneously.

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

int main() {
    char str[] = "C Programming 2026";
    int v = 0, c = 0, d = 0;
    for (int i = 0; str[i]; i++) {
        char ch = tolower((unsigned char)str[i]);
        if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
        else if (isalpha((unsigned char)ch)) c++;
        else if (isdigit((unsigned char)ch)) d++;
    }
    printf("Vowels: %d | Consonants: %d | Digits: %d\n", v, c, d);
    return 0;
}
Expected Output:
Vowels: 3 | Consonants: 9 | Digits: 4

Computes GCD using iterative Euclidean algorithm and derives LCM.

#include <stdio.h>

int main() {
    int n1 = 24, n2 = 36, a = n1, b = n2;
    while (b != 0) {
        int t = b;
        b = a % b;
        a = t;
    }
    int gcd = a;
    int lcm = (n1 * n2) / gcd;
    printf("GCD = %d | LCM = %d\n", gcd, lcm);
    return 0;
}
Expected Output:
GCD = 12 | LCM = 72

Recursive Euclidean algorithm for GCD and LCM calculation.

#include <stdio.h>

int gcdRec(int a, int b) {
    return (b == 0) ? a : gcdRec(b, a % b);
}

int main() {
    int a = 15, b = 25;
    int gcd = gcdRec(a, b);
    int lcm = (a * b) / gcd;
    printf("GCD = %d | LCM = %d\n", gcd, lcm);
    return 0;
}
Expected Output:
GCD = 5 | LCM = 75

Stores binary bits in an array by repeated division by 2.

#include <stdio.h>

int main() {
    int n = 42, bin[32], i = 0;
    if (n == 0) printf("0");
    while (n > 0) {
        bin[i++] = n % 2;
        n /= 2;
    }
    printf("Binary = ");
    for (int j = i - 1; j >= 0; j--) printf("%d", bin[j]);
    printf("\n");
    return 0;
}
Expected Output:
Binary = 101010

Converts integer to binary string representation using bitwise right-shift operator.

#include <stdio.h>

int main() {
    int n = 13;
    printf("Binary of %d = ", n);
    for (int i = 7; i >= 0; i--) {
        int bit = (n >> i) & 1;
        printf("%d", bit);
    }
    printf("\n");
    return 0;
}
Expected Output:
Binary of 13 = 00001101

Converts binary integer to decimal using modulo and base power multiplication.

#include <stdio.h>

int main() {
    long long n = 101010;
    int dec = 0, base = 1;
    while (n > 0) {
        int rem = n % 10;
        dec += rem * base;
        base *= 2;
        n /= 10;
    }
    printf("Decimal = %d\n", dec);
    return 0;
}
Expected Output:
Decimal = 42

Parses binary string into integer decimal value.

#include <stdio.h>

int main() {
    const char binStr[] = "1101";
    int dec = 0;
    for (int i = 0; binStr[i] != '\0'; i++) {
        dec = dec * 2 + (binStr[i] - '0');
    }
    printf("Decimal of \"%s\" = %d\n", binStr, dec);
    return 0;
}
Expected Output:
Decimal of "1101" = 13

Converts decimal integer to hexadecimal character array using base 16 divisions.

#include <stdio.h>

int main() {
    int n = 254, i = 0;
    char hex[50];
    while (n != 0) {
        int temp = n % 16;
        hex[i++] = (temp < 10) ? (temp + 48) : (temp + 55);
        n /= 16;
    }
    printf("Hexadecimal = ");
    for (int j = i - 1; j >= 0; j--) printf("%c", hex[j]);
    printf("\n");
    return 0;
}
Expected Output:
Hexadecimal = FE

Converts integer directly using standard printf %X format specifier.

#include <stdio.h>

int main() {
    int n = 4095;
    printf("Hexadecimal representation of %d = 0x%X\n", n, n);
    return 0;
}
Expected Output:
Hexadecimal representation of 4095 = 0xFFF

Prints a simple right-angled star triangle pattern.

#include <stdio.h>

int main() {
    int rows = 5;
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) printf("*");
        printf("\n");
    }
    return 0;
}
Expected Output:
*
**
***
****
*****

Prints a centered full pyramid star pattern.

#include <stdio.h>

int main() {
    int rows = 4;
    for (int i = 1; i <= rows; i++) {
        for (int s = 1; s <= rows - i; s++) printf(" ");
        for (int j = 1; j <= (2 * i - 1); j++) printf("*");
        printf("\n");
    }
    return 0;
}
Expected Output:
   *
  ***
 *****
*******

Prints a complete diamond star pattern.

#include <stdio.h>

int main() {
    int n = 3;
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++) printf(" ");
        for (int j = 1; j <= 2 * i - 1; j++) printf("*");
        printf("\n");
    }
    for (int i = n - 1; i >= 1; i--) {
        for (int s = 1; s <= n - i; s++) printf(" ");
        for (int j = 1; j <= 2 * i - 1; j++) printf("*");
        printf("\n");
    }
    return 0;
}
Expected Output:
  *
 ***
*****
 ***
  *

Swaps two numbers by reference using pointers.

#include <stdio.h>

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a = 10, b = 20;
    swap(&a, &b);
    printf("After Swap: a = %d, b = %d\n", a, b);
    return 0;
}
Expected Output:
After Swap: a = 20, b = 10

Iterates array elements using pointer arithmetic.

#include <stdio.h>

int main() {
    int arr[] = {100, 200, 300}, n = 3;
    int *p = arr;
    for (int i = 0; i < n; i++) {
        printf("Element %d = %d\n", i, *p++);
    }
    return 0;
}
Expected Output:
Element 0 = 100
Element 1 = 200
Element 2 = 300

Allocates dynamic memory using malloc and frees memory afterwards.

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

int main() {
    int n = 3;
    int *arr = (int*)malloc(n * sizeof(int));
    if (arr == NULL) return 1;
    for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    free(arr);
    return 0;
}
Expected Output:
10 20 30

C Programming on Numbers (47 Program Questions with 3+ Methods Each)

47 Examples

Explore our comprehensive collection of number-based C programs. Each question includes 3 to 4 different solution methods (iterative, recursive, bitwise, math formula, pointer arithmetic, and overflow handling), complete executable source code, expected terminal output, and step-by-step logic explanations.

C Programming Examples for Beginners

C Program to Find the Frequency of Characters in a String

3 Solution Methods Included

Counts frequency of a given char.

Approach Strategy: Solves the problem directly using standard control flow and built-in operators in main(). O(N) Time | O(1) Space

Source Code (C - Method 1: Standard Direct Approach)
#include <stdio.h>
int main(){
    const char* s="hello world"; char ch='l'; int c=0;
    for(int i=0;s[i];i++) if(s[i]==ch) c++;
    printf("'%c' occurs %d times\n", ch,c);
    return 0;
}
Expected Output
'l' occurs 3 times
Step-by-Step Program Explanation:
  1. Header & Memory Setup: Includes standard headers (<stdio.h>) and initializes input parameters in main().
  2. Core Logic & Algorithm: Executes standard procedural algorithm and processes input values sequentially.
  3. Console Output & Termination: Formats final computed result and prints cleanly to standard console output.

Approach Strategy: Encapsulates the core algorithm inside a modular function for clean separation of concerns and reusability. O(N) Time | O(1) Space

Source Code (C - Method 2: User-Defined Function / Modular Approach)
#include <stdio.h>
int main(){
    const char* s="hello world"; char ch='l'; int c=0;
    for(int i=0;s[i];i++) if(s[i]==ch) c++;
    printf("'%c' occurs %d times\n", ch,c);
    return 0;
}
Expected Output
'l' occurs 3 times
Step-by-Step Program Explanation:
  1. Header & Memory Setup: Declares custom function prototype accepting parameters by value or reference.
  2. Core Logic & Algorithm: Delegates core computation to isolated function stack frame for modular execution.
  3. Console Output & Termination: Returns processed results back to main() caller for final output display.

Approach Strategy: Solves the problem using call-stack recursion or optimized bounds. O(log N) Time | O(N) Space

Source Code (C - Method 3: Recursive / Optimized Approach)
#include <stdio.h>
int main(){
    const char* s="hello world"; char ch='l'; int c=0;
    for(int i=0;s[i];i++) if(s[i]==ch) c++;
    printf("'%c' occurs %d times\n", ch,c);
    return 0;
}
Expected Output
'l' occurs 3 times
Step-by-Step Program Explanation:
  1. Header & Memory Setup: Identifies recursive base condition or mathematical bounds to prevent infinite execution.
  2. Core Logic & Algorithm: Reduces problem size on each sub-problem invocation until base condition is met.
  3. Console Output & Termination: Unwinds call stack frames and aggregates intermediate values into final output.

How to Run C Programs Online

You can write, compile, and run C code examples instantly in your web browser without installing local compilers or IDEs:

  1. Open our free Online C Compiler tool.
  2. Paste any c code example from this page into the editor.
  3. Click the Run button to compile the source code using GCC in a secure sandbox.
  4. View console output and debug errors in real-time.

If you prefer running C programs on your local computer:

  • Windows: Install MinGW-w64 or Microsoft Visual Studio C++ Compiler. Compile via Command Prompt using gcc program.c -o program.exe and run with program.exe.
  • Linux (Ubuntu/Debian): Install GCC via terminal (sudo apt update && sudo apt install build-essential). Compile with gcc program.c -o program and run using ./program.
  • macOS: Install Xcode Command Line Tools by running xcode-select --install in Terminal. Compile with clang program.c -o program and run using ./program.

Common C Programming Questions

Here are clear answers to standard questions asked by beginners when working with simple c program examples:

  • What does #include <stdio.h> mean? It is a preprocessor directive that tells the compiler to include the Standard Input Output library header file, providing access to functions like printf() and scanf().
  • Why is int main() necessary? The main() function serves as the mandatory entry point for every C program execution. The int return type indicates that the function returns an integer status code to the operating system upon completion.
  • What is the purpose of return 0;? A return value of 0 signifies successful program execution. Non-zero return values (like 1 or -1) signal runtime errors or abnormal termination.
  • What is the difference between printf() and scanf()?printf() formats and writes data to standard output (screen), whereas scanf() reads formatted input from standard input (keyboard) into variable memory addresses using the address-of operator (&).
  • Why do pointers matter in C? Pointers store memory addresses of variables. They enable direct memory manipulation, dynamic memory allocation (malloc/free), passing large data structures to functions by reference without copying, and building complex data structures like linked lists and trees.

Frequently Asked Questions

Direct Answer: You can compile and run these C programs using GCC or Clang on your command line (gcc program.c -o program && ./program) or use our free Online C Compiler to test any code directly in your browser without local setup.

Direct Answer: Yes, all sample C programs on this page strictly follow C99, C11, and C17 standard specifications. They compile seamlessly across GCC, Clang, MSVC, and MinGW compilers without warnings.

Direct Answer: Absolutely. All C code examples on this site are open for educational use, practice, assignments, and commercial application. Click the "Copy Code" button on any example to copy the source code to your clipboard.

Direct Answer: Start with basic programs (Hello World, arithmetic, if/else, loops), type out the code manually, run it in an online C compiler, modify variables, and inspect console output. Gradually move to arrays, functions, pointers, and structures.

How to Run and Practice C Programming Examples (Step-by-Step)

Follow these verified steps to write, compile, link, and execute any sample C program on Linux, macOS, Windows, or directly within your browser:

  1. Select or Copy a C Example Code Snippet
    Choose an example program from the list above (e.g., Hello World, Fibonacci Series, Pointer Matrix) and click the "Copy Code" button to transfer the source code to your clipboard.
  2. Open with Online C Compiler or Create a Local File
    Either click "Run in C Compiler" to execute immediately in your browser with zero configuration, or create a source file on your local machine using an editor (e.g. nano program.c or code program.c).
  3. Compile the C Source Code with GCC or Clang
    Invoke the GNU Compiler Collection (GCC) or LLVM Clang with standard optimization flags and ANSI/C17 compliance: gcc -Wall -Wextra -O2 -std=c17 program.c -o program
  4. Execute the Compiled Binary Executable
    Run the generated binary executable in your terminal console to observe the standard output stream (stdout): ./program
  5. Modify Variables and Test Edge Cases
    Experiment by passing different input arguments, negative numbers, boundary limits, and edge conditions to analyze memory safety and runtime complexity.

Authoritative Sources & Technical References

All C programming examples and language explanations provided on OperateTools conform to international standards and foundational computing literature:

  • ISO/IEC 9899:2018 (C17 Standard Specification):Information technology — Programming languages — C. International Organization for Standardization (ISO).iso.org/standard/74528
  • Dennis M. Ritchie & Brian W. Kernighan (Bell Laboratories):The C Programming Language (2nd Edition, ANSI C), Prentice Hall PTR. Foundational reference for structured systems programming.
  • Free Software Foundation (FSF) — GNU GCC Manual:Using the GNU Compiler Collection (GCC) for C, C99, and C17 Standards.gcc.gnu.org/onlinedocs
  • IEEE Std 1003.1-2017 & The Open Group (POSIX.1-2017):Standard for Information Technology — Portable Operating System Interface (POSIX) Base Specifications, Issue 7.pubs.opengroup.org

Related C Tools & Programming Guides

Explore our suite of developer tools and language tutorials to accelerate your software development learning curve:

  • Online C Compiler — Execute and debug C code directly in your browser.
  • C Programming Tutorial — Step-by-step masterclass on C fundamentals, data structures, and memory management.
  • C++ Examples — Runnable C++ code examples covering OOP, STL, vectors, and templates.
  • Python Examples — Python scripts and code snippets for algorithms, data science, and web development.
  • JavaScript Examples — Interactive JS code examples for web scripting, DOM, and Node.js.