# Thread: Search a number from a given list

1. ## Search a number from a given list

Ok .. I'm a newbie..
I'm goin' on to write the program to find if a given number is present in a given list of numbers or not!
I'm stuck midway.. Here's my progress

Code:
``` #include<stdio.h>
#include<conio.h>
main()
{
int i,x,y,a[i];
printf("\n Enter the no. of elements available in list : ");
scanf("%d",&y);
printf("\n Enter the List : \n");
for(i=0;i<y;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the number which is to be searched in  list : ");
scanf("%d",&x);
-------------------------------
-------------------------------
-------------------------------
-------------------------------
-------------------------------
getch();
}
sub()
{
printf("\n The Number is present in the list");
}
subno()
{
printf("\n The Number is not present in the list");
}```
OK .. What logic do i use in the part filled with hyphens??
I tried the for(i=0;i<x;i++) loop with 'if' condition but I couldn't satisfy my original condition properly..
Can someone guide?

2. Code:
```if( numbertofind == array[ thisspot ] )
...match, so stop looking...```
Just like you compare any other number.

Quzah.

3. Originally Posted by quzah
Code:
```if( numbertofind == array[ thisspot ] )
...match, so stop looking...```
Just like you compare any other number.

Quzah.
Hey .. That's what I'm telling ya..
I tried that, but I can't make it stop after the match
Can u paste the full code please.. I'm not getting your point.

4. break; will exit the for loop.

But you can just combine the logic into the for loop, like this:

Code:
```i = 0;
for(!end_of_array && array[i] != search_num); /* <-- note this semicolon, the for loop ends here */```

5. Originally Posted by jafet
break; will exit the for loop.

But you can just combine the logic into the for loop, like this:

Code:
```i = 0;
for(!end_of_array && array[i] != search_num); /* <-- note this semicolon, the for loop ends here */```
Thanx for the tip jafet, but I've already used the break command but to no avail!
I didn't get your other logic though...
Can u write the whole prog. with my code and adding your code into them and post pls?

6. Can u paste the full code please.. I'm not getting your point.
I have a better idea. You paste your full code and we'll tell you what you are doing wrong.

7. Originally Posted by Thantos
I have a better idea. You paste your full code and we'll tell you what you are doing wrong.
OK.. Here goes..
My problem was : I was too embarassed to type in my wrong code!
Code:
``` #include<stdio.h>
#include<conio.h>
main()
{
int i,x,y,a[i];
//int sub();
printf("\n Enter the no. of elements available in list : ");
scanf("%d",&y);
printf("\n Enter the List : \n");
for(i=0;i<y;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the number which is to be searched in  list : ");
scanf("%d",&x);
for(i=0;i<x;i++)
{
if(x==a[i])
{
sub();
break;
}
else
{
subno();
break;
}
}
getch();
}
sub()
{
printf("\n The Number is present in the list");
}
subno()
{
printf("\n The Number is not present in the list");
}```
I know this is woefully wrong.. Can ya ppl make the corrections pls??

8. When you make the array a[i], i is undefined, so that doesn't really work. I don't know about newer implementations allowing variable length arrays, but generally you would allocate space for one with malloc.

Code:
```	int i,x,y,b=0,*a;

printf("\n Enter the no. of elements available in list : ");
scanf("%d",&y);

a = malloc(y);
...
...
getch();
free(a);
}```
For searching, you could use a flag 'b' to see whether it was found or not. You would search through the entire array, and say while i<y.

Code:
```	for(i=0;i<y;i++)
{
if(x==a[i])
{
b=1
break;
}
}
if(b) sub();
else subno();```

9. Thanx Tonto
I guess I get your point.. Thank You!
But I've never had experience using malloc myself. (Actually, I didn't even know how and where to use it before you posted this! )
I'll try and post back. Thanx for the help! This board is gr8.

EDIT:
I think there's some small problem in the code.. I guess I can understand the logic but..
Code:
``` #include<stdio.h>
#include<conio.h>
main()
{
int i,x,y,b=0,*a;
printf("\n Enter the no. of elements available in list : ");
scanf("%d",&y);
printf("\n Enter the List : \n");
a = malloc(y);
scanf("%d",&a);
printf("\n Enter the number which is to be searched in  list : ");
scanf("%d",&x);
for(i=0;i<y;i++)
{
if(x==a[i])
{
b=1;
break;
}
}
if(b) sub();
else subno();
getch();
free(a);
}
sub()
{
printf("\n The Number is present in the list");
}
subno()
{
printf("\n The Number is not present in the list");
}```
I guess the highlighted part of the code is wrong..
What's the mistake guys?

10. OK... All worked fine!!!
Here's the full working code.. I had to accept the input 'a' inside a for loop!
Code:
``` #include<stdio.h>
#include<conio.h>
main()
{
int i,x,y,b=0,*a;
printf("\n Enter the no. of elements available in list : ");
scanf("%d",&y);
printf("\n Enter the List : \n");
a = malloc(y);
for(i=0;i<y;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the number which is to be searched in  list : ");
scanf("%d",&x);
for(i=0;i<y;i++)
{
if(x==a[i])
{
b=1;
break;
}
}
if(b) sub();
else subno();
getch();
free(a);
}
sub()
{
printf("\n The Number is present in the list");
}
subno()
{
printf("\n The Number is not present in the list");
}```
Thanks for all your support guys.. I'll ask if I need help in other programs too!

11. You should break your bad habits ASAP. It'll only be harder later on:
Code:
``` #include<stdio.h>
#include<conio.h>```
Put your space after "#include" instead of before (e.g. "#include <stdio.h>"). Also, conio.h is a non-standard header and it's best to avoid those when possible.
Code:
`main()`
main() should be defined as: int main(void) unless you want to accept command-line arguments, which you're not.
Code:
```{
int i,x,y,b=0,*a;```
Try to use meaningful variable names. It will avoid a lot of mistakes once your programs get larger. Using i for a counter variable is fine as long as you consistently do it, but variables that represent the length of an array or whatever should actually indicate that that's what they do.
Code:
`    printf("\n Enter the no. of elements available in list : ");`
When printing a prompt, follow-up the printf() with a fflush(stdout); because not all environments will print the prompt otherwise.
Code:
```    scanf("%d",&y);
printf("\n Enter the List : \n");
a = malloc(y);```
You should always check the return value of malloc(). And again, isn't array = malloc(array_len); a lot easier to see on first-sight than some non-descript variables?
Code:
```    printf("\n Enter the number which is to be searched in  list : ");
scanf("%d",&x);```
Again, x? How about search_val or something?
Code:
```	if(b) sub();
else subno();```
This isn't exactly the greatest use of functions. You're calling them fine, but in larger projects you're not going to want to be jumping all over trying to see what these functions do just to find out that they print a simple message. Also, I always find it helpful to include the user's input in a message like this one. You could even replace both of those lines with a single one: printf("\n The Number %d is %spresent in the list\n", search_val, b ? "" : "not ");
Code:
`    getch();`
getch() is a non-standard function. Use it for homework problems if you wish, but when you work on larger projects, avoid it.
Code:
```sub()
{
printf("\n The Number is present in the list");
}
subno()
{
printf("\n The Number is not present in the list");
}```
I know I already suggested not using these functions, but if you do use them, make sure you use them correctly. You should have prototypes for these functions and they should be defined like: void subno(void).

12. Consistent indentation works wonders you know....

> a = malloc(y);
1. You should have included stdlib.h
2. You need to scale the amount you allocate - you allocated 'y' chars, not 'y' ints.
The result being you stomped all over some memory which you didn't own.
a = malloc(y * sizeof *a);
would fix that.

13. uh.. sorry I understood atleast some of itsme86's post, but couldn't even make heads or tails of Salem's last post. I guess its about the memory though.
The Code did run on the Bloodshed Dev c++ IDE, but I highly doubt it running on the conventional Turbo C compiler. Maybe itsme86's suggestions have to be taken into account for that..

14. I'll break it down into plain terms then:

>>1. You should have included stdlib.h

This is the header file where the details of the malloc function
are stored - basically it tells the compiler what malloc is, and
how it is supposed to be used. The same as you must include
<conio.h> to use your getch(), so you must to use malloc

>>2. You need to scale the amount you allocate - you
allocated 'y' chars, not 'y' ints.

The argument which malloc takes is the number of bytes of
memory to allocate. Basically calling malloc is like this:

a = malloc (number_of_bytes);

in your code, y is an integer, storing the number of allocations you
want to make, lets say that it is 10. In that case, the call

a = malloc(y);

is the same as:

a = malloc(20);

This would be fine if each element was 1 byte in size, but you
are allocating for integers, which are typically 4 bytes, in which,
you are only allocating space for 5 integers, not 20 as you
thought. What Salem said was actually to multiply the number
of integers you want to allocate by the size of the integer type -
sizeof is a C keyword that gives you the amount of memory a
datatype or variable takes in memory. Your variable "a" is an
int pointer, hence "*a" evaluates to an int. So in essence, the
part that says sizeof *a is equivalent to sizeof (int) in this case.

You could replace the *a part with this and it would still work,
except Salems syntax is more versatile, since it will still work
if you decided to change the type of variable you allocated,
to a float for some reason perhaps.

>>Consistent indentation works wonders you know....

I have to echo this, indentation helps readability a lot. The basic
idea is that you indent a tab or a consistant number of spaces
every time a code block begins - also, some vertical white space
helps a lot too. Here's your code reworked to my own style,
with the first 2 of itsme86's suggestions (I refuse to leave it
as it was!):

Code:
```#include <stdio.h>
#include <conio.h>

//QUICK NOTE: Never put a comment in the same line as preprocessor directive (#define etc)

int main(void)
{
int i, x, y, b = 0, *a;

printf("\n Enter the no. of elements available in list : ");
scanf("%d", &y);

printf("\n Enter the List : \n");

a = malloc(y);

for(i = 0; i < y; i++)	//some spacing in expressions is nice too
{
scanf("%d", &a[i]);
}

printf("\n Enter the number which is to be searched in  list : ");
scanf("%d", &x);

for(i = 0; i < y; i++)
{
if(x == a[i])
{
b = 1;
break;
}
}

if(b) sub();

else subno();

getch();
free(a);

return 0; //Not essential, but I always put it in out of habit
}
void sub()
{
printf("\n The Number is present in the list");
}

void subno()
{
printf("\n The Number is not present in the list");
}```

15. Excellent post, except
Code:
`//QUICK NOTE: Never put a comment in the same line as preprocessor directive (#define etc)`
Why not? Comments are stripped before anything else. You can put them at the end of #includes, #defines, #endifs, whatever.