semicolon
semicolon

Reputation: 5

Count output in C

My program input is 6 and output is 6! = 6 x 5 x 4 x 3 x 2 x 1 = 720. So i want to count all characters in output including 'x' and space characters. And after that i want to print * as output character number above the output. This is code i used for factorial but i couldn't find how to count characters.

#include <stdio.h>

void fact_calc ( int n );

int main (void)
{
    int number;

    scanf ("%d", &number);
    printf ("%d! = %d x", number, number);
    fact_calc ( number );
}

void fact_calc ( int n )
{
    static long long int total = 1;

    if ( n != 2 && n >= 2 )
    {
        printf (" %d x", n - 1);
        total *= n;
        fact_calc ( n - 1 );
    }
    else
    {
        total *= 2;
        printf (" %d = %lld", n - 1, total);
    }
}

Upvotes: 0

Views: 1728

Answers (3)

acampana
acampana

Reputation: 479

You can add an int count that you increase with every character you add to your output, or you can output it to a file, and count that file size using getline().

Upvotes: 0

user3629249
user3629249

Reputation: 16540

the function: printf() returns the number of characters displayed, so you could simply keep track of the sum of those returned values

Upvotes: 0

P.P
P.P

Reputation: 121347

printf returns the number of character it printed. So you could sum all the return values of printf calls to get the total.

Here's your code modified:

#include <stdio.h>

void fact_calc ( int n, int *count );

int main (void)
{
    int number;
    int count = 0;

    scanf ("%d", &number);
    int t = printf ("%d! = %d x", number, number);
    if (t > 0) count += t;
    fact_calc ( number, &count );
    printf("\nTotal chars printed: %d\n", count);
}

void fact_calc ( int n, int *count )
{
    static long long int total = 1;

    if ( n != 2 && n >= 2 )
    {
        int t = printf (" %d x", n - 1);
        if (t > 0) *count += t;
        total *= n;
        fact_calc ( n - 1, count );
    }
    else
    {
        total *= 2;
        int t = printf (" %d = %lld", n - 1, total);
        if (t > 0) *count += t;
    }
}

Upvotes: 1

Related Questions