Search a number from a given list

This is a discussion on Search a number from a given list within the C Programming forums, part of the General Programming Boards category; Ok .. I'm a newbie.. I'm goin' on to write the program to find if a given number is present ...

  1. #1
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8

    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. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    if( numbertofind == array[ thisspot ] )
        ...match, so stop looking...
    Just like you compare any other number.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    Quote 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. #4
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    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 */
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  5. #5
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    Quote 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. #6
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    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. #7
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    Quote 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. #8
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    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. #9
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    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?
    Last edited by =CrAzYG33K=; 06-12-2006 at 10:10 AM.

  10. #10
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    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!
    Last edited by =CrAzYG33K=; 06-12-2006 at 10:20 AM.

  11. #11
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,164
    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).
    If you understand what you're doing, you're not learning anything.

  12. #12
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  13. #13
    Registered User =CrAzYG33K='s Avatar
    Join Date
    Jun 2006
    Posts
    8
    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. #14
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    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
    you made:

    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");
    }
    Last edited by Richie T; 06-12-2006 at 03:10 PM.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    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.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  3. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  4. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 12:21 PM
  5. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 05:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21