WAP to convert in uppar case
Objective
Write a C++ program to manually convert a string to uppercase.
Algorithm / Approach
- Read a string into
s1. - Loop through each character from 0 to
s1.length(). - Check if the character's ASCII value falls in the lowercase range (97 to 122).
- If it does, subtract 32 from it:
s1[i] = s1[i] - 32. - Print the converted string.
main.cpp
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main() {
string s1;
cout<<"Enter a string : ";
getline(cin,s1);
for(int i = 0; i< s1.length(); i++) {
if(s1[i]>=97 && s1[i]<=122) {
s1[i] = s1[i]-32;
}
cout<<"In Upper case: "<< s1[i];
}
return 0;
}
Expected Output
Enter a string : cproWess In Upper case: CPROWESS
Explanation of the Program
- This program manipulates the raw ASCII integer values of characters.
- In the ASCII table, lowercase 'a' is 97 and uppercase 'A' is 65. Because the entire alphabet is sequential, subtracting exactly 32 from ANY lowercase letter will perfectly shift its value to its uppercase equivalent!
Complexity
Time Complexity
O(n)
Space Complexity
O(1)
Common Mistakes
- Placing the
coutstatement INSIDE theforloop (as seen in the provided code). This will cause the program to awkwardly print the "In Upper case: " prefix over and over for every single character, instead of printing the final string once at the end.