You are here:

C/Help in debugging

Advertisement


Question
The following program is supposed to take the side of square and a character from user and display square of that character. For example if side is 5 and character is # then program should display:

#####
#####
#####
#####
#####

but program does not work. I have tried my best to figure out the problem but could not find out. Can you please help? I am beginner programmer.

#include<stdio.h>
int main(void)
{
  int side;
  char x;
  void solidSquare(int, char);
  
  printf("Enter the side of square: ");
  scanf("%d", &side);
  
  printf("Enter the character: ");
  scanf("%c", &x);
  
  printf("\n");
  
  solidSquare(side,x);

  getch();
  return 0;
}
void solidSquare(int s, char x)
{
  int i, j;
  for(i=1;i<=s;i++)
       {
     for(j=1;j<=s;j++)
         {
         printf("%c", x);
     }
     printf("\n");
  }
}

Answer
Hi,
The problem is the way you are reading from standard input.

#include<stdio.h>
void solidSquare(int, char);
int main(void)
{
       int side;
       char x;
  char buf[1024];
       printf("Enter the side of square: ");
  side = atoi(gets(buf));
       printf("Enter the character: ");
       gets(buf);
  x = buf[0];

       printf("%i %c \n", side, x);

       solidSquare(side,x);

       gets(buf);
       return 0;
}
void solidSquare(int s, char x)
{
       int i, j;
       for(i=1;i<=s;i++)
       {
         for(j=1;j<=s;j++)
         {
         printf("%c", x);
         }
         printf("\n");
       }
}

output:
Enter the side of square: 5
Enter the character: x
5 x
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tony Nazzal

Expertise

I will answer any c language programming and syntax questions.

Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.

©2016 About.com. All rights reserved.