0

I'm making a program that if a user enters a word (and that's maximum length is 20), then prints the word in alphabetical order.

This code below is that I wrote.

#include <stdio.h>
#include <string.h>
#pragma warning (disable:4996)

#define MAX 20

void bubble_sort(char* arr, int n);

int main(void) {

    char words[MAX];

    int n = sizeof(words) / sizeof(char);

    scanf("%s", words);

    bubble_sort(words, n);

    printf("%s", words);

    return 0;
}

void bubble_sort(char* arr, int n) {

    int i, j, tmp = 0;

    for (i = 0; i < n - 1; i++) {
        for(j=0;j<i-1;j++)
            if (*(arr+j) > *(arr+j+1)) {
                tmp = *(arr+j);
                *(arr+j) = *(arr+j+1);
                *(arr+j+1) = tmp;
            }
    }

}

But it doesn't work. I used bubble sorting. I am not skilled to use pointer arrays and sorting, so I can't catch what's wrong.

I'm working on Visual Studio 2019, and it says that return value ignored scanf(). I can't understand. What's wrong?

1 Answer 1

1

I have Corrected it Check it out...

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

#define MAX 20

void bubble_sort(char* arr, int n);

int main(void) {

    char words[MAX];

    scanf("%s", words);
    int n=0;
    /*for(int i=0;i<sizeof(words);i++){
        if(words[i]=='\0'){
            break;
        }
        n++;
    }*/
    
    n=strlen(words); //same as above for loop
    bubble_sort(words, n);

    printf("%s", words);

    return 0;
}

void bubble_sort(char* arr, int n) {

    int i, j, tmp = 0;

    for (i = 0; i < n; i++) {
        for(j=0;j<n-i-1;j++)
            if (*(arr+j) > *(arr+j+1)) {
                tmp = *(arr+j);
                *(arr+j) = *(arr+j+1);
                *(arr+j+1) = tmp;
            }
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

You are correct we can use strlen() there is no problem in that I thought in diffrent perspective sorry for that.
Thank you for answering my question. By the way, I have one more question. What is different from int n = sizeof(words) / sizeof(char); and your answer n=strlen(words);?
int n = sizeof(words) / sizeof(char); will give n=20 because sizeof(words)=20 and sizeof(char)=1 , But we wanted Total number of character entered in the array so we used strlen() function
Oh I didn't realize it. Thank you soooo much. God bless you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.