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 no. of vowels in a string in C #include<stdio.h> void strcount(char []); void main() {   char str[50];   char c;   while(1)   {     printf("enter string\n");     //gets(str);     scanf("%s",str); &nb… Read More
  • Find fibonacci series in C#include<stdio.h> void fibonacci(int); void main() {     int n,first=0,second=1;     printf("Enter the number of fibonacci series to be printed : ");     scanf("%d",&n);     p… Read More
  • Find triangular no. in C#include<stdio.h> void main() {     int n1,n2,i,t;     printf("Enter two numbers : ");     scanf("%d%d",&n1,&n2);     for(i=1;i<=n2;i++)     {     &… Read More
  • 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
  • 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

0 comments:

Post a Comment