C/c

Advertisement


Question
sir
please give me a recursive program in c using functions to print pascal's triangle with 0,1

Answer
Here is the code to print the lines of a Pascal's Triangle.  Note that there is no attempt here to shift the lines to make them look more like a standard triangle.  Think of this as Pascal's Right Triangle, perhaps. :)  I'm also not cleaning up dynamic memory in this, nor am I doing any error checking (such as verifying that the _prevRow pointer isn't NULL).  This is purely an algorithm demonstration, not production-quality code.  If you have further questions, feel free to ask.

#include <stdio.h>
#include <malloc.h>

void pascalTri(int* _prevRow, int _prevRowSize, int _rowsToPrint);

int main()
{
   int startRow = 1;
   pascalTri(&startRow, 1, 16);
}

void pascalTri(int* _prevRow, int _prevRowSize, int _rowsToPrint)
{
   int i;
   for (i = 0; i < _prevRowSize; ++i)
   {
       printf("%d ", _prevRow[i]);
   }
   printf("\n");

   if (_rowsToPrint > 1)
   {
       int* newRow = malloc(sizeof(int) * _prevRowSize + 1);
       
       newRow[0] = newRow[_prevRowSize] = 1;
       for (i = 1; i < _prevRowSize; ++i)
       {
           newRow[i] = _prevRow[i - 1] + _prevRow[i];
       }

       pascalTri(newRow, _prevRowSize + 1, _rowsToPrint - 1);
   }
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2012 About.com, a part of The New York Times Company. All rights reserved.