#include <stdio.h>
int main(){
int number[3][4] = {
{10,20,30,40},
{15,25,35,45},
{47,48,49,50},
};
printf("%s",number[]);
return 0;
}
Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?
P.S: Im a newbie.
Use nested for loops. For example
for ( size_t i = 0; i < 3; i++ )
{
for ( size_t j = 0; j < 4; j++ )
{
printf( "%2d ", number[i][j] );
}
putchar( '\n' );
}
Pay attention to that it is a bad idea to use magic numbers like 3
and 4
. Instead use named constants.
As for the conversion specifier %s
then it is used to output one-dimensional character arrays that contain strings
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
enum { M = 3, N = 4 };
int number[M][N] =
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 },
};
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%2d ", number[i][j] );
}
putchar( '\n' );
}
return 0;
}
Its output is
10 20 30 40
15 25 35 45
47 48 49 50
To output a two-dimensional integer array as a one-dimensional integer array apply casting to the array designator to the type int *
or const int *
.
For example
#include <stdio.h>
int main(void)
{
enum { M = 3, N = 4 };
int number[M][N] =
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 },
};
const int *p = ( const int * )number;
for ( size_t i = 0; i < M * N; i++ )
{
printf( "%2d ", p[i] );
}
putchar( '\n' );
return 0;
}
The program output is
10 20 30 40 15 25 35 45 47 48 49 50
And vice versa to print a one dimensional array as a two-dimensional array use the following approach.
#include <stdio.h>
int main(void)
{
enum { N = 12 };
int number[N] = { 10, 20, 30, 40, 15, 25, 35, 45, 47, 48, 49, 50 };
size_t rows = 3, cols = 4;
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ )
{
printf( "%2d ", number[i * cols + j] );
}
putchar( '\n' );
}
return 0;
}
The program output is
10 20 30 40
15 25 35 45
47 48 49 50
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加