Variables And Data Types

Lesson 2.1: Variables and Data Types


In this lesson, you'll learn how to store and work with different kinds of data in your C programs using variables and data types.


What are Variables?


Imagine variables as labeled containers in computer memory. Each container stores a specific piece of information.

You can think of variables like labeled boxes where you can put things (values) and take them out later when you need them.

In C, you must declare a variable before you can use it. This tells the compiler:

The name of the variable (how you'll refer to it).

The data type (what kind of information it can hold).

What are Data Types?


Data types define the kind of information a variable can store and how that information is represented in memory.

C provides several built-in data types for common types of values:

Data Type Description Example Values

int Stores whole numbers (integers) 10, -5, 0, 12345

float Stores floating-point numbers (numbers with decimals) with single precision (less accuracy) 3.14, -0.5, 2.0e6 (2 million)

double Stores floating-point numbers with double precision (more accuracy) 3.14159, 1.0e-9 (0.000000001)

char Stores a single character 'A', 'b', '3', '$'



Declaring and Initializing Variables


C

int age;           // Declare an integer variable named "age"

float pi = 3.14159;  // Declare and initialize a float variable

char grade = 'A';   // Declare and initialize a char variable

double balance;      // Declare a double variable (no initial value)


Naming Conventions: Variable names in C:

Must start with a letter or underscore (_).

Can contain letters, numbers, and underscores.

Are case-sensitive (e.g., age and Age are different).

Should be descriptive (e.g., studentCount instead of sc).

Using Variables


C

age = 25;                 // Assign a value to the "age" variable

balance = 1000.50;       // Assign a value to the "balance" variable

printf("Your age is %d\n", age);   // Print the value of "age"

printf("Your balance is %f\n", balance); // Print the value of "balance"


Format Specifiers in printf


%d: Placeholder for integer values (int).

%f: Placeholder for floating-point values (float or double).

%c: Placeholder for character values (char).

%s: Placeholder for strings (character arrays).

Example Program


C

#include <stdio.h>


int main() {

    int numApples = 5;

    double applePrice = 0.89;

    char grade = 'A';


    printf("You have %d apples.\n", numApples);

    printf("Each apple costs $%.2f.\n", applePrice);

    printf("You got an %c on your test.\n", grade);


    return 0;

}

Let me know if you'd like more explanation on a particular topic!

Course Syllabus