in Programming in C edited by
184 views
2 votes
2 votes

Consider the following C code and find output, consider all positive numbers in an array
 

#include<stdio.h>
int fun(int arr[], int n)
{
if (n < 2)
{
return 0;
}
int res = 0;
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
if ( res < (arr[i]-arr[j]-i+j) )
res = (arr[i]-arr[j]-i+j);

return res;
}

int main()
{
int arr[] = {9, 15, 4, 12, 13};
int n = sizeof(arr)/sizeof(arr[0]);
printf(“%d”,fun(arr, n));
return 0;
}
in Programming in C edited by
184 views

1 Answer

1 vote
1 vote

Answer will be 12.

        #include<stdio.h>
        int fun(int arr[], int n)
        {
        if (n < 2)
        {
        return 0;
        }
        int res = 0,i,j;
        for (i=0; i<n; i++)
        for (j=0; j<n; j++)
        if ( res < (arr[i]-arr[j]-i+j) )//not take -ve value or less than previous value
        res = (arr[i]-arr[j]-i+j);
     
        return res;
        }
     
        int main()
        {
        int n;
        int arr[] = {9, 15, 4, 12, 13};
        n = sizeof(arr)/sizeof(arr[0]);//here n is 5
        printf("%d",fun(arr, n));
        return 0;
        }

We are simply running a 1D array in C code.

Sizeof(arr)=5X4=20

So, value of n=20/4=5

Now, coming to fun(arr[],n)

first it is checking for i=0,j=0

So, 2 array pointer pointing to same value 9

(arr[i]-arr[j]-i+j )=9-9-0+0=0

Next i=0,j=1

(arr[i]-arr[j]-i+j )=9-15-0+1$\ngtr$0

like that go on...................

when i=1,j=2

(arr[i]-arr[j]-i+j )=15-4-1+2=12

it will give maximum value in whole calculation

So, answer is 12

Related questions