-1

I was just trying to write a linear search program in C. But I'm not getting expected output for some reason that I don't understand. Please, someone, explain what I've done wrong.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(){
    int arr[5];
    int query;
    bool found = false;
    int index;

    printf("Insert five elements of your choice: \n");
    /*
        Getting 5 input from user.
    */
    for(int i=0; i<5; i++){
        printf("Element %d: ", i+1);
        scanf("%d\n", &arr[i]);
    }

    printf("What number you are looking for: ");
    scanf("%d\n", &query);

    /*
        Checking if the the number is in the array or not!
    */
    for(int check=0; check<5; check++){
        if(arr[check] == query){
            found = true;
            index = check;
        }
    }

    if(found){
        printf("Result: %d was found in index %d.\n", query, index);
    }else
    {
        printf("Result: Item was not found!");
    }
}
Austin
  • 25,759
  • 4
  • 25
  • 48
intelligent
  • 57
  • 1
  • 6
  • 1
    What is your expected output? What is the actual output? Please provide a [minimal, complete and verifyable example](https://stackoverflow.com/help/minimal-reproducible-example). – dan1st Nov 26 '19 at 16:13
  • 1
    By the way, it won't help you using the `#` for the question text. You won't get any attention with this and some peaple who could answer your question that see this may look for other questions immediately. – dan1st Nov 26 '19 at 16:15
  • When I was getting user input to fill the array, it hangs after the first input. And even if the number is in the array it fails to check. I don't know why. – intelligent Nov 26 '19 at 16:18
  • I'm new here. I don't understand much about the formalities. So, I am sorry for any kind of mistake and please guide me through if possible. Thanks. – intelligent Nov 26 '19 at 16:23

1 Answers1

1

The scanf function is able to read variables (using conversion specifiers like %d), exact symbols and any number of whitespace characters. If you specify \n in your format string, the scanf function will try to process any number of newlines you've hit. You may fix it by removing \n from format string at scanf call.

Northsoft
  • 171
  • 4