I had a school project to solve, which I did. The basic focus of the project was to create the simplest code possible to solve it. This topic was created just to ensure if I wrote the code correctly.
The problem is the following:
We have declared a dynamic array which will take numeric values from a txt file. We want to read the array backwards and to make a simple check. Read every 'i' element in the array and check if the value of the array is greater than > the last one.If it is the value saved in the
int
calledtemp_max
which will be the > value of the array in thei
position. The program will continue to check every number and if a value in the array is greater thantemp_max
we will overwrite the value of thetemp_max
to the value of the array in that position.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *input, *output;
int *children;
int size, i;
input = fopen("xxx.in", "r");
if(input == NULL)
return 1;
fscanf(input,"%d",&size);
if(size < 1 || size > 1000000)
return 1;
children = malloc(size * sizeof(int));
if (children==NULL)
return 1;
for ( i = 0; i < size; i++ )
{
fscanf(input, "%d",&children[i]);
}
fclose(input);
int total = 0;
int temp_max = 0;
for(i = size - 1; i >= 0; i--)
{
if(children[i] > temp_max) {
temp_max = children[i];
total++;
}
}
free(children);
output = fopen("xxx.out", "w+");
fprintf(output, "%d\n", total );
fclose(output);
//This is the end, my dear friend!
exit(0);
}
The
int size
was declared in one step above and is the size of the dynamic array.The
int total
calculate how many times a number is greater than another. Default value is zero cause, I believe that should be what is your opinion.The array hasn't any zero values or negative values at all.
The text file has the following format:
Example (xxx.in) 1:
5
9 6 5 4 2
Example (xxx.in) 2:
6
8959 5594 595 2 949 9
children[i] < temp_min
in the forward direction. \$\endgroup\$children[i] < temp_min
I couldn't understand you. I want to check the numbers backwards and to find the max value. Why to mess thinks up. By the time that you didn't find any bug in my program I am happy! Thank you for your point! :) \$\endgroup\$