Day 3: Data Types, Variables & Constants#

Overview#

Today we’ll explore the different data types available in C, learn how to properly declare and initialize variables, and understand constants. These are fundamental building blocks of any C program.

What We’ll Learn Today#

  • Basic data types in C
  • Variable declaration and initialization
  • Variable naming conventions
  • Memory and data type sizes
  • Constants (const and #define)
  • Type casting

Data Types in C#

C has several basic data types, each with different sizes and ranges:

Integer Types#

int#

  • Stores whole numbers
  • Size: Typically 4 bytes (32 bits)
  • Range: -2,147,483,648 to 2,147,483,647
int age = 25;
int temperature = -15;

short#

  • Smaller integer type
  • Size: 2 bytes (16 bits)
  • Range: -32,768 to 32,767
short count = 100;

long#

  • Larger integer type
  • Size: 4 or 8 bytes
  • Range: Varies by system
long population = 7800000000L;  // L suffix indicates long

unsigned int#

  • Only positive numbers (including 0)
  • Size: 4 bytes
  • Range: 0 to 4,294,967,295
unsigned int quantity = 500;

Floating-Point Types#

float#

  • Stores decimal numbers
  • Size: 4 bytes
  • Precision: 6-7 significant digits
float price = 19.99f;  // f suffix indicates float

double#

  • Double precision floating-point
  • Size: 8 bytes
  • Precision: 15-16 significant digits
  • Preferred over float for most calculations
double pi = 3.14159265359;

Character Type#

char#

  • Stores a single character
  • Size: 1 byte
  • Actually stores the ASCII code of the character
char initial = 'A';
char grade = 'B';

Data Type Summary Table#

TypeSizeRangeExample
char1 byte-128 to 127'A'
unsigned char1 byte0 to 255'B'
short2 bytes-32,768 to 32,7671000
int4 bytes±2 billion42
long4-8 bytes±9 × 10^181000000000L
float4 bytes±3.4 × 10^383.14f
double8 bytes±1.7 × 10^3083.14159

Variables: Declaration and Initialization#

Declaration#

Telling C about a variable before using it:

int age;
float salary;
char letter;

Initialization#

Giving a variable an initial value:

int age = 25;
float salary = 50000.50;
char letter = 'A';

Multiple Variables of Same Type#

// Method 1: Separate declarations
int a = 10;
int b = 20;
int c = 30;

// Method 2: Single declaration
int a = 10, b = 20, c = 30;

Complete Example#

#include <stdio.h>

int main() {
    // Declaration and initialization
    int age = 25;
    float height = 5.9;
    char initial = 'J';
    double salary = 45000.75;

    // Print the values
    printf("Age: %d years\n", age);
    printf("Height: %.1f feet\n", height);
    printf("Initial: %c\n", initial);
    printf("Salary: $%.2f\n", salary);

    return 0;
}

Variable Naming Conventions#

Rules for Variable Names#

  1. Must start with a letter (a-z, A-Z) or underscore (_)
  2. Can contain letters, digits, and underscores
  3. Case-sensitive (age is different from Age)
  4. Cannot be a C keyword (reserved words)
  5. Keep names descriptive and readable

Good Naming Examples#

// ✅ Good names
int studentAge = 20;
float monthlyExpenses = 1200.50;
char userInitial = 'A';
int total_students = 100;

// ❌ Poor names
int x = 20;           // Too vague
int x1 = 20;          // Not descriptive
float a = 1200.50;    // Not meaningful

Common Naming Styles#

camelCase (popular in modern C):

int studentAge;
float monthlyExpenses;

snake_case:

int student_age;
float monthly_expenses;

Understanding Variable Size with sizeof()#

Use sizeof() to check the size of a data type:

#include <stdio.h>

int main() {
    printf("Size of char: %lu bytes\n", sizeof(char));
    printf("Size of int: %lu bytes\n", sizeof(int));
    printf("Size of float: %lu bytes\n", sizeof(float));
    printf("Size of double: %lu bytes\n", sizeof(double));
    printf("Size of long: %lu bytes\n", sizeof(long));

    return 0;
}

Typical Output:

Size of char: 1 bytes
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of long: 8 bytes

Constants#

Constants are values that don’t change. There are two ways to create them:

Method 1: Using const Keyword#

const int MAX_STUDENTS = 100;
const float PI = 3.14159;

// ❌ This will cause an error
// MAX_STUDENTS = 150;

Advantages:

  • Type checking
  • Scope rules apply
  • Can be used in functions
#include <stdio.h>

int main() {
    const int DAYS_IN_WEEK = 7;
    const float PI = 3.14159;
    const char GRADE = 'A';

    printf("Days in a week: %d\n", DAYS_IN_WEEK);
    printf("PI value: %.5f\n", PI);
    printf("Grade: %c\n", GRADE);

    return 0;
}

Method 2: Using #define Preprocessor Directive#

#define MAX_STUDENTS 100
#define PI 3.14159

// ❌ This will cause an error
// MAX_STUDENTS = 150;

Note: #define is a preprocessor directive that replaces text before compilation.

#include <stdio.h>

#define MAX_ATTEMPTS 5
#define PENALTY 10.5
#define WELCOME_MSG "Welcome to the Program"

int main() {
    printf("%s\n", WELCOME_MSG);
    printf("Max attempts: %d\n", MAX_ATTEMPTS);
    printf("Penalty points: %.1f\n", PENALTY);

    return 0;
}

const vs #define#

Featureconst#define
Type Checking✅ Yes❌ No
Debugging✅ Easier❌ Harder
Memory✅ Stored❌ Text replacement
Scope✅ Has scope❌ Global
Recommendation✅ PreferredFor macros

Best Practice: Use const for constants unless you specifically need #define features.


Type Casting#

Converting one data type to another:

Implicit Casting (Automatic)#

int x = 10;
double y = x;  // Automatically converts int to double
printf("%.1f\n", y);  // Output: 10.0

Explicit Casting (Manual)#

double price = 19.99;
int discounted_price = (int)price;  // Cast to int
printf("%d\n", discounted_price);   // Output: 19

Complete Casting Example#

#include <stdio.h>

int main() {
    int total = 100;
    int items = 3;

    // Without casting (truncates the result)
    int division1 = total / items;
    printf("Without casting: %d\n", division1);  // Output: 33

    // With casting (preserves decimals)
    double division2 = (double)total / items;
    printf("With casting: %.2f\n", division2);   // Output: 33.33

    return 0;
}

Practical Example: Student Record System#

#include <stdio.h>

#define MAX_NAME_LENGTH 50

int main() {
    // Student data
    int roll_number = 101;
    const float GPA_REQUIREMENT = 3.5;
    float student_gpa = 3.8;
    int semester = 5;

    // Display information
    printf("=== Student Information ===\n");
    printf("Roll Number: %d\n", roll_number);
    printf("Semester: %d\n", semester);
    printf("Current GPA: %.2f\n", student_gpa);
    printf("Required GPA: %.2f\n", GPA_REQUIREMENT);

    if (student_gpa >= GPA_REQUIREMENT) {
        printf("Status: EXCELLENT\n");
    } else {
        printf("Status: NEEDS IMPROVEMENT\n");
    }

    return 0;
}

Practice Exercises#

Exercise 1: Student Grade Tracker#

Declare variables for:

  • Student name (char array - we’ll learn this tomorrow)
  • Roll number (int)
  • 3 test scores (float each)
  • Calculate and print the average

Exercise 2: Bank Account System#

Create variables for:

  • Account holder name
  • Account number
  • Balance (double)
  • Interest rate (const float)
  • Print account details

Exercise 3: Unit Conversion#

  • Read temperature in Celsius
  • Cast to appropriate types
  • Convert to Fahrenheit
  • Print with proper precision

Summary#

✅ Learned all basic data types
✅ Understood variable declaration and initialization
✅ Followed proper naming conventions
✅ Used sizeof() to check memory sizes
✅ Created constants with const and #define
✅ Performed type casting

Key Points to Remember#

  1. Choose the right data type for your data
  2. Always initialize variables before use
  3. Use meaningful variable names
  4. Prefer const over #define for type safety
  5. Be aware of data type ranges to avoid overflow
  6. Use explicit casting when converting types

Next Steps#

Tomorrow we’ll learn about operators - how to perform calculations and comparisons, and understand operator precedence!

→ Continue to Day 4

← Back to Day 2