Finding the sum of elements of the largest sub array of increasing order in C?
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;
}
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;
那么,我来自C ++,但也许我可以帮助...你可以试试这个:
for(i=1;i<=1000;i++)
{
if(a[i]<a[i+1])
counter++;
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)
链接地址: http://www.djcxy.com/p/85942.html
上一篇: 将2d数组C代码转换为malloc