Hi!
I'm trying to write a program using a two-dimensional array (for school), and I think I've got it, but my teacher sent back the code I sent to him, saying there is a "grave mistake" in it. I've been trying to figure it out for the past two hours, but I don't get what he's getting at, so I thought I'd ask around here.
What I want to accomplish is this:
I give the program an 'n' number, which is the number of both the rows and the colums of a matrix, after which I'm asked to input further n*n numbers for the matrix. After this, the program is supposed to multiply these numbers by two then write the matrix to the screen.
What I've come up with for this is:
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,j; //n is the number of rows and columns in the matrix, i and j are for the for cycles
int k,l; //k and l are used so that the program starts asking for 1st row 1st number and not 0r 0n
int temp1,temp2;
int **p=NULL;
printf("n="); scanf("%d", &n); //inputting n
p=(int**)malloc(n*sizeof(int)); //allocating memory for the matrix
for(i=0;i<n;i++)
{
p[i]=(int*)malloc(n*sizeof(int));
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
k=i+1;
l=j+1;
printf("%d. row %d. number: ",k,l); //asking for the numbers in the matrix
scanf("%d",&temp1); //inputting the numbers into the first temporary variable
p[i][j]=temp1; //putting it into the matrix
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
temp2=p[i][j]; //putting each number in the matrix into a second temporary variable
temp2=2*temp2; //multiplying by two
p[i][j]=temp2; //putting it back into the matrix
printf("%3d",p[i][j]); //printing out the matix
if(j==(n-1)) {printf("\n");} //if the end of a row is reached, start a new row
}
}
}
As you can see, I'm not exactly experienced here. After I thought about it a bit, I've figured out that using temp2 is unnecessary and that I could put the second for cycle inside the first (though I don't think this makes the program any better). Also, I figured that I'd set every variable I'm using to 0, so there can be no problem there.
So this is my second version:
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n=0,i,j;
int k=0,l=0;
int temp1=0;
printf("n="); scanf("%d", &n);
int **p=(int**)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
p[i]=(int*)malloc(n*sizeof(int));
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
k=i+1;
l=j+1;
printf("%d. row %d. number: ",k,l);
scanf("%d",&temp1);
temp1=2*temp1;
p[i][j]=temp1;
if((i==(n-1))&(j==(n-1))) //only start writing the matrix once every number has been read and multiplied
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",p[i][j]);
if(j==(n-1)) {printf("\n");}
}
}
}
}
}
}
Is this any better than the first? What was the "grave mistake" in the first one, and did I accidentally solve it with the second one? Also, the teacher mentioned that there was a simpler way of doing this. If anyone could help, I would much appreciate it.
Thank you very much, in advance.