Data Structures Practical 7

Question 1
Modify the bubble sort program to handle invalid input, such as non-string data or strings that exceed the maximum length.
strbubblesort.c
C
				#include <stdio.h>
#include <conio.h>
#include <string.h>

#define MAX_STRINGS 100
#define MAX_LENGTH 10

void bubbleSortStrings(char arr[][MAX_LENGTH], int size) 
{
    int i, j;
    char temp[MAX_LENGTH];

    for (i = 0; i < size - 1; i++) 
	{
        for (j = 0; j < size - i - 1; j++) 
		{
            if (strcmp(arr[j], arr[j + 1]) > 0) 
			{
                strcpy(temp, arr[j]);
                strcpy(arr[j], arr[j + 1]);
                strcpy(arr[j + 1], temp);
            }
        }
    }
}

void main() 
{
    int n, i, j;
    char arr[MAX_STRINGS][MAX_LENGTH];

    printf("Enter the number of strings: ");
    scanf("%d", &n);

    printf("Enter %d strings:\n", n);
    for (i = 0; i < n; i++) 
	{
		char str[20];
		int flag;
        scanf("%s", str);
		while(1)
		{
			flag=0;
			int len=strlen(str);
			if(len>MAX_LENGTH)
			{
				printf("\nString exceeds maximum length! Enter string again: ");
				flag=1;
			}
			else
			{
				for(j=0;j<len;j++)
				{
					if(str[j]>='0' && str[j]<='9')
					{
						printf("\nString can not have digits! Enter string again: ");
						flag=1;
						break;
						
					}
				}	

			}
			
			if(flag==1)
				scanf("%s", str);
			else
			{
				strcpy(arr[i],str);
				break;
			}
		}
	}

    bubbleSortStrings(arr, n);

    printf("\nStrings sorted in alphabetical order:\n");
    for (i = 0; i < n; i++) 
	{
        printf("%s\n", arr[i]);
    }

    getch();
}

			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *