cout << "Enter the amount of numbers you would like generated: " << endl;
cin >> num;
cout << endl;
int x[num];
for (int j=0; j<=num; j++)
{
x[j]=(rand()%10)+1;
}
for (int j=0; j<=num; j++)
{
switch (x[j])
{
case 1:
y[1]+=1;
break;
case 2:
y[2]+=1;
break;
case 3:
y[3]+=1;
break;
case 4:
y[4]+=1;
break;
case 5:
y[5]+=1;
break;
case 6:
y[6]+=1;
break;
case 7:
y[7]+=1;
break;
case 8:
y[8]+=1;
break;
case 9:
y[9]+=1;
break;
case 10:
y[10]+=1;
break;
}
}
for (int a=0;a<=y[1]+1; a++)
{
switch (a)
{
case 0:
cout << "1: ";
break;
default:
cout << "*";
}
}
}
This program is intended to print an asterisk for every time the number 1 appears in the array. However, the output is an infinite number of asterisks. I'm not sure what is wrong.
#include <iostream>
#include <cstdlib>
#include <vector>
usingnamespace std;
int main()
{
int num;
int y [11] {}; // initialize
cout << "Enter the amount of numbers you would like generated: " << endl;
cin >> num;
cout << endl;
// int x[num]; // ERROR: array size is not constexpr
std::vector<int> x( num );
for (int j=0; j<=num; j++) // ERROR: 'num' is not a valid index
{
x[j] = (rand()%10)+1;
}
for (int j=0; j<=num; j++) // ERROR: 'num' is not a valid index
{
if ( 0 < x[j] and x[j] < 11 )
{
++y[ x[j] ];
}
}
// This looks complex
for (int a=0; a<=y[1]+1; a++)
{
switch (a)
{
case 0:
cout << "1: ";
break;
default:
cout << "*";
}
}
cout << "\n\n1: ";
for ( int a=0; a<=y[1]; a++ )
{
cout << "*";
}
cout << '\n';
cout << "1: ";
for ( int j=0; j<num; ++j )
{
int z = (rand()%10)+1;
if ( 1 == z ) cout << "*";
}
cout << '\n';
}