开发者

Sorting letters C programming

I'm trying to make the letters of a matrix sort alphabetically and then be written out in a single string.For instance you type ten words,which are then stored in an array,and every letter has its place in the matrix then,right?But after I've written the words I want to bunch all the letters of all words together and then type all the letters out in alphabetical order.This is what I have so far:

#include <stdio.h>
#include <conio.h>

int main(void){
    int i, j, k, f, n, m; 
    //was trying out various things,that's why I have so many useless ints up there
    char word[10][15],temp;

    for(i=0;i<=9;i++)
    {
        printf("Type in wword number %d: ", i+1);
        gets(word[i]);
    }

    for(k=i-1;k>=0;k--)
    {
        for(m=0;m<k;m++)
            if(word[k][f] > word[m][n])
            {
                temp=word[k][f];
                word[k][f]=word[m][n];
                word[m][n]=temp;
            }
    }
    printf("Letters alphabetically sorted: ");
    for(i=0;i<=9;i++){
        for(j=0;j<=14;j++){
            printf("%d",word[i][j]);
        }
    }
    printf("\n");
    getch();
}

I'm still in the process of learning about matrixes and I've gotten pretty familiar with arrays by now.But the sorting thing is confusing me,this was my attempt but it d开发者_JAVA百科oesn't work.It lets you write all the words,and then it crashes.

What am I doing wrong here?And how do I correct it?


In your code here:

        temp=word[k][f];
        word[k][f]=word[m][n];
        word[m][n]=temp;

the variables n and f are used uninitialised. That will most likely be the cause of the crash.


f,n are uninitialized. It has garbage and is the reason for crashing at this point.

for(k=i-1;k>=0;k--)
{
    for(m=0;m<k;m++)

    if(word[k][f] > word[m][n]) // f,n are uninitialized and are error prone


I think this will work..Please excute and tell me..

void main()    
{

char word[10][15],temp,sorted_word[15];

int i,j,ii,k,l=0;

for(i=0;i<=9;i++)             
{                  
printf("Type in wword number %d: ", i+1);                 
gets(word[i]);            
}


for(i=0;i<=9;i++)

{

for(j=0;word[i][j]!='\0';j++)

{

ii=i;
for(k=j+1;1;k++)
{
if(ii==9 && word[ii][k]=='\0')
break;
if(word[ii][k]=='\0')
{
ii++;
k=0;
}
if(word[i][j]>word[ii][k])
{
temp=word[i][j];
word[i][j]=word[ii][k];
word[ii][k]=temp;
} 
}
sorted_word[l++]=word[i][j];
}

}

sorted_word[l]='\0';

printf("%s",sorted_word);

getch();

}


here the

for(i=0;i<=9;i++)
{ printf("type in wword %d: ",i+1);
gets(word[i]); 
}

gets (word[1]);

stores the value from word[1] onwards but where as the character array starts from word[0].

may be this is not the full solution for u problem this issue may help u in solving your doubt.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜