(Basic) Find Sum Using Dynamic Memory Allocation: C++

Advertisement:

This video tutorial illustrates basics of Dynamic memory allocation in C++. It shows the use of new and delete operator for allocating and deallocating the memory dynamically.

Find the sum of entered elements using dynamic memory allocation in c++.

In cpp, dynamic memory management can be done using the operators new and delete.
Operator new is used to allocate the memory during execution time or run time, the dynamically allocated memory can be freed / released using the operator delete.
Syntax:

< data_type >  < pointer_variable > = new < data_type >[size];

Full Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include< iostream .h>
#include< conio .h>
 
void main()
{
  int sum=0, N;
  clrscr();
 
  cout< <"Enter array size\n";
  cin>>N;
 
  int *a = new int[N];
  cout< <"\nEnter "<<N<<" integer numbers"<<endl;
  for(int i=0; i<N; i++)
   cin>>a[i];
 
   cout< <"Input array is.."<<endl;
   for(i=0; i<N; i++)
   {
    cout<<a[i]<<endl;
    sum = sum + a[i]; // sum += a[i];
   }
   cout<<"Total Sum: "<<sum;
 
   delete(a);
   getch();
}

We need not include any extra header file to perform dynamic memory allocation or de-allocation.

int *ptr = new int[N];

here it is mandatory to take pointer variable for dynamic memory allocation.

for de-allocation we use delete operator: delete(ptr);

NOTE:
Student *p = new Student[3];

where Student is a user defined data type, maybe structure or class.

Student *p = new Student; // This is for only 1 student.

Video Tutorial:(Basic) Find Sum Using Dynamic Memory Allocation


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=Iqqfa-UjONo [Watch the Video In Full Screen.]



Output:
Enter array size
5
Enter 5 integer numbers
1
2
3
4
5
Input array is..
1
2
3
4
5
Total Sum: 15

Advertisement:

Enter your email address:

RSS Feed




Leave a Reply