Hi guys, this program asks to input numbers between 0 and 5 and print the time a number occurred; and it works. BUT: I cannot understand why, if I inizialize n=0, the outcomes go crazy. theoretically any n>=0 get me into the while and then, the first thing the program does is to put the imput into n. I don't see any problems with that(maybe is something else).
I really need your help. Thank you all for your time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main() {
constint p=6;
int n=6;
int v[n]={};
while(n>=0){
cout << "insert an integer number between 0 and 5(negative if you want to end the program) \n";
cin >> n;
if(n>5) {
cout << "try agan \n";
continue;
}
v[n]++;
}
for(int i=0; i<p; i++) {
if(v[i]>0) cout << "recurrences of " << i << ": \t" << v[i] << endl;
}
return 0;
}
Ok, thanks! anyway even now the same problem remain. If I inizialize n to a number lower than 6, the values of the array seems to be random. here's the code:
int main() {
constint p=6;
int n=6;
int v[n]={};
while(true){
cout << "insert an integer number between 0 and 5(negative if you want to end the program) \n";
cin >> n;
if (n<0) break;
if(n>5) {
cout << "try agan \n";
continue;
}
if(n>=0) v[n]++;
}
for(int i=0; i<p; i++) {
if(v[i]>0) cout << "recurrences of " << i << ": \t" << v[i] << endl;
}
return 0;
}
#include <iostream>
int main() {
const size_t p {6};
int v[p] {};
for (int n {}; n >= 0; ) {
std::cout << "insert an integer number between 0 and " << p - 1 << " (negative if you want to end the program) \n";
std::cin >> n;
if (n >= 0)
if (n > p - 1)
std::cout << "try again \n";
else
++v[n];
}
for (size_t i = 0; i < p; ++i)
if (v[i] > 0)
std::cout << "recurrences of " << i << ": \t" << v[i] << '\n';
}
#include <iostream>
int main()
{
// if you don't initialize the array it holds "garbage" values
int arr1[5];
// use a range-based for loop to "walk through" the array elements
for (constauto& itr : arr1)
{
std::cout << itr << ' ';
}
std::cout << "\n\n";
// zero initialize the array when created
int arr2[5] { };
// whitespace can be your friend
for (constauto& itr : arr2) { std::cout << itr << ' '; }
std::cout << "\n\n";
// trying to use 'uniform initialization' on an array is tricky
int arr3[5] { 10 };
for (constauto& itr : arr3) { std::cout << itr << ' '; }
std::cout << "\n\n";
// proper uniform initialization of an array, specify each element
int arr4[] { 5, 10, 15, 20, 25 };
for (constauto& itr : arr4) { std::cout << itr << ' '; }
std::cout << '\n';
}
Braced array initialisation will only initialise with the number of specified elements. If there are fewer specified than the number of elements, the rest are default initialised.