In: Computer Science
(In C++ (very quick question))
1. Write a complete program. Declare a 2-Dimensional (size 20 x 30) integer array and use random numbers from 0 to 99 to initialize it. Define the prototype and the definition for a function called Find99(). The function takes three parameters: a 2-Dimensional array of integers (size 20 x 3), and 2 integers to specify the sizes of row and column of the array. (These two parameters should be used in your loops for checking the sizes of row and column.)
The function must check each element of the array. If the element contains the integer 99, the function should print the position of the number 99. (Hint: there may be multiple 99s or no 99 at all.)
Sample output: 99 is located at row 0 and column 0.
Please find below the code for the required problem, having comment for each line section to make the code understandable:
#include <iostream> //for input and output
#include<stdlib.h>// to use srand numbers function
#include<time.h> //to use time in strand so that everytime new sequence is generated
using namespace std;
int main()
{
int i,j; //declare the loop counters
const int row = 20, col = 30; //set a constant column and row value to make a 20*30 2d array
int arrayInput[row][col]; //2darray named arrayInput with size 20*30 having type int
// function declaration with void retun type and passing array, number of columns and number of rows
void Find99(int arrayInput[20][30], int row, int col);
srand(time(0)); //helps to generate differnt sequence everytime.It is called once to generate random number
//loops to generate random numbers and put in the arrayInput array
for (i = 0; i<row; i++)
{
for(j=0;j<col;j++)
{
arrayInput[i][j]=rand()%100; //get random number and store in the 2darray
}
}
Find99(arrayInput, row, col); //call the function Fin99 with array and cout of row and columns in it
return 0;
}
void Find99(int arrayInput[20][30], int row, int col){//function definition
int i, j; //counters to be used in the function
//loop counter to traverse each element in the array
for (i = 0; i<row; i++)
{
for(j=0;j<col;j++)
{
if(arrayInput[i][j]==99) //if the located array element is 99?
{
//print the details when 99 is located
cout<< "99 is located at row "<<i<<" and column " <<j<<endl;
}
}
}
return;
}
Please find below the screenshot for the code orientation:
Description: The program will have an array named arrayInput with size 20*30 as per the problem requirements. rand()%100 will generate a random number between 0 to 99 and store the number in array. Static variable col and row will be passed to the function to define the number of rows and columns in the 2 dimensional array.
Please be noted that as per the sample output provided in the question, the row and column number will start from 0
Please find below the output for the program:
The numbers generated everytime will differ from the last execution. Thus the result will differ from one each other.
Run1:
Run 2: