CSC115 ยท 2077 ยท 5 marks
What is data type? Why do we need it in programming? Explain any three basic data types with example. [1+1+3]
What is data type? Why do we need it in programming? Explain any three basic data types with example. [1+1+3]
Quick answer
A data type defines the type of data that a variable can store, the amount of memory it occupies, and the range of values it can hold. In C, there are four fundamental data types: int, char, float, and double. The storage representation of these data types is different in memory.
Data Types in C Programming
What is a Data Type? [1 mark]
Why Do We Need Data Types in Programming? [1 mark]
Data types are needed in programming for the following reasons:
- Memory allocation: Different data types occupy different amounts of memory (e.g.,
chartakes 1 byte,inttakes 2 bytes). Specifying a data type tells the compiler how much memory to reserve. - Data validity: They ensure that only appropriate values are stored in a variable (e.g., an
intvariable cannot store a decimal value accurately). - Operations: They determine what operations are valid on a variable (e.g., arithmetic on
intandfloat, character operations onchar). - Type safety: They help the compiler detect errors when incompatible data is used.
Three Basic Data Types with Examples [3 marks]
1. int (Integer Data Type)
- Used to store whole numbers (positive, negative, or zero).
- On a 16-bit machine, it occupies 2 bytes of memory.
- Range: -32768 to 32767 (for signed int).
Example:
#include <stdio.h>
int main() {
int age = 20;
printf("Age = %d", age);
return 0;
}
Output:
Age = 20
2. float (Floating Point Data Type)
- Used to store single precision floating point numbers (numbers with decimal points).
- Occupies 4 bytes of memory.
- Range: 3.4E-38 to 3.4E+38.
Example:
#include <stdio.h>
int main() {
float price = 99.50;
printf("Price = %.2f", price);
return 0;
}
Output:
Price = 99.50
3. char (Character Data Type)
- Used to store a single character (letter, digit, or symbol).
- Occupies 1 byte of memory.
- Range: -128 to 127 (for signed char), or 0 to 255 (for unsigned char).
- Characters are stored internally as their ASCII values.
Example:
#include <stdio.h>
int main() {
char grade = 'A';
printf("Grade = %c", grade);
return 0;
}
Output:
Grade = A
Summary Table
| Data Type | Size (bytes) | Range | Use |
|---|---|---|---|
int | 2 | -32768 to 32767 | Whole numbers |
float | 4 | 3.4E-38 to 3.4E+38 | Decimal numbers |
char | 1 | -128 to 127 | Single characters |
Note: The size and range shown above are for a 16-bit machine. Values may vary on machines with different word sizes.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.