Thread: Help me to optimize this code

  1. #1
    Registered User
    Join Date
    Apr 2015
    Posts
    7

    Help me to optimize this code

    Question :
    input 5 numbers to array X and display input. integer Y= 10
    find out the number in Y appears in array X

    Code:
    #include <stdio.h>
    int main()
    {
    	int x[5];
    	int i;
    	int y=10;
    	 
    	
    	for (i=0;i<5;i++)
          	{	
      			printf("\n Enter number:");
    			scanf("%d",&x[i]);
    		}
    	
    		for (i=0;i<5;i++)
    		{	
    		printf("\n %d",x[i]);
    		}
    		printf("\n ===========================");
    	
    			for (i=0;i<5;i++)
    			{
    				
    			     if (x[i]==y)
    				 {
    				  printf("\n  found");
    			     }
    				  else
    				{
    				printf("\n  not found");
    				}
    			}
    		return 0;		
    		
    		}
    Output


    Enter number:10


    Enter number:5


    Enter number:8


    Enter number:7


    Enter number:6


    10
    5
    8
    7
    6
    ===========================
    found
    not found
    not found
    not found
    not found
    --------------------------------
    Process exited after 4.951 seconds with return value 0
    Press any key to continue . . .

    i want to modify the code to display "found or not found" only once from number in Y found among the five numbers stored in array x

  2. #2
    Registered User
    Join Date
    Aug 2015
    Posts
    26
    Not sure if this is what you're trying to do but couldn't you just create another variable and set the variable to 1 if Y is found in X[] and to zero other wise? Then a simple printf() statement that prints the 'found'/'not found' depending in the variables value?

  3. #3
    Registered User
    Join Date
    Sep 2015
    Location
    Australia
    Posts
    63
    Hi..

    Depends on whats needed, the question says display input and you do that " enter number:7 " so is displaying the numbers again needed..? if not, you don't need a Printf.. and you can use the one "for Loop". Then it comes down to, do you want the answer formatted and looking pretty or just Input displayed Y found/Not Found..?

    Code:
    #include <stdio.h>
    int main() {
     int x[5];
     int i;
     int y=10;
    
     printf("\n Enter 5 numbers: ");
     scanf("%d%d%d%d%d",&x[0],&x[1],&x[2],&x[3],&x[4]);
    
     for (i=0;i<5;i++) {
      if (x[i]==y) {
       printf("\nFound");
       return 0;
         }
        }
        printf("\n Not Found");
     return 0;
    }
    Last edited by JohnGM; 09-26-2015 at 10:18 PM.

  4. #4
    Registered User
    Join Date
    Apr 2015
    Posts
    7
    Thank you for simplified code.

  5. #5
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by JohnGM View Post
    Code:
    …
        scanf("%d%d%d%d%d",&x[0],&x[1],&x[2],&x[3],&x[4]);
    …
    I hope this is a joke.
    What you think make this line?
    Last edited by WoodSTokk; 09-27-2015 at 02:20 AM.
    Other have classes, we are class

  6. #6
    Registered User
    Join Date
    Sep 2015
    Location
    Australia
    Posts
    63
    Hi ..

    WoodSTokk........we can all make smart comments.....I am here to learn.....I am looking for your contribution but can't find it..?

    John

  7. #7
    Registered User
    Join Date
    Jun 2009
    Posts
    486
    You could do the same thing with
    Code:
    scanf("%5d",x)
    C is fun

  8. #8
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by JohnGM View Post
    Hi ..

    WoodSTokk........we can all make smart comments.....I am here to learn.....I am looking for your contribution but can't find it..?

    John
    Ops. I realy think thats a joke. Sorry.

    To the problem.
    The format "%d%d%d%d%d" expect 5 numbers in a row without delimiter.
    Asume we enter "1234567890". What numbers will scanf read in the variables?
    It can be 1, 2, 3, 4 and 567890 ... or 123456, 7, 8, 9 and 0 ... nobody knows.
    It is better to use a delimiter.
    In this example, i use space as delimiter:
    Code:
    …
            scanf(" %d %d %d %d %d", &x[0], &x[1], &x[2], &x[3], &x[4]);
    …
    Asume we enter "12 34 56 78 90".
    Now we can enter 5 numbers and scanf see where one number begin and where it end.

    But there is another problem. It dosn't matter what we enter, scanf is allways happy.
    If we enter "12 34 56", scanf assign 12 to x[0], 34 to x[1] and 56 to x[2].
    x[3] and x[4] will leave unchanged (they have garbage values since declaration).
    For this case we can use the return value of scanf.
    scanf returns the number of successfully assigned elements.
    In our case, we want 5 numbers, so scanf should return 5.
    Is this not the case, the input was not correct.
    The result is:
    Code:
    …
        int x[5], ret;
    …
        do {
            ret = scanf(" %d %d %d %d %d", &x[0], &x[1], &x[2], &x[3], &x[4]);
        } while (ret != 5);
    Other have classes, we are class

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    To the problem.
    The format "%d%d%d%d%d" expect 5 numbers in a row without delimiter.
    Asume we enter "1234567890". What numbers will scanf read in the variables?
    In this case you have only entered one number, the number 1234567890. It doesn't matter if you used the spaces or not in the format string, scanf() knows what a number looks like. And even without the spaces if you entered "1 2 3 4 5" scanf() knows that there were 5 numbers entered, remember scanf() stops processing when it encounters a whitespace character, and by default skips leading whitespace characters for everything other than the "%c" specifier.

    Jim

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by KBriggs
    You could do the same thing with
    Code:
    scanf("%5d",x)
    No, you cannot. The "5" in "%5d" specifies the field width, e.g., if the user entered "123456", it will match "12345". Nonetheless, the format specification only matches for a single int, i.e., the first int in the array since x is converted to a pointer to its first element.

    Quote Originally Posted by WoodSTokk
    The format "%d%d%d%d%d" expect 5 numbers in a row without delimiter.
    Asume we enter "1234567890". What numbers will scanf read in the variables?
    It can be 1, 2, 3, 4 and 567890 ... or 123456, 7, 8, 9 and 0 ... nobody knows.
    It is better to use a delimiter.
    No, while I do prefer to insert such spaces, JohnGM's code is fine in this respect:
    Quote Originally Posted by C11 Clause 7.21.6.2 Paragraphs 5, 7, 8, 15a
    A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

    (...)

    A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:

    Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.

    (...)

    Trailing white space (including new-line characters) is left unread unless matched by a directive.
    Therefore, it does not matter that there are no spaces separating the "%d": scanf will read "1234567890" as matching the first "%d". The format string will still correctly match say, "12 34 56 78 90".

    Personally though, I would have kept to the idea of a loop from the original code rather than hard coding the five "%d" in a single format string.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Okay, the "%d" format skip whitespaces automaticly, so we can write the format "%d%d%d%d%d".
    But this those not check if 5 numbers entered and without checking, the program runs with garbage values.

    @laserlight: yes, the loop in post #1 was for me also nice and clear. I don't know, why JohnGM has changed this snippet.
    Other have classes, we are class

  12. #12
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    A more efficient search like binary search would be something to look at. Consider reading (at least) the relevant section in this article: Linear Search and Binary Search - Cprogramming.com

  13. #13
    Registered User
    Join Date
    Sep 2015
    Location
    Australia
    Posts
    63
    hi...

    I appreciate the positive comments, I find participating in answering questions is a great way to learn....If I get something wrong do tell me.. or as in this case maybe a better way to do something,,,also good for learning..

    John

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to optimize C++ code in Linux?
    By MutantJohn in forum Linux Programming
    Replies: 5
    Last Post: 04-01-2014, 11:43 AM
  2. How to optimize C++ code in Linux?
    By MutantJohn in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2014, 05:27 AM
  3. How can i optimize this code
    By ArunS in forum C Programming
    Replies: 15
    Last Post: 08-08-2011, 02:11 PM
  4. Please help me optimize my code
    By lazyme in forum C++ Programming
    Replies: 3
    Last Post: 01-25-2010, 04:05 AM
  5. Wanna Optimize my code?
    By Echo in forum C++ Programming
    Replies: 10
    Last Post: 08-15-2005, 01:24 AM