-1

I need to read a word from main function and convert the characters in UCASE if the first character is LCASE and vice versa using the user defined function.I tried ways for returning the array from function but still I am lacking some core ideas. Please debug this program and explain the way it works.

#include <stdio.h>
#include <string.h>
int* low (char str)
{
    int i;
   for (i=1; i<strlen(str);i++)
    {
        if(str[i]<91)
        {
            str[i]=str[i]+32;
        }
        else
        {

        }
    }
    return &str;
}
int* high (char str[50])
{
    int i;
    for (i=0; i<strlen(str);i++)
    {
        if(str[i]>91)
        {
            str[i]=str[i]-32;
        }
        else
        {

        }
    }
    return &str;
}
void main()
{
    char str[50];
    char* strl;
    printf("Enter any string....\n");
    scanf("%s",str);
    if (str[0]<91)
    {
        *strl=low(str);
    }
    else
    {
        *strl=high(str);
    }
    printf("Converted string is %s.",*strl);
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
G-aura-V
  • 145
  • 1
  • 7

2 Answers2

0

There is already a problem here: So if you are saying this code is perfect and you want us to debug it and explain how (on earth) this works, then here you go.

In function int* low (char str), you have if(str[i]<91). Thats a problem right there. str is a char received as an argument, and hence str[i] is a straight compile-time error.

Another one to deal with is the return statement. You have a statement:

return &str;

which would return the address of str, which by the way is a char, whereas function low is supposed to return a pointer to an int.

The same is applicable to high function as well.

Suggestion: Leave aside this bad code and get a beginner level C programming book first. Read it and the try some codes out of it.


A few inputs for improvement: (Which you may not comprehend)

change

void main()

to

int main(void)

Why? Refer this legendary post: What should main() return in C and C++?

Secondly, int both functions you are using strlen() in loop which will always return a fixed value. So, instead of

for (i=0; i<strlen(str);i++)

I'd suggest,

size_t strlength = strlen(str);
for (i=0; i < strlength; i++)
WedaPashi
  • 3,561
  • 26
  • 42
0

You can try the code and method as below:

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

char* caseConverter (char *str)
{
    int i;
    for (i=0; i<strlen(str);i++)
    {
        if(str[i]>=65 && str[i]<=90)
        {
            str[i]=str[i]+32; //To lower case
        }
        else if((str[i]>=97 && str[i]<=122))
        {
            str[i]=str[i]-32; //To upper case
        }
        else
        printf("%c is not an alphabet \n",str[i]);
    }
    return str;
}
void main()
{
    char inputStr[50]= "Stubborn";
    char* opStr= caseConverter(inputStr);
    printf("Converted string is %s",opStr);
}
Stubborn
  • 780
  • 1
  • 5
  • 20