array programming practice exercises

Discussion in 'Programmer's Corner' started by anukalp, Aug 27, 2018.

  1. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    Exercises :1 write a c program to find the duplicate element in an array

    I have written program to find the duplicate element in an array. Please check this program and let me know if you see any logic error's
    Code (C):
    1. /*c program to find the duplicate element in an array
    2. Author   : Anukalp
    3. Language : C Programming
    4. Date     : 27.8.2018
    5. */
    6.  
    7. #include <stdio.h>
    8.  
    9. int i, j, size, array[50];
    10.  
    11. int main (void)
    12. {
    13.     printf ("Enter array size : ");
    14.     scanf ("%d", &size);
    15.    
    16.         if ( size >  0 && size  <  50 )    /* Check valid size */
    17.             {  
    18.                 printf("Array size : %d \n", size);
    19.             }
    20.      
    21.         else
    22.             {
    23.                 printf("Please try again \n");
    24.                 printf("size you enterd is not valid \n");
    25.                 printf("1. number shouldn't be more then 50 \n");        
    26.                 printf("2. You can't enter neagtive value \n");
    27.    
    28.                 while (!( size > 0 && size < 50 ))
    29.                  {          
    30.                     printf ("Enter array size : ");
    31.                     scanf ("%d", &size);
    32.    
    33.                     printf("Please try again \n");
    34.                     printf("size you enterd is not valid \n");
    35.                     printf("1. number shouldn't be more then 50 \n");        
    36.                     printf("2. You can't enter neagtive value \n");
    37.            
    38.                     if(size >  0 && size  <  50 )
    39.                     {
    40.                        printf("Entered  array size : %d \n", size);
    41.                  
    42.                        break;
    43.                     }
    44.                 }
    45.             }
    46.                            
    47.     printf ( "\nEnter array Elements \n" ) ;
    48.  
    49.         for ( i = 0; i  <  size ;  i++ )
    50.         {
    51.                scanf ( "%d",  &array[i] ) ;
    52.         }
    53.         for ( i = 0;  i <  size;  i++ )
    54.         {
    55.                printf ( "%d ",  array[i] ) ;
    56.         }
    57.      
    58.         for( i = 0; i < size; i++)
    59.         {
    60.    
    61.             for( j = i+1; j < size; j++)
    62.                  
    63.                 if (array[i] == array[j])
    64.                 {
    65.                     printf("\nDuplicate number : %d ", array[i] );                                                        
    66.                 }                      
    67.         }
    68.     return 0;
    69. }
    When I run code it gives following output

    Enter array size : 6
    Array size : 6

    Enter array Elements
    1
    2
    3
    3
    4
    5
    1 2 3 3 4 5
    Duplicate number : 3
     
    Last edited: Aug 27, 2018
  2. dl324

    AAC Fanatic!

    Mar 30, 2015
    6,943
    1,606
    It would be more efficient if you sorted the array so you only needed one pass through the array to find duplicates.
     
  3. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    I didn't understand your point. Can you tell me little bit more about it. https://en.wikipedia.org/wiki/Sorted_array
     
  4. dl324

    AAC Fanatic!

    Mar 30, 2015
    6,943
    1,606
    Put a counter in the program to count how many times you access array elements when the array is 6 and then 50 elements long. It doesn't grow linearly.

    Using qsort() to sort the array and then checking for duplicates will be significantly more efficient on large arrays.
     
  5. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    Your suggestion is very good. Quicksort is an sorting algorithm. I don't think that I'm fully prepared for algorithm. I think I should solve some more array exercises. I should take some time to understand the algorithm now.

    do you see any error in my program
     
    Last edited: Aug 27, 2018
  6. dl324

    AAC Fanatic!

    Mar 30, 2015
    6,943
    1,606
    You don't need to understand the algorithm to use the function.
    You're expecting users of your program to use "programming" lingo and specify a 50 element array as 49.

    I don't care to read your programming style. Too much whitespace; both for line indents and newlines. It's like you're getting paid by the line, so you throw them in whenever you can.

    For example, this
    Code (Text):
    1.     printf ( "\nEnter array Elements \n" ) ;
    2.  
    3.         for ( i = 0; i  <  size ;  i++ )
    4.         {
    5.                scanf ( "%d",  &array[i] ) ;
    6.         }
    7.         for ( i = 0;  i <  size;  i++ )
    8.         {
    9.                printf ( "%d ",  array[i] ) ;
    10.         }
    11.  
    12.         for( i = 0; i < size; i++)
    13.         {
    14.  
    15.             for( j = i+1; j < size; j++)
    16.  
    17.                 if (array[i] == array[j])
    18.                 {
    19.                     printf("\nDuplicate number : %d ", array[i] );            
    20.                 }
    21.         }
    could be written as
    Code (Text):
    1.   printf("\nEnter array Elements \n");
    2.   for (i = 0; i < size; i++) {
    3.     scanf("%d", &array[i]);
    4.   }
    5.   for (i = 0; i < size; i++) {
    6.     printf("%d ", array[i]);
    7.   }
    8.  
    9.   for (i = 0; i < size; i++) {
    10.     for (j = i + 1; j < size; j++)
    11.       if (array[i] == array[j]) {
    12.         printf("\nDuplicate number : %d ", array[i]);
    13.       }
    14.   }
    You omitted the curly braces on the last for loop. You could have done it on all of them. At least try to be consistent.
     
  7. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    I have seen some code on Wikipedia. This type of style has been used there

    I think the whitespace makes the code look good, and anyone can easily catch the mistake in program.
     
  8. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    Do not use quick sort. The point of these exercises is to see how the inside of functions work. You need to make the alghoritm by yourself. You can get familiar with the different sort methods also and see their advantages.
     
  9. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    I have done that I thought I should use a nested loop in logic so I used it in program.

    Exercises :2 write a c program to reverse string entered by user

    Now I'm thinking how to reverse the string. I'm making alghoritm for it. When I complete program, I will post the code to check any error
     
  10. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    There is more than 1 way. I suggest using "for" if you know how to use a "for" with 2 counters, one decreasing and one increasing it will work.
     
  11. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    This is a first way that came in my mind
    Code (C):
    1. #include <stdio.h>
    2.  
    3. int main()
    4. {
    5.     char array[50];
    6.     int j,  i = 0;
    7.  
    8.     printf("Enter a string\n");
    9.     scanf("%s", array);
    10.     printf("You entered the string : %s",array);
    11.  
    12.     for(i = 0; array[i] != '\0'; i++);
    13.  
    14.     printf("\nLength of string: %d ", i);
    15.  
    16.     printf("\nReverse  of string: ");
    17.  
    18.      for( j = i; j >= 0; j--)
    19.         {      
    20.           printf("%c", array[j] );                                                                                          
    21.         }
    22.    
    23.     return 0;
    24. }
    This program can reverse the string. I checked it on my computer

    Enter a string
    anukalp
    You entered the string : anukalp
    Length of string: 7
    Reverse of string: plakuna
     
    Last edited: Aug 28, 2018
  12. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    "for (i=0, j=0; i<50, j>0; i++, j--)".

    Of course I put mistakes and you have to find them.

    EDIT: Do not forget to put the new values in a second array or to rearrange them only in the first.
     
    Last edited: Aug 28, 2018
  13. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    Do you find anything wrong in my alghoritm. Does the program fail at any condition.
    Code (C):
    1. #include <stdio.h>
    2.  
    3. int main()
    4. {
    5.     char array[50];
    6.     int j, i;
    7.  
    8.     printf("Enter a string\n");
    9.     scanf("%s", array);
    10.  
    11.     printf("You entered the string : %s",array);
    12.  
    13.  
    14.     for (i=0, j=0; i<50, j>0; i++, j--)
    15.  
    16.         {      
    17.           printf("%c ", array[j] );                                                                                                
    18.         }
    19.  
    20.     return 0;
    21. }
    What's wrong in above code. It should be print reverse string but It doesn't print reverse string
     
    Last edited: Aug 28, 2018
  14. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    I might be blind but it seems ok.
    The idea is to make it in 1 "for" cycle if possible.
     
  15. anukalp

    Thread Starter Member

    Jul 28, 2018
    65
    0
    How do you find reverse string with your alghoritm post #10 ?
     
  16. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    Wait a moment, I am doing 7 things at once, which is very bad for my processor. I will see again and tell you.
     
  17. ArakelTheDragon

    Active Member

    Nov 18, 2016
    737
    38
    Something like this:
    Code (Text):
    1.  
    2. char* reverse_string(char *str)
    3. {
    4.   char temp;
    5.   size_t len = strlen(str) - 1;
    6.   size_t stop = len/2;
    7.   size_t i,k;
    8.  
    9.   for(i = 0, k = len; i < stop; i++, k--)
    10.   {
    11.   temp = str[k];
    12.   str[k] = str[i];
    13.   str[i] = temp;
    14.   }
    15.   return str;
    16. }
    17.  
     
  18. dl324

    AAC Fanatic!

    Mar 30, 2015
    6,943
    1,606
    Who said the point was for the OP to understand how sorting worked? He wrote a program that looked for duplicates. I pointed out that his brute force algorithm was inefficient on larger arrays and he should consider sorting the array before looking for duplicates.

    Many people who use qsort don't understand how to implement the algorithm or why it's better or worse than any other sorting algorithm written by some of the Greats in CS. We stand on the shoulders of giants in this area and I see little point in trying to reverse engineer what they did if all the OP wanted to do was scan an array for duplicate numbers more efficiently.

    I don't know, or care, how most functions were implemented; I just use them. When I write code, I'm trying to accomplish whatever it is I wanted to accomplish; not understand implementation details of the functions I'm using to do it.
     
    bogosort likes this.
  19. bogosort

    Active Member

    Sep 24, 2011
    147
    51
    Assuming that you're learning programming for practical (rather than academic) reasons, here are some general thoughts:

    1. Don't use scanf.

    In the testing stage, simply hard code your data at the beginning of your program. This keeps the coder shorter and focused on the problem at hand.

    Note that scanf was designed for reading in data from well-formed files, not for handling arbitrary user input. (To see why this is the case, try entering unexpected input to scanf, e.g., a string when it expects an integer.) For non-GUI programs, the "pro" way to handle user input is with command-line parameters. There are libraries that make it relatively easy to write robust command-line parsers, but this is something you'd do for an actual application, not for practice code.

    2. Use library functions when possible.

    Writing effective algorithms is a very different kind of skill than writing effective programs. Presumably you're working on the latter, so ignore the algorithmic details of sorting, searching, etc. and use library functions. You'll run into (and learn from) plenty of meaningful problems just trying to get a program to behave correctly.

    3. Focus on writing programs that do interesting things.

    There's nothing wrong with writing little programs to explore specific details, such as how pointers work. But that method doesn't scale on the learning curve -- you'll soon become bored and unsure of what to try next. Instead, I'd recommend working on applications that solve a problem that is meaningful to you. Maybe you'd like a reminder app, something that reads dates from a text file and alerts when that date has arrived. Or it could be a simple personal contact lookup app, where you give it a name (as a command-line parameter) and it returns their contact info. Or maybe you'd like an app that parses your system logs and alerts on important messages. The idea is to find some reasonably useful, reasonably programmable application idea and work on it. You'll learn about specific details (how to use pointers, how to read from a file, etc.) through trying to solve the inevitable challenges that will naturally arise. The advantage to this method is that it does scale: as you learn more and gain more confidence, you'll want to write more ambitious programs, from which you'll learn even more and gain even more confidence.

    In this sense, learning to program is a lot like learning a foreign language: while you can make some progress just by studying the grammar and vocabulary, the fastest and most effective route is to immerse yourself in actual conversation.

    4. Read lots of code.

    One of the most important things that a programmer can do is read other people's code, both professional and amateur code. This makes you literate in the full sense of the word. You'll be exposed to various coding styles, organizational paradigms, and problem solving techniques. You'll also develop a sense of language idioms, and your code will start to look more professional. You'll notice that you can glance at a block of code and instantly tell that it was written by a novice. And sometimes, like a composer looking at a Mozart score, you'll come across a piece of code and literally see that it is beautiful.

    Reading code should be a significant part of your practice regiment.
     
    anukalp and dl324 like this.
  20. dl324

    AAC Fanatic!

    Mar 30, 2015
    6,943
    1,606
    The style you're using is very similar to the GNU style of code, but I still don't like it. Too much whitespace.
    I think the extra whitespace makes it look like it was written by a novice.

    When I was in first grade in elementary school, we wrote on paper that forced us to make characters very large with a lot of space between lines. That's what the GNU coding style reminds me of.

    I prefer a modified K&R style. They invented the language, but it still has too much whitespace for my taste. I like my code more compact so I can see more actual code on a page or screen.
     
Loading...