A couple of observations that may be contributing to the problem:
This function prototype:
void prem_dern(float t[], int n, float r)
includes no way to return results to the caller. i.e. it is void, and none of the arguments include the address of something to be changed. This is legal, but would be more useful with the ability to do work, then pass its results.
Additionally, the size of the array float t[]
is not passed, so the function has no way to know how many elements it contains.
It seems that the declaration of float t[100];
should be moved and changed from:
float r;
float t[100];
To:
scanf("%d",&n);
float t[n];//creating a variable length array that ties array size to n
for(i=0;i<n;i++)
{
printf("donner un element :");
scanf("%f",&t[i]);
}
This then provides an explicit tie between the array, and its size:
void prem_dern(float t[], int n, float r)
^^^^^
Next, for execution flow to see the break
statement, change the following:
if (t[i]==r) printf("la premiere position %d:",i);
break;
To:
if (t[i]==r)
{
printf("la premiere position %d:",i)
break;
}
Edit to address OP main question
To create ability to return first and last indices of number entered by user modify the struct to return either a pointer to array, or a pointer to struct, or via a function parameter. Here is an adaptation of your function to return via function a struct *
parameter:
Given for example this struct definition:
typedef struct {
int first;
int last;
float r;
}index_s;
Here is the adaptation of your function, that will return the float value entered (in the function), and the index of the array that contains same value.
void prem_dern(float t[], int n, index_s *val)
{
int i,j;
int *array = malloc(2*sizeof(*array));
if(array)
{
printf("donner le reel pour savoir les positions ");
scanf("%f",&val->r);
for(i=0;i<n;i++)
{
if (t[i]==val->r)
{
printf("la premiere position %d:",i);
break;
}
}
for (j=n-1;j>0;j--)
{
if(t[j]==val->r)
{
printf("la derniere position %d:",j);
break;
}
}
val->first = i;
val->last = j;
}
}
Calling example:
int main()
{
index_s val;//create instance of struct typedef
//all your other relevant code
...
scanf("%d",&n);
float t[n];//creating a variable length array that ties array size to n
for(i=0;i<n;i++)
{
printf("donner un element :");
scanf("%f",&t[i]);
}
...
prem_dern(t, n, &val);//pass struct as pointer (&)
val.first; //contains first index
val.last; //contains last index
val.r; //contains float val searched for
return 0;
}