C++:Pointers-new and delete operator examples

Example:4
Write a C++ program to take input for “n” element using an array further display all the elements. Also check and print the lowest array element. Allocate the memory dynamically.

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
	int n,i,m;
	char ch;
	do
	{
		cout<<"Enter total elements ";
		cin>>n;
		//dynamic memory allocation
		int *p=new int[n];
		//input
		for(i=0;i<n;i++)
		{
			cout<<"Enter "<<i<<" element ";
			cin>>p[i];
		}
		//display
		m=p[0];
		//or
		//m=*p;
		for(i=0;i<n;i++)
		{
			cout<<p[i]<<endl;
			if(p[i]<m)
			m=p[i];
		}
		//release memory
		delete []p;
		cout<<"Min element = "<<m<<endl;
		cout<<"Lke to cont .... (y/n) ";
		cin>>ch;
	}while(ch=='y' || ch=='Y');
	

	return(0);
	
}

Output:

Enter total elements 5
Enter 0 element 24
Enter 1 element 6
Enter 2 element 32
Enter 3 element 5
Enter 4 element 95
24
6
32
5
95
Min element = 5
Lke to cont …. (y/n) y
Enter total elements 2
Enter 0 element 54
Enter 1 element 25
54
25
Min element = 25
Lke to cont …. (y/n) n

Example:5
Write a C++ program to take input for “n” element using an array further display all the elements. Also check and print the following:
1. lowest array element.
2. Largest array element.
3. Difference between largest and lowest array element.

Allocate the memory dynamically.
Sol:

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
	int n,i,ma,mi,d;
	char ch;
	do
	{
		cout<<"Enter total elements ";
		cin>>n;
		//dynamic memory allocation
		int *p=new int[n];
		//input
		for(i=0;i<n;i++)
		{
			cout<<"Enter "<<i<<" element ";
			cin>>p[i];
		}
		//display
		ma=p[0];
		mi=p[0];
		//or
		//ma=*p;
		//mi=*p;
		for(i=0;i<n;i++)
		{
			cout<<p[i]<<endl;
			//max no
			if(p[i]>ma)
			ma=p[i];
			//min no
			if(p[i]<mi)
			mi=p[i];
		}
		//release memory
		delete []p;
		cout<<"Max element = "<<ma<<endl;
		cout<<"Min element = "<<mi<<endl;
		d=ma-mi;
		cout<<"Diff  = "<<d<<endl;
		cout<<"Lke to cont .... (y/n) ";
		cin>>ch;
	}while(ch=='y' || ch=='Y');
	

	return(0);
	
}

Output:

Enter total elements 5
Enter 0 element 24
Enter 1 element 63
Enter 2 element 2
Enter 3 element 85
Enter 4 element 6
24
63
2
85
6
Max element = 85
Min element = 2
Diff = 83
Lke to cont …. (y/n) y
Enter total elements 3
Enter 0 element 25
Enter 1 element 6
Enter 2 element 45
25
6
45
Max element = 45
Min element = 6
Diff = 39
Lke to cont …. (y/n) n