173k views
5 votes
Create a dynamic array of 100 integer values named myNums. Use a pointer variable (like ptr) which points to this array. Use this pointer variable to initialize the myNums array from 2 to 200 and then display the array elements. Delete the dynamic array myNums at the end. You just need to write part of the program.

2 Answers

4 votes

Final answer:

To create a dynamic array of integers in C++, you can use the 'new' operator. Here is an example program that demonstrates how to do it.

Step-by-step explanation:

To create a dynamic array of 100 integer values named myNums, you can use the 'new' operator in C++. Initialize a pointer variable named ptr and assign it the memory address of the dynamic array. Use a for loop to assign values from 2 to 200 to the elements of the myNums array. Then, use another for loop to display the array elements.

Here is an example of how you can do this:

#include <iostream>
using namespace std;

int main() {
int* ptr;
ptr = new int[100];

for (int i = 0; i < 100; i++) {
ptr[i] = i + 2;
}

for (int i = 0; i < 100; i++) {
cout << ptr[i] << ' ';
}

delete[] ptr;
return 0;
}

In this example, we create a dynamic array 'ptr' of size 100 using the 'new' operator. We then use two for loops: the first one to assign values from 2 to 200 to the elements of the array, and the second one to display the elements. Finally, we use 'delete[]' to free the memory allocated for the dynamic array.

User Takeradi
by
3.6k points
2 votes

Answer:

The required part of the program in C++ is as follows:

int *ptr;

int *myNums = new int(100);

srand (time(NULL));

for (int i = 0; i < 100; i++) {

myNums[i] = rand() % 200 + 2; }

ptr = myNums;

cout << "Output: ";

for (int i = 0; i < 100; i++) {

cout <<*(ptr + i) << " "; }

delete[] myNums;

Step-by-step explanation:

This declares a pointer variable

int *ptr;

This declares the dynamic array myNums

int *myNums = new int(100);

This lets the program generate different random numbers

srand (time(NULL));

This iterates through the array

for (int i = 0; i < 100; i++) {

This generates an integer between 2 and 200 (inclusive) for each array element

myNums[i] = rand() % 200 + 2; }

This stores the address of first myNums in the pointer

ptr = myNums;

This prints the header "Output"

cout << "Output: ";

This iterates through the pointer

for (int i = 0; i < 100; i++) {

Print each element of the array, followed by space

cout <<*(ptr + i) << " "; }

This deletes the dynamic array

delete[] myNums;

User Loremar Marabillas
by
4.1k points