C Variables - Examples: Practical Applications

Explore practical examples of C variables in action. This section showcases how simplified variable names like myInt or myChar can effectively represent different data types, along with a real-life example of storing diverse data about a college student.



C Variables - Examples

Real-Life Example

Often in our examples, we simplify variable names to match their data type (for instance, myInt or myNum for integer types, myChar for character types, and so on). This simplification helps avoid confusion.

However, here's a practical example of using variables in a program that stores different data about a college student:

Example

// Student data
int studentID = 42;
int studentAge = 20;
float studentFee = 89.75;
char studentGrade = 'A';

// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %.2f\n", studentFee);
printf("Student grade: %c", studentGrade);

Calculate the Area of a Rectangle

In this real-life example, we create a program to calculate the area of a rectangle by multiplying its length and width:

Example

// Create integer variables
int length = 5;
int width = 8;
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);