Home > Back-end >  how to print a right angle triangle in c using single loop
how to print a right angle triangle in c using single loop

Time:11-06

this is the code that I wrote for printing the pattern using single however it doesn't work can you help me out.


    #include<iostream>
    using namespace std;
    int main()
    {
        int line, star = 0, n;
        cin >> n;
        for (line = 1; line <= n; line  )
        {
            if (star < n)
            {
                cout << "*";
                star  ;
                continue;
            }
            if (star == line)
            {
                cout << endl;
                star 
            }
        }
        
        system("pause");
        return 0;
    }

CodePudding user response:

To print the right angle traingle we can use the string and then add some of the part to it to increase the length of string which look similer to triangle.

void solve()
{  
   string a = "*";
   string add_to_a= "*";
   int n;
   cin>>n;
   for (int i = 0; i < n;   i)
   {
       cout<<a<<"\n";
       a =add_to_a;
   }
} 

this is code written by me this may help

CodePudding user response:

//Try this Code to print right angled triangle in c

#include<bits/stdc  .h>

using namespace std;

void printPattern(int n)
{

    // Variable initialization

    int line_no = 1; // Line count
 

    // Loop to print desired pattern

    int curr_star = 0;

    for (int line_no = 1; line_no <= n; )

    {

        // If current star count is less than

        // current line number

        if (curr_star < line_no)

        {

           cout << "* ";

           curr_star  ;

           continue;

        }
 

        // Else time to print a new line

        if (curr_star == line_no)

        {

           cout << "\n";

           line_no  ;

           curr_star = 0;

        }

    }
}
 
// Driver code

int main()
{

    printPattern(7);

    return 0;
}

//Output of the code

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
  • Related