Variables and Data Types in C - Codingque

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Variables and Data Types

Variables
Variables are storage locations in memory with a name and a type. They hold data that can be used and manipulated by your program.

Declaring and Using Variables
To declare a variable, you specify its type followed by its name. You can also initialize it with a value.

#include <stdio.h>

int main() {
    int age = 25;            // Declares an integer variable named 'age' and initializes it with 25
    float salary = 3500.50;  // Declares a float variable named 'salary' and initializes it with 3500.50
    char grade = 'A';        // Declares a char variable named 'grade' and initializes it with 'A'
    
    // Printing variable values
    printf("Age: %d\\n", age);
    printf("Salary: %.2f\\n", salary);
    printf("Grade: %c\\n", grade);
    
    return 0;
}

Data Types
Data types define the type of data a variable can hold. Here are some common data types in C:

Example Program
Here’s a complete example that demonstrates declaring and using different data types:

#include <stdio.h>

int main() {
    int age = 30;             // Integer variable
    float height = 5.9;       // Floating point variable
    double weight = 68.75;    // Double precision floating point variable
    char initial = 'J';       // Character variable

    // Displaying values
    printf("Age: %d\\n", age);
    printf("Height: %.1f\\n", height);
    printf("Weight: %.2f\\n", weight);
    printf("Initial: %c\\n", initial);

    return 0;
}

Explanation of the Output:
%d is used to print integers.
%.1f is used to print floats with one decimal place.
%.2f is used to print doubles with two decimal places.
%c is used to print characters.

Size of Data Types
The size of each data type can vary based on the system and compiler, but common sizes are:

You can check the size of these data types on your system using the sizeof operator:

#include <stdio.h>

int main() {
    printf("Size of int: %zu bytes\\n", sizeof(int));
    printf("Size of float: %zu bytes\\n", sizeof(float));
    printf("Size of double: %zu bytes\\n", sizeof(double));
    printf("Size of char: %zu bytes\\n", sizeof(char));
    
    return 0;
}
Previous Next
Modern Footer