ADVERTISEMENT
ADVERTISEMENT

C program to find a number from array elements

In this program, we are reading an array of integers and a number to find it from the given array elements.

Example:

    Input array elements are:
    10, 20, 30, 40, 50
    Element to find: 30
    Output:
    30 found at 2 index.

    Input array elements are:
    10, 20, 30, 40, 50
    Element to find: 70
    Output:
    70 does not exists in the array.

Program:

/*program to find a number from array elements.*/

#include <stdio.h>
#define MAX 20

/*  function    :   readArray() 
    to read array elements. 
*/

void readArray(int a[], int size)
{
    int i;
    for (i = 0; i < size; i++) {
        printf("Enter %d element :", i + 1);
        scanf("%d", &a[i]);
    }
}

/*  function    : findElement(), 
    to find an item from array elements. 
    return      : -1 for fail, 
              position to success. 
*/
int findElement(int a[], int size, int item)
{
    int i, pos = -1;
    for (i = 0; i < size; i++) {
        if (a[i] == item) {
            pos = i;
            break;
        }
    }
    return pos;
}

int main()
{
    int arr[MAX];
    int n, item, pos;

    printf("\nEnter size of an Array :");
    scanf("%d", &n);

    printf("\nEnter elements of Array 1:\n");
    readArray(arr, n);

    printf("Enter an item to find :");
    scanf("%d", &item);

    pos = findElement(arr, n, item);
    if (pos == -1)
        printf("\n%d does not exists in array.\n", item);
    else
        printf("\n%d find @ %d position.\n", item, pos);

    printf("\n\n");
    return 0;
}

Output

first run
Enter size of an Array :5 

Enter elements of Array 1: 
Enter 1 element :12 
Enter 2 element :23 
Enter 3 element :34 
Enter 4 element :45 
Enter 5 element :56 
Enter an item to find :45 

45 find @ 3 position. 

second run
Enter size of an Array :5 

Enter elements of Array 1: 
Enter 1 element :12 
Enter 2 element :23 
Enter 3 element :34 
Enter 4 element :45 
Enter 5 element :56 
Enter an item to find :10 

10 does not exists in array. 

C One-Dimensional Array Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.