Reputation: 59
I have a file named sample.txt which contains 1000 integers(both positive and negative numbers). First I copied the file into an array of size 1000 (say a). My aim is to locate the largest sub array in a and find the sum of elements in it. An array is a sub array if it's consecutive elements are in increasing order. For example in the array {12,23,3,1,-56,2,4,6,45,49,1,2,-10} the sub array is {-56,2,4,6,45,49}. Then I need to calculate the sum of elements of this sub array.
Given below is my attempt to solve the problem using a C program. I'm a non-CS major just finished C programming in this semester. Your help would be very much appreciated.
int sum(int a[],int i,int temp)
{
int sum=0,j;
for(j=i;j<i+temp;j++)
sum+=a[j];
printf("Sum = %d", sum);
return 0;
}
int main()
{
FILE *f1;
int a[1000],b[900];
int number,i=-1,counter=0,temp=1,check=1,j;
f1 = fopen("sample.txt","r");
while (!feof (f1) && fscanf (f1, "%d", &number) && i++ < 1000 )// copying the file to an array
a[i] = number;
fclose(f1);
for(i=1;i<1000;i++)
{
if(a[i-1]<a[i])
counter++;
else
{
if(counter>temp)
temp=counter;
counter=0;
}
}
temp++;
printf("Temp= %d", temp); // the length of the largest sub array whose elements are in increasing order
sum(a,i,temp);
return 0;
}
Upvotes: 0
Views: 465
Reputation: 15121
to locate the largest sub array in a
"To locate the largest", I suppose you mean longest sub-array.
Anyway, here is an implementation (it works for your test input):
int longest_increasing(int array[], int length, int *start, int *end)
{
int pos, curr_pos;
*start = 1;
*end = 0;
curr_pos = 0;
while (curr_pos + 1 < length) {
while (curr_pos+1 < length && array[curr_pos] >= array[curr_pos+1])
curr_pos++;
for (pos = curr_pos; pos+1 < length && array[pos] < array[pos+1]; pos++)
;
if (*end - *start < pos - curr_pos) {
*start = curr_pos;
*end = pos;
}
curr_pos = pos+1;
}
if (*start < *end)
return 1;
else
return 0;
}
Upvotes: 0
Reputation: 1432
I introduced a new variable temp_index which will hold the starting index of the largest sub-array and used j to store the starting index in the loop.
Try this
if(a[i-1]<a[i])
{
if (counter == 0) { j = i }
counter++;
}
else
{
if(counter>temp) {
temp_index = j;
temp=counter;
}
counter=0;
}
}
temp++;
printf("Temp= %d", temp); // the length of the largest sub array whose elements are in increasing order
sum(a,temp_index,temp)
Upvotes: 0
Reputation: 1468
Well, I come from C++ but maybe I can help..you could try this :
for(i=1;i<=1000;i++)
{
if(a[i]<a[i+1])
counter++;
Upvotes: 0
Reputation: 30136
Just a general advice, in order to prevent your program from crashing:
Change this:
while (!feof (f1) && fscanf (f1, "%d", &number) && i++ < 1000 )
a[i] = number;
To this:
while (!feof (f1) && fscanf (f1, "%d", &number) && i < 1000 )
a[i++] = number;
Upvotes: 1