The problem is caused because bad practices come together with ideas that are not entirely clear.
The bad practices are to declare all the variables at the beginning. Since C99 (dating from 1999 eye, that those who begin to be of age had not yet been born at that time) it is possible to declare the variables in almost any part of the code. Reducing the life of variables helps detect silly mistakes. If we apply it to your code, the problem begins to sing on its own:
int main ()
{
int datos[3][5];
for (int i=0; i<=2; i++)
{
for (int j=0; j<=4; j++)
{
printf ("Agregar Datos \n");
scanf("%d",&datos[i][j]);
}
}
for(int i=0; i<=2; i++)
{
printf(" \n");
for(int j=0; j<=4; j++)
printf(" %d " ,datos[i][j]);
}
for(int i=0; i<=2; i++)
{
int s /* = 0 */;
for(int j=0; j<=4; j++)
{
s+=datos[i][j];
}
datos[i][j]=s; // <<--- Error, j no esta declarada
}
for(int i=0; i<=2; i++)
{
printf("%d\n",datos [i]);
}
getch();
}
And, as I said, there we have the error. We are trying to use j
to save the result of the sum ... What value does it have to have j
? It is clear that if we are saving the result of the sum we will move from a 3x5 matrix to a 3x1 matrix. Perhaps it would be convenient to use a separate vector to store the results ...
int main ()
{
int datos[3][5];
for (int i=0; i<=2; i++)
{
for (int j=0; j<=4; j++)
{
printf ("Agregar Datos \n");
scanf("%d",&datos[i][j]);
}
}
for(int i=0; i<=2; i++)
{
printf(" \n");
for(int j=0; j<=4; j++)
printf(" %d " ,datos[i][j]);
}
int resultado[3];
for(int i=0; i<=2; i++)
{
int s /* = 0 */;
for(int j=0; j<=4; j++)
{
s+=datos[i][j];
}
resultado[i]=s;
}
for(int i=0; i<=2; i++)
{
printf("%d\n",resultado[i]);
}
getch();
}
Now the program compiles, it is already an important step. However we see that it gives incorrect results. The problem is solved by removing the comment from the code, which initializes the variable s
to 0
.
Why did I put that comment there if in your initial code the variable was initialized?
The reason is to demonstrate, once again, the benefits of reducing the life of the variables to a minimum. In your initial code you declared s
at the beginning of the program and if you initialized it to 0 ... but the variable was never initialized again, then the first sum was going to calculate well but it was going to fail in the second and the third ... simply because in those cases I would not start adding from zero.
However, when moving the declaration within the loop, in each iteration the variable s
will be declared and, once the comment is removed, said variable will be initialized to 0, with which the program will be able to add all the rows correctly.
And, to finish, the math.h
library is only necessary when you use mathematical functions ( abs
, sin
, cos
, ...), which you do not do, so you can eliminate that bookstore without problems.