Home » C++ programs

C++ program to declare, read and print dynamic integer array

In this C++ program, we are going to declare, read and print a one dimensional array of the integers, to declare dynamic array we are using new operator and to delete/free memory, we are using delete operator.
Submitted by IncludeHelp, on May 03, 2018

Prerequisite: new and delete operator in C++

Here, we will learn how to declare, read and print dynamically allocated array?

A dynamic array declares by new operator and deletes by delete operator.

Here we will read total number of elements, read total elements and print them.

Consider the following program:

#include <iostream>

using namespace std;

int main()
{
	int *arr;	
	int i,n;
	
	cout<<"Enter total number of elements:";
	cin>>n;
	
	//declare memory
	arr=new int(n);
	
	cout<<"Input "<<n<<" elements"<<endl;
	for(i=0;i<n;i++)
	{
		cout<<"Input element "<<i+1<<": ";
		cin>>arr[i];
	}
	
	cout<<"Entered elements are: ";
	for(i=0;i<n;i++)
	{
		cout<<arr[i]<<" ";
	}
	cout<<endl;
	
	delete (arr);
	return 0;	
}

Output

Enter total number of elements:5
Input 5 elements
Input element 1: 10 
Input element 2: 20 
Input element 3: 30 
Input element 4: 40 
Input element 5: 50 
Entered elements are: 10 20 30 40 50 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.