Relational Operator on String Objects in C++

Several string comparison operators are defined in the string class and these operators operate by comparing the string characters and all these comparisons are case-sensitive. But one extra point to keep in mind is that when we do a comparison of two strings using a relational operator then comparison takes place lexicographically.


What is lexicographical order?

Lexicographical order is basically a dictionary order of arranging words. For example, In a dictionary, the word 'Accutane' will come before 'Accutron' because the letter 'a' comes before 'r' in the English alphabetic system.


List of Relational Operators:

  • Equal to (==): This operator is used to test the equality of two strings.
  • Not Equal to (!=): This operator is used to test whether two strings are unequal. 

Note: Two strings are said to be equal when they have the same length and contain the same characters.


C++ example code:

/*C++ program to check equality operator*/
#include<iostream>
#include<string>
using namespace std;

int main(){
  string str1 = "Welcome to Algolesson";
  string str2 = "welcome to algolesson";

  if(str1 == str2)
     cout<<"Both the string are equal"<<endl;

  if(str1 != str2)
    cout<<"Both the strings are not equal"<<endl;   
  
  return 0;
}
Output:
Both the strings are not equal

More Relational Operators:
  • Greater than(>): This operator is used to check whether one string is greater than another string.
  • Lesser than (<): This operator is used to check whether one string is lesser than another string.
  • Greater than and equal to (>=): This operator is used to check whether one string is greater than or equal to another string.
  • Lesser than and equal to (>=): This operator is used to check whether one string is lesser than or equal to another string.
Note: One string is smaller than the other string when the length of the first string is smaller than the second string or the first mismatched character of the first string is smaller than the character of the second string. 

Let's understand more C++ code implementation,
/*C++ program to check relational operator*/
#include<iostream>
#include<string>
using namespace std;

int main(){
  string str1 = "Accutane";
  string str2 = "Accutron";
  string str3 = "Axe";

  if((str1 > str2) && (str1 > str3))
    cout<<"Largest string is: "<<str1<<endl;
  else if((str2 > str1) && (str2 > str3))
    cout<<"Largest string is: "<<str2<<endl;
  else
    cout<<"Largest string is: "<<str3<<endl;

  return 0;
}
Output:
Largest string is: Axe

In the above code, if you observe the output is the third string that is "Axe" considered the longest string out of all three but the length of the third string is smaller than the other two strings but still, it is the largest because if you compare all three strings the second character of the third string that is 'x' is bigger than the second character of other two strings.
I hope you are now able to understand how string comparison takes place in lexicographical order when we use relational operators.

Next:

 (getButton) #text=(String Member Functions in C++) #icon=(link) #color=(#2339bd)

C++ Program to Count Vowels in a String

Vowels consist of 5 English letters of the alphabet and these are 'a', 'e', 'i', 'o', and 'u'. In this C++ program, we need to count how many vowels are present in a given string and print the count.


Note: We are including both upper case and lower case alphabets for counting vowels.


Below are the following steps to count vowels:

  • Declare a count variable and initialize it with 0.
  • Run a for loop for the complete length of the given string.
  • Check each character for vowel and increment count by one whenever found.
  • Print the total count of vowels.
Below is the C++ code Implementation:

//C++ Code to count number of vowels in a string
#include<iostream>
using namespace std;

int main(){
   char str[50] = "Algolesson";
   //size of string
   int n = sizeof(str)/sizeof(str[0]);
   int count = 0;

   for(int i = 0; i < n; i++){
    if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
       str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'){
        count++;
       }
   }

   cout<<"Number of Vowels: "<<count;
   return 0;
}
Output:
Number of Vowels: 4

C++ Program to Swap Values of Two Variables.

In this post, we will learn how to swap the values of two numbers in the C++ programming language. Here in this post, we are going to discuss two different methods to swap numbers. 

  • Using a third variable.
  • Without using a third variable.

Approach 1: Using a third variable.

We are going to use one temporary variable which will copy the value of the first variable and then we will copy the value of the second variable into the first variable and at the end, we will copy the value of the temp variable into the second variable.

Let's understand with one Example:
Given:
Values before swapping:
first = 10  and second = 20 

Explanation:
temp = first = 10
first = second = 20
second  = temp = 10

Values after swapping:
second = 10 and first = 20

Below is C++ Code Implementation: 
//C++ Code to swap two number using temp
#include<iostream>
using namespace std;

int main(){
   
   int a = 10, b = 20;
   int temp;

   cout<<"Before swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   //swapping using temp
   temp = a;
   a = b;
   b = temp;

   cout<<"After swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   return 0;
}
Output:
Before swapping
a = 10 b = 20
After swapping
a = 20 b = 10

Approach 2: Without using a third variable.

To swap the values of two variables without using any temporary variable we need to do some mathematical calculations with the given two numbers.

Let's understand with one Example:
Given:
Values before swapping:
a = 10  and b = 20 

Explanation:
a = a + b = 10 + 20 = 30
b = a - b = 30 - 20 = 10
a = a - b = 30 - 10 = 20

Values after swapping:
b = 10 and a = 20

Below is the C++ Code Implementation:
//C++ Code to swap two number without using temp
#include<iostream>
using namespace std;

int main(){
   
   int a = 10, b = 20;
   int temp;

   cout<<"Before swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   //swapping without using temp
   a = a + b;
   b = a - b;
   a = a - b;

   cout<<"After swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   return 0;
}
Output:
Before swapping
a = 10 b = 20
After swapping
a = 20 b = 10

Next:


C++ Program to Reverse an Integer Number.

In this post, we are going to learn how to reverse an integer and write code for it using the C++ programming language. This is a very good example to understand the while loop concept.


Let's understand the process of reversing an integer using one example:

Example:
Input: num = 2468
Output: 8642

Explanation:
num = 2468,  Let reverse = 0
reminder = 2468 % 10 = 8 
reverse = reverse * 10 + 8 
        = 0 * 10 + 8
        = 8
num = 2468 / 10 = 246

reminder = 246 % 10 = 6
reverse = reverse * 10 + 6 
        = 8 * 10 + 6
        = 86
num = 246 / 10 = 24

reminder = 24 % 10 = 4
reverse = reverse * 10 + 4 
        = 86 * 10 + 4
        = 864
num = 24 / 10 = 2

reminder = 2 % 10 = 2
reverse = reverse * 10 + 2 
        = 864 * 10 + 2
        = 8642 -> Output 
num = 2 / 10 = 0 
Loop end when we get num = 0.

So the basic logic behind the solution for this problem is there in below two points: 
  • Whenever we perform a modulo operation on any given integer by 10 then it returns us the remainder which is the last digit of that number. (432 % 10 = 2)
  • Whenever we divide any integer by 10 then it removes the last digit of that number. (432 / 10 = 43)

Below is the C++ Code Implementation:
//C++ Code for reversing an integer number
#include<iostream>
using namespace std;

int main(){
    int num, reverse, remainder;

    cout<<"Enter the number: ";
    cin>>num;

    while (num != 0)
    {
        remainder = num % 10;
        reverse = reverse * 10 + remainder;
        num = num / 10;
    }
    cout<<"The reverse number is: "<<reverse<<endl;

    return 0;
}
Output:
Enter the number: 4567
The reverse number is: 7654

Also see:

Program to Find Transpose of 2D Matrix.

What is the Transpose of a Matrix?

A Transpose of a Matrix is obtained by changing the rows of a matrix to columns and columns to rows. Swapping the values of rows and columns (arr[i][j] with arr[j][i]).

Example:

Find Transpose of Matrix
Transpose of a Matrix

We can transpose any given array simply by running two nested loops and swapping elements of position arr[i][j] with the element of position arr[j][i]


Below is the C++ Code Implementation:

//C++ Code to Transpose a Matrix
#include<bits/stdc++.h>
using namespace std;

//function to transpose matrix
void transpose(int arr[][3]){

    for(int i = 0; i < 3; i++){
        for(int j = i+1; j < 3; j++){
            swap(arr[i][j], arr[j][i]);
        }
    }
}

int main(){
    int arr[3][3] = {{2, 3, 6},
                     {1, 4, 1},
                     {9, 2, 5}};

    transpose(arr);

    cout<<"Transpose of given Matrix: "<<endl;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }    
    return 0;             
}
Output:
Transpose of given Matrix: 
2 1 9
3 4 2
6 1 5
  • Time Complexity: O(MxN) where M is the number of rows and N is the number of columns.
  • Space Complexity: O(1), no extra space is required to solve this problem.
Next:

Program for the Multiplication of Two 2D Matrix.

In this post, we are going to learn the process of multiplication of two 2D arrays and display the resulting array on screen. 

Example:

Multiplication of Two 2D Matrix
Multiplication of Matrices

Below are a few points to keep in mind before performing Matrix Multiplication:

  • Matrix multiplication is only possible when the number of columns of the first matrix should be equal to the number of rows of the second matrix. 
  • In matrix multiplication, the product of an m x k matrix and k x n matrix is an m x n matrix.
  • Matrix multiplication is not commutative in nature, it means the order multiplication of two matrices matters and can change our result.
  • Each entry in the resulting matrix is the dot product of row elements of the first matrix with column elements of the second matrix.

Below is C++ Code Implementation:

//Program to for Multiplication of 2D Array (Matrix)
#include<iostream>
using namespace std;

int main(){
    int arr1[50][50], arr2[50][50], prod[50][50] = {0};
    int row1, col1, row2, col2;
    //column of first matrix should be equal to row of second matrix
    do{
        cout<<"Enter number of rows and columns for first matrix: ";
        cin>>row1>>col1;

        cout<<"Enter number of rows and columns for second matrix: ";
        cin>>row2>>col2;
    }while(col1 != row2);
    
    //Taking input for first matrix
    cout<<"Enter the elements of first Array: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col1; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr1[i][j];
        }
    }
    //Taking input for second matrix
    cout<<"Enter the elements of second Array: "<<endl;
    for(int i = 0; i < row2; i++){
        for(int j = 0; j < col2; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr2[i][j];
        }
    }
    //Multiplication of Matrix
    cout<<"The Multiplication of two Matrices: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col2; j++){
            for(int k = 0; k < col1; k++){
                prod[i][j] = arr1[i][k] * arr2[k][j];
            }
        }
    }

    cout<<"Displaying Product of Two Matrix: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col2; j++){
            cout<<prod[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
Output:
Enter number of rows and columns for first matrix: 2 3
Enter number of rows and columns for second matrix: 3 2
Enter the elements of first Array: 
Enter element for position arr[0][0] = 1
Enter element for position arr[0][1] = 2
Enter element for position arr[0][2] = 3
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 5 
Enter element for position arr[1][2] = 6
Enter the elements of second Array: 
Enter element for position arr[0][0] = 6
Enter element for position arr[0][1] = 5
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 3
Enter element for position arr[2][0] = 2
Enter element for position arr[2][1] = 1
The Multiplication of two Matrices: 
6 3
12 6

In the above code, we have taken the first matrix of size 2 x 3 and the second matrix of size 3 x 2 and the resultant matrix that we get after multiplication is of size 2 x 2 which is satisfying our matrix property.

Next:

Program for the Addition of Two 2D Matrix.

In this post, we will learn how to add two (2D arrays) matrices and print them in the form of a single Matrix of the same size. Before moving directly to the program, let's first understand how this addition of two matrices happened and what the conditions record required for this operation. 

Note: A matrix can be used for addition or subtraction with another matrix only if both matrices have the same dimensions which means that both matrices should have an equal number of rows and the equal number of columns. (alert-success) 

Example: 

Addition of Two 2D Matrix.
Matrix Addition

Below is the C++ Code Implementation:
//C++ Program to for Addition of 2D Array (Matrix)
#include<iostream>
using namespace std;

int main(){
    int arr1[50][50], arr2[50][50], sum[50][50];
    int row, col;
    
    cout<<"Enter number of rows: ";
    cin>>row;

    cout<<"Enter number of column: ";
    cin>>col;
    //Taking input for first matrix
    cout<<"Enter the elements of first Array: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr1[i][j];
        }
    }
    //Taking input for second matrix
    cout<<"Enter the elements of second Array: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr2[i][j];
        }
    }
    
    //Addition of Matrix  
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            sum[i][j] = arr1[i][j] + arr2[i][j];
        }
    }

    cout<<"Displaying Sum of Two Matrix: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<sum[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
Output:
Enter number of rows: 3
Enter number of column: 3
Enter the elements of first Array: 
Enter element for position arr[0][0] = 2
Enter element for position arr[0][1] = 3
Enter element for position arr[0][2] = 6
Enter element for position arr[1][0] = 1
Enter element for position arr[1][1] = 4
Enter element for position arr[1][2] = 1
Enter element for position arr[2][0] = 9
Enter element for position arr[2][1] = 2
Enter element for position arr[2][2] = 5
Enter the elements of second Array: 
Enter element for position arr[0][0] = 1
Enter element for position arr[0][1] = 2
Enter element for position arr[0][2] = 3
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 5
Enter element for position arr[1][2] = 6
Enter element for position arr[2][0] = 7
Enter element for position arr[2][1] = 8
Enter element for position arr[2][2] = 9
Displaying Sum of Two Matrix: 
3 5 9
5 9 7
16 10 14
In the above code, we have taken two 3x3 matrices for addition, and after adding we have stored our result in a sum matrix which is of the same 3x3 size. 

In the same way, you can write a program for the subtraction of two matrices, you just need to change the arithmetic operation from addition to subtraction and everything else will remain the same as it is.

Next:

Program to Find Duplicate Element of an Array.

Given a positive integer array of sizes n and we need to find the element that appears more than one time in the given array. If no such element is present then return -1.

Example 1:

Input: arr[] = {9, 2, 7, 3, 10, 2}
Output: 2
Explanation: 2 appears more than one times.

Input: arr[] = {4, 2, 7, 3, 10, 21}
Output: -1
Explanation: All elements are unique, not duplicate element found.

Approach 1: Brute Force.

We can find the duplicate element in the given array but run two nested loops where the first loop will pick the element one by one and the inner loop will compare that element with all remaining elements of the array to check if any duplicate element exists.

Steps to solve the problem:
  • Run two nested loops, the first loop will run from i = 0 to i = n-1 and the second loop will run from j = i+1 to j = n-1.
  • If at any moment, arr[i] == arr[j] it means a duplicate element exist,s and then prints the duplicate element.
C++ code Implementation:
//C++ code to find duplicate elements of array
#include<bits/stdc++.h>
using namespace std;

//function to find duplicate element in array
int duplicate(int arr[], int n){
    int ans;

    for(int i = 0; i < n; i++){
        for(int j = i+1; j < n; j++){
            if(arr[i] == arr[j]){
                ans = arr[i];
                break;
            }
        }
    }
    return ans;
}

int main(){
    
    int arr[] = {9, 2, 7, 3, 10, 2};
    //size of the given array
    int n = sizeof(arr)/sizeof(arr[0]);
    
    cout<<"The element present more than one time: "<<duplicate(arr, n);

    return 0;
}
Output:
The element present more than one time: 2
  • Time Complexity: O(n^2) 
  • Space Complexity: O(1)

Approach 2: Using a Hash Table (Optimized).

For this approach, we are going to use an unordered map (internally implemented using Hash Table) that is an associated container used to store data in the form of Key and Value pair. 

Steps to solve the problem:
  • Declare a unordered_map<int, int> in which the key and value type is an integer. 
  • Traverse the array and take each element as Key and store their count as a value to that key.
  • If you found any key with a value greater than 1 then it means there exists a duplicate element in the array.
  • Print that key with having count greater than 1.
Find Duplicate Element of an Array.

C++ code Implementation:
//C++ code to find duplicate elements of array using Hash Table
#include<bits/stdc++.h>
using namespace std;

//function to find duplicate element in array
int duplicate(int arr[], int n){
    int ans;
    unordered_map<int, int> mp{0};

    for(int i = 0; i < n; i++){
        mp[arr[i]]++;
    }

    for(auto it: mp){
        if(it.second > 1){
          ans = it.first;
          break;
        }    
    }
    return ans;
}

int main(){
    
    int arr[] = {9, 2, 7, 3, 10, 2};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    
    cout<<"The element present more than one times: "<<duplicate(arr, n);

    return 0;
}
Output:
The element present more than one time: 2
  • Time Complexity: O(n) As we need to traverse the array only one time to get the count of each unique element and there is no nested loop required. 
  • Space Complexity: O(n) As we are using extra n space for storing the count of each unique element. 

Also see:

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson