-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertintoarray.cpp
75 lines (70 loc) · 1.71 KB
/
insertintoarray.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//C++ program to insert elements into the array using static and dynamic array by Vishruth codes
#include<iostream>
using namespace std;
//Creation of template function displayed
template <typename t>
void displayed(t a[], int n)
{
cout<<"\nThe elements of the array are: ";
for(int i=0;i<n;i++)
{
cout<<a[i]<<", ";
}
}
//Creation of template function staticarray
template <typename t>
void staticarray(int n)
{
//declaring a dynamic array 'ar' of size n
t ar[n];
cout<<"\nEnter the "<<n<<" elements (separated by a space): ";
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
displayed(ar,n);
}
//Creation of template function dynamicarray
template <typename t>
void dynamicarray(int n)
{
//declaring a dynamic array 'p' of size n
t *p=new t[n];
cout<<"\nEnter the "<<n<<" elements (separated by a space): ";
for(int i=0;i<n;i++)
{
cin>>p[i];
}
displayed(p, n);
//deleting the dynamic array to prevent memory leak
delete []p;
}
int main()
{
int n,ch;
cout<<"\nEnter the size of the array: ";
cin>>n;
cout<<"\nEnter -\n1. for static array\n2. for dynamic array\n:- ";
cin>>ch;
switch(ch)
{
case 1:
{
//declaring the datatype that the function 'staticarray' will receive
staticarray<char>(n);
break;
}
case 2:
{
//declaring the datatype that the function 'dynamicarray' will receive
dynamicarray<char>(n);
break;
}
default:
{
cout<<"\nInvalid input!";
exit(0);
}
}
return 0;
}