Home > Software design >  Anyone know why this 'linear search' code won't show the correct result?
Anyone know why this 'linear search' code won't show the correct result?

Time:11-27

this is code for linear search in 10 array table btw it has to be in do-while or while loop not for loop.

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

int
search(int t[], int x, int n)
{
    int i;

    i == 0;

    do {
        i = i   1;
    } while ((t[i] != x) || (n > i));

    if (t[i] == x) {
        printf("index=%d", i   1);
    }
    else {
        printf("element not found");
    }
}

int
main()
{
    int t[10];
    int x, i;

    printf("enter x: ");
    scanf("%d", &x);

    for (i = 0; i < 10; i  ) {
        printf("enter table element : ");
        scanf("%d", &t[i]);
    }

    search(t, x, 10);

    return 0;
}

i excepted to get the index of the specified number (x) in the table but the problem is that results are wrong (it show 3 digit number) and sometimes won't show anything at all

CodePudding user response:

This line of code has no effect. The == is comparison operator

i == 0;

Instead, you should use asignemnt operator:

i = 0;

I slightly changed your code and made it works. Please pay attention of forma t strings in scanf function, it is important.Please read article scanf() leaves the newline character in the buffer

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int
search(int t[], int x, int n)
{
    int i = 0;

    do {
           if( t[i] == x )
           {
              printf("index=%d", i);   
              return 0;
           }  
    } while (i   < n );

    printf("element not found");
    return 1;
}



int
main()
{
    int t[10];
    int x;

    printf("enter x: ");
    scanf(" %d*c", &x);
    if( errno) perror("scanf x");

    for (int i = 0; i < 10; i  ) {
        printf("enter table element : ");
        scanf(" %d*c\n", &t[i]);
    }

    search(t, x, 10);

    return 0;
}
  •  Tags:  
  • c
  • Related