vanllabean81

Triangle - Recursion

Jul 11th, 2012
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void mLine (char ch1, char ch2);
  6. void Triangle(char ch1, char ch2) {
  7.    // Last line should have no spaces in it
  8.    static int spaceCounter = 0;
  9.    if (ch1 < ch2) {
  10.       // The previous line should have one extra space
  11.       spaceCounter ++;
  12.       Triangle(ch1, ch2 - 1);
  13.    }
  14.    // Display our spaces
  15.    mLine(' ', spaceCounter);
  16.    // Display our letters
  17.    mLine(ch1, ch2);
  18.    spaceCounter --;
  19.    cout << "\n";
  20. }
  21.  
  22. void mLine(char ch1, char ch2) {
  23.    // Handle our space recursion
  24.    if(ch1 == ' ') {
  25.       // If we still have spaces left
  26.       if(ch2 != 0) {
  27.          cout << ch1;
  28.          mLine(ch1, ch2 - 1);
  29.       }
  30.    }
  31.    else if(ch1 <= ch2) {
  32.       cout << ch1;
  33.       mLine(ch1 + 1, ch2);
  34.       if(ch1 < ch2)
  35.          cout << ch1;
  36.    }
  37. }
  38.  
  39. int main() {
  40.    Triangle ('a', 'm');
  41.    return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment