Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

printing character in a square of board without arrays C program

#include<stdio.h>

int main(){
    int size;
    int i ;
    int k;

    printf("room size : ");
    scanf("%d",&size);

    for(k=2; k<=size; k++) {
        for(i=0; i<=size; i++) {
            printf("| ");
        }
        printf("\n");
    }

    for(i=0; i<=size; i++) {
        printf("| ");
    }
}

and output is:

room size : 5
| | | | | | 
| | | | | | 
| | | | | | 
| | | | | | 
| | | | | | 

I want to print a character With char ‘C’ in a random square of this board but I cant use arrays. How to store this rooms without arrays?

expected output is( example: random coordinates are 3,4)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

room size : 5
| | | | | | 
| | | | | | 
| | | | | | 
| | |C| | | 
| | | | | | 

>Solution :

If you want all grid squares to have a ' ' (space) as its content, except for one specific square which should have 'C' as its content, then one way of printing the grid is to check in every loop iteration whether you are printing this specific square or not. If you are, then you print 'C', otherwise you print ' '.

Here is an example:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main( void )
{
    int size;
    int random_x, random_y;

    //seed random number generator
    srand( (unsigned)time(NULL) );

    //get the size of the room from the user
    printf( "Room size: " );
    scanf( "%d", &size );

    //generate a random set of coordinates for the
    //grid square which should have the 'C'
    random_x = rand() % size;
    random_y = rand() % size;

    //print the grid
    for ( int y = 0; y < size; y++ )
    {
        for( int x = 0; x < size; x++ )
        {
            printf( "|" );

            if ( x == random_x && y == random_y )
            {
                printf( "C" );
            }
            else
            {
                printf( " " );
            }
        }

        printf( "|\n" );
    }
}

Here is an example output of the program (the selected grid square is random):

Room size: 5
| | | | | |
| |C| | | |
| | | | | |
| | | | | |
| | | | | |
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading