Share

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

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

Java

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

C++

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

Javascript

let height=5;
  
   for (var i = 1; i <= height; i++) {
     var row = '';
     
     for (var j = 1; j <= (height - i); j++) {
       row += ' ';
     }
     
     for (var k = 1; k <= i; k++) {
       row += '*';
     }
     
     console.log(row);
   }
   for (var i = 1; i <= height; i++) {
      var row = '';
   
      for (var j = 1; j <= (i - 1); j++) {
        row += ' ';
      }
   
      for (var j = 1; j <= (height - i + 1); j++) {
        row += '*';
      }
          
      console.log(row);

   }