Nom
Nom

Reputation: 11

C Programme has stopped working while uppercase the Word

This code is not returning Uppercase Word rather it stops working.Here is the code.Where have I made mistake?

char Uppercase(char country[]){
    
        int i;
        for(i=0;i<100;i++){
            if(country[i]>=97 && country[i]<=122){
    
                country[i] = 'A'+(country[i]-'a');
            }
        }

    return country;
}

int main(){
    char country[100];
    printf("Enter The Country Name: ");
    scanf("%s",country);

    char x = Uppercase(country);
    printf("Uppercase is: %s",x);


}

Upvotes: 0

Views: 46

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

You declared the variable x as having the type char and trying to output it using the conversion specifier %s designed to output strings instead of a single character.

char x = Uppercase(country);
printf("Uppercase is: %s",x);

that results in undefined behavior.

And the return type char of the function Uppercase

char Uppercase(char country[]){
    
        int i;
        for(i=0;i<100;i++){
            if(country[i]>=97 && country[i]<=122){
    
                country[i] = 'A'+(country[i]-'a');
            }
        }

    return country;
}

does not make a sense. Moreover the compiler should issue a message for this return statement

    return country;

The return type of the function must be the pointer type char *.

Also this for loop with the magic number 100

        for(i=0;i<100;i++){

does not make a sense. The passed array can have a string that contains much less characters than 100.

And using magic numbers like 97 and 122 makes the code unreadable and error prone.

if(country[i]>=97 && country[i]<=122){

AT least you could write

if(country[i] >= 'a' && country[i] <= 'z'){

The function can be defined for example the following way

#include <ctype.h>

//...

char * Uppercase( char country[] )
{
    for ( char *s = country; *s; ++s )
    {
        *s = toupper( ( unsigned char ) *s );
    }

    return country;
}

Upvotes: 1

0___________
0___________

Reputation: 67820

Better use standard functions not magic numbers:

char *strtoupper(char *str)
{
    char *wrk = str;
    while(*str)
    {
        *str = toupper((unsigned char)*str);
        str++;
    }
    return wrk;
}

Upvotes: 1

Related Questions