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.
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;
}
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;
}
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;
}
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;
}
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;
}
% 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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
Bubble sort swaps neighbours until the array is sorted.
25. Linear Search
#include <stdio.h>
int main() {
int n, i, key, arr[100], found = -1;
printf("Enter size: ");
scanf("%d", &n);
printf("Enter elements: ");
for (i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Enter number to search: ");
scanf("%d", &key);
for (i = 0; i < n; i++)
if (arr[i] == key) { found = i; break; }
if (found != -1) printf("Found at position %d\n", found);
else printf("Not found\n");
return 0;
}
Checks each element one by one until the key is found.
26. Binary Search
#include <stdio.h>
int main() {
int n, i, key, arr[100];
printf("Enter size: ");
scanf("%d", &n);
printf("Enter sorted elements: ");
for (i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Enter number to search: ");
scanf("%d", &key);
int low = 0, high = n - 1, pos = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) { pos = mid; break; }
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (pos != -1) printf("Found at position %d\n", pos);
else printf("Not found\n");
return 0;
}
Halves the search range each step (needs a sorted array).
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}| Step | i ki value | Condition | Kya hua | i ab |
|---|---|---|---|---|
| 1 | 0 | 0 < 26 → true | loop body chalta hai | i → 1 |
| 2 | 1 | 1 < 26 → true | loop body chalta hai | i → 2 |
| 3 | 2 | 2 < 26 → true | loop body chalta hai | i → 3 |
| 4 | 3 | 3 < 26 → true | loop body chalta hai | i → 4 |
| 5 | 4 | 4 < 26 → true | loop body chalta hai | i → 5 |
| 6 | 5 | 5 < 26 → true | loop body chalta hai | i → 6 |
| 7 | 6 | 6 < 26 → true | loop body chalta hai | i → 7 |
| 8 | 7 | 7 < 26 → true | loop body chalta hai | i → 8 |
| 9 | 8 | 8 < 26 → true | loop body chalta hai | i → 9 |
| 10 | 9 | 9 < 26 → true | loop body chalta hai | i → 10 |
| 11 | 10 | 10 < 26 → true | loop body chalta hai | i → 11 |
| 12 | 11 | 11 < 26 → true | loop body chalta hai | i → 12 |
| 13 | 12 | 12 < 26 → true | loop body chalta hai | i → 13 |
| 14 | 13 | 13 < 26 → true | loop body chalta hai | i → 14 |
| 15 | 14 | 14 < 26 → true | loop body chalta hai | i → 15 |
| 16 | 15 | 15 < 26 → true | loop body chalta hai | i → 16 |
| 17 | 16 | 16 < 26 → true | loop body chalta hai | i → 17 |
| 18 | 17 | 17 < 26 → true | loop body chalta hai | i → 18 |
| 19 | 18 | 18 < 26 → true | loop body chalta hai | i → 19 |
| 20 | 19 | 19 < 26 → true | loop body chalta hai | i → 20 |
| 21 | 20 | 20 < 26 → true | loop body chalta hai | i → 21 |
| 22 | 21 | 21 < 26 → true | loop body chalta hai | i → 22 |
| 23 | 22 | 22 < 26 → true | loop body chalta hai | i → 23 |
| 24 | 23 | 23 < 26 → true | loop body chalta hai | i → 24 |
| 25 | 24 | 24 < 26 → true | loop body chalta hai | i → 25 |
| … loop isi tarah chalta rahता hai | ||||
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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);
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);
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
| Program | Time complexity | Why |
|---|---|---|
| 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 digits | O(d) | d = number of digits |
| GCD (Euclid) | O(log min(a, b)) | remainder shrinks fast |
| Linear search | O(n) | may check every element |
| Binary search | O(log n) | halves the sorted array each step |
| Bubble sort | O(n²) | nested loops over the array |
| Matrix multiplication (n×n) | O(n³) | three nested loops |
| Pattern with n rows | O(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?
Do these C programs take user input?
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.