Reputation: 19
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("color f0");
int k,i,j,n;
printf("Generate tables upto:");
scanf("%d",&n);
int tables[n][10];
printf("Table\t");
for(k=1;k<=10;k++)
{
printf("%dx\t",k);
}
printf("\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=10;j++)
{
tables[i][j]=i*j;
printf("%d\t",tables[i][j]);
}
}
return 0;
}
This is my code which i am working on but unfortunately I am not able to generate it the way I want. The required output should look like this.
Upvotes: 0
Views: 111
Reputation: 121357
Array indexing starts from 0
and goes up to n-1
. So you are accessing out of bounds which is undefined behaviour.
So you need to rewrite the loops as:
for(i=0; i < n; i++) {
for(j=0; j < 10; j++) {
tables[i][j] = (i+1)*(j+1);
printf("%d\t", tables[i][j]);
}
}
Upvotes: 1
Reputation: 140168
proposal fix for your code
code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("color f0");
int k,i,j,n;
printf("Generate tables upto:");
scanf("%d",&n);
int tables[n][10];
printf("Table\t");
for(k=1;k<=10;k++)
{
printf("%dx\t",k);
}
printf("\n");
for(i=2;i<=n;i++)
{
printf("%d\t",i);
for(j=1;j<=10;j++)
{
tables[i-1][j-1]=i*j;
printf("%d\t",tables[i-1][j-1]);
}
printf("\n");
}
return 0;
}
display with n=4
Generate tables upto:4
Table 1x 2x 3x 4x 5x 6x 7x 8x 9x 10x
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
Upvotes: 1