fonction recurcive returner la position d'un entier c
#include <stdio.h>
int findPosition(int arr[], int n, int x, int index) {
if (index == n) {
return -1;
}
else if (arr[index] == x) {
return index;
}
else {
return findPosition(arr, n, x, index + 1);
}
}
int main() {
int arr[] = {2, 4, 6, 8, 10};
int x = 6;
int n = sizeof(arr) / sizeof(arr[0]);
int position = findPosition(arr, n, x, 0);
if (position != -1) {
printf("Element %d found at position %d", x, position);
}
else {
printf("Element %d not found", x);
}
return 0;
}
This C program uses recursion to find the position of an integer in an array. The findPosition
function takes an array arr
, its size n
, the integer to search for x
, and an index
as parameters. If the index
is equal to n
, it means the element is not found, so the function returns -1. If the element at the current index
matches x
, the function returns the index
. Otherwise, it recursively calls itself with the next index. In the main
function, it initializes an array, the integer to search for, and then calls the findPosition
function with initial parameters. If the returned position is not -1, it prints the element and its position; otherwise, it prints that the element is not found.