Share

loop programming exercises in java, c++, python and javascript —08

loop programming exercises in java, c++, python and javascript

Java

int num=20;
	 int i,j,k;
	 for( i=1;i<=5;i++){
		 for( j=1;j<=num;j++){
			 System.out.print(" ");
		 }
	 num--;
	 	   for( k=1;k<=i;k++){
	 		 System.out.print("* ");
	 	   }
	 	System.out.println();
	 }
	 num=20; 
	 for(i=4;i>=1;i--){
		 for(j=4;j<=num;j++){
			 System.out.print(" ");
		 }
	num++;
		for(k=1;k<=i;k++){
			System.out.print("* ");
		}
		System.out.println();
  
	 }

C++

int num=20;
	 for(int i=1;i<=5;i++){
		 for(int j=1;j<=num;j++){
			cout<<" ";
		 }
		 num--;
		 for(int k=1;k<=i;k++){
			 cout<<"* ";
		 }
		 cout<<endl;
	 }
 num=20;
	 for(int i=4;i>=1;i--){
		 for(int j=4;j<=num;j++){
			cout<<" ";
		 }
		 num++;
		 for(int k=1;k<=i;k++){
			 cout<<"* ";
		 }
		 cout<<endl;
	 }

Javascript

let rows=5;
    for (let i = 0; i < rows; i++) {
        var output = " ";
        for (let j =0; j < rows - i; j++) {
            output += ' ';
        }
        for (let k = 0; k <= i; k++) {
            output += '* ';
       }
       console.log(output);  
} 
rows=5;
    for (let i = 0; i < rows; i++) {
        var output1 = " ";
        for (let j =4; j < rows + i; j++) {
            output1 += ' ';
        }
        for (let k = 4; k >= i; k--) {
            output1 += '* ';
        }
       console.log(output1);  
    }