2

In this code for linear search, after line 8 is executed it jumps to line 13 without executing the for loop.

Output: Enter the size of array 5 Enter the elements Enter the element to be searched

Here is the code:

#include<stdio.h>

int main()
{
   int array[100],search,c,n;
   printf("Enter the size of array\n");
   scanf("%d",&n);
   printf("Enter the elements:\n");
   for(c=0; c>n; c++)
   { 
       scanf("%d",&array[c]);
   }
   printf("Enter the no. to be searched\n");
   scanf("%d",&search);
   for(c = 0; c>n; c++)
   {
       if(array[c] == search)
       {
           printf("%d is at location %d\n",search,c);
           break;
       }    
       if(c == n)
           printf("Item not found\n");    
   }    
   return 0;
}





Asfiya Shaikh
  • 107
  • 2
  • 7
  • 6
    Change the condition to `cn` is false from the beginning. – eduffy Sep 16 '19 at 14:41
  • otherwise enter a negative number XD – Xxx Xxx Sep 16 '19 at 14:43
  • when the program outputs: `printf("Enter the size of array\n");`, Exactly what did you enter? – user3629249 Sep 16 '19 at 22:50
  • The program could tell you a lot if the code were to check the returned value (not the parameter values) from functions like: `scanf()` – user3629249 Sep 16 '19 at 22:51
  • regarding statements like: `for(c = 0; c>n; c++)` The second parameter is to say when the code is to STAY in the loop NOT when the code is to exit the loop. Suggest: `for(c = 0; c – user3629249 Sep 16 '19 at 22:55
  • when the `for()` statements are correctly written, then this kind of code block: `if(c == n)` will NEVER be entered. Note: in C, the allowed index into an array is 0...( number of elements in the array -1 ). So any access when `c` == `n` is accessing past the end of the array, resulting in undefined behavior – user3629249 Sep 16 '19 at 22:58
  • regarding: `int array[100]` and `scanf("%d",&n);` This is a VERY bad idea. Suggest placing the declaration of `array[]` after the call to `scanf()` and writing it as: `int array[ n ];` ( which makes use of the VLA (variable length array) feature of C ) – user3629249 Sep 16 '19 at 23:02
  • OT: for ease of readability and understanding: 1) separate code blocks: `for` `if` `else` `while` `do...while` `switch` `case` `default` via a single blank line 2) insert appropriate space: inside parens, inside braces, inside brackets, after commas, after semicolons, around C operators – user3629249 Sep 16 '19 at 23:06

1 Answers1

4

You're not entering the for loop because of the condition c > n, try change it to c < n.

for(c=0; c < n; c++)
XBlueCode
  • 785
  • 3
  • 18