BCSL-021: Create a menu driven program to read and print a list and delete duplicates

Today we are going to look at the solution of a frequently asked question in your semester exam along with its fundamental explanation.
For detailed and easy explanation, watch my YouTube videos.

Question

Write a menu driven program to read a list of numbers, then print the list. Also, eliminate all the duplicate element from the list.

Solution

How do we do this? If you think carefully you will notice that we can use a simple concept of Array and Loops to create our program in the simplest way.

Let's do this.

The source code of the program is given below.

#include<stdio.h>
int main() {
   int arr[20], i, j, k, x, size;
   do
{
printf("\n\n\t\tMain Menu\n\n1. Enter number in the list\n2. Display the list\n3. Delete the Duplicates from the list\n4. Exit\t\n");
scanf("%d",&x);
switch(x)
{
    case 1: printf("\nEnter array size : ");
   scanf("%d", &size);
   printf("\nAccept Numbers : ");
   for (i = 0; i < size; i++)
      scanf("%d", &arr[i]);
    break;
   
   
    case 2: printf("The list is:\n\n");
    for(i=0;i<size;i++)
    {
    printf("%d",arr[i]);
    printf("\t");
    }
    break;
   
    case 3: printf("\nAfter removing duplicates: ");
   for (i = 0; i < size; i++) {
      for (j = i + 1; j < size;) {
         if (arr[j] == arr[i]) {
            for (k = j; k < size; k++) {
               arr[k] = arr[k + 1];
            }
            size--;
         } else
            j++;
      }
   }

   for (i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
   
    break;
   
    }
   
    }while(x<4);

   return (0);
}

Explanation

Our first step is to include the stdio.h library, then we have main() function whose data type is integer (int).

Then we declare some integer variables which we will use further in our program like i,j,k,x, and array arr[20]. In arr[20], arr is the name of the array while [20] resembles the capacity of the array.

Then we use a do() while function in order to get a self repeating menu.

Then we use printf() function to showcase our main menu. After that, we use scanf() function to take input corresponding the main menu.

Using switch() function, we use it to switch between different tasks like reading the list, printing the list and deleting the duplicates from the list. After every case in switch function we use a break; to stop the task then and there.

Finally, Return(0); depicts that the program is returning no specific value.

For more detailed explanation while performing the tutorial live, watch my videos on Igor11 Coding YouTube channel

Post a Comment

What do you think?

Copyright © Igor11 Coding Theme by