Question #27262

Write a program that asks user to input an integer number N. The program then fills out the array of N integers with random numbers and prints the array on the screen.

Expert's answer

#include <iostream>

#include <vector>

using namespace std;

#include <cstdlib>

int main() {

int N = -1;

//N can be only non-negative, so we ask to input N while it becomes greater or equal to zero

while (N < 0) {

& cout << "Input the array length N: ";

& cin >> N;

}

vector<int> a(N); //Create a dynamic array with N elements

cout << "Random numbers array:" << endl;

srand(time(0)); //Initialize the pseudo-random generator with the current time

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

& a[i] = rand() - rand(); //rand() returns only positive numbers, but rand()-rand() can return also negative numbers

& cout << a[i] << " ";

}

}

#include <vector>

using namespace std;

#include <cstdlib>

int main() {

int N = -1;

//N can be only non-negative, so we ask to input N while it becomes greater or equal to zero

while (N < 0) {

& cout << "Input the array length N: ";

& cin >> N;

}

vector<int> a(N); //Create a dynamic array with N elements

cout << "Random numbers array:" << endl;

srand(time(0)); //Initialize the pseudo-random generator with the current time

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

& a[i] = rand() - rand(); //rand() returns only positive numbers, but rand()-rand() can return also negative numbers

& cout << a[i] << " ";

}

}

Learn more about our help with Assignments: C++

## Comments

## Leave a comment