Arun Kumar
Arun Kumar

Reputation: 13

Searching in array in C

#include <stdio.h>

int main()
{

    int arr[] = {10, 20, 30, 8, 2};
    int index = -1, ele;

    printf("Enter the elment you want to search :");
    scanf("%d", ele);
    for (int i = 0; i < 5; i++)
    {
        if (arr[i] == ele)
            ;
        index = i;
        break;
    }

    if (index == -1)
    {
        printf("Not found\n");
    }
    else
    {
        printf("Found at %d", index);
    }

    return 0;
}

the above code isn't printing the result. I am learning C programing from past few days. Can You please help me out with this. I am not getting any type of error.

Upvotes: 0

Views: 76

Answers (2)

Girija
Girija

Reputation: 118

There are 2 mistakes in the code

    #include<stdio.h>
int main()
{

    int arr[] = {10, 20, 30, 8, 2};
    int index = -1, ele;

    printf("Enter the elment you want to search :");
    scanf("%d", &ele);//mistake here
    for (int i = 0; i < 5; i++)
    {
        if (arr[i] == ele)
        {                               //Here a semi colon is used 
            index = i;
            break;
        }
    }

    if (index == -1)
    {
        printf("Not found\n");
    }
    else
    {
        printf("Found at %d", index);
    }

    return 0;
}

Correcting these will give correct outputenter image description here

Upvotes: 0

robthebloke
robthebloke

Reputation: 9682

Your if statement doesn't have any code within it (just a semi colon). Prefer using braces


        if (arr[i] == ele) {
          index = i;
          break;
        }

Also, you'll need to specify the address of the variable you are reading into when using scanf, e.g.

    scanf("%d", &ele); //< take the address of 'ele' using &

Upvotes: 2

Related Questions