#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
}
return 0;
}
Asked
Active
Viewed 47 times
-2

463035818_is_not_an_ai
- 109,796
- 11
- 89
- 185

heung min son
- 9
- 2
-
Use a loop and `cout`. Have you made an attempt at outputting the values? – NathanOliver Oct 19 '18 at 19:44
-
1Please consider to pick a [better resource for learning](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Your code is not valid c++ – 463035818_is_not_an_ai Oct 19 '18 at 19:44
-
2`int array[n];` is a compiler extension that is best being avoided, use `std::vector` instead – 463035818_is_not_an_ai Oct 19 '18 at 19:45
2 Answers
0
You can use std::cout like :
#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
if(i ==0)
std::cout<<"{" <<array[i];
else if(i == n-1)
std::cout<<","<<array[i]<<"}";
else
std::cout<<","<<array[i];
}
return 0;
}

mystic_coder
- 462
- 2
- 10
-
1`cin >> n; int array[n];` is a VLA and is non-standard. I would suggest using `std::vector
`. – alter_igel Oct 19 '18 at 19:56
0
@mystic's answer uses arrays, which works fine. You can also use vector. There are more advanced methods of iterating over a vector, but I have not included that here to keep it simple.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> intVector{};
int n;
int input;
cout << "No. of values : ";
cin >> n;
for (int i = 0; i < n; i++) {
cin >> input;
intVector.push_back(input);
}
// Print out the array
cout << "{";
for(int i = 0; i < intVector.size(); i++) {
cout << intVector[i];
// print out the comma, except for the last number
if(i < intVector.size() - 1) {
cout << ", ";
}
}
cout << "}" << endl;
return 0;
}
If you want to use an iterator for printing the array, you can replace the print loop with this code:
// Print out the array
cout << "{";
for(auto i=intVector.begin(); i!=intVector.end(); ++i) {
if (i != intVector.begin()) {
cout << ", ";
}
cout << *i;
}
cout << "}" << endl;

Gardener
- 2,591
- 1
- 13
- 22