Miałem za zadanie:
W tablicy A zastąp elementy ujemne zerami i policz sumę elementów dodatnich tej tablicy.
Mam wszystko oprócz tego zliczania. Najlepiej jakby się obeszło bez wskaźników, bo nie czuje się w nich zbyt pewnie.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{
printf("Za malo argumentow");
return 0;
}
int rowlength, collength;
printf("Input number of rows for the first array!");
scanf("%d", &rowlength);
printf("Input number of columns for the first array!");
scanf("%d", &collength);
int tab[rowlength][collength];
printf("Elements in the text file:\n\n");
FILE *file = fopen(argv[1], "r");
ReaderValues(file, rowlength, collength, tab);
fclose(file);
changer(rowlength,collength,tab);
printf("Sum of plus numbers is %d", sumCounter(rowlength,collength,tab, sum));
Save(rowlength, collength, tab, argv, sumCounter(rowlength,collength,tab, sum));
return 0;
}
void readValue(FILE *file, int rowlength, int collength, int tab[rowlength][collength])
{
int row = 0, col = 0;
while (fscanf(file, "%d,", &tab[row][col]) != EOF)
{
printf("%d ", tab[row][col]);
col++;
if (col == collength)
{
printf("\n");
col = 0;
row++;
}
}
printf("\n");
}
int sumCounter(int rowlength, int collength, int tab[rowlength][collength], int sum)
{
int i,j;
for(i=0; i < rowlength; i++)
{
for(j=0; j < collength; j++)
{
if(tab[i][j]>0)
sum = sum + tab[i][j];
}
}
return sum;
}
void changeNegativeNumbers(int rowlength, int collength, int tab[rowlength][collength])
{
int i,j;
for(i=0; i < rowlength; i++)
{
for(j=0; j < collength; j++)
{
if(tab[i][j]<0)
tab[i][j] = 0;
}
}
printf("Matrix after 0 \n");
for(i=0; i < rowlength; i++)
{
for(j=0; j < collength; j++)
{
printf("%d ", tab[i][j]);
}
printf("\n");
}
}
void Save(int rowlength, int collength, int tab[rowlength][collength], char *argv[], int sum)
{
int i, j;
FILE *file2;
file2 = fopen(argv[2], "w");
if (file2 == NULL)
printf("Can't open the file!");
else
{
fprintf(file2, "The result: \n");
fprintf(file2, "The sum: %d \n", sum);
for (i = 0; i < rowlength; i++)
{
for (j = 0; j < collength; j++)
{
fprintf(file2, "%d ", tab[i][j]);
}
fprintf(file2, "\n");
}
fclose(file2);
}
}