Modify and Sort Words in C Program: Help with C Programming

Click For Summary

Discussion Overview

The discussion revolves around a C programming task where participants are trying to create a program that prompts users to enter words, modifies them by changing case and reversing the order, and then displays the words in both unsorted and sorted formats. The conversation includes troubleshooting issues with the current implementation and suggestions for improvements.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • The original poster describes issues with their program not allowing re-entry of words longer than 9 characters and not producing the expected output format.
  • Some participants request clarification on what "doesn't work" means, asking for specific error messages or unexpected behaviors.
  • One participant points out that the code lacks indentation, making it difficult to read, and suggests using code formatting tags.
  • Another participant identifies several bugs, including uninitialized variables and duplicated function declarations, and suggests stopping until better code is provided.
  • Some participants propose using alternative functions like _gets() for input handling, while others caution against its portability.
  • A later reply provides a revised version of the code that aims to be clearer and more portable, addressing some of the original issues raised.

Areas of Agreement / Disagreement

Participants express various opinions on the best approach to handle input and output in C, with some advocating for specific functions while others raise concerns about their portability. The discussion remains unresolved regarding the optimal solution.

Contextual Notes

There are limitations in the original code regarding variable initialization, input handling, and output formatting that remain unaddressed in a definitive manner. The discussion includes multiple proposed solutions, each with its own set of assumptions and potential issues.

liukinhei
Messages
2
Reaction score
0
Hello,
I am writing a c program to Prompts the user (altogether 10 times) to enter a word not longer than 9 characters: for this part, it doesn't seems working. it didnt return back to the loop to re-entry a correct word(less than 9 characters) " And it needs the modification of each word by changing lower case to upper and then the reverse of the word is concatenated with the word- i can only print out the word (my input : chester, output CHESTER). it can't show like (my input : Chester , output RETSEHccHESTER) , show them in unsorted way and sorted way.
After that, the program terminates. I have made many attempts at writing this program and this is where i am at right now and it still doesn't work. Thanks in advance for the input.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char toupper(char);
char tolower(char);

int main(void)
{
  #include <stdio.h>
#include <stdlib.h>
#include <string.h>

char toupper(char);
char tolower(char);

int main(void)
{
   char words[10][19];
   char c;
   int i, j;
   int k;
   char swap[10][19];

while ( j != 10)
{
   for ( i = 0; i < 10; i++ )
   {

      printf("enter the character \n");
      fflush(stdout);

      for ( j = 0; j < 10; j++ )
      {

         words[i][j] =fgetc(stdin);
         if ( words[i][j] == '\n' )
         {
            words[i][j] = '\0';
            break;
         }
       }
     }
      printf(" you have entered more than 9 characters! \n");  }

   for ( i = 0; i < 10; i++ )
   {
      for ( j = 0; j < 10; j++ )
      {
         k = (int)(words[i][j]);
         if ( k >= 64 && k <= 91 )
         {
            words[i][j]= tolower(words[i][j] );
         }

         else if ( k >= 96 && k<= 123 )
         {
            words[i][j]= toupper(words[i][j] );
         }
      }
   }

   printf("unsort \n");

   for ( i = 0; i < 10; i++ )
   {
      printf("%s \n ", words[i]);
      fflush(stdout);
   }

   printf("Sorted: \n");  
   for ( i=9; i>0; i-- )
   {
      for ( j=0; j<i; j++ )
      {
         if ( strcmp(words[j],words[j+1])>0 )
         {
            strcpy(swap[j],words[j]);
            strcpy(words[j],words[j+1]);
            strcpy(words[j+1],swap[j]);
         }
      }
      printf("%s \n", words[i]);
   }

   return 0;
}


char toupper(char let)
{
   int d;
   d = (int)let;
   let = (char)d-32;
   return let;
}

char tolower(char let)
{
   int d;
   d = (int)let;
   let = (char)d+32;
   return let;
}
 
Last edited:
Technology news on Phys.org
liukinhei said:
this is where i am at right now and it still doesn't work.

Can you please be more specific than "doesn't work?" Do you get compiler error messages? Does the program compile, but crash when you try to run it? Does it produce the wrong output? (If so, please give a sample input, the output you expect, and the output you actually get.) Does it make your monitor flash on and off? :smile:
 
Another suggestion. Us C/C++ programmers cannot read unindented code.

Please use [ c o d e ] [ / c o d e ] tags (I wrote them with spaces between each character, remove the spaces.) We are helping you, but you have to help us old f*rts.
 
Hi Ho!

Let's do it bit-by-bit:

Code:
int main(void)
{
  #include <stdio.h>
#include <stdlib.h>
#include <string.h>

char toupper(char);
char tolower(char);

Duplicated function declarations. Here is your zeroth bug.

Code:
int i, j;
.
.
.
while ( j != 10)

'j' is not initialized. Here you have your first bug.

Code:
while ( j != 10)
{

Unclosed 'while' block in which 'j' is not incremented properly. Here you have your second bug.

I think I must stop here till you provide a better code.


Eus
 
Also you could use _gets(), a getline function that goes back to dos (int 21h, function 0ah).

Code:
#define LINESZ 10
static char acBuffer=[LINESZ+2];

int main()
{
int iNumChar;
...

    acBuffer[0] = LINESZ;   // initialize # of characters in buffer
    _cgets(acBuffer);       // read up to LINESZ characters into acBuffer[2...]
    iNumChar = (int)(acBuffer[1]); // get number of characters input
    // ... acBuffer[2]  == 1st character of user input

...
}
 
Jeff, showed you how to apply the techniques. You, should code it using a descriptive style associated with your particular solution. I added one storage byte, and tacked on a null byte making the buffer, c-compatible, when it does a name change to "word". Pack this code into a function and you have go.

Example using _gets(), a getline function that goes back to dos (int 21h, function 0ah).

Code:
#define WORDsize 10
static char inWORD [WORDsize+2+1];
static char *word = &inWORD [2]
int main()
{
int charactersIN ;
...

    inWORD[0] = WORDsize   // initialize # of characters for read buffer
    _cgets(inWORD);       // read up to WORDsize  characters into buffer/inWORD[2...]
    charactersIN = (int)(inWORD [1]); // get number of characters input/entered
    inWORD [charactersIN+2] = '\n' ;  // termniate sequence entered with a null byte.
    // ...  inWORD [2]  == 1st character of user input
    // ..
    // ...   word is now a c-string, strlen(word) will return charactersIN
    // ...   and it can be used as: firstCHARACTER = word[0] ;

...
}
 
Last edited:
thanks a lot !
it really help!
 
inWORD [charactersIN+2] = '\n';
For a C string, you would want

inWORD [charactersIN+2] = 0;
 
Hi Ho!

I think the use of _gets () is not portable.
I have revised the code to make it clearer and more portable.
Just give it a try.

Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv, char **envp)
{
    char words [10][19] = {0};
    char swap [19] = {0};
    int i = 0;
    int j = 0;
    int k = 0;
    int word_len = 0;

    for (i = 0; i < 10; i++)
    {
        printf ("Enter at most nine characters [#%d]: ", i + 1);

        for (j = 0; j < 10; j++)
        {
            words [i][j] = fgetc (stdin);
            if (words [i][j] == '\n')
            {
                words [i][j] = '\0';
                break;
            }
        }

        if (j == 10)
        {
            printf ("You have entered more than nine characters! Please repeat!\n\n");
            i--;
            while (fgetc (stdin) != '\n');
        }
    }

    for (i = 0; i < 10; i++)
    {
        for (j = 0; j < 10; j++)
        {
            if (isupper (words [i][j]))
            {
                words [i][j] = tolower (words[i][j]);
            }
            else if (islower (words [i][j]))
            {
                words [i][j] = toupper (words[i][j]);
            }
        }
    }

    for (i = 0; i < 10; i++)
    {
        word_len = strlen (words [i]);
        words [i][word_len * 2] = '\0';
        for (j = 0; j < word_len; j++)
        {
            words [i][j + word_len] = words [i][j];
        }
        for (j = 0, k = word_len * 2 - 1; j < k; j++, k--)
        {
            words [i][j] = words [i][k];
        }
    }

    printf("\nUnsorted:\n");

    for (i = 0; i < 10; i++)
    {
        printf ("%s\n", words[i]);
    }

    printf("\nSorted (Ascending):\n");

    for (i = 0; i < 9; i++)
    {
        for (j = 9; j > i ; j--)
        {
            if (strcmp (words [j], words [j - 1]) < 0)
            {
                strcpy (swap, words [j]);
                strcpy (words [j], words [j - 1]);
                strcpy (words [j - 1], swap);
            }
        }
        printf ("%s\n", words [i]);
    }
    printf ("%s\n", words [i]);

    return 0;
}


Eus
 

Similar threads

Replies
12
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
7K
Replies
73
Views
6K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 30 ·
2
Replies
30
Views
5K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
89
Views
7K
  • · Replies 89 ·
3
Replies
89
Views
6K
  • · Replies 32 ·
2
Replies
32
Views
4K