-2

The problem is : Write a C program to covert lowercase letters to uppercase letters and vice versa of string S. 1<=S<=100

EXAMPLE:

INPUT

HelloWORLD

Expected OUTPUT

hELLOworld

INPUT

RanDoM

Expected OUTPUT

rANdOm

My code

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

int main()
{ char s[100];
int i;
for (int j=0; j<=100 ; j++)
{
 scanf("%s",&s[j]) ;
}
for (i=0; s[i]!='\0'; i++)
    {
        if (s[i]>='a' && s[i]<='z')
        {
            s[i] = s[i] - 32;

        }
        else
        {
            s[i] = s[i] +32;

        }

    }
    for (int k=0; k<=100 ; k++)
    {    
        if (s[k]!='\0')
      {  printf("%c",s[k]) ; }
    }


    return 0;

}

The OUTPUT which I am getting is:

INPUT

HelloWORLD

Current OUTPUT

hELLOworldԯ@ _�"����ԯ8_�"�>sn�"�

INPUT

 RanDoM

Current OUTPUT

rANdOm�
�$@0�������$H����>s�

What changes in the code do I need to make so that I can get rid of the symbols at the end of the word?

After all the suggestions and help I have found the code which gives the expected output:

#include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    int main()
    {  char str[100];
 scanf("%s",str);
       int i;

    for (i=0; i<sizeof(str); i++)
        {    
            if (str[i]>='a' && str[i]<='z'&& str[i]!='\0')
            {
                str[i] = str[i] - 32;

            }
            else if(str[i]>='A' && str[i]<='Z'&& str[i]!='\0')
            {
                str[i] = str[i] +32;

            }

        } 
         printf("%s",str);
        return 0;

    }

1 Answers1

1

Hi There some extra code in your program and some mistakes also. I am doing some correction in your program to complete your task.

  • I am not writing new code for your better understanding
  • I am not removing lines, just commenting those lines and giving reason in line comments
  • You should read all comments and remove before use.
  • For any confusion ask in comment section

    #include<stdio.h>
    #include<string.h>
    
    int main()
    { char s[100];
    int i,j,k;
    
     //Loop not required
     //for (j=0; j<=100 ; j++)
     //{
      scanf("%s",&s[j]) ;
     //}
    for (i=0; s[i] != '\0'; i++)
        {
     //You should have to compare with ASCII or use string methods like islower
    
     //if (s[i]>='a' && s[i]<='z')
     if (s[i]>= 97 && s[i]<= 122) // ASCII for a-97 and z-122
     {
         s[i] = s[i] - 32;
     }
     else //u may put a check here for upper case to handle errors
     {
         s[i] = s[i] + 32;
    
     }
    
        }
    
        //No loop or if statement required
       // for (k=0; k<=100 ; k++)
        //{
          // if (s[k]!='\0')
         // {
         printf("%s",s) ;
           // }
        //}
    
    
        return 0;
    
    }
SayAz
  • 751
  • 1
  • 9
  • 16