array programming practice exercises

Thread Starter

anukalp

Joined Jul 28, 2018
158
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
C:
/*c program to find the duplicate element in an array
Author   : Anukalp
Language : C Programming
Date     : 27.8.2018
*/

#include <stdio.h>

int i, j, size, array[50];

int main (void)
{
    printf ("Enter array size : ");
    scanf ("%d", &size);
    
        if ( size >  0 && size  <  50 )    /* Check valid size */
            {  
                printf("Array size : %d \n", size);
            }
     
        else
            {
                printf("Please try again \n");
                printf("size you enterd is not valid \n");
                printf("1. number shouldn't be more then 50 \n");        
                printf("2. You can't enter neagtive value \n");
   
                while (!( size > 0 && size < 50 ))
                 {          
                    printf ("Enter array size : ");
                    scanf ("%d", &size);
   
                    printf("Please try again \n");
                    printf("size you enterd is not valid \n");
                    printf("1. number shouldn't be more then 50 \n");        
                    printf("2. You can't enter neagtive value \n");
           
                    if(size >  0 && size  <  50 )
                    {
                       printf("Entered  array size : %d \n", size);
                 
                       break;
                    }
                }
            }
                           
    printf ( "\nEnter array Elements \n" ) ;

        for ( i = 0; i  <  size ;  i++ )
        {
               scanf ( "%d",  &array[i] ) ;
        }
        for ( i = 0;  i <  size;  i++ )
        {
               printf ( "%d ",  array[i] ) ;
        }
      
        for( i = 0; i < size; i++)
        {
    
            for( j = i+1; j < size; j++)
                 
                if (array[i] == array[j])
                {
                    printf("\nDuplicate number : %d ", array[i] );                                                         
                }                       
        }
    return 0;
}
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:

dl324

Joined Mar 30, 2015
16,846
It would be more efficient if you sorted the array so you only needed one pass through the array to find duplicates.
 

dl324

Joined Mar 30, 2015
16,846
I didn't understand your point. Can you tell me little bit more about it.
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.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Using qsort() to sort the array and then checking for duplicates will be significantly more efficient on large arrays.
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:

dl324

Joined Mar 30, 2015
16,846
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.
You don't need to understand the algorithm to use the function.
do you see any error in my program
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:
    printf ( "\nEnter array Elements \n" ) ;

        for ( i = 0; i  <  size ;  i++ )
        {
               scanf ( "%d",  &array[i] ) ;
        }
        for ( i = 0;  i <  size;  i++ )
        {
               printf ( "%d ",  array[i] ) ;
        }

        for( i = 0; i < size; i++)
        {

            for( j = i+1; j < size; j++)

                if (array[i] == array[j])
                {
                    printf("\nDuplicate number : %d ", array[i] );            
                }
        }
could be written as
Code:
  printf("\nEnter array Elements \n");
  for (i = 0; i < size; i++) {
    scanf("%d", &array[i]);
  }
  for (i = 0; i < size; i++) {
    printf("%d ", array[i]);
  }

  for (i = 0; i < size; i++) {
    for (j = i + 1; j < size; j++)
      if (array[i] == array[j]) {
        printf("\nDuplicate number : %d ", array[i]);
      }
  }
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.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
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.
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.
 

ArakelTheDragon

Joined Nov 18, 2016
1,362
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.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
You need to make the alghoritm by yourself.
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
 

ArakelTheDragon

Joined Nov 18, 2016
1,362
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
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.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
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.
This is a first way that came in my mind
C:
#include <stdio.h>

int main()
{
    char array[50];
    int j,  i = 0;

    printf("Enter a string\n");
    scanf("%s", array);
    printf("You entered the string : %s",array);
 
    for(i = 0; array[i] != '\0'; i++);
 
    printf("\nLength of string: %d ", i);
 
    printf("\nReverse  of string: ");
 
     for( j = i; j >= 0; j--)
        {      
          printf("%c", array[j] );                                                                                           
        }
    
    return 0;
}
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:

ArakelTheDragon

Joined Nov 18, 2016
1,362
"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:

Thread Starter

anukalp

Joined Jul 28, 2018
158
"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.
Do you find anything wrong in my alghoritm. Does the program fail at any condition.
C:
#include <stdio.h>

int main()
{
    char array[50];
    int j, i;

    printf("Enter a string\n");
    scanf("%s", array);

    printf("You entered the string : %s",array);


    for (i=0, j=0; i<50, j>0; i++, j--)

        {      
          printf("%c ", array[j] );                                                                                                 
        }

    return 0;
}
What's wrong in above code. It should be print reverse string but It doesn't print reverse string
 
Last edited:

ArakelTheDragon

Joined Nov 18, 2016
1,362
Something like this:
Code:
char* reverse_string(char *str)
{
  char temp;
  size_t len = strlen(str) - 1;
  size_t stop = len/2;
  size_t i,k;

  for(i = 0, k = len; i < stop; i++, k--)
  {
  temp = str[k];
  str[k] = str[i];
  str[i] = temp;
  }
  return str;
}
 

dl324

Joined Mar 30, 2015
16,846
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.
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

Joined Sep 24, 2011
696
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.
 

dl324

Joined Mar 30, 2015
16,846
I have seen some code on Wikipedia. This type of style has been used there
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 whitespace makes the code look good, and anyone can easily catch the mistake in program.
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.
 
Top