给定高度h和宽度w,打印一个矩形图案,如下例所示。
null
例如:
Input : h = 4, w = 5 Output : @@@@@ @ @ @ @ @@@@@ Input : h = 7, w = 9 Output : @@@@@@@@ @ @ @ @ @ @ @ @ @ @ @@@@@@@@
这个想法是运行两个循环。一个用于打印行数,另一个用于列数。仅当当前行是第一行或最后一行时才打印“@”。或当前列是第一列或最后一列。
C++
// CPP program to print a rectangular pattern #include<iostream> using namespace std; void printRectangle( int h, int w) { for ( int i=0; i<h; i++) { cout << "" ; for ( int j=0; j<w; j++) { // Print @ if this is first row // or last row. Or this column // is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) cout << "@" ; else cout << " " ; } } } // Driver code int main() { int h = 4, w = 5; printRectangle(h, w); return 0; } |
JAVA
// JAVA program to print a rectangular // pattern class GFG { static void printRectangle( int h, int w) { for ( int i = 0 ; i < h; i++) { System.out.println(); for ( int j = 0 ; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h- 1 || j== 0 || j == w- 1 ) System.out.print( "@" ); else System.out.print( " " ); } } } // Driver code public static void main(String args[]) { int h = 4 , w = 5 ; printRectangle(h, w) ; } } /*This code is contributed by Nikita Tiwari.*/ |
Python3
# Python 3 program to print a rectangular # pattern def printRectangle(h, w) : for i in range ( 0 , h) : print ("") for j in range ( 0 , w) : # Print @ if this is first row # or last row. Or this column # is first or last. if (i = = 0 or i = = h - 1 or j = = 0 or j = = w - 1 ) : print ( "@" ,end = "") else : print ( " " ,end = "") # Driver code h = 4 w = 5 printRectangle(h, w) # This code is contributed by Nikita Tiwari. |
C#
// C# program to print a rectangular // pattern using System; class GFG { static void printRectangle(int h, int w) { for (int i = 0; i < h; i++) { Console.WriteLine(); for (int j = 0; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) Console.Write("@"); else Console.Write(" "); } } } // Driver code public static void Main() { int h = 4, w = 5; printRectangle(h, w) ; } } /*This code is contributed by vt_m.*/ |
PHP
<?php // php program to print // a rectangular pattern function printRectangle( $h , $w ) { for ( $i = 0; $i < $h ; $i ++) { echo "" ; for ( $j = 0; $j < $w ; $j ++) { // Print @ if this is first row // or last row. Or this column // is first or last. if ( $i == 0 || $i == $h - 1 || $j == 0 || $j == $w - 1) echo "@" ; else echo " " ; } } } // Driver code $h = 4; $w = 5; printRectangle( $h , $w ); // This code is contributed by mits ?> |
@@@@@ @ @ @ @ @@@@@
时间复杂度是 O(n) 2. ) . 本文由 阿努拉格·拉瓦特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END