Answer to Question #27262 in C++ for Calvin

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] << " ";

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be the first!

Leave a comment

Ask Your question

New on Blog