C Real-Life Examples
Practical Examples
This page contains a list of practical examples used in real world projects.
Variables and Data Types
Example
Use variables to store different data of a college student:
// Student data
int studentID = 15;
int studentAge = 23;
float
studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n",
studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student
grade: %c", studentGrade);
Try it Yourself »
Example
Calculate the area of a rectangle (by multiplying the length and width)
// Create integer variables
int length = 4;
int width = 6;
int
area;
// Calculate the area of a rectangle
area = length * width;
// Print the variables
printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d",
area);
Try it Yourself »
Example
Use different data types to calculate and output the total cost of a number of items:
// Create variables of different data types
int items = 50;
float
cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char
currency = '$';
// Print variables
printf("Number of items: %d\n",
items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
Try it Yourself »
Example
Calculate the percentage of a user's score in relation to the maximum score in a game:
// Set the maximum possible score in the game to 500
int maxScore = 500;
// The actual score of the user
int userScore = 420;
//
Calculate the percantage of the user's score in relation to the maximum
available score
float percentage = (float) userScore / maxScore * 100.0;
// Print the percentage
printf("User's percentage is %.2f", percentage);
Try it Yourself »
For a tutorial about variables and data types in C, visit our Variables Chapter and Data Types Chapter.
Booleans
Example
Find out if a person is old enough to vote:
int myAge = 25;
int votingAge = 18;
printf("%d", myAge >=
votingAge); // Returns 1 (true), meaning 25 year olds are allowed to vote!
Try it Yourself »
You could also wrap the code above in an
if...else
to perform different actions depending on the result:
Example
Output "Old enough to vote!" if myAge
is greater than or equal to 18
. Otherwise output "Not old enough to vote.":
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough
to vote.");
}
Try it Yourself »
For a tutorial about booleans in C, visit our Booleans Chapter.
Conditions (If..Else)
Example
Use if..else statements to output some text depending on what time it is:
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Try it Yourself »
Example
Check whether the user enters the correct code:
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct
code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe
door remains closed.");
}
Try it Yourself »
Example
Find out if a number is positive or negative:
int myNum = 10;
if (myNum >
0) {
printf("The value is a positive number.");
} else if (myNum
< 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Try it Yourself »
Example
Find out if a person is old enough to vote:
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough
to vote.");
}
Try it Yourself »
Example
Find out if a number is even or odd:
int myNum = 5;
if (myNum % 2 ==
0) {
printf("%d is even.\n",
myNum);
} else {
printf("%d is odd.\n", myNum);
}
Try it Yourself »
For a tutorial about conditions in C, visit our If..Else Chapter.
Switch
Example
Use the weekday number to calculate and output the weekday name:
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
Try it Yourself »
For a tutorial about switch in C, visit our Switch Chapter.
While Loops
Example
Use a while loop to create a simple "countdown" program:
int countdown = 3;
while (countdown > 0) {
printf("%d\n",
countdown);
countdown--;
}
printf("Happy New Year!!\n");
Try it Yourself »
Example
Use a while loop to play a game of Yatzy:
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yatzy!\n");
}
dice = dice + 1;
}
Try it Yourself »
Example
Use a while loop to reverse some numbers:
// A variable with some specific numbers
int numbers = 12345;
// A variable to store the reversed number
int revNumbers = 0;
//
Reverse and reorder the numbers
while (numbers) {
// Get the last
number of 'numbers' and add it to 'revNumber'
revNumbers =
revNumbers * 10 + numbers % 10;
// Remove the last number of
'numbers'
numbers /= 10;
}
Try it Yourself »
For a tutorial about while loops in C, visit our While Loop Chapter.
For Loops
Example
Use a for loop to create a program that only print even values between 0 and 10:
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
Try it Yourself »
Example
Use a for loop to create a program that prints the multiplication table of a specified number (2 in this example):
int number = 2;
int i;
// Print the multiplication table for the
number 2
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n",
number, i, number * i);
}
return 0;
Try it Yourself »
For a tutorial about for loops in C, visit our For Loop Chapter.
Arrays
Example
Create a program that calculates the average of different ages:
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26,
87, 70};
float avg, sum = 0;
int i;
// Get the length of the
array
int length = sizeof(ages) / sizeof(ages[0]);
// Loop through
the elements of the array
for (int i = 0; i <
length; i++) {
sum += ages[i];
}
// Calculate the average
by dividing the sum by the length
avg = sum / length;
// Print the
average
printf("The average age is: %.2f", avg);
Try it Yourself »
Example
Create a program that finds the lowest age among different ages:
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26,
87, 70};
// Get the length of the array
int length = sizeof(ages) /
sizeof(ages[0]);
// Create a variable and assign the first array
element of ages to it
int lowestAge = ages[0];
// Loop through
the elements of the ages array to find the lowest age
for (int i = 0; i <
length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
Try it Yourself »
For a tutorial about for arrays in C, visit our Arrays Chapter.
Strings
Example
Use strings to create a simple welcome message:
char message[] = "Good to see you,";
char fname[] = "John";
printf("%s %s!", message, fname);
Try it Yourself »
Example
Create a program that counts the number of characters found in a specific word:
char word[] = "Computer";
printf("The word '%s' has %d characters in it.",
word, strlen(word));
Try it Yourself »
For a tutorial about strings in C, visit our Strings Chapter.
User Input
Example
Get the name of a user and print it:
char fullName[30];
printf("Type your full name: \n");
fgets(fullName, sizeof(fullName), stdin);
printf("Hello %s",
fullName);
Run example »
For a tutorial about user input in C, visit our User Input Chapter.
Functions
Example
Use a function to create a program that converts a value from fahrenheit to celsius:
// Function to convert Fahrenheit to Celsius
float toCelsius(float
fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}
int main() {
// Set a fahrenheit value
float f_value =
98.8;
// Call the function with the fahrenheit value
float result = toCelsius(f_value);
// Print the fahrenheit value
printf("Fahrenheit: %.2f\n", f_value);
// Print the result
printf("Convert Fahrenheit to Celsius: %.2f\n", result);
return
0;
}
Try it Yourself »
For a tutorial about functions in C, visit our Functions Chapter.
Structures
Example
Use a structure to store and output different information about Cars:
struct Car {
char brand[50];
char model[50];
int
year;
};
int main() {
struct Car car1 = {"BMW", "X5",
1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct
Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %d\n",
car1.brand, car1.model, car1.year);
printf("%s %s %d\n", car2.brand,
car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model,
car3.year);
return 0;
}
Try it Yourself »
For a tutorial about structures in C, visit our Structures Chapter.