以“+”模式在矩陣中列印字串 C++
給定一個字串 str,我們在矩陣中以“+”模式列印給定的字串 str。要形成矩陣中的加號圖案,該矩陣必須是方陣。方陣是行數和列數相同的矩陣。
例如,我們有一個字串“Tutor”,我們的任務是從中心列印水平和垂直相交的字串,並將矩陣的其餘元素設定為“x”,如下面的給定圖形所示−
輸入
str[] = {“Point”}
輸出
輸入
str[] = {“this”}
輸出
Pattern not possible
下面使用的方法來解決問題
獲取輸入。
檢查輸入是否不是偶數長度。
最初用“x”設定整個矩陣
在中間行和中間列中設定字串
列印結果矩陣。
演算法
Start In function int stringcross(char str[], int n) Step 1→ If n % 2 == 0 then, Step 2→ Printf "Pattern not possible” Step 3→ Else Declare a str2[max][max] Declare m and set as n / 2 For i = 0 and i < n and i++ For j = 0 and j < n and j++ Set str2[i][j] as 'x' For i = 0 and i < n and i++ Set str2[i][m] as str[i] For i = 0 and i < n and i++ Set str2[m][i] as str[i] For i = 0 and i < n and i++ For j = 0 and j < n and j++ Print str2[i][j] Print newline In Function int main() Step 1→ Declare and Initialize str[] as "TUTOR" Step 2→ Declare and Initialize n with the size of the string Step 3→ Call stringcross(str, n-1) Stop
示例
#include <stdio.h> #define max 100 int stringcross(char str[], int n){ if (n % 2 == 0){ //odd length string is only possible printf("Pattern not possible\n"); } else { //decalaring a 2-d character array char str2[max][max]; int m = n / 2; //Initially setting x for all elements for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { str2[i][j] = 'x'; } } //Placing the string in a manner //a cross is formed. for (int i = 0; i < n; i++){ //for middle columns str2[i][m] = str[i]; } for (int i = 0; i < n; i++){ //for middle row str2[m][i] = str[i]; } //printing for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%c ",str2[i][j]); } printf("\n"); } } return 0; } int main(){ char str[] = {"TUTOR"}; int n = sizeof(str)/sizeof(str[0]); stringcross(str, n-1); return 0; }
輸出
如果執行以上程式碼,它將生成以下輸出 −
廣告