Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 47

50 C Programs with Output – Basic C Programming Examples

In this lesson: Top 50 C programs with code & output: prime, Fibonacci, factorial, palindrome, patterns, arrays & strings. Run each in the free online compiler.

Why practice + how the compiler works

You cannot learn C by only reading — you learn by writing and running programs. This page gives you 50 important C programs with full solutions: complete code, sample input, and output. Each one also has a Try it Yourself button that opens a real C compiler right on this page, so you can run the program, change the input, and see the result instantly.

💡 How to use: read the code, look at the output, then click Try it Yourself ▶. The compiler opens with the code already loaded — press Run, type your input at the bottom, and experiment.

Every program uses scanf() so you enter the values. Try your own numbers each time — that is how the logic really sticks.

All 50 programs at a glance

Jump straight to any program. Start with the beginner groups, then move to arrays and strings.

Number Programs

1. Check Even or Odd

#include <stdio.h>
int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n % 2 == 0) printf("%d is Even\n", n);
    else printf("%d is Odd\n", n);
    return 0;
}
Enter a number: 7 7 is Odd

Uses % 2: remainder 0 means even, else odd.

2. Check Prime Number

#include <stdio.h>
int main() {
    int n, i, isPrime = 1;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n <= 1) isPrime = 0;
    for (i = 2; i <= n / 2; i++)
        if (n % i == 0) { isPrime = 0; break; }
    if (isPrime) printf("%d is Prime\n", n);
    else printf("%d is Not Prime\n", n);
    return 0;
}
Enter a number: 13 13 is Prime

A prime has no divisor except 1 and itself, so test 2 to n/2.

3. Factorial of a Number

#include <stdio.h>
int main() {
    int n, i;
    long long fact = 1;
    printf("Enter a number: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) fact *= i;
    printf("Factorial of %d = %lld\n", n, fact);
    return 0;
}
Enter a number: 5 Factorial of 5 = 120

Multiplies 1 to n. long long because factorials grow fast.

4. Fibonacci Series

#include <stdio.h>
int main() {
    int n, i, a = 0, b = 1, c;
    printf("Enter terms: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        printf("%d ", a);
        c = a + b; a = b; b = c;
    }
    printf("\n");
    return 0;
}
Enter terms: 7 0 1 1 2 3 5 8

Each term is the sum of the previous two, from 0 and 1.

5. Reverse a Number

#include <stdio.h>
int main() {
    int n, rev = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    while (n != 0) {
        rev = rev * 10 + n % 10;
        n = n / 10;
    }
    printf("Reversed = %d\n", rev);
    return 0;
}
Enter a number: 1234 Reversed = 4321

% 10 gets the last digit; rev*10 + digit builds the reverse.

6. Sum of Digits

#include <stdio.h>
int main() {
    int n, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    while (n != 0) { sum += n % 10; n = n / 10; }
    printf("Sum of digits = %d\n", sum);
    return 0;
}
Enter a number: 456 Sum of digits = 15

Adds each digit via % 10, then removes it via / 10.

7. Check Palindrome Number

#include <stdio.h>
int main() {
    int n, rev = 0, temp;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    while (temp != 0) { rev = rev * 10 + temp % 10; temp /= 10; }
    if (n == rev) printf("%d is a Palindrome\n", n);
    else printf("%d is Not a Palindrome\n", n);
    return 0;
}
Enter a number: 121 121 is a Palindrome

Reverses the number and compares with the original.

8. Check Armstrong Number

#include <stdio.h>
int main() {
    int n, temp, rem, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    while (temp != 0) { rem = temp % 10; sum += rem*rem*rem; temp /= 10; }
    if (n == sum) printf("%d is Armstrong\n", n);
    else printf("%d is Not Armstrong\n", n);
    return 0;
}
Enter a number: 153 153 is Armstrong

For 3 digits, sums the cubes: 1³+5³+3³ = 153.

9. Largest of Three Numbers

#include <stdio.h>
int main() {
    int a, b, c;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    if (a >= b && a >= c) printf("Largest = %d\n", a);
    else if (b >= c) printf("Largest = %d\n", b);
    else printf("Largest = %d\n", c);
    return 0;
}
Enter three numbers: 12 45 30 Largest = 45

Compares each number against the others with if-else.

10. Multiplication Table

#include <stdio.h>
int main() {
    int n, i;
    printf("Enter a number: ");
    scanf("%d", &n);
    for (i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);
    return 0;
}
Enter a number: 5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50

A loop from 1 to 10 printing n times i.

11. Decimal to Binary

#include <stdio.h>
int main() {
    int n, bin[32], i = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    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;
}
Enter a number: 10 Binary = 1010

Divides by 2, stores remainders, prints them in reverse.

12. GCD and LCM

#include <stdio.h>
int main() {
    int a, b, x, y, gcd, lcm;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    x = a; y = b;
    while (y != 0) { int t = y; y = x % y; x = t; }
    gcd = x; lcm = (a * b) / gcd;
    printf("GCD = %d, LCM = %d\n", gcd, lcm);
    return 0;
}
Enter two numbers: 12 18 GCD = 6, LCM = 36

Euclidean algorithm for GCD, then LCM = (a×b)/GCD.

Pattern Programs

13. Right-Angled Star Triangle

#include <stdio.h>
int main() {
    int rows, i, j;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= i; j++) printf("* ");
        printf("\n");
    }
    return 0;
}
Enter rows: 4 * * * * * * * * * *

Row i prints i stars using nested loops.

14. Inverted Star Triangle

#include <stdio.h>
int main() {
    int rows, i, j;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = rows; i >= 1; i--) {
        for (j = 1; j <= i; j++) printf("* ");
        printf("\n");
    }
    return 0;
}
Enter rows: 4 * * * * * * * * * *

Outer loop counts down, so each row has fewer stars.

15. Pyramid of Stars

#include <stdio.h>
int main() {
    int rows, i, j;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= rows - i; j++) printf(" ");
        for (j = 1; j <= 2*i - 1; j++) printf("*");
        printf("\n");
    }
    return 0;
}
Enter rows: 4 * *** ***** *******

Prints spaces then (2i-1) stars to center each row.

16. Number Triangle

#include <stdio.h>
int main() {
    int rows, i, j;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= i; j++) printf("%d", j);
        printf("\n");
    }
    return 0;
}
Enter rows: 4 1 12 123 1234

Inner loop prints 1 to i on each row.

17. Floyd's Triangle

#include <stdio.h>
int main() {
    int rows, i, j, num = 1;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= i; j++) printf("%d ", num++);
        printf("\n");
    }
    return 0;
}
Enter rows: 4 1 2 3 4 5 6 7 8 9 10

A single counter keeps rising across all rows.

18. Pascal's Triangle

#include <stdio.h>
int main() {
    int rows, i, j, c = 1;
    printf("Enter rows: ");
    scanf("%d", &rows);
    for (i = 0; i < rows; i++) {
        c = 1;
        for (j = 0; j <= i; j++) {
            printf("%d ", c);
            c = c * (i - j) / (j + 1);
        }
        printf("\n");
    }
    return 0;
}
Enter rows: 4 1 1 1 1 2 1 1 3 3 1

Each value uses the binomial coefficient formula.

19. Diamond Pattern

#include <stdio.h>
int main() {
    int n, i, j;
    printf("Enter rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= n - i; j++) printf(" ");
        for (j = 1; j <= 2*i - 1; j++) printf("*");
        printf("\n");
    }
    for (i = n - 1; i >= 1; i--) {
        for (j = 1; j <= n - i; j++) printf(" ");
        for (j = 1; j <= 2*i - 1; j++) printf("*");
        printf("\n");
    }
    return 0;
}
Enter rows: 3 * *** ***** *** *

An upper pyramid plus an inverted one below it.

20. Hollow Square Pattern

#include <stdio.h>
int main() {
    int n, i, j;
    printf("Enter size: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= n; j++) {
            if (i == 1 || i == n || j == 1 || j == n) printf("*");
            else printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Enter size: 4 **** * * * * ****

Prints a star only on the border rows and columns.

Array & Matrix Programs

21. Largest and Smallest in Array

#include <stdio.h>
int main() {
    int n, i, arr[100];
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) scanf("%d", &arr[i]);
    int max = arr[0], min = arr[0];
    for (i = 1; i < n; i++) {
        if (arr[i] > max) max = arr[i];
        if (arr[i] < min) min = arr[i];
    }
    printf("Largest = %d, Smallest = %d\n", max, min);
    return 0;
}
Enter size: 5 Enter elements: 3 8 1 9 4 Largest = 9, Smallest = 1

Tracks max and min in a single pass through the array.

22. Sum and Average of Array

#include <stdio.h>
int main() {
    int n, i, arr[100], sum = 0;
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) { scanf("%d", &arr[i]); sum += arr[i]; }
    printf("Sum = %d, Average = %.2f\n", sum, (float)sum / n);
    return 0;
}
Enter size: 4 Enter elements: 10 20 30 40 Sum = 100, Average = 25.00

Adds all elements, then divides by n. Cast to float for decimals.

23. Reverse an Array

#include <stdio.h>
int main() {
    int n, i, arr[100];
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) scanf("%d", &arr[i]);
    printf("Reversed: ");
    for (i = n - 1; i >= 0; i--) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Enter size: 5 Enter elements: 1 2 3 4 5 Reversed: 5 4 3 2 1

Prints the array from the last index down to the first.

24. Sort an Array (Bubble Sort)

#include <stdio.h>
int main() {
    int n, i, j, arr[100];
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) scanf("%d", &arr[i]);
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - 1 - i; j++)
            if (arr[j] > arr[j+1]) {
                int t = arr[j]; arr[j] = arr[j+1]; arr[j+1] = t;
            }
    printf("Sorted: ");
    for (i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Enter size: 5 Enter elements: 5 2 8 1 9 Sorted: 1 2 5 8 9

Bubble sort swaps neighbours until the array is sorted.

27. Second Largest in Array

#include <stdio.h>
#include <limits.h>
int main() {
    int n, i, arr[100];
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) scanf("%d", &arr[i]);
    int first = INT_MIN, second = INT_MIN;
    for (i = 0; i < n; i++) {
        if (arr[i] > first) { second = first; first = arr[i]; }
        else if (arr[i] > second && arr[i] != first) second = arr[i];
    }
    printf("Second largest = %d\n", second);
    return 0;
}
Enter size: 5 Enter elements: 10 5 20 8 15 Second largest = 15

Tracks the largest and second largest in one pass.

28. Count Even and Odd in Array

#include <stdio.h>
int main() {
    int n, i, arr[100], even = 0, odd = 0;
    printf("Enter size: ");
    scanf("%d", &n);
    printf("Enter elements: ");
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        if (arr[i] % 2 == 0) even++;
        else odd++;
    }
    printf("Even = %d, Odd = %d\n", even, odd);
    return 0;
}
Enter size: 6 Enter elements: 1 2 3 4 5 6 Even = 3, Odd = 3

Increments the even or odd counter for each element.

29. Merge Two Arrays

#include <stdio.h>
int main() {
    int a[50], b[50], c[100], n1, n2, i, k = 0;
    printf("Enter size of first: ");
    scanf("%d", &n1);
    printf("Enter first elements: ");
    for (i = 0; i < n1; i++) scanf("%d", &a[i]);
    printf("Enter size of second: ");
    scanf("%d", &n2);
    printf("Enter second elements: ");
    for (i = 0; i < n2; i++) scanf("%d", &b[i]);
    for (i = 0; i < n1; i++) c[k++] = a[i];
    for (i = 0; i < n2; i++) c[k++] = b[i];
    printf("Merged: ");
    for (i = 0; i < k; i++) printf("%d ", c[i]);
    printf("\n");
    return 0;
}
Enter size of first: 3 Enter first elements: 1 2 3 Enter size of second: 2 Enter second elements: 4 5 Merged: 1 2 3 4 5

Copies the first array, then the second, into a bigger array.

30. Matrix Addition

#include <stdio.h>
int main() {
    int a[10][10], b[10][10], c[10][10], r, col, i, j;
    printf("Enter rows and cols: ");
    scanf("%d %d", &r, &col);
    printf("Enter first matrix: ");
    for (i = 0; i < r; i++) for (j = 0; j < col; j++) scanf("%d", &a[i][j]);
    printf("Enter second matrix: ");
    for (i = 0; i < r; i++) for (j = 0; j < col; j++) scanf("%d", &b[i][j]);
    for (i = 0; i < r; i++) for (j = 0; j < col; j++) c[i][j] = a[i][j] + b[i][j];
    printf("Sum:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < col; j++) printf("%d ", c[i][j]);
        printf("\n");
    }
    return 0;
}
Enter rows and cols: 2 2 Enter first matrix: 1 2 3 4 Enter second matrix: 5 6 7 8 Sum: 6 8 10 12

Adds matching cells: c[i][j] = a[i][j] + b[i][j].

31. Matrix Multiplication

#include <stdio.h>
int main() {
    int a[10][10], b[10][10], c[10][10], i, j, k, n;
    printf("Enter size n (n x n): ");
    scanf("%d", &n);
    printf("Enter first matrix: ");
    for (i=0;i<n;i++) for (j=0;j<n;j++) scanf("%d", &a[i][j]);
    printf("Enter second matrix: ");
    for (i=0;i<n;i++) for (j=0;j<n;j++) scanf("%d", &b[i][j]);
    for (i=0;i<n;i++) for (j=0;j<n;j++) {
        c[i][j] = 0;
        for (k=0;k<n;k++) c[i][j] += a[i][k] * b[k][j];
    }
    printf("Product:\n");
    for (i=0;i<n;i++) { for (j=0;j<n;j++) printf("%d ", c[i][j]); printf("\n"); }
    return 0;
}
Enter size n (n x n): 2 Enter first matrix: 1 2 3 4 Enter second matrix: 5 6 7 8 Product: 19 22 43 50

Each cell is a row of A dotted with a column of B (three loops).

32. Transpose of a Matrix

#include <stdio.h>
int main() {
    int a[10][10], r, c, i, j;
    printf("Enter rows and cols: ");
    scanf("%d %d", &r, &c);
    printf("Enter matrix: ");
    for (i=0;i<r;i++) for (j=0;j<c;j++) scanf("%d", &a[i][j]);
    printf("Transpose:\n");
    for (i=0;i<c;i++) {
        for (j=0;j<r;j++) printf("%d ", a[j][i]);
        printf("\n");
    }
    return 0;
}
Enter rows and cols: 2 3 Enter matrix: 1 2 3 4 5 6 Transpose: 1 4 2 5 3 6

Swaps rows and columns by printing a[j][i] instead of a[i][j].

String Programs

33. String Length

#include <stdio.h>
int main() {
    char str[100];
    int len = 0;
    printf("Enter a string: ");
    scanf("%s", str);
    while (str[len] != '\0') len++;
    printf("Length = %d\n", len);
    return 0;
}
Enter a string: Hello Length = 5

Counts characters until the null terminator '\0'.

34. Reverse a String

#include <stdio.h>
#include <string.h>
int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    int len = strlen(str);
    printf("Reversed: ");
    for (int i = len - 1; i >= 0; i--) printf("%c", str[i]);
    printf("\n");
    return 0;
}
Enter a string: Hello Reversed: olleH

Prints characters from the last index down to the first.

35. Check String Palindrome

#include <stdio.h>
#include <string.h>
int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    int len = strlen(str), i, isPal = 1;
    for (i = 0; i < len / 2; i++)
        if (str[i] != str[len - 1 - i]) { isPal = 0; break; }
    if (isPal) printf("Palindrome\n");
    else printf("Not a Palindrome\n");
    return 0;
}
Enter a string: madam Palindrome

Compares characters from both ends moving inward.

36. Count Vowels and Consonants

#include <stdio.h>
int main() {
    char str[100];
    int v = 0, c = 0, i;
    printf("Enter a string: ");
    scanf("%s", str);
    for (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') v++;
        else c++;
    }
    printf("Vowels = %d, Consonants = %d\n", v, c);
    return 0;
}
Enter a string: hello Vowels = 2, Consonants = 3

Checks each character against the list of vowels.

37. Convert to Uppercase

#include <stdio.h>
int main() {
    char str[100];
    int i;
    printf("Enter a string: ");
    scanf("%s", str);
    for (i = 0; str[i] != '\0'; i++)
        if (str[i] >= 'a' && str[i] <= 'z') str[i] -= 32;
    printf("Uppercase: %s\n", str);
    return 0;
}
Enter a string: hello Uppercase: HELLO

Subtracts 32 from each lowercase letter's ASCII value.

38. Count Words in a Sentence

#include <stdio.h>
int main() {
    char str[200];
    int i, words = 1;
    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);
    for (i = 0; str[i] != '\0'; i++)
        if (str[i] == ' ') words++;
    printf("Words = %d\n", words);
    return 0;
}
Enter a sentence: I love C programming Words = 4

Counts spaces and adds one. Uses fgets to read a full line.

39. Check Anagram

#include <stdio.h>
#include <string.h>
int main() {
    char a[100], b[100];
    int count[26] = {0}, i;
    printf("Enter first string: ");
    scanf("%s", a);
    printf("Enter second string: ");
    scanf("%s", b);
    if (strlen(a) != strlen(b)) { printf("Not Anagram\n"); return 0; }
    for (i = 0; a[i]; i++) count[a[i]-'a']++;
    for (i = 0; b[i]; i++) count[b[i]-'a']--;
    int anagram = 1;
    for (i = 0; i < 26; i++) if (count[i] != 0) anagram = 0;
    printf(anagram ? "Anagram\n" : "Not Anagram\n");
    return 0;
}
Dry Run — dekhiye har step kaise chalta hai (i = 0 se shuru)
Stepi ki valueConditionKya huai ab
100 < 26 → trueloop body chalta haii → 1
211 < 26 → trueloop body chalta haii → 2
322 < 26 → trueloop body chalta haii → 3
433 < 26 → trueloop body chalta haii → 4
544 < 26 → trueloop body chalta haii → 5
655 < 26 → trueloop body chalta haii → 6
766 < 26 → trueloop body chalta haii → 7
877 < 26 → trueloop body chalta haii → 8
988 < 26 → trueloop body chalta haii → 9
1099 < 26 → trueloop body chalta haii → 10
111010 < 26 → trueloop body chalta haii → 11
121111 < 26 → trueloop body chalta haii → 12
131212 < 26 → trueloop body chalta haii → 13
141313 < 26 → trueloop body chalta haii → 14
151414 < 26 → trueloop body chalta haii → 15
161515 < 26 → trueloop body chalta haii → 16
171616 < 26 → trueloop body chalta haii → 17
181717 < 26 → trueloop body chalta haii → 18
191818 < 26 → trueloop body chalta haii → 19
201919 < 26 → trueloop body chalta haii → 20
212020 < 26 → trueloop body chalta haii → 21
222121 < 26 → trueloop body chalta haii → 22
232222 < 26 → trueloop body chalta haii → 23
242323 < 26 → trueloop body chalta haii → 24
252424 < 26 → trueloop body chalta haii → 25
… loop isi tarah chalta rahता hai
Enter first string: listen Enter second string: silent Anagram

Counts letters of one word, subtracts the other; all zero means anagram.

40. Concatenate Two Strings

#include <stdio.h>
#include <string.h>
int main() {
    char a[100], b[100];
    printf("Enter first string: ");
    scanf("%s", a);
    printf("Enter second string: ");
    scanf("%s", b);
    strcat(a, b);
    printf("Result: %s\n", a);
    return 0;
}
Enter first string: Coding Enter second string: Easily Result: CodingEasily

strcat joins the second string onto the end of the first.

Miscellaneous & Projects

41. Swap Two Numbers

#include <stdio.h>
int main() {
    int a, b, temp;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    temp = a; a = b; b = temp;
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Enter two numbers: 5 9 After swap: a = 9, b = 5

Uses a temporary variable to exchange the two values.

42. Simple Calculator

#include <stdio.h>
int main() {
    double a, b;
    char op;
    printf("Enter expression (e.g. 5 + 3): ");
    scanf("%lf %c %lf", &a, &op, &b);
    switch (op) {
        case '+': printf("= %.2f\n", a + b); break;
        case '-': printf("= %.2f\n", a - b); break;
        case '*': printf("= %.2f\n", a * b); break;
        case '/':
            if (b != 0) printf("= %.2f\n", a / b);
            else printf("Cannot divide by zero\n");
            break;
        default: printf("Invalid operator\n");
    }
    return 0;
}
Enter expression (e.g. 5 + 3): 5 + 3 = 8.00

Reads two numbers and an operator, then uses switch.

43. Celsius to Fahrenheit

#include <stdio.h>
int main() {
    float c, f;
    printf("Enter Celsius: ");
    scanf("%f", &c);
    f = (c * 9 / 5) + 32;
    printf("Fahrenheit = %.2f\n", f);
    return 0;
}
Enter Celsius: 37 Fahrenheit = 98.60

Applies the formula F = (C × 9/5) + 32.

44. Check Leap Year

#include <stdio.h>
int main() {
    int year;
    printf("Enter a year: ");
    scanf("%d", &year);
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        printf("%d is a Leap Year\n", year);
    else
        printf("%d is Not a Leap Year\n", year);
    return 0;
}
Enter a year: 2024 2024 is a Leap Year

Divisible by 4 and not 100, or divisible by 400.

45. Sum of First N Natural Numbers

#include <stdio.h>
int main() {
    int n, i, sum = 0;
    printf("Enter n: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) sum += i;
    printf("Sum = %d\n", sum);
    return 0;
}
Enter n: 10 Sum = 55

Adds 1 to n in a loop (or use n*(n+1)/2).

46. Count Digits in a Number

#include <stdio.h>
int main() {
    int n, count = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n == 0) count = 1;
    while (n != 0) { count++; n /= 10; }
    printf("Digits = %d\n", count);
    return 0;
}
Enter a number: 4567 Digits = 4

Removes one digit per loop with / 10 and counts the loops.

47. Power of a Number

#include <stdio.h>
int main() {
    int base, exp, i;
    long long result = 1;
    printf("Enter base and exponent: ");
    scanf("%d %d", &base, &exp);
    for (i = 1; i <= exp; i++) result *= base;
    printf("%d^%d = %lld\n", base, exp, result);
    return 0;
}
Enter base and exponent: 2 5 2^5 = 32

Multiplies the base by itself exp times.

48. Check Perfect Number

#include <stdio.h>
int main() {
    int n, i, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    for (i = 1; i < n; i++)
        if (n % i == 0) sum += i;
    if (sum == n) printf("%d is Perfect\n", n);
    else printf("%d is Not Perfect\n", n);
    return 0;
}
Enter a number: 6 6 is Perfect

A perfect number equals the sum of its proper divisors (6 = 1+2+3).

49. Count Positive, Negative, Zero

#include <stdio.h>
int main() {
    int n, i, x, pos = 0, neg = 0, zero = 0;
    printf("Enter how many numbers: ");
    scanf("%d", &n);
    printf("Enter numbers: ");
    for (i = 0; i < n; i++) {
        scanf("%d", &x);
        if (x > 0) pos++;
        else if (x < 0) neg++;
        else zero++;
    }
    printf("Positive=%d Negative=%d Zero=%d\n", pos, neg, zero);
    return 0;
}
Enter how many numbers: 5 Enter numbers: 3 -2 0 7 -5 Positive=2 Negative=2 Zero=1

Classifies each number with if-else-if into three counters.

7 common mistakes in these programs (with real output)

1. Factorial overflow: using int

int f = 1;  long long g = 1;
for (int i = 1; i <= 13; i++) { f *= i; g *= i; }
printf("13! with int       = %d\n", f);
printf("13! with long long = %lld\n", g);
13! with int = 1932053504 13! with long long = 6227020800

An int holds up to about 2.1 billion, so 13! overflows. Signed overflow is undefined behaviour in C – you silently get a wrong number. That is why program 3 uses long long (correct up to 20!).

2. = instead of == in a condition

int marks = 35;
if (marks = 40) printf("Passed with %d\n", marks);
eq.c:4:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses] Passed with 40

The condition assigns 40, which is non-zero, so it is always true. Compile with gcc -Wall – the compiler warns you.

3. Forgetting & in scanf

scanf("%d", n); passes the value instead of the address, so the program may crash or read garbage. Always scanf("%d", &n); – except for strings (char name[50]; scanf("%49s", name);), because an array name is already an address.

4. Off-by-one in loops and arrays

An array of size 5 has indexes 0–4. for (i = 0; i <= n; i++) reads one element past the end. Use i < n for arrays and test with the smallest input (n = 1).

5. Slow prime check

n = 1000003 (a prime)
loop to n/2      : 500000 checks
loop to sqrt(n)  : 999 checks

If n has a divisor bigger than √n it also has one smaller than √n, so checking i * i <= n is enough – 500 times faster here. Program 2 uses n/2 for simplicity; in exams and interviews mention the √n improvement.

6. Unsafe string input

Never use gets() – it was removed from C11 because it cannot stop at the array size. Use fgets(str, sizeof str, stdin) and remove the trailing newline, or scanf("%49s", str) for a single word.

7. Integer division

avg = sum / n; with int variables drops the decimal part (7 / 2 = 3). Cast first: avg = (float) sum / n; – see program 22.

Time complexity of key programs

ProgramTime complexityWhy
Prime check (to n/2)O(n)one loop up to n/2
Prime check (to √n)O(√n)stop at i * i > n
Sum / reverse / count digitsO(d)d = number of digits
GCD (Euclid)O(log min(a, b))remainder shrinks fast
Linear searchO(n)may check every element
Binary searchO(log n)halves the sorted array each step
Bubble sortO(n²)nested loops over the array
Matrix multiplication (n×n)O(n³)three nested loops
Pattern with n rowsO(n²)row loop × column loop

How to practise well

  • Try first, then peek. Read the problem, attempt the code yourself, and only then check the solution.
  • Change the input. Run each program with your own values in the compiler to test edge cases.
  • Trace by hand. For tricky ones (reverse, prime, patterns), follow the loop with a small input on paper.
  • Rewrite from memory. After understanding, close the page and type the program again.

Frequently Asked Questions

How do I run these C programs on the page?
Every program has a "Try it Yourself" button. Click it and a real C compiler opens right below the code, already loaded with that program. Press Run, type any input in the box at the bottom, and see the output instantly.
Do these C programs take user input?
Yes. Each program uses scanf() so you enter the values yourself. When you run a program in the compiler, type your input in the input box and it is passed to the program, just like on your own computer.
Are these C programs complete with solutions?
Yes. Unlike a plain list, every one of the 50 programs here includes the full working code, a sample input and output, and a short explanation of the logic — ready to run and study.
What topics do these 50 C programs cover?
They span number programs (even/odd, prime, factorial, Fibonacci, Armstrong), patterns (stars, pyramids, Floyd, Pascal), arrays and matrices (search, sort, multiply), strings (reverse, palindrome, anagram), and small projects like a calculator and a menu-driven program.
Are these programs good for exams and interviews?
Absolutely. Classics like prime check, palindrome, reversing a number or string, sorting and matrix operations appear constantly in viva exams and interviews. Running and rewriting them here builds the confidence to reproduce them from memory.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicC Interview Questions Your progress: 47 / 67 (70%) · Lesson 48 / 67 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free