Batool
Batool

Reputation: 79

How to print specific numbers with loop in C?

I have a program where I have to print months and specific numbers of "~". I have one function called: graphLine

    void graphLine(int month,const struct MonthlyStatistic* monthly){

    int totalStars;
    int i;
    int j;

    total = (monthly->totalPrecipitation * 10.0) / 10.0;

    for (j=0;j<total;j++) {
          printf("%d  | ~ \n", month);
    }


}

and I have main function which calls this functions using a loop:

for (i=0;i<12;i++){
    graphLine(i+1,&monthly[i]);
}

the problem is that I want to print specific number of ~ depending on result of variable total in graphLine, but I can't use a loop in graphLine becaue if I do it would overlap with for loop in main. So how can I use a loop in graphLine function, so that I print a result something like this:

1 | ~~~~
2 | ~~~
3 | ~~~~~~~~~
.......

Thanks

Upvotes: 1

Views: 174

Answers (3)

chqrlie
chqrlie

Reputation: 145297

Use this trick:

void print_month_stats(int month, int count) {
    const char *maxbar = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

    printf("%d  | %.*s\n", month, count, maxbar);
}

printf will print count tildes, upto the length of maxbar. This trick is most convenient if you want to print some pattern, such as ----+----+-- or \/\/\/\/\/\/\ or even 1234567890123456789012345.

Upvotes: 2

Gajendra Bagali
Gajendra Bagali

Reputation: 177

Why can't you print month in main and the tildes(~) inside the graphLine function?

In main:

for (i=0;i<12;i++){
   printf("%d | ",i+1); 
   graphLine(i+1,&monthly[i]);
}

And the graphLine function

void graphLine(int month,const struct MonthlyStatistic* monthly){

int totalStars;
int i;
int j;

total = (monthly->totalPrecipitation * 10.0) / 10.0;

for (j=0;j<total;j++) {
      printf("~");
}
printf("\n");

}

Upvotes: 0

John Bode
John Bode

Reputation: 123578

Here's one solution:

total = (monthly->totalPrecipitation * 10.0) / 10.0;

printf( "%d | ", month );
for (j=0;j<total;j++) 
{
  putchar( '~' );
}
putchar( '\n' );

Upvotes: 1

Related Questions