ให้สตริง str เราต้องพิมพ์สตริงที่กำหนดในรูปแบบ '+' ในเมทริกซ์ ในการสร้างรูปแบบบวกในเมทริกซ์ เมทริกซ์ต้องเป็นเมทริกซ์กำลังสอง เมทริกซ์สี่เหลี่ยมจัตุรัสคือเมทริกซ์ที่มีจำนวนแถวและคอลัมน์เท่ากัน
เช่นเดียวกับที่เรามีสตริง "ติวเตอร์" หน้าที่ของเราคือพิมพ์สตริงในแนวนอนและแนวตั้งที่ตัดกันจากจุดศูนย์กลาง และทำให้องค์ประกอบที่เหลือของเมทริกซ์เป็น "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;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -