Showing posts with label c histogram printing. Show all posts
Showing posts with label c histogram printing. Show all posts

Wednesday, April 30, 2014

histogram printing

Program to print a histogram pattern for a given array.
For example 
Array   =     4 5 3 2
pattern 
4 5 3 2
   *
* *
* * *
* * * *
* * * *

Outer loop: depends on the maximum element in the array.
The very basic technique to find the maximum element is to assign first element of array as maximum and then subsequently checking it with other array elements and changing the maximum element appropriately.

Inner loop: controls the printing and also depends on maximum element. Find the maximum element and compare it with elements. If the given element is greater than the max element than print "*" otherwise print a space. Decrement the maximum element for a full completion of inner loop. 
                      
Program:

#include<stdio.h>
int main()
{
int a[]={5,7,3,6,4,8,2};
int size=7;
int max=a[0];
int i,j,temp;

for(i=1;i<size;i++)
{
if(max<a[i])
max=a[i];
}

for(i=0;i<size;i++)
     printf("%d ",a[i]);

printf("\n");

temp=max;

for(i=0;i<max;i++)
{
for(j=0;j<size;j++)
{
if(a[j]>=temp)
printf("* ");
else
printf("  ");
        }
temp--;
printf("\n");
}

return 0;
}