Reputation: 33
My task is to draw matrix with asteriks, but the problem is that user enters the number of points and their coordinates and asteriks should only be drawn in their position. The total size of matrix is 20x20. And the coordinates are in range [0,19]. I just don't know how to save the input numbers. I am beginner, and I hope you could help.
#include <stdio.h>
int main()
{
int n, i, j, a, b;
char m[20][20] = {{0}}, x = '*';
printf("Enter the number of points: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[a][b])
printf("%c", m[a][b]);
else
printf(" ");
}
printf("\n");
}
}
Upvotes: 0
Views: 307
Reputation: 104
When you declare a variable (or an array of variables) you have to initialize it to a certain value. Otherwise the value saved in that memory cell remains the same as before the allocation (often nonsense numbers that do not correspond to ascii characters).
You can initialize them manually or using library functions like memset
or bzero
.
Initialize the array manually:
for(i = 0; i < 20; i++)
for(j = 0; j < 20; j++)
m[i][j] = 0;
Initialize with memset:
memset(&m, 0, sizeof(char[20][20]));
Fixed code using memset:
#include <stdio.h>
#include <string.h>
int main()
{
int n, i, j, a, b;
char m[20][20], x = '*';
memset(&m, 0, sizeof(char[20][20]));
printf("Enter the number of points: \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d\n", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[i][j])
printf("%c", m[i][j]);
else
printf(" ");
}
printf("\n");
}
}
Fixed code using a for loop:
#include <stdio.h>
#include <string.h>
int main()
{
int n, i, j, a, b;
char m[20][20], x = '*';
for (i = 0; i < 20; i++)
for (j = 0; j < 20; j++)
m[i][j] = 0;
printf("Enter the number of points: \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d\n", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[i][j])
printf("%c", m[i][j]);
else
printf(" ");
}
printf("\n");
}
}
Output:
****
* *
* *
* *
* *
****
Upvotes: 0
Reputation: 75062
You should
m
.i
and j
instead of a
and b
to decide what character to print.Fixed code:
#include <stdio.h>
int main() {
int n,i,j,a,b;
char m[20][20]={{0}},x='*'; /* add ={{0}} to initialize the array */
printf("Enter the number of points: ");
scanf("%d", &n);
for(i=0;i<n;i++){
printf("Enter the point %d",i+1);
scanf("%d %d",&a,&b);
m[a][b]=x;
}
for(i=0;i<20;i++){
for(j=0;j<20;j++){
if (m[i][j])
printf("%c", m[i][j]);
else printf(" ");
}
printf("\n");
}
}
Upvotes: 1