C Variables - Examples
Real-Life Example
Often in our examples, we simplify variable names to match their data type (myInt
or myNum for int types, myChar for char types,
and so on). This is done to avoid confusion.
In real programs, variables often represent real-world data.
The following example stores information about a college student:
Example
// 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 »
Notice: Each variable stores a different type of information, but they are all used together in one program.
Calculate the Area of a Rectangle
Variables are often used to store values, perform calculations, and then show the result.
In this example, we calculate the area of a rectangle:
Example
// Create variables
int length = 4;
int width = 6;
int area;
// Calculate the area
area = length * width;
// Print the result
printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d", area);
Try it Yourself »
Tip: Calculations are usually done first, and the result is stored in a variable before being printed.