Showing posts with label Loop. Show all posts
Showing posts with label Loop. Show all posts

Monday, December 3, 2012

Pascal's Triangle programm using c++

The way to compute any given position's value is to add up the numbers to the position's right and left in the preceding row. For instance, to compute the middle number in the third row, you add 1 and 1; the sides of the triangle are always 1 because you only add the number to the upper left or the upper right (there being no second number on the other side).
The program should prompt the user to input a row and a position in the row. The program should ensure that the input is valid before computing a value for the position.

#include <iostream>
using namespace std;

int compute_pascal(int row, int position)
{
 if(position == 1)
 {
  return 1;
 }
 else if(position == row)
 {
  return 1;
 }
 else
 {
  return compute_pascal(row-1, position) + compute_pascal(row-1, position-1);
 }
}
int main()
{
        int row, position;
        cout<<"Please input a row and a position along the row: ";
        cin>>row>>position;
        if(row<position)
        {
                cout<<"Invalid entry.  Position must be less than or equal to row.";
                return 0;
        }
        cout<<"Value at row "<<row<<" and position " <<position<<" is "<<compute_pascal(row, position);
}

Printing Patterns Using Asterisks in c++

It is a very common question for both C and C++ programmers that printing a diamond shape using asterisks (*) and this question is going to be ask in almost every freaking semester ;) .There are a lot of different ways to do that. But among them I found this one easier. Those who likes to use C code for printing diamond just change the header #include<iostream> to #include<stdio.h>, cout to printf and cin to scanf.Lets start the fun :)

#include<iostream>

#include<cstdlib>

using namespace std;

int main()

{

int i=0, j=0, NUM=3;

for(i=-NUM; i<=NUM; i++)

{

for(j=-NUM; j<=NUM; j++)

{

if( abs(i)+abs(j)<=NUM) // Change this condition

 { cout<<"*"; }

else { cout<<" ";}

}

cout<<endl;

}
return 0;
}

The above code will prints-
 *
***
*****
*******
*****
***
*
 Wait I haven’t done yet. You can have fun with it. Just change the ‘ if ‘ condition. You will get new design :) . Wanna see???. Lets take a look-



if( abs(i)*abs(j)<= NUM)
prints-
***
***
*******
*******
*******
***
***


if( abs(i)*abs(j)<= NUM)
prints-
*
*  *
*      *
*          *
*      *
*  *
*


if(abs(i)==abs(j)
prints-
*          *
*      *
*  *
*
*  *
*      *
*          *


if( abs(i)==0||abs(j)==0)
prints-
*
*
*
*******
*
*
*


if(abs(i)>=abs(j))
prints-
*******
*****
***
*
***
*****
*******


if(abs(i)<=abs(j))
prints-
*          *
**      **
***  ***
*******
***  ***
**      **
*          *

That’s it. Just change the condition and have fun with it. ENJOY !