Count the number of Upper cases in a string in C++

In this tutorial, we will learn to write the code to count all the upper cases alphabets in a string in C++

#include <iostream>
using namespace std;
int main()
    int i;
    int upper=0;//variable declaration
    string str="CodeSPeeDy";//initializing a string
     for(i=0; str[i]!=0; i++){
if(str[i]>='A' && str[i]<='Z'){ //Using If statement to count upper case alphabet in given string
cout<<"\nuppercase letters:"<<upper;
    return 0;

Code Explanation

1)In the code first we have initialized integer variable “upper” , “i” and string variable “str” in which we have taken our string that has uppercase.

2)We have taken the value of “upper” as 0 initially.

3) After that inside a For loop we used the If statement to check every character in a given string.

4)In the If statement we used the condition that if a character in the string lies between “A” and “Z” then increase the count of “upper” by one.

5)So in every iteration of For loop character in the string will be checked and if the condition is matched then the count of “upper” will be increased.

6)At the end we take the “upper” count as our output.


uppercase letters:4

In the code, we used the string “CodeSPeeDY” which has 4 upper case letters therefore we got “4” as our output.

Leave a Reply

Your email address will not be published. Required fields are marked *