巢狀指的是像鳥巢一般,一層包一層包下去…
在這裡是指 while
/for
裡面還有 while
/for
的情況。
請印出以*拼成的長方形。
整數X、整數Y
寬為X,高為Y的長方形
6 3
******
******
******
4 5
****
****
****
****
****
#include<iostream>
using namespace std;
int main()
{
int X, Y;
int i, j;
cin >> X >> Y;
for( i=1 ; i<=Y ; i=i+1 )
{
for( j=1 ; j<=X ; j=j+1 )
{
cout << "*";
}
cout << endl;
}
return 0;
}
先假想要處理 X=6、Y=3的情形
若只要印出一列******
後換行,可以寫出
for( j=1 ; j<=6 ; j=j+1 )
{
cout << "*";
}
cout << endl;
因為總共要重複3次上述動作,外層再加上 for( i=1 ; i<=3 ; i=i+1 )
,變成
for( i=1 ; i<=3 ; i=i+1 )
{
for( j=1 ; j<=6 ; j=j+1 )
{
cout << "*";
}
cout << endl;
}