I want to create a 2nd array using a function; the user will enter the dimensions(x,y) and the function will print it; in the first row must appear the numbers 1,2,3…x and in the first column the characters a,b,c,d,e….y(y is given as a number).
For example if the user enters x=5 y=7 it will print:
1 2 3 4 5
a _ _ _ _ _
b _ _ _ _ _
c _ _ _ _ _
d _ _ _ _ _
f _ _ _ _ _
h _ _ _ _ _
i _ _ _ _ _
I wrote some code but I don’t know how to do this with the letters.
void function(int x,int y)
{
char th[x][y];
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
if(i==1 )
{
for (int k = 1; k < x; k++)
{
th[i][j]=k;
}
}
else if(j==1)
{
th[i][j]='a';
}
else
{
th[i][j]='_';
}
std:: cout << th[i][j] <<'\t';
}
cout << std::endl;
}
}
Use the character code representations and the fact that ‘b’ == ‘a’ + 1 (and so forth).
If you have a zero-based index I, and you want to convert that to letters, it really is as easy as printing ‘a’ + I. If you want it in caps, print ‘A’ + I.
Also note that you can really simplify those loops. There’s no reason to have three loops nested. You need a single for loop for the first row (generating the numeric column headers), and then a doubly-nested for-loop for the remaining rows. Something like the following (completely untested) code:
Following up on your desire to have data in cells, you need to allocate space for them. if you have X columns by Y rows, you need X*Y cells. You can index these by using X*j+i, where i,j is the column,row you want to access. Something like:
If you want to keep the underscore for “empty” values, you need to pick some integer to represent a nil value (zero, negative, INT_MAX, whatever) and fill the vector with that. Then put in an if condition to print the underscore if the cell value is the nil value, and print the cell value directly otherwise.