Print the triangle increase and then decreasing left to right order
Example:
** ** * ** * * ** * * * ** * * ** * ** **
Approach
Java
public class Triangle {public static void main(String[] args) {int n = 10;printTriangle(n);}public static void printTriangle(int r) {int k = 1;for (int i = 1; i <= r; i++) {if (i > r / 2) {--k;}for (int j = 0; j < k; j++) {System.out.print("* ");}System.out.println("");if (i < r / 2) {++k;}}}}
C++
#include <bits/stdc++.h>using namespace std;void printTriangle(int n){//print triangle in increasing//no of columnsfor(int i=1;i<=n/2;i++){for(int j=1;j<=i;j++)cout<<"* ";cout<<"\n";}//print the middle onefor(int i=1;i<=(n+1)/2;i++)cout<<"* ";cout<<"\n";//print triangle in decreasingfor(int i=n/2;i>=1;i--){for(int j=1;j<=i;j++)cout<<"* ";cout<<"\n";}}int main(){//n should be oddint n = 9;printTriangle(n);}
No comments:
Post a Comment