In this first c++ tutorial we are going to fill a 2 dimensional array and search for a specific alphabetic character.
I’m going to give you the code first, because there isn’t much explaining to do here.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand(time(0));
const int ROW=5,COL=4;
char table [ROW][COL] ;
for(int r=0; r < ROW ;r++){
for (int k=0; k < COL; k++){
table[r][k] = rand()%26 + 'a';
cout << table[r][k] << "\t";
}
cout << endl;
}
for (int i=0; i<5; i++){
for (int j=0; j<4; j++){
if (table[i][j] == 'a')
cout <<"a appears on row "<<i+1<<" column "<<j+1<<endl;
}
}
return 0;
}
As you can see I first declared the numbers of rows and columns, needed for the array and made them constant, so it won’t be possible to alter the variable afterwards.
Then after I created the array, I start writing random numbers in it with “rand()%26 + ‘a’;”
%26 will ensure that the numbers that are being generated will lay between 0 and 26, the “+ ‘a’” will be added somewhere in the array.
To be sure that every time a new random number is chosen you will need to use the function “srand(time(0));”
As some of you may notice, the numbers will be transformed into alphabetic characters, because the array is declared as char and every number that is generated stands for an alphabetic character.
Got questions, suggestions or something else?