printing the below pattern using just one loop - c++

ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop

Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}

I'd like to just use one loop.
I'll take it literally and show a starting point for a possible solution.
// Let's start by figuring out some dimensions.
int n;
std::cin >> n;
int height = 2 * n - 1;
int area = n * height;
// Now we'll print the "rectangle", one piece at a time.
for (int i = 0; i < area; ++i)
{ // ^^^^^^^^
// Extract the coordinates of the char to be printed.
int x = i % n;
int y = i / n;
// Assign a symbol, based on such coordinates.
if ( x <= y and x <= height - y - 1 )
{ // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals.
std::cout << '*'; // This prints correctly the triangle on the left...
}
else
{
std::cout << '_'; // <--- But of course, something else should done here.
}
// End of row.
if ( x == n - 1 )
std::cout << '\n';
}

If you look at the pattern, then you can see a sort of "triangles". And this already gives a hint for the solution. Use a triangle function.
Please read about it here.
Then you will notice that always the "aboslute"-function, in C++ std::abs, is involved.
But first of all, it is easily visible that the number rows to print is always the width of a triangle * 2.
And the number of charcters in the pattern, can be calculated by applying the triangle function. Example for width 5:
Number of stars number of dashdot
Row width-abs(row-width) abs(row-width)
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0
6 4 1
7 3 2
8 2 3
9 1 4
And this can be implemented easily now.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std::string_literals;
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create dashDot pattern
std::string ddp(std::abs(row - maxWidth), '\0');
std::generate(ddp.begin(), ddp.end(), [i = 0]() mutable { return i++ % 2 ? '.' : '_'; });
// Show output
std::cout << (starPattern+ddp) << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Of course you can also create the whole pattern wit std::generate.
Maybe it is too complex for now.
And less understandable.
See:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
int main() {
// Get the max width of the pattern and perform a short input validation
if (int width{}; (std::cin >> width) and (width > 0)) {
std::vector<std::string> row(2 * width - 1);
std::for_each(row.begin(), row.end(), [&, r = 1](std::string& s) mutable {
s = std::string(width - std::abs(r - width), '*');
std::string ddp(std::abs(r++ - width),'\0');
std::generate(ddp.begin(), ddp.end(), [&, i = 0]() mutable{ return i++ % 2 ? '.' : '_'; });
s += ddp; std::cout << s << '\n'; });
}
else std::cout << "\n*** Error: Invalid input\n\n";
}

Related

I have to do a program that do a square in c++ with incremental letter

Hello and thank you for coming here.
I have to do a program that will draw a number of square choosed by the user with incremental letter.
For example, if the user choose 4 square, it will return :
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
At the time being, my code look like this ;
#include <iostream>
using namespace std;
int main()
{
int size;
int nbsquareletter;
cout << " How many square ?" << endl;
cin >> nbsquareletter;
size = nbsquareletter * 2 - 1;
char squareletter = 'a';
for (int row = 1; row <= size; ++row)
{
for (int col = 0; col <= size; ++col)
{
if (row < col) {
cout << (char)(squareletter + row - 1) << " ";
}
else if (row > col)
{
cout << (char)(squareletter + col) << " ";
}
/*
cout << col << " ";
cout << row << " ";
*/
}
cout << endl;
}
}
If you have any ideas to help me, don't hesitate, I'm struggling. it's been 3.5 hours. Thanks you for reading and have a good day !
Try to keep things simple. If you start write code before you have a clear idea of how to solve it you will end up with convoluted code. It will have bugs and fixing them will make the code even less simple.
Some simple considerartions:
The letter at position (i,j) is determined by the "distance" from the center. The distance is max(abs(i - i_0), abs(j - j_0).
The center is at (i,j) = (size-1,size-1) when we start to count at upper left corner (0,0).
The letters can be picked from an array std::string letters = "ABCDEFG...".
i and j are in the range [0,2*size-1)
Just writing this (and nothing more) down in code results in this:
#include <iostream>
#include <string>
void print_square(int size){
std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i_0 = size-1;
int j_0 = size-1;
for (int i=0;i< 2*size-1;++i){
for (int j=0;j< 2*size-1;++j) {
int index = std::max(std::abs(i-i_0),std::abs(j-j_0));
std::cout << letters[index];
}
std::cout << "\n";
}
}
int main() {
print_square(4);
}
Which produces output
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
Your code cannot print the right output, because when row == col there is no output, and it misses the diagonal. I didnt look further than that.
Instead of fixing bugs in your code I decided to suggest you my own solution. Maybe some other answers will be related to bugs in your code.
On piece of paper I figured out 4 different formulas for 4 parts of a drawn picture, formulas computing what letter to take inside English alphabet. Afterwards I take this letter from array with alphabet.
Try it online!
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
char const letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 2 * n - 1; ++i) {
for (int j = 0; j < 2 * n - 1; ++j)
std::cout << letters[
i <= j && i + j < 2 * n - 1 ? n - i - 1 :
i <= j && i + j >= 2 * n - 1 ? j - n + 1 :
i > j && i + j < 2 * n - 1 ? n - j - 1 :
i > j && i + j >= 2 * n - 1 ? i - n + 1 : 25
];
std::cout << std::endl;
}
}
Input:
7
Output:
GGGGGGGGGGGGG
GFFFFFFFFFFFG
GFEEEEEEEEEFG
GFEDDDDDDDEFG
GFEDCCCCCDEFG
GFEDCBBBCDEFG
GFEDCBABCDEFG
GFEDCBBBCDEFG
GFEDCCCCCDEFG
GFEDDDDDDDEFG
GFEEEEEEEEEFG
GFFFFFFFFFFFG
GGGGGGGGGGGGG
Let's define some functions, to make the recurrence relation obvious.
std::vector<std::string> WrapInLetter(char letter, std::vector<std::string> lines)
{
for (auto & line : lines)
{
line.insert(line.begin(), letter);
line.insert(line.end(), letter);
}
std::size_t size = (lines.size() * 2) + 1;
std::string edge(size, letter); // A string formed of size copies of letter
lines.insert(lines.begin(), edge);
lines.insert(lines.end(), edge);
return lines;
}
std::vector<std::string> SquareLetter(char letter)
{
if (letter == 'A') return { "A" };
return WrapInLetter(letter, SquareLetter(letter - 1));
}
Now main just has to call that function and loop over the result.
int main()
{
std::cout << "How many square ?" << std::endl;
int size;
std::cin >> size;
for (auto line : SquareLetter('A' + size - 1))
{
std::cout << line << std::endl;
}
}

Why does the code below causes Segmentation Fault (SIGSEGV)?

PROBLEM STATEMENT
You are given a strictly increasing sequence of integers A1,A2,…,AN. Your task is to compress this sequence.
The compressed form of this sequence is a sequence of ranges separated by commas (characters ','). A range is either an integer or a pair of integers separated by three dots (the string "..."). When each range a...b in the compressed form is decompressed into the subsequence (a,a+1,…,b), we should obtain the (comma-separated) sequence A again.
For each maximal contiguous subsequence (a,a+1,…,b) of A such that b≥a+2, the compressed form of A must contain the range a...b; if b≤a+1, such a sequence should not be compressed into a range. A contiguous subsequence is maximal if it cannot be extended by at least one element of A next to it. It can be proved that the compressed form of any sequence is unique (i.e. well-defined).
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one string ― the compressed form of the given sequence.
Constraints
1≤T≤100
1≤N≤100
1 ≤ Ai ≤ 1000 for each valid i
A1 < A2 < …... <AN
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
3
12
1 2 3 5 6 8 9 10 11 12 15 17
4
4 5 7 8
1
4
Example Output
1...3,5,6,8...12,15,17
4,5,7,8
4
MY Code:
#include <bits/stdc++.h>
using namespace std;
bool b[1005];
int a[1005];
int main()
{
int test, i, j, size, count;
cin >> test;
while (test--)
{
for (i = 0; i < 1005; i++)
b[i] = false;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> a[i];
b[a[i]] = true;
}
for (i = 0; i < 1005; i++)
{
if (b[i] == true)
{
cout << i;
j = i;
count = 0;
while (b[j] == true)
{
count++;
j++;
}
if (count > 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "..." << i - 1 << ",";
else
cout << "..." << i - 1;
}
if (count == 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "," << i - 1 << ",";
else
cout << "," << i - 1;
}
if (count == 1 && ((j - 1) != a[size - 1]))
cout << ",";
}
}
}
return 0;
}
}
MY Question:
Above code runs perfectly on my device giving desired output. But when I am submitting this solution to
Online Judge , it says segmentation fault. It's sure that fundamentally I am accessing the memory incorrectly. Could you please show me where it is?
b is defined a bool[1005]
In this part
for(i=0 ; i<4000 ; i++)
b[i] = false;
You are writing false value 4000 times, exceeding the array size.
Overwriting past the array is allowed on the compiler but will have undefined behaviour in runtime.
In short: it can or can not cause a segfault.
Here is another approach given that the input data is in a file input.txt:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
class Reader {
public:
Reader(const std::string& filename) :
filename_(std::move(filename)), is_(filename_)
{
is_.exceptions( std::ifstream::failbit | std::ifstream::badbit );
}
int get_N() {
int N;
is_ >> N;
return N;
}
std::vector<int> get_ints(int N) {
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++ ) {
int value;
is_ >> value;
v.push_back(value);
}
return v;
}
int get_num_cases() {
int num_cases;
is_ >> num_cases;
return num_cases;
}
private:
std::string filename_;
std::ifstream is_;
};
bool start_range_cur( std::vector<int> &v, int j, int N )
{
if ( j>= (N - 2) ) return false;
return ((v[j+1] - v[j]) == 1) && ((v[j+2] - v[j+1]) == 1);
}
bool in_range_cur( std::vector<int> &v, int j )
{
return (v[j+1] - v[j]) == 1;
}
void print_range( int min, int max, bool print_comma)
{
std::cout << min << ".." << max;
if (print_comma) std::cout << ",";
}
void print_single(int val, bool print_comma)
{
std::cout << val;
if (print_comma) {
std::cout << ",";
}
}
int main() {
Reader is {"input.txt"};
int num_cases = is.get_num_cases();
for (int i = 0; i < num_cases; i++) {
int N = is.get_N();
std::vector<int> v = is.get_ints(N);
bool in_range = false;
int range_start;
for( int j = 0; j< N; j++ ) {
if (in_range) {
if (j == (N - 1)) {
print_range(range_start, v[j], false);
}
else if (in_range_cur(v, j)) {
continue;
}
else {
print_range(range_start, v[j], true);
in_range = false;
}
}
else {
if (j == (N - 1)) {
print_single(v[j], false);
}
else if (start_range_cur(v, j, N)) {
in_range = true;
range_start = v[j];
}
else {
print_single(v[j], true);
}
}
}
std::cout << '\n';
}
return 0;
}

C++, sort through array of numbers to find uniqueness

Say I have an array of 4 different numbers.
int numbers[4] = {50234, 50356, 50454, 50934};
How do you make a nested for loop in C++ to sort through these numbers from back to front in order to identify the required amount of digits needed for uniqueness?
From the example you can tell that you'll need 3 digits from the back to make sure no numbers contain similar tails of numbers. 50234, 50934 = 3 digits to have them unique = 502 and 509 respectively.
What would the for loop look like to go through each of these numbers one by one, number by number, and sort out identical numbers to reach an output of 3?
It would go like this:
4
6 - discard this number, it's not identical
4
4
Then:
3
5 - discard this number
3
Then:
2
9 Hurray! No similar numbers anymore, print out 3 being the answer.
I'm stumped and can't figure it out.
Any help would be greatly appreciated, thank you.
Say you start with
#include <unordered_set>
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
const std::vector<int> numbers{50234, 50356, 50454, 50934};
You can transform it into a vector of strings:
std::vector<std::string> string_numbers;
std::for_each(std::begin(numbers), std::end(numbers), [&](int n){ string_numbers.push_back(std::to_string(n)); });
Now we'll check the number of digits required, starting at 1:
size_t digits = 1;
while(true) {
At each iteration, we'll create an unordered_set
std::unordered_set<std::string> partials;
For each number, we'll attempt to place digits digits of it into the set:
for(const auto &s: string_numbers) {
if(s.size() <= digits) {
std::cout << "not unique" << std::endl;
return 0;
}
partials.insert(s.substr(0, digits));
}
If the size of the set is the size of the vector, we're done:
if(partials.size() == numbers.size()) {
std::cout << digits << " required" << std::endl;
return 0;
}
Otherwise, we need to increase the number of digits:
++digits;
}
}
Full code:
#include <unordered_set>
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
const std::vector<int> numbers{50234, 50356, 50454, 50934};
std::vector<std::string> string_numbers;
std::for_each(std::begin(numbers), std::end(numbers), [&](int n){ string_numbers.push_back(std::to_string(n)); });
size_t digits = 1;
while(true) {
std::unordered_set<std::string> partials;
for(const auto &s: string_numbers) {
if(s.size() <= digits) {
std::cout << "not unique" << std::endl;
return 0;
}
partials.insert(s.substr(0, digits));
}
if(partials.size() == numbers.size()) {
std::cout << digits << " required" << std::endl;
return 0;
}
++digits;
}
}
if you want to sort numbers so use one of sort algorithms let's say bubble sort. then check for uniqueness and store the unique values in a new array then print them:
we make our code for understanding and practice but in a real program we use libraries they are too much powerful and quick:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int numbers[4] = {50234, 50356, 50454, 50934};
// int numbers[4] = {50234, 50356, 50454, 50356};
for(int i(0); i < 4; i++)
{
for(int j(i + 1); j < 4; j++)
{
if(numbers[i] > numbers[j])
{
numbers[i] ^= numbers[j];
numbers[j] ^= numbers[i];
numbers[i] ^= numbers[j];
}
}
}
for(int i = 0; i < 4; i++)
cout << numbers[i] << ", ";
int nUniq = 0;
bool isUniq = true;
for(int i = 0; i < 4; i++)
{
isUniq = true;
for(int j(i + 1); j < 4; j++)
{
if(numbers[i] == numbers[j])
{
isUniq = false;
break;
}
}
if(isUniq)
nUniq++;
}
cout << nUniq << endl;
int* ptrUniq = new int[nUniq];
int k = 0;
for(int i = 0; i < 4; i++)
{
isUniq = true;
for(int j(i + 1); j < 4; j++)
{
if(numbers[i] == numbers[j])
{
isUniq = false;
break;
}
}
if(isUniq)
{
ptrUniq[k] = numbers[i];
k++;
}
}
cout << "\nhere are uniq values:\n\n";
for(int i = 0; i < nUniq; i++)
cout << ptrUniq[i] << ", ";
delete[] ptrUniq;
ptrUniq = NULL;
cout << endl << endl;
return 0;
}

spoj (Ambiguous Permutations)

I was solving a simple problem on spoj called Ambiguous Permutations(http://www.spoj.com/problems/PERMUT2/), it worked fine when I tested for small inputs, but on submission it shows runtime error - segmentation fault. I'm not able to figure it out (though I've wasted a lot of time, and gained frustration only). Please help.
#include <iostream>
#include <stdlib.h>
#include <string.h>
char arr1[200000];//stores original string.
char arr2[200000];//stores inverse permutation.
long int n;
using namespace std;
int main()
{
while (1)
{
cin >> n;
if (n == 0)
{
exit(0);
}
getchar();
gets(arr1);
//creating inverse permutation.
for (long int i = 0; i < 2 * n - 1; i++)
{
if (i % 2 == 1)
{
arr2[i] = ' ';
}
else
{
arr2[2 * (arr1[i] - '0') - 2] = i / 2 + '1';
}
}
arr2[2 * n - 1] = '\0';
//comparing string with it's inverse permutation.
if (strcmp(arr1, arr2) == 0)
{
cout << endl << "ambiguous";
}
else
{
cout << endl << "not ambiguous";
}
}
return 0;
}
The problem is that you are using a char array to represent integers, and your code assumes that each number is represented by one char (note for example checking i % 2 == 1 to determine whether number or space).
Hence, any number bigger than 9 will cause correctness / memory problems.
If you'll use integer arrays it will be a lot easier.
You'll stop worrying about the space character ' ', won't need to decrement '0' char from the cells, and won't need your loops to run till 2 * n - 1.
I think it is much clearer this way:
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
int arr1[MAX_SIZE];
int arr2[MAX_SIZE];
int size = 0;
bool areArrsEqual()
{
for (int i = 0; i < size; ++i)
{
if (arr1[i] != arr2[i])
{
return false;
}
}
return true;
}
int main()
{
cin >> size;
while (size > 0 && size <= MAX_SIZE)
{
for (int i = 0; i < size; ++i)
{
cin >> arr1[i];
}
// creating inverse permutation.
for (int i = 0; i < size; i++)
{
// if (arr[i] - 1 >= size) ==> illegal input.
arr2[arr1[i] - 1] = i + 1;
}
// comparing permutation with it's inverse permutation.
if (areArrsEqual())
{
cout << "ambiguous" << endl;
}
else
{
cout << "not ambiguous" << endl;
}
cin >> size;
}
return 0;
}
Output:
4
1 4 3 2
ambiguous
5
2 3 4 5 1
not ambiguous
1
1
ambiguous
13
1 2 3 4 5 6 7 8 9 10 11 12 13
ambiguous
0

how to create a pyramid using for loop in c++

Hello guys I just want to ask how can I create a triangle using c++?
Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid?
Here's my code below.
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
for(x=1; x <= 23; x++){
if((x%2) != 0){
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
For a triangle och height Y, then first print Y-1 spaces, followed by an asterisk and a newline. Then for the next line print Y-2 spaces, followed by three asterisks (two more than previously printed) and a newline. For the third line print Y-3 spaces followed by five asterisks (again two more than previous line) and a newline. Continue until you have printed your whole triangle.
Something like the following
int asterisks = 1;
for (int y = HEIGHT; y > 0; --y, asterisks += 2)
{
for (int s = y - 1; s >= 0; --s)
std::cout << ' ';
for (int a = 0; a < asterisks; ++a)
std::cout << '*';
std::cout << '\n';
}
To calculate the number of spaces needed to center each row use this algorithm:
numSpaces = (23 - x) / 2;
and then a for loop to apply the spaces numSpaces times.
Here is the complete code:
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
int numSpaces = 0;
for(x=1; x <= 23; x++){
if((x%2) != 0){
numSpaces = (23 - x) / 2; // Calculate number of spaces to add
for(int i = 0; i < numSpaces; i++) // Apply the spaces
{
cout << " ";
}
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
And the output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
One way to do
this is to nest two inner loops, one to print spaces and one to print *(s), inside an outer
loop that steps down the screen from line to line.
#include <iostream>
using namespace std;
int main(){
int row = 5;
for(int i=0; i<row; i++){
for(int j=row; j>i; j--){
cout << " ";
}
for(int k=0; k<2*i+1; k++){
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
*
***
*****
*******
*********
This code is in C#, but you can convert it in c++.
class Program
{
static void Main()
{
int n = 5; // Number of lines to print.
for(int i = 1; i<= n; i++){
//loop for print space in the order (4,3,2,1,0) i.e n-i;
for(int j= 1; j<= n-i; j++){
Console.Write(" ");
}
//loop for print * in the order (1,3,5,7,9..) i.e 2i-1;
for(int k= 1; k<= 2*i-1; k++){
Console.Write("*");
}
Console.WriteLine(); // Next Line.
}
}
}
Here's another solution that doesn't use division or if statements
#include <iostream.h>
int main() {
int height = 17, rowLength, i, j, k;
char symbol = '^';
// print a pyramid with a default height of 17
rowLength = 1;
for (i = height; i > 0; i--) { // print a newline
cout << endl;
for (j = 1; j <= i; j++) // print leading spaces
cout << " ";
for (k = 0; k < rowLength; k++) // print the symbol
cout << symbol;
rowLength = rowLength + 2; // for each row increase the number of symbols to print
}
cout << "\n\n ";
return 0;
}
Star pyramid using for loop only:-
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout << "enter the number of rows of pyramid you want : ";
cin >> n;
"\n";
for (int i = 0; i <= n; ++i) {
cout << "\n";
for (int j = 0; j <= n - i; ++j) {
cout << " ";
}
for (int k = 1; k <= i; k++) {
cout << setw(3) << "*";
}
}
return 0;
}
I did that using two loops
here is my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int rows, star, spaces;
int number_of_stars = 5;
int number_of_rows = number_of_stars;
string str1 = "*";
for (rows=1; rows <= number_of_rows; rows++) {
for (spaces=1; spaces <= number_of_stars; spaces++) {
if (spaces==number_of_stars)
{
cout<<str1;
str1+="**";
}
else
cout<<(" ");
}
cout<<("\n");
number_of_stars = number_of_stars - 1;
}
return 0;
}
and the result is
*
***
*****
*******
*********
Url of code on Online compiler
and you can solve it using only one loop, its simple and easy
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfLines=4;
string spaces=string( numberOfLines , ' ' );//this is 4 spaces
string stars="*";
while(spaces!="")
{
cout<<spaces<<stars<<endl;
spaces = spaces.substr(0, spaces.size()-1);
stars+="**";
}
}
Url of code on Online compiler
#include<iostream>
using namespace std;
int for1(int &row);//function declaration
int rows;//global variable
int main()
{
cout<<"enter the total number of rows : ";
cin>>rows;
for1(rows);//function calling
cout<<"just apply a space at the end of the asteric and volla ";
}
int for1(int &row)//function definition
{
for(int x=1;x<=row;x++)//for loop for the lines
{
for(int y=row;y>=x;y--) //for loop for spaces (dynamic loop)
{
cout<<" ";
}
for(int k=1;k<=x*2-x;k++)//for loop for asteric
{
cout<<"* ";/*apply a space and you can turn a reverse right angle triangle into a pyramid */
}
cout<<endl;
}
}