反向字串模式的 C 程式
給定一個字串 str,我們的任務是列印其反向模式。該模式將以反向順序遞增,當字串完成後,用 '*' 填充剩餘的位置。
比如我們輸入一個字串 “abcd”,現在在第一行我們將列印 “a”,然後在下一行我們將列印 “cb”,然後在第三行我們將列印 “**d”。
示例
Input: str[] = { “abcd” } Output: a c b * * d
解釋 −
- 在第一行列印 1 個字元
- 在第二行按反向順序列印 2 個字元
- 在第三行按反向順序列印 3 個字元,如果字串不足 3 個,則列印字元並用 * 填充空格。
Input: str[] = {“tutorialspoint”} Output:
下面使用的方法是 −
- 我們將從 i=0 開始遍歷字串,並且會檢查 i<n && k<(n-i)*2 是否為真
- 然後我們將獲取一個變數 k 並將 k 設定為 ((i*(i+1))/2)-1
- 我們將檢查 If k >= n-1 是否成立,如果成立,將列印 "* ",否則將按反向順序列印字串的值
演算法
Start In function int reverse_it(char str[], int n) Step 1-> Declare and Initialize i, j=0 , k=0 Step 2-> Loop For i=0 and i<n && k<(n-i)*2 and i++ Set k as ((i*(i+1))/2)-1 Loop For j=0 and j<i && k<(n-i)*2 and j++ If k >= n-1 then, Print "* " Else Print "%c ",str[k] Decrement k by 1 End loop Print new line End loop In Function int main(int argc, char const *argv[]) Step 1-> Declare and initialize string str[] Step 2-> Declare and Initialize size as sizeof(str)/sizeof(str[0]) Step 3-> Call function reverse_it(str, size); Stop
示例
#include <stdio.h> int reverse_it(char str[], int n) { int i, j=0 , k=0; for(i=0; i<n && k<(n-i)*2; i++) { //Assigning k k = ((i*(i+1))/2)-1; for(j=0; j<i && k<(n-i)*2; j++) { //will check if k is greater than the total number of characters //then we will print * for filling the extra characters if(k >= n-1) printf("* "); //print the string in reverse order else printf("%c ",str[k]); k--; } //for line break after reverse sequence printf("
"); } return 0; } //Main Function int main(int argc, char const *argv[]) { char str[] = {"tutorialspoint"}; int size = sizeof(str)/sizeof(str[0]); reverse_it(str, size); return 0; }
輸出
如果執行上述程式碼,它將生成以下輸出 −
廣告