Friday, February 10, 2012

Program to print a traingle and a diamond

WAP to print a triangle with any special character

Triangle:
#include<stdio.h>
#include<iostream>

int main()
{
   int row, c, n, temp;

   printf("Enter the number of rows in pyramid of stars you wish to see ");
   scanf("%d",&n);

   temp = n;

   for ( row = 1 ; row <= n ; row++ )
   {
      for ( c = 1 ; c < temp ; c++ )
         printf(" ");

      temp--;

      for ( c = 1 ; c <= 2*row - 1 ; c++ )
         printf("*");

      printf("\n");
   }
   system("pause");
   return 0;
}

Right Angled Triangle:
#include<stdio.h>
 
main()
{
    int n, c, k;
 
    printf("Enter number of rows\n");
    scanf("%d",&n);
 
    for ( c = 1 ; c <= n ; c++ )
    {
        for( k = 1 ; k <= c ; k++ )
            printf("*");
 
        printf("\n");
    }
 
    return 0;
}

Diamond:
#include <iostream.h>
#include <conio.h>

int main()
{
  int i,j,k,s,n,m;
  clrscr();
  cout << "Enter the value of m: ";
  cin >> m;
  n = (2*m)-1;
  for(i = 1, s = n; i <= n; i++,s--)
  {
  for(k = 1; k < s; k++)
    cout << " ";
    for(j = 1; j <= i; j++)
      {
    cout << "* ";
      }
      cout << "\n";
  }

 for(i = (n-1), s = 1; i >= 1; i--, s++)
 {
  for(k = 1; k <= s; k++)
    cout << " ";
    for(j = 1; j <= i; j++)
    {
    cout << "* ";
    }
    cout << "\n";
  }
  getch();
     return 0;
}

No comments:

Post a Comment