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

  • #1
3
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 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

  • #2
35,651
12,217
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.
 
  • #3
3
0
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
 
  • #4
35,287
7,140
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);
 
  • #5
35,287
7,140
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.
 

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

Replies
2
Views
2K
Replies
8
Views
11K
  • Last Post
Replies
1
Views
1K
Replies
3
Views
759
Replies
2
Views
7K
Replies
1
Views
5K
  • Last Post
Replies
9
Views
945
Replies
17
Views
3K
Top