Department of Engineering Technology
Computer programming (CET-121)
Fall 2023
Lab 24
Objective:
To familiarize students basic Pointers – II in using C++.
Student Information
Student Name
Student ID
Date
Assessment
Marks Obtained
Remarks
Signature
Lab 24: Pointers – II
Dynamic Memory Allocation (DMA)
Many times, you are not aware in advance how much memory you will need to store particular information
in a defined variable and the size of required memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given type using a special operator
in C++ which returns the address of the space allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-
allocates memory that was previously allocated by new operator.
Following example shows the implementation of DMA concept in C++:
#include <iostream>
using namespace std;
int main()
{
int *ptr;
int i, val;
ptr = new int[4];
for(i=0;i<4;i++)
{
cout<<"Enter value at "<<i<<": ";
cin>>*(ptr+i);
}
for(int i=0;i<4;i++)
{
val = *(ptr+i);
val = val*val;
cout << val << endl;
}
delete [] ptr;
ptr = NULL;
ptr = new int[10];
for(i=0;i<10;i++)
{
cout<<"Enter value at "<<i<<": ";
cin>>*(ptr+i);
}
for(int i=0;i<10;i++)
{cout << *(ptr+i) << endl;}
delete [] ptr;
ptr = NULL;
return 0;
}
Task 1
Write a C++ program that performs the following operations:
Dynamically allocate the memory to hold 10 integer values
Take input from the user
Sort the values using Bubble Sort algorithm which was already covered in Lab # 17.
Free the memory after display the sorted data.
Task 2
Write a C++ program that performs the following operations:
Dynamically allocate the memory to hold 10 integer values
Take input from the user
Take another value as input from the user to search
Perform the searching using Linear Search algorithm which was already covered in Lab # 17.
Free the memory after display the sorted data.
Task 3
Write a C++ program that performs the following operations:
Dynamically allocate the memory to hold 10 integer values
Display the minimum, maximum and average from the entered values.
Free the memory after display the sorted data.