Home > Back-end >  Trying to return a conditional statement in program to search for an array element
Trying to return a conditional statement in program to search for an array element

Time:11-09

I am writing a program to search an array element and return a conditional statement "Array element not found" if the entered element doesn't match any of the array elements. I tried following code:

#include <stdio.h>
 
int main()
{
    int a[100];
    int n,i,num;
    int *p=a;
    printf("Enter size of array:");
    scanf("%d",&n);
    printf("Enter array elements:");
    for(i=0;i<n;i  ){
        printf("Enter the element [%d]:",i);
        scanf("%d",p i);
    }
    printf("Enter an element: ");
    scanf("%d",&num);
    for (i=0;i<n;i  ){
        if (*(p i)==num){
            printf("Array element Location is %d",i);
            break;
        }
        else{
            printf("Array element not found");
        }
        }
    }

But when an element not in the array is entered, the conditional statement "Array element not found" is printed n times as following: enter image description here

My desired output is that the conditional statement should be printed just once if the array element is not found in the array.

Is there any different method I should try?

CodePudding user response:

Replace break; with return 0; to end the program. Then move the line that prints "Array element not found" to be after the loop. The loop body runs multiple times so of course "Array element not found" could be printed multiple times if you put it in the loop body.

Also put \n at end of your strings to add a line break so your program's output is readble.

  • Related