Как вывести элементы массива?
Нужно сделать так, чтобы один раз выводился текст, а рядом выводились элементы массива. Например:
ввод
5
вывод
output of numbers: 56 53 2 87 76
Код:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "size array:" << endl;
cin >> N;
if (N > 1 && N < 256) {
int* arr = new int[N];
bool alreadyThere;
for (int j = 0; j < N;)
{
alreadyThere = false;
int newRandomValue = rand() % 256;
for (int i = 0; i < j; i++)
{
if (arr[i] == newRandomValue)
{
alreadyThere = true;
break;
}
}
if (!alreadyThere)
{
arr[j] = newRandomValue;
j++;
}
}
cout << "output of numbers: " << arr[j];
}
else {
cout << "wrong number entered" << endl;
}
return 0;
}
Ответы (2 шт):
Автор решения: Mikhailo
→ Ссылка
Так годится?
unsigned int N;
cin >> N;
cout << "output of numbers: ";
for(;N-->0;) cout << rand() % 256 << " ";
cout << endl;
Автор решения: gbg
→ Ссылка
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "size array:" << endl;
cin >> N;
if (N > 1 && N < 256) {
int* arr = new int[N];
bool alreadyThere;
cout << "output of numbers: ";
for (int j = 0; j < N;)
{
alreadyThere = false;
int newRandomValue = rand() % 256;
for (int i = 0; i < j; i++)
{
if (arr[i] == newRandomValue)
{
alreadyThere = true;
break;
}
}
if (!alreadyThere)
{
arr[j] = newRandomValue;
cout << " " << arr[j];
j++;
}
}
}
else
{
cout << "wrong number entered" << endl;
}
return 0;
}
Просмотр онлайн в IDEONE