I saw the following as an exercise in a website. It basically says write the following function without using recursion and without using structures like vector, stack, etc:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
At first I thought it was going to be easy, but I'm suprisingly struggling to accomplish it.
To understand it better, I defined it like a math function as the following:
f(x) = {1 if x = 0, f(x-1) + f(x-1) otherwise} (where + operator means concatenation and - is the normal minus)
However, Unrolling this made it harder, and I'm stuck. Is there any direct way to write it as a loop? And also, more generally, is there an algorithm to solve this type of problems?
If you fiddle with it enough, you can get at least one way that will output the ordered sequence without revisiting it :)
let n = 5
// Recursive
let rec_str = ''
function rec(n) {
if (n != 0) {
rec_str += n
rec(n-1);
rec(n-1);
}
}
rec(n)
console.log(rec_str)
// Iterative
function f(n){
let str = ''
for (let i=1; i<1<<n; i++){
let t = i
let p = n
let k = (1 << n) - 1
while (k > 2){
if (t < 2){
break
} else if (t <= k){
t = t - 1
p = p - 1
k = k >> 1
} else {
t = t - k
}
}
str += p
}
console.log(str)
}
f(n)
(The code is building a string, which I think should be disallowed according to the rules, but only for demonstration; we could just output the number instead.)
void loop(int n)
{
int j = 0;
int m = n - 1;
for (int i = 0; i < int(pow(2, n)) - 1; i++)
{
j = i;
if (j == 0)
{
std::cout << n << " ";
continue;
}
m = n - 1;
while (true)
{
if (m == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
if (j >= int(pow(2, m)))
{
j = j - int(pow(2, m)) + 1;
}
if (j == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
else
{
j--;
}
m--;
}
}
std::cout << std::endl;
}
For n = 3 for instance
out = [3 2 1 1 2 1 1]
indexes = [0 1 2 3 4 5 6]
Consider the list of indexes; for i > 0 and i <= 2^(m) the index i has the same value as the index i + 2^(m)-1 where m = n - 1. This is true for every n. If you are in the second half of the list, find its correspondent index in the first half by this formula. If the resulting number is 1, the value is m. If not, you are in a lower level of the tree. m = m - 1 and repeat until the index is 1 or m =1, in which case you've reached the end of the tree, print 1.
For instance, with n = 4, this is what happens with all the indexes, at every while step. p(x) means the value x gets printed at that index. A / means that index has already been printed.:
n = 4,m = 3
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
m = 3
[p(n=4) 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
if(i >=2^3) -> i = i -2^3 + 1)
[/ 1 2 3 4 5 6 7 1 2 3 4 5 6 7]
if(i == 1) -> print m, else i = i -1
[/ p(3) 1 2 3 4 5 6 p(3)1 2 3 4 5 6]
m = 2
if (i >=2^2) -> i = i - 2^2 +1
[/ / 1 2 3 1 2 3 / 1 2 3 1 2 3]
if(i == 1) -> print m, else i = i -1
[ / / p(2) 1 2 p(2) 1 2 / p(2) 1 2 p(2) 1 2]
m = 1
if (m == 1) -> print(m)
[ / / / p(1) p(1) / p(1) p(1) / / p(1) p(1) / p(1) p(1)]
Therefore the result is:
[4 3 2 1 1 2 1 1 3 2 1 1 2 1 1]
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
Idea is to save result from the previous computation of each number. Full code:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
int main() {
int n = 5;
cout << "Rec : ";
rec(n);
cout << endl;
cout << "Loop: ";
via_loop(n);
cout << endl;
}
Output:
Rec : 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Loop: 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Related
I was creating a Pascal's triangle program in C++, but the output displayed is not as expected.
Output Expected
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Output got
1
1 1
1 2 1
1 3 3 1
1 2 2 2 1
1 6 6 6 6 1
Till i = 4, output displayed is correct, but after that I couldn't figure out how it goes wrong. Hers is the source code to get reviewed
int main()
{ int num, a[37680], t = 0, b = 2, l;
cout<<"Enter the number of rows: ";
cin>>num;
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= (num - i); j++)
{
cout<<" ";
}
for (int k = 1; k <= i; k++)
{
l = k;
if (k == 1 || k == i)
{
a[t] = 1;
cout<<a[t]<<" ";
t+=1;
}
else
{
a[t] = a[t - b] + a[t - b - 1];
cout<<a[t]<<" ";
t+=1;
if ( l = (i - 1) )
{
b+=1;
}
}
}
cout<<endl;
}
return 0;}
Equality checking in c++ is done using == and not =, so:
if(l=(i-1))
Should be:
if(l==(i-1))
I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)
My question looks like this
For numbers from 2 to 20, output the proper divisors and their sum.
So it should look like this:
2: 1 = 1
3: 1 = 1
4: 1+2 = 3
5: 1 = 1
6: 1+2+3 = 6
...
20: 1+2+4+5+10 = 23
This is what i wrote so far:
#include <iostream>
int main () {
int a=2;
int sum=1;
while (a<=10){
std::cout<<a<<": ";
for(int b=1; b<a; b=b+1)
{
if(a%b == 0)
{
std::cout<<b<<" + ";
sum+=b;}
if (b == a-1){
std::cout<<"= "<<sum<<"\n";
}
}
a++;
}
return 0;
}
When i compile and run, the output ends up looking like this:
2: 1 + = 2
3: 1 + = 3
4: 1 + 2 + = 6
5: 1 + = 7
6: 1 + 2 + 3 + = 13
7: 1 + = 14
8: 1 + 2 + 4 + = 21
9: 1 + 3 + = 25
10: 1 + 2 + 5 + = 33
My issues are currently:
Why does it give me the sum of all of the previous b results? I am trying to get the sum of only the divisors for each number. It gives me the sum of all previous sums.
Also, how do i get rid of the extra (+) at the end?
Many thanks!
EDIT:
Thanks guys! Here's the code after i adjusted it and cleaned it up a little bit!
#include <iostream>
int main() {
int a = 2;
while (a <= 20) {
std::cout <<a <<": ";
int sum = 0;
for (int b = 1; b < a; b = b + 1) {
if (a%b == 0) {
if (b == 1) {
std::cout <<b;
} else {
std::cout <<" + " <<b; }
sum += b; }
if (b == a-1) {
std::cout <<"= " <<sum <<"\n";
}
}
a++;
}
return 0;
}
It now works like a charm. The output has a few too many whitespaces but its good enough. Many thanks!
You need to reset the value of sum to zero at the beginning of each iteration of the while loop to avoid the multiple sum problem.
As far as the extra +, you could print "+" before the value of 'b' instead of after, and only if b > 1 (there is guaranteed a printed value before the current value of b).
Try something like this it uses this answer for not adding the + after the last item of divisors:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main()
{
for(size_t i = 2; i <= 20; ++i)
{
std::vector<int> divisors = properDivisors(i);
std::cout << i << ": ";
const char *padding = "";
for (auto iter = divisors.begin(); iter != divisors.end(); ++iter) {
std::cout << padding << *iter;
padding = " + ";
}
int sum = 0;
for (auto& n : divisors)
sum += n;
std::cout << " = " << sum;
std::cout << std::endl;
}
}
Output:
2: 1 = 1
3: 1 = 1
4: 1 + 2 = 3
5: 1 = 1
6: 1 + 2 + 3 = 6
7: 1 = 1
8: 1 + 2 + 4 = 7
9: 1 + 3 = 4
10: 1 + 2 + 5 = 8
11: 1 = 1
12: 1 + 2 + 3 + 4 + 6 = 16
13: 1 = 1
14: 1 + 2 + 7 = 10
15: 1 + 3 + 5 = 9
16: 1 + 2 + 4 + 8 = 15
17: 1 = 1
18: 1 + 2 + 3 + 6 + 9 = 21
19: 1 = 1
20: 1 + 2 + 4 + 5 + 10 = 22
Try it here!
I am trying to get this number pattern
Input: 7
Output:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
But I can't figure out how to make it like that, any suggestion how to make that pattern??
My code so far :
int n, temp1, temp2,i,j;
cin >> n;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
temp1 = j;
temp2 = n-j+1;
if (temp1 < temp2) cout << temp1;
else cout << temp2;
}
cout << endl;
}
The output so far is
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
Thanks in advance.
I hope this code(working) might give you a better idea about the implementation.
int main() {
int n;
cin >> n;
int arr[n][n];
//Numbers in the grid vary from 1 - (n/2 + 1)
for(int i = 0; i <= n / 2; i++) {
//Start filling the array in squares
//Like fill the outer square with 1 first followed by 2...
for(int j = i; j < n - i; j++) {
arr[i][j] = i + 1;
arr[n - 1 - i][j] = i + 1;
arr[j][i] = i + 1;
arr[j][n - 1 - i] = i + 1;
}
}
The main thing that solves the problem is to divide this square into 4 quadrants:
---n-->
111|222 |
111|222 |
111|222 |
------- n
333|444 |
333|444 |
333|444 v
Each quadrant can be presented with limits:
1 - row <= (n + 1) / 2 && column <= (n + 1) / 2
2 - row <= (n + 1) / 2 && column > (n + 1) / 2
3 - row > (n + 1) / 2 && column <= (n + 1) / 2
4 - row > (n + 1) / 2 && column > (n + 1) / 2
Then every quadrant has to be divided into two slices
\ | /
\ | /
\|/
-------
/|\
/ | \
/ | \
These diagonals can be described using equations:
column_index = row_index
column_index = (n + 1) - row_index
Right now you just have to check if current 'cell' is under or above one of the diagonals, and use row or column index accordingly. Of course if row or column index is larger than (n + 1) / 2 then you have to adjust by subtracting it from n.
If you understand this, writing your own code shouldn't be a problem. It is good idea if you have to print everything immediately without storing it in some kind of array. If you can use array then #baymaxx solution is a lot cleaner.
It is my code if you would like to compare your implementation:
#include <iostream>
int main() {
int n;
std::cin >> n;
for (int row_index = 1; row_index <= n; row_index++) {
for (int column_index = 1; column_index <= n; column_index++) {
if (row_index <= (n + 1) / 2 && column_index <= (n + 1) / 2) {
if (column_index < row_index) {
std::cout << column_index << " ";
} else {
std::cout << row_index << " ";
}
} else if (row_index <= (n + 1) / 2 && column_index > (n + 1) / 2) {
if (column_index < (n + 1) - row_index) {
std::cout << row_index << " ";
} else {
std::cout << (n + 1) - column_index << " ";
}
} else if (row_index > (n + 1) / 2 && column_index <= (n + 1) / 2) {
if (column_index < (n + 1) - row_index) {
std::cout << column_index << " ";
} else {
std::cout << (n + 1) - row_index << " ";
}
} else {
if (column_index > row_index) {
std::cout << (n + 1) - column_index << " ";
} else {
std::cout << (n + 1) - row_index << " ";
}
}
}
std::cout << "\n";
}
}
I was trying to write a code that would display pascals triangle. Instead of displaying the result as :
my result is displayed as
1
1 1
1 2 1
1 3 3 1
Please help me figure out how to modify it to be able to get the actual triangle. I cant use arrays and pointers since those aren't covered in my class yet. Here's my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
cin >> n;
PascalsTriangle(n);
return 0;
}
void PascalsTriangle (int n){
int i,j,x;
for(i=0;i<n;i++)
{
x=1;
for(j=0;j<=i;j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}
Here is the updated version. Works for any n. I've added a function to return the number of digits in a number since that computation is needed each iteration of the inner loop.
#include <iostream>
#include <string>
using namespace std;
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
cin >> n;
cout << endl;
PascalsTriangle(n);
return 0;
}
int numdigits(int x)
{
int count = 0;
while(x != 0) {
x = x / 10;
++count;
}
return count;
}
void PascalsTriangle (int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
len = string((n-i-1)*(n/2), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x) - 1;
if(n % 2 == 0)
cout << y << string(n - 1 - maxlen, ' ');
else {
cout << y << string(n - 2 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUTS:
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
UPDATE for a more tighter triangle:
void PascalsTriangle(int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
if(n % 2 != 0)
len = string((n-i-1)*(n/2), ' ');
else
len = string((n-i-1)*((n/2)-1), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x);
if(n % 2 == 0)
cout << y << string(n - 2 - maxlen, ' ');
else {
cout << y << string(n - 1 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
Try this :
#include <iostream>
using namespace std;
int main()
{
int n,k,i,x;
cout << "Enter a row number for Pascal's Triangle: ";
cin >> n;
for(i=0;i<=n;i++)
{
x=1;
for(k=0;k<=i;k++)
{
cout << x << " ";
x = x * (i - k) / (k + 1);
}
cout << endl;
}
return 0;
}
EDITED:
#include <iostream>
using namespace std;
int main()
{
int n,coef=1,space,i,j;
cout<<"Enter number of rows: ";
cin>>n;
for(i=0;i<n;i++)
{
for(space=1;space<=n-i;space++)
cout<<" ";
for(j=0;j<=i;j++)
{
if (j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
cout<<" "<<coef;
}
cout<<endl;
}
}
Do you expect this result?
1111
123
13
1
You need to add endl or constant string equivalent to "\r\n" to the end of the output string, or use commas in output, then, for example:
"1111,123,13,1"
"1,11,121,1331"
If you want it to look like a 'triangle', that is, a symmetric looking isosceles triangle, try this code for your PascalTriangle function. The only problem with this is that when you get larger digits, it will break some of the symmetry but up to 5 rows it'll work fine.
void PascalsTriangle(int n)
{
int i, j, x;
string len;
for(i = 0; i < n; i++)
{
x = 1;
len = string(n - i - 1, ' ');
cout << len;
for(j = 0; j <= i; j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
As opposed to:
Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
#include <iostream>
using namespace std;
const int MAXC = 13; //-- Max column constant
const int MAXF = 7; //-- Max row constant
int m, n, k, x, y; //-- Counters and accumulators for loops
int arrayTriangulo[MAXF][MAXC]; // Array that stores the values of the Pascal Triangle
int main() {
m = (MAXC/2); // Middle Column
k = (MAXC/2); // Middle row
//-- 1.- Fill in the Array from Left to Right and from Top to Bottom
//-- 2.- Fill in the Array starting from row 0 through 13 (MAXF)
for ( x = 0; x < MAXF; x++ ) {
n = 1;
//-- 3.- Fill in the Array starting from Column 0 through 7 (MAXC)
for ( y = 0; y < MAXC; y++ ) {
//-- Assign 0 to the Array element that is not part of the triangle.
arrayTriangulo[x][y] = 0;
//-- 4.- If it is on the edges of the triangle assigns the value of "n". Which we initialize in 1.
if (( y == m ) || ( y == k )) {
arrayTriangulo[x][y] = n;
}
//-- 5.- For the rest of the internal values of the triangle other than the edges.
//-- The sum of the value is assigned (upper left row -1) + (upper right row + 1)
if ( ( x > 1 ) && ( x < MAXF ) && ( y < MAXC-1 ) ) {
arrayTriangulo[x][y] = arrayTriangulo[x-1][y-1] + arrayTriangulo[x-1][y+1];
}
//-- 6.- Finally Draw the Triangle by omitting the values at zero.
if ( arrayTriangulo[x][y] > 0 )
cout << arrayTriangulo[x][y] << " ";
else
cout << " ";
}
cout << endl;
m--;
k++;
}
return 0;
}