Calculate Storage for Different Array Types

Calculate Storage for Different Array Types

Medium C++ C++ Data Types 36 views
Explanation Complexity

Problem Statement

Show memory consumption of arrays with different data types. This teaches memory optimization.
Logic: Calculate array size = elements × sizeof(type)

Input Format

No user input.
Arrays of different data types are defined in the program.

Output Format

Memory used by each array.

Example

Arrays with 5 elements of each type:

• int

• char

• float

• double
int array size    = 20 bytes
char array size   = 5 bytes
float array size  = 20 bytes
double array size = 40 bytes

Constraints

• Array size is fixed

• Memory depends on data type size

• System architecture affects size

Concept Explanation

Each array consumes memory based on:

• number of elements

• size of each element

Bigger data types use more memory.

Step-by-Step Explanation

1.Decide number of elements in array (for example n = 5).

2.Create arrays of different data types.

3.Find size of one element using sizeof(type).

4.Calculate total memory:

• array_size = n × sizeof(type)

5.Print memory used by each array.

Concept Explanation

Each array consumes memory based on:

• number of elements

• size of each element

Bigger data types use more memory.

Step-by-Step Explanation

1.Decide number of elements in array (for example n = 5).

2.Create arrays of different data types.

3.Find size of one element using sizeof(type).

4.Calculate total memory:

• array_size = n × sizeof(type)

5.Print memory used by each array.

Input / Output Format

Input Format
No user input.
Arrays of different data types are defined in the program.
Output Format
Memory used by each array.
Constraints
• Array size is fixed

• Memory depends on data type size

• System architecture affects size

Examples

Input:
Arrays with 5 elements of each type: • int • char • float • double
Output:
int array size = 20 bytes char array size = 5 bytes float array size = 20 bytes double array size = 40 bytes

Example Solution (Public)

C++
void question9_array_memory() {
    int intArray[10];
    char charArray[10];
    double doubleArray[10];
    
    cout << "Memory for int[10]: " << sizeof(intArray) << " bytesn";
    cout << "Memory for char[10]: " << sizeof(charArray) << " bytesn";
    cout << "Memory for double[10]: " << sizeof(doubleArray) << " bytesn";
}

Official Solution Code

void question9_array_memory() {
    int intArray[10];
    char charArray[10];
    double doubleArray[10];
    
    cout << "Memory for int[10]: " << sizeof(intArray) << " bytesn";
    cout << "Memory for char[10]: " << sizeof(charArray) << " bytesn";
    cout << "Memory for double[10]: " << sizeof(doubleArray) << " bytesn";
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.