Skip to content

Commit 264963b

Browse files
committed
added: 2-int_index.c
1 parent 99ab672 commit 264963b

File tree

3 files changed

+81
-1
lines changed

3 files changed

+81
-1
lines changed

0x0F-function_pointers/2-int_index.c

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include "function_pointers.h"
2+
3+
/**
4+
* int_index - searches for an integer.
5+
*
6+
* @array: array to search in.
7+
* @size: size of the array.
8+
* @cmp: pointer to check the searched value.
9+
*
10+
* Return: index of the first elem found, (-1) if not found.
11+
*/
12+
int int_index(int *array, int size, int (*cmp)(int))
13+
{
14+
int index = 0;
15+
int result = -1;
16+
17+
while (array != NULL && cmp != NULL && size > 0 && index < size)
18+
{
19+
result = cmp(array[index]);
20+
if (result == 1)
21+
break;
22+
index++;
23+
}
24+
return (result == 1 ? index : -1);
25+
}

0x0F-function_pointers/2-main.c

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <stdio.h>
2+
#include "function_pointers.h"
3+
4+
/**
5+
* is_98 - check if a number is equal to 98
6+
* @elem: the integer to check
7+
*
8+
* Return: 0 if false, something else otherwise.
9+
*/
10+
int is_98(int elem)
11+
{
12+
return (98 == elem);
13+
}
14+
15+
/**
16+
* is_strictly_positive - check if a number is greater than 0
17+
* @elem: the integer to check
18+
*
19+
* Return: 0 if false, something else otherwise.
20+
*/
21+
int is_strictly_positive(int elem)
22+
{
23+
return (elem > 0);
24+
}
25+
26+
27+
/**
28+
* abs_is_98 - check if the absolute value of a number is 98
29+
* @elem: the integer to check
30+
*
31+
* Return: 0 if false, something else otherwise.
32+
*/
33+
int abs_is_98(int elem)
34+
{
35+
return (elem == 98 || -elem == 98);
36+
}
37+
38+
/**
39+
* main - check the code
40+
*
41+
* Return: Always 0.
42+
*/
43+
int main(void)
44+
{
45+
int array[20] = {0, -98, 98, 402, 1024, 4096, -1024, -98, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 98};
46+
int index;
47+
48+
index = int_index(array, 20, is_98);
49+
printf("%d\n", index);
50+
index = int_index(array, 20, abs_is_98);
51+
printf("%d\n", index);
52+
index = int_index(array, 20, is_strictly_positive);
53+
printf("%d\n", index);
54+
return (0);
55+
}

0x0F-function_pointers/function_pointers.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
int _putchar(char);
66
void print_name(char *, void (*)(char *));
77
void array_iterator(int *, size_t, void (*)(int));
8-
8+
int int_index(int *, int, int (*)(int));
99

1010
#endif /* FUNCTION_POINTERS_H */

0 commit comments

Comments
 (0)