C Examples
These C examples combine everything from this tutorial into small, complete programs. Read each one, predict the output, then compile and modify it. Practicing with real programs is the fastest way to get comfortable with C.
Check for a Prime Number
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
int main(void) {
for (int n = 1; n <= 20; n++)
if (isPrime(n)) printf("%d ", n);
printf("\n");
return 0;
}2 3 5 7 11 13 17 19
Reverse a String in Place
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
size_t i = 0, j = strlen(s);
while (j > i + 1) {
j--;
char t = s[i]; s[i] = s[j]; s[j] = t;
i++;
}
}
int main(void) {
char word[] = "portfolio";
reverse(word);
printf("%s\n", word);
return 0;
}oiloftrop
Bubble Sort an Array
#include <stdio.h>
void bubbleSort(int a[], int n) {
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
int main(void) {
int nums[] = {42, 7, 19, 3, 25};
bubbleSort(nums, 5);
for (int i = 0; i < 5; i++) printf("%d ", nums[i]);
printf("\n");
return 0;
}3 7 19 25 42
Grade Report with Structs
#include <stdio.h>
typedef struct { const char *name; int marks; } Student;
char grade(int m) {
return m >= 90 ? 'A' : m >= 75 ? 'B' : m >= 50 ? 'C' : 'F';
}
int main(void) {
Student cls[] = {{"Hina", 93}, {"Usman", 78}, {"Zara", 45}};
int total = 0;
for (int i = 0; i < 3; i++) {
printf("%-6s %3d %c\n", cls[i].name, cls[i].marks, grade(cls[i].marks));
total += cls[i].marks;
}
printf("Average: %.1f\n", total / 3.0);
return 0;
}Hina 93 A Usman 78 B Zara 45 F Average: 72.0
Exercises to Try Next
- Write a program that counts the vowels in a sentence read with fgets.
- Print the Fibonacci sequence up to 1000.
- Store a list of contacts in a dynamically growing array using realloc.
- Save the grade report to a file and read it back.
Frequently asked questions
What are good C projects for beginners?
Try a calculator, a number guessing game, a to-do list saved to a file, a student record system using structs, or a simple text-based bank account manager.
How can I practice C programming every day?
Solve one small problem a day, rewrite the examples from this tutorial without looking, and use sites with coding exercises. Reading other people's C code also helps a lot.
What should I learn after C?
Common next steps are data structures and algorithms in C, C++ for object-oriented programming, or embedded systems with microcontrollers like Arduino and STM32.