Article by: Manish Methani
Last Updated: November 8, 2021 at 2:04pm IST
Data types in C programming are used to specify the type of data that a variable can hold. Each data type has a different size, range, and usage, and it is essential to understand them to write efficient and error-free code. Here's a tutorial to help you understand data types in C programming:
C programming has four basic datatypes: int, float, double, and char.
Here's an example of using basic datatypes in C programming:
#include <stdio.h> int main() { int age = 30; float temperature = 36.5; double salary = 2000.50; char grade = 'A'; printf("Age is %d", age); printf("Temperature is %.1f", temperature); printf("Salary is %.2lf", salary); printf("Grade is %c", grade); return 0; }
Derived datatypes in C programming are created by combining basic datatypes or other derived datatypes.
Here's an example of using derived datatypes in C programming:
#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; int *p; struct student { char name[50]; int age; float gpa; }; struct student s1 = {"John Doe", 20, 3.5}; p = &numbers[0]; printf("First element of the array: %d", *p); printf("Student name: %s", s1.name); printf("Student age: %d", s1.age); printf("Student GPA: %.1f", s1.gpa); return 0; }
Output:
First element of the array: 10 Student name: John Doe Student age: 20 Student GPA: 3.5
Enumerated data types in C programming are used to define a set of named constants.
Here's an example of using enumerated datatypes in C programming:
#include <stdio.h> enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; int main() { enum week today = Monday; printf("Today is %d", today); return 0; }
Output:
Today is 0
In conclusion, datatypes are an essential concept in C programming. By following this tutorial, you have learned about basic, derived, and enumerated datatypes in C programming and how to use them effectively with code examples.