In C programming, data types define the type and size of data that can be stored in a variable. C has several built-in data types, each designed for specific purposes. Here’s an overview of the primary data types in C:
These are the fundamental data types in C, primarily used to define variables for storing simple values like integers and characters.
int: Used to store integers (whole numbers) without decimal points.
Example: int age = 25;
Size: Typically 4 bytes.
Range: Depends on the system (e.g., -2,147,483,648 to 2,147,483,647 on 32-bit systems).
float: Used to store single-precision floating-point numbers (numbers with decimal points).
Example: float height = 5.9;
Size: Typically 4 bytes.
Precision: Up to 6-7 decimal digits.
double: Used to store double-precision floating-point numbers for higher precision than float.
Example: double distance = 12345.6789;
Size: Typically 8 bytes.
Precision: Up to 15-16 decimal digits.
char: Used to store single characters. It’s also treated as an integer data type in C because each character has an ASCII code.
Example: char grade = 'A';
Size: 1 byte.
Range: -128 to 127 or 0 to 255, depending on if char is signed or unsigned.
Derived data types are built from the basic data types and used for more complex data structures.
Arrays: A collection of variables of the same type stored in contiguous memory locations.
Example: int numbers[5] = {1, 2, 3, 4, 5};
Usage: Accessed using indices, starting from 0.
Pointers: Variables that store the memory address of another variable.
Example: int *ptr = # (pointer to an integer)
Usage: Allows direct memory manipulation, which is powerful but requires careful handling.
Structures (struct): A user-defined data type that groups variables of different types.
Example:-
struct Student {
int id;
char name[50];
float grade;
};
Usage: Useful for representing complex data structures (e.g., a student with ID, name, and grade).
Unions (union): Similar to structures but store only one of the member variables at a time, as all members share the same memory location.
Example:-
union Data {
int id;
float value;
};
Usage: Saves memory when only one member is needed at a time.
enum: A user-defined data type consisting of named integer constants, improving code readability.
Example:
enum Days { MON, TUE, WED, THU, FRI, SAT, SUN };
Usage: Assigns symbolic names to integral values, making code more understandable.
void: Represents the absence of a data type. Commonly used in functions.
Function without a return value: void display() { ... }
Void pointer: void *ptr; (a generic pointer that can point to any data type)
#include <stdio.h>
int main() {
int age = 21;
float height = 5.9;
char grade = 'A';
double largeNumber = 123456789.123456;
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);
printf("Large Number: %lf\n", largeNumber);
return 0;
}
Here are ten practical examples of basic data types in C programming: int, float, double, and char. These examples demonstrate how each type is used in simple scenarios.
#include <stdio.h>
int main() {
int age1 = 25;
int age2 = 30;
int difference = age2 - age1;
printf("Age difference: %d years\n", difference);
return 0;
}
#include <stdio.h>
int main() {
int itemCount = 150;
printf("Items in stock: %d\n", itemCount);
return 0;
}
#include <stdio.h>
int main() {
float temp1 = 72.5;
float temp2 = 68.4;
float averageTemp = (temp1 + temp2) / 2;
printf("Average temperature: %.2f°F\n", averageTemp);
return 0;
}
#include <stdio.h>
int main() {
float radius = 5.2;
float area = 3.14 * radius * radius;
printf("Area of the circle: %.2f\n", area);
return 0;
}
#include <stdio.h>
int main() {
double balance = 123456789.987654;
printf("Account balance: %.6lf\n", balance);
return 0;
}
#include <stdio.h>
int main() {
double speed = 89.45; // in km/h
double time = 2.5; // in hours
double distance = speed * time;
printf("Distance traveled: %.2lf km\n", distance);
return 0;
}
int main() {
char grade = 'A';
printf("Student grade: %c\n", grade);
return 0;
}
#include <stdio.h>
int main() {
char firstInitial = 'J';
char lastInitial = 'D';
printf("Initials: %c%c\n", firstInitial, lastInitial);
return 0;
}
#include <stdio.h>
int main() {
int dividend = 29;
int divisor = 5;
int remainder = dividend % divisor;
printf("Remainder: %d\n", remainder);
return 0;
}
#include <stdio.h>
int main() {
float celsius = 36.6;
float fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
return 0;
}
Here are ten examples of derived data types in C programming: arrays, pointers, structures, and unions. Each example demonstrates practical uses of these derived types in real-world scenarios.
#include <stdio.h>
int main() {
int scores[5] = {78, 85, 92, 88, 76};
for (int i = 0; i < 5; i++) {
printf("Score of student %d: %d\n", i + 1, scores[i]);
}
return 0;
}
#include <stdio.h>
int main() {
float monthlySales[3] = {1200.50, 1345.75, 1289.90};
float totalSales = 0;
for (int i = 0; i < 3; i++) {
totalSales += monthlySales[i];
}
printf("Total sales: %.2f\n", totalSales);
return 0;
}
#include <stdio.h>
int main() {
int number = 25;
int *ptr = &number;
printf("Value of number: %d\n", number);
printf("Address of number: %p\n", (void*)ptr);
return 0;
}
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("Swapped values: x = %d, y = %d\n", x, y);
return 0;
}
#include <stdio.h>
struct Book {
int id;
char title[50];
float price;
};
int main() {
struct Book book1 = {101, "C Programming", 29.99};
printf("Book ID: %d\n", book1.id);
printf("Title: %s\n", book1.title);
printf("Price: %.2f\n", book1.price);
return 0;
}
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {5, 10};
printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
#include <stdio.h>
union Data {
int i;
float f;
char c;
};
int main() {
union Data data;
data.i = 10;
printf("Integer: %d\n", data.i);
data.f = 2.5;
printf("Float: %.2f\n", data.f);
data.c = 'A';
printf("Character: %c\n", data.c);
return 0;
}
#include <stdio.h>
union Measurement {
int length;
float weight;
double temperature;
};
int main() {
union Measurement measure;
measure.length = 25;
printf("Length: %d cm\n", measure.length);
measure.weight = 55.5;
printf("Weight: %.2f kg\n", measure.weight);
measure.temperature = 36.6;
printf("Temperature: %.2f °C\n", measure.temperature);
return 0;
}
#include <stdio.h>
struct Employee {
int id;
char name[50];
float salary;
};
int main() {
struct Employee employees[2] = {
{1, "Alice", 50000},
{2, "Bob", 55000}
};
for (int i = 0; i < 2; i++) {
printf("Employee ID: %d\n", employees[i].id);
printf("Name: %s\n", employees[i].name);
printf("Salary: %.2f\n\n", employees[i].salary);
}
return 0;
}
#include <stdio.h>
struct Car {
char model[20];
int year;
float price;
};
int main() {
struct Car car1 = {"Toyota Corolla", 2020, 20000};
struct Car *ptr = &car1;
printf("Car Model: %s\n", ptr->model);
printf("Year: %d\n", ptr->year);
printf("Price: %.2f\n", ptr->price);
return 0;
}
Here are ten practical examples using the enum (enumeration) data type in C. Enumerations are used to define a set of named integer constants, which improve readability and maintainability by giving meaningful names to integer values.
#include <stdio.h>
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
enum Day today = WED;
printf("Today is day number %d of the week.\n", today + 1); // Adds 1 to make it more intuitive (1 for Monday)
return 0;
}
#include <stdio.h>
enum TrafficLight { RED, YELLOW, GREEN };
int main() {
enum TrafficLight signal = RED;
if (signal == RED) {
printf("Stop\n");
} else if (signal == YELLOW) {
printf("Get Ready\n");
} else {
printf("Go\n");
}
return 0;
}
#include <stdio.h>
enum OrderStatus { ORDERED, SHIPPED, DELIVERED, CANCELED };
int main() {
enum OrderStatus status = SHIPPED;
switch (status) {
case ORDERED:
printf("Your order is placed.\n");
break;
case SHIPPED:
printf("Your order is on the way.\n");
break;
case DELIVERED:
printf("Your order has been delivered.\n");
break;
case CANCELED:
printf("Your order was canceled.\n");
break;
}
return 0;
}
#include <stdio.h>
enum LogLevel { INFO, WARNING, ERROR, CRITICAL };
void logMessage(enum LogLevel level) {
if (level == CRITICAL) {
printf("Critical error occurred.\n");
} else if (level == ERROR) {
printf("Error occurred.\n");
} else if (level == WARNING) {
printf("Warning issued.\n");
} else {
printf("Informational message.\n");
}
}
int main() {
logMessage(ERROR);
return 0;
}
#include <stdio.h>
enum Month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
int main() {
enum Month birthMonth = JUN;
printf("Birth month: %d\n", birthMonth);
return 0;
}
#include <stdio.h>
enum Temperature { LOW, MEDIUM, HIGH };
int main() {
enum Temperature currentTemp = HIGH;
if (currentTemp == HIGH) {
printf("Temperature is high.\n");
} else if (currentTemp == MEDIUM) {
printf("Temperature is moderate.\n");
} else {
printf("Temperature is low.\n");
}
return 0;
}
#include <stdio.h>
enum Boolean { FALSE, TRUE };
int main() {
enum Boolean isRaining = TRUE;
if (isRaining) {
printf("Take an umbrella.\n");
} else {
printf("No need for an umbrella.\n");
}
return 0;
}
#include <stdio.h>
enum PaymentMethod { CASH, CREDIT, DEBIT, PAYPAL };
int main() {
enum PaymentMethod payment = CREDIT;
switch (payment) {
case CASH:
printf("Payment by cash.\n");
break;
case CREDIT:
printf("Payment by credit card.\n");
break;
case DEBIT:
printf("Payment by debit card.\n");
break;
case PAYPAL:
printf("Payment by PayPal.\n");
break;
}
return 0;
}
#include <stdio.h>
enum PowerState { OFF, ON, SLEEP };
int main() {
enum PowerState deviceState = SLEEP;
if (deviceState == OFF) {
printf("Device is turned off.\n");
} else if (deviceState == ON) {
printf("Device is running.\n");
} else {
printf("Device is in sleep mode.\n");
}
return 0;
}
#include <stdio.h>
enum EducationLevel { HIGH_SCHOOL, UNDERGRADUATE, GRADUATE, POSTGRADUATE };
int main() {
enum EducationLevel level = GRADUATE;
if (level == POSTGRADUATE) {
printf("Education level: Postgraduate\n");
} else if (level == GRADUATE) {
printf("Education level: Graduate\n");
} else if (level == UNDERGRADUATE) {
printf("Education level: Undergraduate\n");
} else {
printf("Education level: High School\n");
}
return 0;
}