Monday, July 31, 2017

Sorting names in C

#include<stdio.h>
//#include<string.h>

void copystring(char txt1[], char txt2[])
{
    int k;
    for(k=0;txt2[k]!='\0';k++)
    {
        txt1[k]=txt2[k];
    }
    txt1[k]='\0';
}

int comparestring(char str1[], char str2[])
{
    int p,difference;
    for(p=0;str1[p]!='\0' || str2[p]!='\0';p++)
    {
        difference=str1[p]-str2[p];
        if(difference!=0)
        {
            break;
        }
    }
    return(difference);
}

void swapstring(char txt1[], char txt2[])
{
    int i,temp[50];
    for(i=0;txt2[i]!='\0';i++)
    {
        temp[i]=txt2[i];
    }
    temp[i]='\0';
    for(i=0;txt1[i]!='\0';i++)
    {
        txt2[i]=txt1[i];
    }
    txt2[i]='\0';
    for(i=0;temp[i]!='\0';i++)
    {
        txt1[i]=temp[i];
    }
    txt1[i]='\0';
}

void main()
{
    char name[25][40],temp[40];
    int n,i,j;

    printf("Enter number of names to be sorted in ascending order : ");
    scanf("%d",&n);

    printf("\nEnter %d names to be sorted : \n",n);
    for(i=0;i<n;i++)
    {
        scanf("%s",name[i]);
    }
    for(i=0;i<=n-2;i++)
    {
        for(j=i+1;j<=n-1;j++)
        {

            if(comparestring(name[i],name[j])>0)
            {
                swapstring(name[i],name[j]);
                //copystring(temp,name[i]);
                //copystring(name[i],name[j]);
                //copystring(name[j],temp);
            }
        }
    }
    printf("\nThe sorted name in ascending order is : \n");
    for(i=0;i<n;i++)
    {
        printf("\n%s",name[i]);
    }
    getch();

}

Related Posts:

  • Find HCF in C#include<stdio.h> int hcf(int a,int b,int c) {     if(a%c==0 && b%c==0)     return c;     hcf(a,b,c-1); } void main() {     int h,x,y;     printf("Enter two numb… Read More
  • Application of struct in C#include<stdio.h> #include<string.h> struct student {     char name[20];     int roll; }; void main() {   struct student s[10],t;   int i,n,j;   printf("Enter no. of students : "… Read More
  • Check if a string is palindrome or not in C ?#include<stdio.h> #include<string.h> void main() {     char word[50];     int i,j,l,c=0;     printf("Enter a word : ");     gets(word);     l=strlen(word);   … Read More
  • Check if a no. is prime or not in C ?#include<stdio.h> int testprime(int ,int); void main() {     int n,prime;     printf("Enter a positive number : ");     scanf("%d",&n);     prime=testprime(n,n/2);   &nbs… Read More
  • Check if 3rd digit of a no. is prime or not in C ?#include<stdio.h> int digitcount(int x) {     int r,c=0,i=0,y=x;     while(x!=0)     {         r=x%10;         x=x/10;         c+… Read More

0 comments:

Post a Comment