Print an N x M matrix such that each row and column has all the vowels in it in C++

C++Server Side ProgrammingProgramming

In this problem, we have to create a 2D matrix of size n X m. And in this matrix, we have to place only vowels in such a way that each row and column has all vowels in it.

All vowels mean all a, e, i, o, u are present in each row and each column of the matrix. This makes the minimum number of rows and columns required is 5 i.e. the smallest matrix is of the size 5X5.

Let’s take an example to understand the topic better

Example 1 

Input : N = 5 and M = 5.
Output :
   a e i o u
   e i o u a
   i o u a e
   o u a e i
   u a e i o

Explanation − In sequence, the vowels a e i o u are arranged in every row and column. The first row with be aeiou, the next will start with e being eioua and next will be iouae.

Example 2

Input : N = 3 M = 4
Output : Matrix cannot be created.

Explanation − minimum value for N and M is 5.

To solve this problem, we first condition that the minimum number of elements in 5 i.e., if value less than 5 is provided in the input “matrix, cannot be created” is printed. Otherwise, we will print the sequence ‘ aeiou ’ in a repeated form. With an array, the sequence to be printed is changed by rotating it one step left making in ‘ eioua ’, then ‘ iouae ’.

Example

 Live Demo

#include <iostream>
using namespace std;
void vowelMatrix(int n, int m) {
   if (n<5||m<5) {
      cout<<"Marix cannot be created!";
      return;
   }
   string s = "aeiou";
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
         cout<<s[(j+i) % 5]<<" ";
      }
      cout << endl;
   }
}
int main(){
   int n = 5, m = 5;
   vowelMatrix(n, m);
   return 0;
}

Output

a e i o u
e i o u a
i o u a e
o u a e i
u a e i o
raja
Published on 03-Jan-2020 14:28:57
Advertisements