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:

  • Telephone directory Code for telephone directory in c #include<stdio.h> #include<string.h> #include<windows.h> #include<time.h> struct teledir {     char firstname[50];     char lastname[50… Read More
  • Copying string 2 to string 1#include<stdio.h> void copystr(char [],char []); void main() {     char str1[50],str2[50];     printf("Enter 1st string,str1 : ");     gets(str1);     printf("\nEnter 2nd string,s… Read More
  • 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];  … Read More
  • Concatenation of two string in C#include<stdio.h> void catstr(char [],char []); void main() {     char str1[50],str2[50];     printf("Enter 1st string (str1) :");     gets(str1);     printf("\nEnter 2nd string (… Read More
  • Code in C to multiply two matrix#include<stdio.h> void matmultiply(int m[3][3], int n[3][3]); void read(int x[3][3]); //void read2(int y[3][3]); void main() {     int a[3][3],b[3][3],l,w;     printf("\nFor matrix a :-\n");   &… Read More

0 comments:

Post a Comment