# I want to redesign my Linear Search C code for Ask the user to input the number to search for

• Comp Sci
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 doesnt 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:

## Answers and Replies

mfb
Mentor
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].
I tried scanf("%d",r); command but doesnt work
What exactly does not work?
This code my first code before the decide Ask user :
The code that causes problems would be more useful to find the problem.

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

Mark44
Mentor
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);

Mark44
Mentor
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.