Reputation: 121
I am working in ADT of an Array and when doing a function to verify if an element is present in the array, it didn't work, actually, it just said the element 1 is present in the array, but it doesn't work with other integers elements of the array. The function is
int checkElement(Array *a, int elem){
for (int i = 0; i < a->size; i++){
if (a->array[i] == elem){
return 1;
}
else return 0;
}
}
Compilable code
#include <stdio.h>
#include <stdlib.h>
typedef struct array{
int size;
int *array;
}Array;
Array* allocateMemory(int size){
Array *a;
a = (Array*) malloc(sizeof(Array));
if (a == NULL)
{
return NULL;
}
a->array = (int*) calloc(size, sizeof(int));
if (a->array == NULL)
{
return NULL;
}
a->size = size;
return a;
}
int add(Array *a, int elem, int c){
if ((c > a->size) || (c < 0)){
return 0;
}
a->array[c] = elem;
return 1;
}
int print(Array *a, int c){
return a->array[c];
}
int checkElement(Array *a, int elem){
for (int i = 0; i < a->size; i++){
if (a->array[i] == elem){
return 1;
}
else return 0;
}
}
int main(void)
{
Array *a1;
a1 = allocateMemory(10);
int elem = 1;
for (int i = 0; i < 10; i++)
{
if (add(a1, elem, i)== 0)
{
printf("Something went wrong\n");
}
elem += 1;
}
printf("Array 1: \n");
for (int i = 0; i < 10; i++)
{
printf("\a[%d] = %d\n", i, print(a1, i));
}
int element = 6;
int flag = checkElement(a1, element);
if (flag == 1) printf("\nElement %d is present in the array", element);
else printf("\nElement %d is not present in the array", element);
return 0;
}
Output:
Array 1:
[0] = 1
[1] = 2
.
.
.
[9] = 10
Element 2 is not present in the array
Upvotes: 0
Views: 412
Reputation: 102
int flag = checkElement(a1, element);
int checkElement(Array *a, int elem){
for (int i = 0; i < a->size; i++){
if (a->array[i] == elem){
return 1;
}
}
return 0;
}
Upvotes: 1