Wednesday, 5 February 2025

C Language Data Types

C Language Data Types

Definition:

A data type in C defines the type of data that a variable can store. It determines:

The size of memory allocated.

The range of values it can hold.

The operations that can be performed on it.



---

Types of Data Types in C

1. Primary (Fundamental) Data Types

These are basic data types provided by C.

Example of Primary Data Types:

#include <stdio.h>
int main() {
    int num = 25;
    float pi = 3.14;
    double largeNum = 12345.6789;
    char grade = 'A';
    _Bool isPass = 1;

    printf("Integer: %d\n", num);
    printf("Float: %.2f\n", pi);
    printf("Double: %.4lf\n", largeNum);
    printf("Character: %c\n", grade);
    printf("Boolean: %d\n", isPass);

    return 0;
}

Output:

Integer: 25
Float: 3.14
Double: 12345.6789
Character: A
Boolean: 1


---

2. Derived Data Types

These are derived from fundamental data types.

Example: Array

#include <stdio.h>
int main() {
    int numbers[3] = {10, 20, 30};
    printf("First element: %d", numbers[0]);
    return 0;
}

Output:

First element: 10

Example: Pointer

#include <stdio.h>
int main() {
    int num = 10;
    int *ptr = &num;
    printf("Value: %d, Address: %p", *ptr, ptr);
    return 0;
}

Output: (Address will vary)

Value: 10, Address: 0x7ffee1b3a1f4

Example: Structure

#include <stdio.h>
struct Student {
    int roll;
    char name[20];
};
int main() {
    struct Student s1 = {101, "John"};
    printf("Roll: %d, Name: %s", s1.roll, s1.name);
    return 0;
}

Output:

Roll: 101, Name: John


---

3. User-Defined Data Types

Example: typedef

#include <stdio.h>
typedef unsigned int uint;
int main() {
    uint age = 25;
    printf("Age: %u", age);
    return 0;
}

Output:

Age: 25

Example: enum

#include <stdio.h>
enum Color {RED, GREEN, BLUE};
int main() {
    enum Color favColor = GREEN;
    printf("Favorite Color: %d", favColor);
    return 0;
}

Output:

Favorite Color: 1


---

4. Void Data Type

Represents an absence of data.

Used in function declarations where no value is returned.


Example: void Function

#include <stdio.h>
void sayHello() {
    printf("Hello, World!");
}
int main() {
    sayHello();
    return 0;
}

Output:

Hello, World!


---

Conclusion

Primary types: int, float, char, double, _Bool

Derived types: array, pointer, structure, union

User-defined types: typedef, enum

Void type: Represents no data


No comments:

Post a Comment