There is an array, you need to divide each element of this array by the product of the last digits of the previous and subsequent element.
Full text of the task: Fill in a one-dimensional array of 20 elements from a file input.txt and display it on the screen. Change the elements of the array by dividing each element of the array by the product of the last digits of the previous and next element. Print the modified array to the screen on a new line.
How can this be done? I have such a code, but it doesn't work:
#include <stdio.h>
#include <stdlib.h>
#define N 20
int main(void) {
FILE *output;
int i, array[N], pred, posl, proizv;
output = fopen("output.txt", "w r");
for (i = 0; i < N; i ) {
array[i] = -100 rand() % (100 100 1);
fprintf(output, "%d ", array[i]);
}
for (i = 0; i < N; i ) {
fscanf(output, "%d ", &array[i]);
printf("%d ", array[i]);
}
fclose(output);
printf("\n\n");
for (i = 1; i < N - 1; i ) {
pred = array[i - 1] % 10;
posl = array[i 1] % 10;
proizv = pred * posl;
printf("%d *%d =%d\n", pred, posl, proizv);
}
printf("\n\n");
return 0;
}
How can I rewrite it so that I can then output the already modified array to a file?
I have a few more tasks that need to be solved. I will supplement the question as soon as we deal with the first one.
CodePudding user response:
output = fopen("output.txt", "w r");
for (i = 0; i < N; i ) {
array[i] = -100 rand() % (100 100 1);
fprintf(output, "%d ", array[i]);
}
for (i = 0; i < N; i ) {
fscanf(output, "%d ", &array[i]);
printf("%d ", array[i]);
}
One, you don't check either the fopen()
nor the fscanf()
for success. Either might fail...
...and the fscanf()
most certainly did fail, because you're still pointing at the end of output
after writing all those values. Try adding rewind( output )
between the two loops.
I have a few more tasks that need to be solved. I will supplement the question as soon as we deal with the first one.
Don't. One question per post, please. If you have new questions after this one is resolved, please make a new post.
CodePudding user response:
As I understand it, the code should work something like this. Yes, I know about the lack of checking when opening a file for reading, I know about division by 0, but this is a little secondary.
#include <stdlib.h>
#define N 20
int main(void) {
FILE *output;
int i, array[N], pred, posl, proizv[N], array2[N];
output = fopen("output.txt", "w r");
for (i = 0; i < N; i ) {
array[i] = -100 rand() % (100 100 1);
fprintf(output, "%d ", array[i]);
}
for (i = 0; i < N; i ) {
fscanf(output, "%d ", &array[i]);
printf("%d ", array[i]);
}
fclose(output);
printf("\n\n");
for (i = 1; i < N - 1; i ) {
pred = array[i - 1] % 10;
posl = array[i 1] % 10;
proizv[i] = pred * posl;
printf("%d *%d =%d\n", pred, posl, proizv[i]);
}
printf("\n\n");
for (i = 1; i < N - 1; i ) {
array2[i] = array[i] / proizv[i];
printf("%d ", array2[i]);
}
return 0;
}