Program to compare two strings are equal or not

Written by

Garvit Gulati

What are equal strings?

Two strings are said to be equal when they are equal in length and contain exactly the same characters at the exact same index.


“Studymite” and “Studymite” are equal strings but “studymite” and “Studymite” are unequal strings as the case of first character is different in both.

Algorithm and Explanation

  1. Input two strings from the user and store them in s1 and s2 respectively.
  2. First check if the length of both strings are equal, if yes proceed to step 3 else print they are unequal and end the program.
  3. Set a counter ctr to zero (this will be set to 1 when an unequal character is found).
  4. Run a for loop to compare each character of the two strings.
  5. Compare the current character of the strings, if they are unequal set ctr to 1 and break out of the for loop. Do this till the last character is compared
  6. Now check if ctr is zero(all characters are equal since ctr can be modified only when unequal characters are encountered), hence the given strings are equal and print they are equal.
  7. If ctr is not zero(i.e. ctr=1), then we must have encountered an unequal character, therefore, print the given strings are unequal.


#include <iostream>

#include<string> //for using string data type

#include<cstdio> //for using getline function to input string

using namespace std;

int main()

{   string s1,s2;

    cout<<"Enter First string\n"; //inputting string1


    cout<<"Enter Second string\n"; //inputting string 2


    if(s1.length()!=s2.length()) //comparing the string length

        cout<<"The given strings are unequal";


    {   int ctr=0; //comparing each character of the two strings

        for(int i=0;i<s1.length();++i)

        {   if(s1[i]!=s2[i])

            {   ctr=1;




        if(ctr==0) //printing the result

            cout<<"The given Strings are equal\n";


            cout<<"The given strings are unequal";


    return 0;



Enter First string: Study Mite

Enter Second string: Study Mite

The given strings are equal.



Program to compare two strings are equal or not