Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Lowercase to Uppercase and Uppercase to Lowercase

Converting lowercase letters to uppercase and vice versa is something that can be done pretty easily with a few lines of code in several programming languages. In C, you can use the built-in function toupper() to convert lowercase characters to uppercase, and tolower() to do the opposite. In C++, you have access to similar functions called std::toupper() and std::tolower(). Python also has a method called upper() and lower(), which can convert strings between uppercase and lowercase. Lastly, in Java, you can use methods such as Character.toUpperCase() and Character.toLowerCase(). With all of these options available, it's never been easier to manipulate text in your programs!

(a.) C Code

#include <stdio.h>
#include <ctype.h>

int main() {
  char str[100];
  printf("Enter a string: ");
  scanf("%s", str);
  
  printf("Converted string: ");
  for (int i = 0; str[i] != ''; i++) {
      if (islower(str[i])) {
          printf("%c", toupper(str[i]));
      } else {
          printf("%c", tolower(str[i]));
      }
  }
  return 0;
}
Output:-
Enter a string: theroyalcoding
Converted string: THEROYALCODING

(b.) C++ Code

#include <iostream>
#include <cctype>
using namespace std;

int main() {
  string str;
  cout << "Enter a string: ";
  cin >> str;
  
  cout << "Converted string: ";
  for (char c : str) {
      if (islower(c)) {
          cout << (char)toupper(c);
      } else {
          cout << (char)tolower(c);
      }
  }
  return 0;
}
Output:-
Enter a string: theroyalcoding
Converted string: THEROYALCODING

(c.) Python Code

str_input = input("Enter a string: ")
converted_str = ''.join([char.upper() if char.islower() else char.lower() for char in str_input])
print("Converted string:", converted_str)
Output:-
Enter a string: theroyalcoding
Converted string: THEROYALCODING

(d.) Java Code

import java.util.Scanner;

public class CaseConversion {
  public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter a string: ");
      String str = scanner.nextLine();
      
      StringBuilder convertedStr = new StringBuilder();
      for (char c : str.toCharArray()) {
          if (Character.isLowerCase(c)) {
              convertedStr.append(Character.toUpperCase(c));
          } else {
              convertedStr.append(Character.toLowerCase(c));
          }
      }
      System.out.println("Converted string: " + convertedStr.toString());
      scanner.close();
  }
}
Output:-
Enter a string: theroyalcoding
Converted string: THEROYALCODING