C++ help Displays the number of times the numbers from 1 through 9 appear in a t
ID: 3767925 • Letter: C
Question
C++ help Displays the number of times the numbers from 1 through 9 appear in a two-dimensional array #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { //declare numbers array int numbers[5][3]; srand(time(0)); // Load the array with random numbers 0-9 for (int i=0; i<5; i++) { for (int j=0; j<3; j++) { numbers[i][j] = rand()%10; } } // declare a one-dimensional array to count the numbers and initialize to 0 // Write nested for loops to traverse the array. Use the two-dimensional // array's values as an index into the counting array and add 1 to the indexed element // Output the results (How many of each number was encountered return 0; } //end of main function
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//declare numbers array
int numbers[5][3];
srand(time(0));
// Load the array with random numbers 0-9
for (int i=0; i<5; i++)
{
for (int j=0; j<3; j++)
{
numbers[i][j] = rand()%10;
}
}
int a[15],x,y,c=0,z=0,s;
// declare a one-dimensional array to count the numbers and initialize to 0
for (int i=0; i<5; i++)
{
for (int j=0; j<3; j++)
{
s=numbers[i][j];
for(x=0;x<5;x++)
{
for(y=0;y<3;y++)
{
if(numbers[x][y]==s)
{
c++;
}
}
}
a[z]=c;
c=0;
z++;
}
}
// Write nested for loops to traverse the array. Use the two-dimensional
// array's values as an index into the counting array and add 1 to the indexed element
// Output the results (How many of each number was encountered
for(int i=0;i<z;i++)
{
cout<<a[i]<<endl;
}
return 0;
} //end of main function
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.