Searching Array for an Element using Linear Search

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
iquicck
Messages
3
Reaction score
0
Homework Statement
I write a Linear Search code but ı redesign for ask to user version
Relevant Equations
Linear Search
I write a Linear Search code,then ı decided ask to user "r" and "int arr".I mean,User decide their r and arr numbers.I tried scanf("%d",r); command but doesn't work
This code my first code before the decide Ask user :
C:
#include <stdio.h>

int search(int arr[], int n, int r)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[ i] == r)
            return i;
    return -1;
}int main(void)
{
    int arr[] = { 7, 9, 12, 28, 17,32 };
    int r = 17;
    int n = sizeof(arr) / sizeof(arr[0]);
 
  
    int result = search(arr, n, r);
    (result == -1)
        ? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}
 
Last edited by a moderator:
Physics news on Phys.org
I fixed a formatting issue with the code. The forum interprets [i] as command to display following text in italics. To avoid that you can put code in [code] tags or write [plain][i][/plain].
iquicck said:
I tried scanf("%d",r); command but doesn't work
What exactly does not work?
iquicck said:
This code my first code before the decide Ask user :
The code that causes problems would be more useful to find the problem.
 
mfb said:
I fixed a formatting issue with the code. The forum interprets [i] as command to display following text in italics. To avoid that you can put code in [code] tags or write [plain][i][/plain].What exactly does not work?The code that causes problems would be more useful to find the problem.
Code is work but I want to redesign my code for ask to user for enter number to "r"
I wrote;
printf("Enter r number);
scanf("%d",r);
but it didnt work
 
iquicck said:
Code is work but I want to redesign my code for ask to user for enter number to "r"
I wrote;
printf("Enter r number);
scanf("%d",r);
but it didnt work
The prompt is not very useful. Instead of printing "Enter r number" it would be better to say "Enter the number to search for".

The scanf function requires the address of the variable you're going to input to.

Try this:
C:
scanf("%d", &r);
 
mfb said:
I fixed a formatting issue with the code. The forum interprets as command to display following text in italics. To avoid that you can put code in
Code:
 tags or write [plain][i][/plain].
I surrounded the code in post #1 with code tags. I also changed one line in the search function to arr[ i], with a space preceding the index i. This keeps the browser from displaying what follows as italics.