C program to print the triangular pattern by using one loop

Given a number n, print triangular pattern. We are allowed to use only one loop.

Example: 

Input: 7
Output:
*
* * 
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
We use a single for-loop and in the loop, we maintain two variables for line count and current star count. If the current star count is less than the current line count, we print a star and continue. Else we print a new line and increment line count.  

// C++ program to print a pattern using single
// loop and continue statement
#include<bits/stdc++.h>
using namespace std;

// printPattern function to print pattern
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: 

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

Comments

Popular posts from this blog

proassignment help backlink data index 41

programming shark backink data index 31

Programming shark backlink data index 67