C++ program to compare two strings are same or not without using string comparision function

//using for loop

#include<iostream>
using namespace std;

int main( )
{
    char str1[80], str2[80];

    cout<<“Enter first string: “;
   cin>>str1;
    cout<<“Enter second string: “;
    cin>>str2;

    int i;
    for (i = 0; str1[i] == str2[i] && str1[i]!=’’ && str2[i]!=’’; i++);

    if(str1[i] – str2[i] == 0)
        cout << “Strings are equal”;
    else
        cout << “Strings are not equal”;

    return 0;
}

Enter first string: bum
Enter second string: bum
Strings are equal
//using while loop
/* This program compare two strings entered by the user and displays the results whether they are 
same or not*/
#include<iostream>
using namespace std;
int main()
{
 char str1[80], str2[80];
 int i=0;
 
 cout<<“Enter first string: “;
 cin>>str1;//input-first string
 
 cout<<“Enter second string:n”;
 cin>>str2;//input-second string
 
 //loop for traversing each element of array
 while(str1[i]!=’’||str2[i]!=’’)
 {
 //condition for checking equality of each character
 if(str1[i]!=str2[i])
 {
 cout<<“Both the string are not same:n”;
 break;
 }
 i++;
 }
 
 //checking condition for length of both strings
 if(str1[i]==’’&& str2[i]==’’)
 cout<<“Both the string are same:n”;
 
 return 0;
}
  • While loop is taken to traverse each element of character array up to last element i.e. ‘’.Inside this loop each character of both string is compared, if any one is mismatched then the string will not be same.So no need to check further , break the execution process and print “Both string are not same”.
  • Another case is when string will be same.If both string will be same then they will have same length so at last execution of while loop it will encounter ‘’.So outside while same condition is checked and display result “Both string are same” if the condition satisfies.

Leave a Comment

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

To Resolve this issue at just 5$ from ServerExpert

https://serverexpert.io/

For Hosting please visit Hostingwebsite.io

You have Successfully Subscribed!

Open chat