Friday, October 26, 2012

Generating Various Patterns Using Loops

Implementing m pattern using 'c'
M Pattern

Code :


main()
{
int i,j,n;
printf("Enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
  for(j=0;j<(4*n-1);j++)
    {
     if(i==(n-1))
       printf("*");
   else
  {
     if((j<(2*i+1))||(j>=((4*n-1)-(2*i+1))))
       printf("*");
     else
       printf(" ");
  }
  }
printf("\n");
}
}


x pattern using 'C'
xpattern

Code :

main()
{
unsigned short int i,j,n;
printf("Enter N:\n");
scanf("%hu",&n);
for(i=0;i<=(2*n);i++)
{
for(j=0;j<=n;j++)
{
  if(i<=n)
  {
     if(j<(i))
       printf(" ");
     else
       printf("* ");
  }
  else
    {
    if((n-j)>(i-n))
     printf(" ");
     else
      printf("* ");
    }
  }
   printf("\n");
}
}


generatin various patterns using Loops
Bit Pattern Reversal

Code:

main()
{
int n,num,i;
printf("Input A Number:");
scanf("%d",&num);
n=sizeof(num)*8-1;
printf("Original Bit Pattern:");
for(i=n;i>=0;printf("%d",(num>>i)&1),i--);
for(i=0;i<=n/2;i++)
{
  if(((num>>i)&1)!=((num>>(n-i))&1))
  {
   num ^= (1<<i);
   num ^= (1<<(n-i));
  }
}
printf("\nReversed Bit Pattern:");
for(i=n;i>=0;printf("%d",(num>>i)&1),i--);
printf("\n");
}