Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

explane this c code for change first char to uppercase

Hello i have this code but i dont understand it what is 32 can someone explance this code whats main

i dont know thats main z
whats main 32
why use this if(input[x]==’ ‘)

this code in c programming

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include<string.h>
#define SIZE 100
int main(void)
{
    char input[SIZE];
    int x = 0, counter = 0, length = 0;
    char *ptr;
    ptr = input;
    printf("Enter a sentence:");
    fgets(input, SIZE, stdin);
    
    for(x = 0; input[x]!='\0'; x++)
    {
    
        if(x==0)
        {
            if((input[x]>='a' && input[x]<='z'))
                input[x]=input[x]-32;
            continue;
        }
        if(input[x]==' ')
        {
            
            ++x;
            
            if(input[x]>='a' && input[x]<='z')
            {
                input[x]=input[x]-32;
                continue;
            }
        }
        else
        {
            
            if(input[x]>='A' && input[x]<='Z')
                input[x]=input[x]+32;
        }
    }
    printf("%s\n",input);
    return 0;
}

>Solution :

This program is performing a conversion of lowercase to uppercase and uppercase to lowercase.

The value 32 is the difference between the ASCII codes for upper case letters and lower case letters. 'A' through 'Z' have ASCII codes 65 to 91, and 'a' through 'z' have ASCII codes 97 to 123. So adding the value 32 to an uppercase letter makes it lowercase, and subtracting the value 32 from a lowercase letter makes it uppercase.

The use of "magic numbers" such as this tend to make the code unclear and would be better off being assigned to a variable or macro such as upper_lower_diff.

This code also makes the assumption that ASCII is the character encoding in use. While other encodings are rare these days, it’s still not a good idea to make such assumptions.

A better way to write this code would be to use the isupper and islower functions to check for uppercase and lowercase, and to use the toupper and tolower functions to switch cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading