C Programming Examples Tutorial Index

C Function Programs

In this C programming example, a C program is demonstrated that performs the task of finding and printing the average number of characters per line of text entered by the user.



Example C Program:
#include <stdio.h>

int line(void); /* Define function prototype. */

void main() {
  /* Variable Declaration and Initialization. */
  int n, c = 0, sum = 0;
  float avg;
  
  printf("Enter some text per line below:\n");
  
  /* Reading the text by line and updating the cumulative counters. */
  while ((n = line()) > 0) {
    sum += n;
    ++c;
  }
  avg = (float) sum / c;
  printf("\nAverage number of characters per line : %5.2f", avg);
}

/* Function Definition - User Defined Function */
int line(void)
/* Reading a line of text and counting the number of characters. */
{
  char l[80];
  int c = 0;
  while ((l[c] = getchar()) != '\n')
    ++c;
  return (c);
}

Program Output:

Enter some text per line below:
Welcome to W3schools.
Here you will have an excellent learning experience.

Average number of characters per line : 36.50


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram