does someone know how I could potray an array like {5, 0, 2, 6} for example, like in the following picture, through a function in c?
I'm new to C, so I could really use some help here :)
This is all I have for now:
#include <stdio.h>
int Diagram(int i, int x, int y, int v[])
{
printf("y \n");
for(i = 0; i <= y; i ){
printf(" |\n");
}
printf(" ");
for(i = 0; i <= x; i ){
printf(" ---");
}
printf(" x");
return 0;
}
int main()
{
int i;
int y = 10;
int x = 5;
int v[4] = {5, 0, 2, 6};
Diagram(i, 5, 10, v);
return 0;
}
CodePudding user response:
As @Eugene said in the comments, the simplest way to tackle this is to create a temporary array, 'draw' into that array, and then print it onto the screen. For example:
void Diagram(int w, int h, int v[]) {
char a[h][w 1];
// initialize with blank lines
for(int y = 0; y < h; y) {
memset(a[y], ' ', w);
a[y][w] = 0;
}
// draw the bars
for(int x = 0; x < w; x)
for(int y = 0; y < v[x] && y < h; y)
a[y][x] = '|';
// print the array onto the screen (in reverse order)
for(int y = h; y --> 0; )
puts(a[y]);
}
int main() {
int v[4] = {5, 0, 2, 6};
Diagram(4, 10, v);
}
This prints:
|
| |
| |
| |
| ||
| ||
I'll leave it for you as an exercise to draw the axes and increase the spacing between the bars. You'll need to increase the size of the array for that (be careful with the math).
CodePudding user response:
I suggest changing the arguments to Diagram
slightly:
#include <stdio.h>
void Diagram(int graph_height, int v[], size_t cols) {
// graph_height the height you want the graph to be
// v[] the values
// cols number of columns in v
}
And you'd call it like so:
int main() {
int graph_height = 10;
int v[] = {8, 5, 0, 2, 6};
Diagram(graph_height, v, sizeof v / sizeof *v);
}
Now, inside Diagram
:
- First loop through all values in
v[]
and find the maximum value. This will be used later to scale the graph. - Let
h
loop from fromgraph_height
to1
(inclusive).- Let
col
loop from0
tocols - 1
(inclusive)- Is
graph_height * v[col] / max >= h
then print!
, otherwise print - Print three spaces
- Is
- Print a newline
- Let
- Finish by printing the
---
line.
Looking closer at graph_height * v[col] / max >= h
:
- In
graph_height * v[col] / max
the result will begraph_height
whenv[col] == max
. The smaller values will be scaled accordingly. If one value ismax / 2
it'll scale to becomegraph_height / 2
. If the result is>= h
the!
should be printed, otherwise