Reputation: 13
Basically what I need to do is print a border of "*" using the 2D array in C. However I managed to print somewhat one part of the border but now I am stuck in printing the other side. I cannot seem to figure out the right loop to do in this case.
I am new to C coding or any type of coding.
-Has to be a 2D array
-Contains spaces in between
-Only prints the border
eg:
***********
* *
* *
***********
I have attached my code so far and my result of that code.
PS: I have used malloc to allocate the 2Darray
for(kk=0;kk<10; kk++)
{
for(ll=0;ll<20; ll++)
{
if (kk == 0)
{
basicMap[kk][ll] = '*';
printf("%c", basicMap[kk][ll]);
}
else if(kk == 9)
{
basicMap[kk][ll] = '*';
printf("%c", basicMap[kk][ll]);
}
else if (ll ==0)
{
basicMap[kk][ll] = '*';
printf("%c", basicMap[kk][ll]);
}
else if(ll == 19)
{
basicMap[kk][ll] = '*';
printf("%c", basicMap[kk][ll]);
}
}
printf("\n");
}
Upvotes: 1
Views: 505
Reputation: 212454
You never print the spaces. Simplifying the code might make that clearer. You've got a lot of redundant code that can be eliminated. Something like:
for( kk = 0; kk < 10; kk += 1 ){
for( ll = 0; ll < 20; ll++ ){
if( kk == 0 || kk == 9 || ll == 19 || ll == 0 ){
basicMap[kk][ll] = '*';
} else {
basicMap[kk][ll] = ' '; /* Perhaps redundant, if previously assigned */
}
putchar(basicMap[kk][ll]);
}
putchar('\n');
}
Upvotes: 1
Reputation: 311068
If I have understood correctly you are trying to do something like the following shown in the demonstrative program below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
size_t m = 4;
size_t n = 11;
char **a = malloc( m * sizeof( char * ) );
for ( size_t i = 0; i < m; i++ )
{
a[i] = malloc( n * sizeof( char ) );
if ( i % ( m - 1 ) == 0 )
{
memset( a[i], '*', n );
}
else
{
memset( a[i] + 1, ' ', n - 2 );
a[i][0] = a[i][n-1] = '*';
}
}
for ( size_t i = 0; i < m; i++ )
{
printf( "%.*s", ( int )n, a[i] );
putchar( '\n' );
}
for ( size_t i = 0; i < m; i++ )
{
free( a[i] );
}
free( a );
return 0;
}
The program output is
***********
* *
* *
***********
Upvotes: 0