Practical Examples of Variables and Data Types in C
Explore real-world applications of variables and data types in C programming. This guide will provide practical examples, such as storing student data, calculating area and perimeter, and working with different data types. Understand how to effectively use variables and data types to solve various programming problems.
Practical Examples
This page contains a list of practical examples used in real-world projects.
Variables and Data Types
Example: Store Student Data
Use variables to store different data of a college student:
Syntax
// Student data
int studentID = 101;
int studentAge = 21;
float studentFee = 65.50;
char studentGrade = 'A';
// 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);
Output
Student ID: 101
Student Age: 21
Student Fee: 65.500000
Student Grade: A
Example: Calculate Area of a Rectangle
Calculate the area of a rectangle by multiplying the length and width:
Syntax
// Create integer variables
int length = 7;
int width = 9;
int area;
// Calculate the area of the rectangle
area = length * width;
// Print the variables
printf("Length: %d\n", length);
printf("Width: %d\n", width);
printf("Area of the rectangle: %d", area);
Output
Length: 7
Width: 9
Area of the rectangle: 63
Example: Calculate Total Cost
Use different data types to calculate and output the total cost of a number of items:
Syntax
// Create variables of different data types
int items = 30;
float cost_per_item = 12.50;
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);
Output
Number of items: 30
Cost per item: 12.50 $
Total cost = 375.00 $
Example: Calculate User Score Percentage
Calculate the percentage of a user's score in relation to the maximum score in a game:
Syntax
// Set the maximum possible score
int maxScore = 1000;
// The actual score of the user
int userScore = 850;
// Calculate the percentage
float percentage = (float) userScore / maxScore * 100.0;
// Print the percentage
printf("User's percentage is %.2f", percentage);
Output
User's percentage is 85.00
Booleans
Example: Voting Age Check
Find out if a person is old enough to vote:
Syntax
int myAge = 19;
int votingAge = 18;
printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 19-year-olds can vote!
Output
1
Example: Voting Eligibility Message
Output "Old enough to vote!" if the user is eligible; otherwise, output "Not old enough to vote.":
Syntax
int myAge = 16;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
Output
Not old enough to vote.
Conditions (If..Else)
Example: Time-based Greeting
Syntax
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Output
Good evening.
Example: Check User Code
Syntax
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
Output
Correct code.
The door is now open.
Example: Positive or Negative Number
Syntax
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.");
}
Output
The value is a positive number.
Example: Old Enough to Vote
Syntax
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
Output
Old enough to vote!
Example: Even or Odd Number
Syntax
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
Output
5 is odd.
Switch
Example: Weekday Name
Syntax
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;
}
Output
Thursday
While Loops
Example: Countdown
Syntax
int countdown = 3;
while (countdown > 0) {
printf("%d\n", countdown);
countdown--;
}
printf("Happy New Year!!\n");
Output
3
2
1
Happy New Year!!
Example: Play Yatzy
Syntax
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yatzy!\n");
}
dice = dice + 1;
}
Output
No Yatzy
No Yatzy
No Yatzy
No Yatzy
No Yatzy
Yatzy!
Arrays
Example: Calculate Average of Ages
Syntax
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);
Output
The average age is: 40.75
Example: Find the Lowest Age
Syntax
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];
}
}
// Print the lowest age
printf("The lowest age is: %d", lowestAge);
Output
The lowest age is: 18
Strings
Example: Welcome Message
Syntax
char message[] = "Good to see you,";
char fname[] = "John";
printf("%s %s!", message, fname);
Output
Good to see you, John!
Example: Count Characters in a Word
Syntax
#include
char word[] = "Computer";
printf("The word '%s' has %d characters in it.", word, strlen(word));
Output
The word 'Computer' has 8 characters in it.
User Input
Example: Get User's Full Name
Syntax
#include
char fullName[30];
printf("Type your full name: \n");
fgets(fullName, sizeof(fullName), stdin);
printf("Hello %s", fullName);
Output
Type your full name:
Hello John Doe
Functions
Example: Convert Fahrenheit to Celsius
Syntax
// 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;
}
Output
Fahrenheit: 98.80
Convert Fahrenheit to Celsius: 37.11
Structures
Example: Store and Output Car Information
Syntax
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;
}
Output
BMW X5 1999
Ford Mustang 1969
Toyota Corolla 2011
Memory Management
Example: Dynamic Memory Allocation in a List
Syntax
#include
#include
struct list {
int *data; // Points to the memory where the list items are stored
int numItems; // Indicates how many items are currently in the list
int size; // Indicates how many items fit in the allocated memory
};
void addToList(struct list *myList, int item);
int main() {
struct list myList;
int amount;
// Create a list and start with enough space for 10 items
myList.numItems = 0;
myList.size = 10;
myList.data = malloc(myList.size * sizeof(int));
// Find out if memory allocation was successful
if (myList.data == NULL) {
printf("Memory allocation failed");
return 1; // Exit the program with an error code
}
// Add any number of items to the list specified by the amount variable
amount = 44;
for (int i = 0; i < amount; i++) {
addToList(&myList, i + 1);
}
// Display the contents of the list
for (int j = 0; j < myList.numItems; j++) {
printf("%d ", myList.data[j]);
}
// Free the memory when it is no longer needed
free(myList.data);
myList.data = NULL;
return 0;
}
// This function adds an item to a list
void addToList(struct list *myList, int item) {
// If the list is full then resize the memory to fit 10 more items
if (myList->numItems == myList->size) {
myList->size += 10;
myList->data = realloc( myList->data, myList->size * sizeof(int) );
}
// Add the item to the end of the list
myList->data[myList->numItems] = item;
myList->numItems++;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44