2077 5

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]

C ProgrammingChapter 2: Elements of CData types

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., char takes 1 byte, int takes 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 int variable cannot store a decimal value accurately).
  • Operations: They determine what operations are valid on a variable (e.g., arithmetic on int and float, character operations on char).
  • 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 TypeSize (bytes)RangeUse
int2-32768 to 32767Whole numbers
float43.4E-38 to 3.4E+38Decimal numbers
char1-128 to 127Single 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.