多重循环语句

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
int main(){
    int n;
    cout<<"please input a number:"; 
    cin>>n;
    for (int i = 0; i <=n; ++i){
        for (int j = 0; j <=i ; ++j){
        cout<<j<<" ";
        }
     cout<<endl;
     }
return 0;
}

edit & run

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>
using namespace std;
int main(){
    int n;
    cout<<"please input a number:"; 
    cin>>n;
    for (int i = 0; i <=n; ++i){
        for (int j = 0; j < n-i; j++) cout<<' ';
        for (int j = 0; j <=i ; ++j)cout<<'*'<<' ';
        cout<<endl;
     }
return 0;
}

edit & run

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
     int n;
     cout<<"please input a number: ";
     cin>>n;
     for (int i = 1; i <=n; i++){
         for (int j = 1; j <=n-i; j++) cout<<' ';
         for (int j = 1; j <=2*i-1; j++) cout<<'*';
         cout<<endl;
      }
      return 0;
}

edit & run

对于给定的自然数n,输出1~n的所有质数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
using namespace std;
int main()
{
    int i,j,n;
    cout<<"input a number:"; cin>>n;
    for ( i = 2; i <=n; ++i){
        for (j = 2; j <i ; ++j)if(i%j==0)break;
        if(j==i)cout<<i<<' ';
    }
return 0;
}

edit & run

根据给定的n,输出乘法口诀表的前n行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostream>
using namespace std;
int main(){
    int i,j,k;
    cout<<"input a number:"; cin>>k;
    for(i=1;i<=k;i++){
        for(j=1;j<=i;j++)cout<<j<<'*'<<i<<'='<<j*i<<' ';
        cout<<endl;
     }
return 0;
}

edit & run

Scroll to Top