Sunday, July 12, 2015

Plotting a Chart of Numbers

We will design a program that asks user to enter 9 numbers, all less than 50, and plot a horizontal and vertical chart showing the values of these numbers. Also enter width value for row size.


User Enters 9 Number that less than 50  and Width


After entered these value. Our program looks like below.

Output of the program

Now shall we speak how to develope this algorithmç Firstly our program must read 9 numbers using scanf. The horizontal chart simply displays the value of each number followed by as many *' chars as the value of the number. The vertical chart displays the same information with '*' chars being printed vertically. The value of the number is printed at the bottom of the chart as illustrated.

The width of the charts can be 1,3,5 or 7.In this example 3 is chosen.

Firstly we should write main class.



int main()

{
 int i, max = 0, A[9], width; // Define variables
 printf("Enter 9 number (less than 50)");

 for (i = 0; i<9; i++) 
 {
            scanf("%d", &A[i]);   //Entered numbers assigned to Array

     if (A[i]>max) max = A[i];//store max value among the entered values
 }

 printf("\nEnter width(1,3,5 or 7):");
 scanf("%d", &width);  // read entered width value inside widht variable 
 printf("max is:%d\n", max);
 horizontal(max, A, width);  call method of horizontal with parameters

 vertical(max, A, width);    call vertical method
    getch(); // these for preventing to closing console
 return 0;
}


Now we develope Horizontal method . For parameters we send entered max value, Array of entered integers and width.





int horizontal(int n, int B[9], int w)
{
 int i, j, k, m, t;
 printf("HORIZONTAL CHART:\n", 0);
 for (i = 0; i<9; i++)
 {
 //root of chart
  printf("%7c", 0);//7 char for empty.
  printf("+");
  for (k = 0; k<n; k++)//for root..
  {
   printf("-");
  }
  printf("+\n");
 //end of root 
 
 //begin of body
  for (j = 0; j<w; j++)//loop according to width ( rows size)
   
   if (j == ((w + 1) / 2) - 1)//display entered value in middle of the begin of the shape 
   {
    printf("%4c", 0);
    printf("%3d", B[i]);
    printf("|");

   }
   else                   
   {
    printf("%7c", 0); // for 7 empty chars
    printf("|");
   }

   for (m = 0; m<B[i]; m++)  //loop according to entered numbers (9 integers ) and plot '*' char (column size)
   {
    printf("*");

   }
   for (t = B[i]; t<n; t++)
    printf(" "); // after '*' chars, write empyt char to end of chart
   printf("|");
   printf("\n");
  }
 //end of body 

 }
 
 ////begin floor
 printf("%7c", 0);
 printf("+");
 for (i = 0; i<n; i++)
 {
  printf("-");
 }
 printf("+\n");
 //end floor
 return(0);
}
Now you can build vertical chart yourself. Please review above algorithm and try to understand the logic. Good luck..

No comments:

Post a Comment