The program is used to demonstrate dynamic memory allocation for arrays in C++.
However, there is an issue in this program. The size of the array is not initialized before it is used to create the array using dynamic memory allocation. This can cause undefined behavior as the value of n is indeterminate and may contain a garbage value. To fix this issue, the program should prompt the user to enter the value of n before allocating memory for the array.
#include<iostream> using namespace std; int main() { int n; int *arr=new int[n]; cout<<"Enter the size of the array : "; std::cin>>n; cout<<"\nEnter the element : "; for(int i=0;i<n;i++) { cin>>arr[i]; } cout<<"\nThe elements that you have entered are :"; for(int i=0;i<n;i++) { cout<<arr[i]<<","; } delete arr; return 0; }To download raw file Click Here
Enter the size of the array : 4 Enter the element : 12 13 14 14 The elements that you have entered are :12,13,14,14,
This program takes in the total number of students and their respective GPAs as input from the user using dynamic memory allocation. It then displays the GPAs entered by the user. Here's a step-by-step explanation of the program:
Overall, this program demonstrates the use of dynamic memory allocation and pointer arithmetic to store and access data in memory.
#include<iostream> #include<cstring> using namespace std; int main() { int num; cout<<"Enter total number of students: "; cin>>num; float* ptr; ptr = new float[num]; cout<<"Enter GPA of students."<<endl; for (int i=0;i<num;++i) { cout<<"Student"<<i+1<<": "; cin>>*(ptr+i); } cout<<"\nDisplaying GPA of students."<<endl; for (int i=0;i<num;++i) { cout<<"Student"<<i+1<<" :"<<*(ptr + i)<<endl; } delete [] ptr; return 0; }To download raw file Click Here
Enter total number of students: 3 Enter GPA of students. Student1: 89 Student2: 78 Student3: 98 Displaying GPA of students. Student1 :89 Student2 :78 Student3 :98
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions