C Examples: Practical Programming
Learning syntax is only half the battle. To become a proficient C programmer, you must see how different libraries work together to solve logic-based problems.
1. The "Number Guessing" Game
This example uses stdlib.h for random numbers, time.h for seeding, and stdio.h for user interaction.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secret, guess;
srand(time(0)); // Seed random number generator
secret = rand() % 100 + 1; // Number between 1-100
do {
printf("Guess (1-100): ");
scanf("%d", &guess);
if (guess > secret) printf("Lower!\n");
else if (guess < secret) printf("Higher!\n");
} while (guess != secret);
printf("Bingo! The number was %d", secret);
return 0;
}
2. Password Strength Checker
This program uses ctype.h and string.h to validate if a string contains digits and letters.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char pass[20];
int hasDigit = 0, hasAlpha = 0;
printf("Create Password: ");
scanf("%s", pass);
for(int i = 0; i < strlen(pass); i++) {
if (isdigit(pass[i])) hasDigit = 1;
if (isalpha(pass[i])) hasAlpha = 1;
}
if (hasDigit && hasAlpha && strlen(pass) >= 8)
printf("Strong Password!");
else
printf("Weak Password: Need 8+ chars, letters, and numbers.");
return 0;
}
3. Geometric Calculator
Using math.h to calculate the Hypotenuse of a triangle using Pythagoras theorem ($a^2 + b^2 = c^2$).
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
printf("Enter Side A and B: ");
scanf("%lf %lf", &a, &b);
c = sqrt(pow(a, 2) + pow(b, 2));
printf("Hypotenuse: %.2f", c);
return 0;
}
4. Array Reversal
A classic logic problem demonstrating how to swap elements in an array using a loop.
int arr[] = {1, 2, 3, 4, 5};
int n = 5;
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
Pro Tip: When testing these examples, always use a compiler like GCC and try to modify the logic. For instance, in the password checker, try adding a check for special characters using ispunct()!