We were asked to make a triangular no.number pattern in c++C++ with min.minimum loops. The triangle pattern is as follows:
____1_____
___2__3____
__4__5__6__
7__8__9__10
____1_____ ___2__3____ __4__5__6__ 7__8__9__10
Code:
#include <iostream>
using namespace std;
int main() {
int n=0, r=0, i=0;
cout << "No. of rows: ";
cin >> r;
for( n=1; n<=r; n++) {
for( i=1; i<=r-n; i++) {
cout << " ";
}
for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
if( i<10 )
cout << " " << i << " ";
else
cout << i << " ";
}
cout << "\n";
}
return 0;
}
Output:
Here's what I'd like reviewed:
- Is it wise to use pattern generating-generating formulas? for egFor example, for putting value of i
i
in the last loop, iI used the formula for the pattern \$1,2,4,7\$... as \$\frac{n*(n-1)}{2}+1\$. Is it efficient? This involves four operations in each iteration, and it's fairly slow. - Is it possible to reduce the number of loops? Is it better to reduce variables or reduce loops?