Advertisement
ruhan008

Untitled

Oct 3rd, 2023
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //Q2) Create an array of integers using dynamic memory allocation. Display the sum, all the integers and there respective addresses.
  2.  
  3. #include <iostream>
  4. #include <stdlib.h>
  5.  
  6. using namespace std;
  7.  
  8. int main(){
  9.    
  10.     int n;
  11.     cout<<"Enter the size of the array: ";
  12.     cin>>n;
  13.     int *arr=(int*)malloc(n*sizeof(int));
  14.     cout<<endl;
  15.     cout<<"Dynamically allocated memory of size: "<<sizeof(int)*n<<endl<<endl;
  16.  
  17.     cout<<"Enter the array elements: ";
  18.     for(int i=0;i<n;i++){
  19.         cin>>*(arr+i);
  20.     }
  21.  
  22.     int sum=0;
  23.     for(int i=0;i<n;i++){
  24.         cout<<"arr["<<i<<"] = "<<*(arr+i) <<", &arr["<<i<<"] = "<<(arr+i)<<endl;
  25.         sum=sum+(*(arr+i));
  26.     }
  27.     cout<<"Sum of all the array elements: "<<sum<<endl<<endl;
  28.     free(arr);
  29.     arr=NULL;
  30.     cout<<"Memory released!!!"<<endl;
  31.  
  32.     return 0;
  33. }
  34. /*
  35.     OUTPUT:
  36.  
  37.     Enter the size of the array: 5
  38.  
  39.     Dynamically allocated memory of size: 20
  40.  
  41.     Enter the array elements: 1 2 3 4 5
  42.     arr[0] = 1, &arr[0] = 0x559908387ad0
  43.     arr[1] = 2, &arr[1] = 0x559908387ad4
  44.     arr[2] = 3, &arr[2] = 0x559908387ad8
  45.     arr[3] = 4, &arr[3] = 0x559908387adc
  46.     arr[4] = 5, &arr[4] = 0x559908387ae0
  47.     Sum of all the array elements: 15
  48.  
  49.     Memory released!!!
  50.  
  51. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement