C Programming
About Lesson

Understanding Variables and Data Types

1: Variables and Data Types in C

In this lesson, we’ll explore the concept of variables and different data types available in C.

  • Variables:

    • A variable is a named location in memory used to store data.
    • Variables must be declared before they can be used.
    • Example:
       
      int age; // Declaration of an integer variable named 'age'
  • Data Types:

    • C supports various data types such as int, float, char, double, etc.
    • Each data type specifies the size and type of values that can be stored.
    • Example:
       
      int score = 95; // Integer data type
      float price = 19.99; // Floating-point data type
      char grade = 'A'; // Character data type
2: Declaration and Initialization of Variables
  • Declaration:

    • To declare a variable, specify its data type followed by the variable name.
    • Example:
      int num; // Declaration of an integer variable
      float salary; // Declaration of a floating-point variable
      char initial; // Declaration of a character variable
  • Initialization:

    • Initialization assigns an initial value to a variable at the time of declaration.
    • Example:
      int age = 30; // Declaration and initialization of an integer variable
      float pi = 3.14; // Declaration and initialization of a floating-point variable
      char grade = 'B'; // Declaration and initialization of a character variable
3: Constants in C
  • Constants:

    • Constants are like variables but their values cannot be changed during program execution.
    • C provides two types of constants:
      • Literal Constants: Directly represented in the code (e.g., 12, 'A', 3.14).
      • Symbolic Constants: Defined using #define preprocessor directive.
    • Example:
       
      #define PI 3.14159 // Symbolic constant for Pi
      const int MAX_SIZE = 100; // Constant variable for maximum size
  • Benefits:

    • Constants make programs more readable and maintainable by giving meaningful names to values.
    • They allow easy modification of values without changing the code.
4: Using Variables and Constants
    • Operations:

      • Variables and constants can be used in mathematical operations, assignments, and function calls.
      • Example:
        int a = 10, b = 20;
        int sum = a + b; // Addition using variables
        float circleArea = PI * radius * radius; // Calculating area using a constant
    • Best Practices:

      • Choose appropriate data types based on the range and precision of values.
      • Use constants for values that do not change during program execution.