Hi, I'm pretty new to C programming. Writing a program to search through an array and print the number and its position. The program compiles and runs and if the value entered is not present in the array i get the correct result , however if the value is present it prints 0 in position 0. If possible could someone please help me find the error.
Code:
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
int Search(const int set[] , int key, int size);/*Linear search function*/
int main(void)
{
int num[SIZE];/*Array of numbers*/
int i;/*counter*/
int search;/*Integer to be searched for*/
int element;/*Stores value returned from function*/
for ( i = 0; i < SIZE ; i++)
{
num[i] = i * 2;/*Get values for array*/
}
printf("Enter a number to search for\n");
scanf("%d" , &search);
element = Search(num , search , SIZE);/*Call function*/
if (element != -1 )
{
printf("The number %d was found at position %d" , num[element] , element);
}
else
{
printf("Not found\n");
}
system("PAUSE");
return 0;
}
int Search(const int set[] , int key , int size)
{
int n = 0;
while( (set[n] != key) && (n < size))
{
if( set[n] == key)
{
return n;
}
else
{
n++;
}
}
if (n >= size)
{
return -1;
}
}