C Program to Count the Total Number of Words using Command Line Argument

This C Program counts total number of words in the sentence using command line argument.

Here is source code of the C Program to Count the total number of words in the sentence using command line argument. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Count the Total Number of Words in the Sentence 
  3.  * using Command Line Argument
  4.  */
  5. #include <stdio.h>
  7. int main(int argc, char *argv[])
  8. {
  9.     int i = 0;
  11.     /* If no sentence is given in the command line */
  12.     if (argc == 1)
  13.     {
  14.         printf("\n No sentence given on command line");
  15.         return;
  16.     }
  17.     else
  18.     {
  19.         printf("\nThe words in the sentence are:");
  20.         /*
  21.          * From argv[1] to argv[argc -1] calculate the number of arguments
  22.          */
  23.         for (i = 1;i < argc;i++)
  24.         {
  25.             printf("\n%s", argv[i]);
  26.          }
  27.         printf("\n\nTotal number of words:");
  28.         printf(" %d", argc-1);
  29.     }
  30. }

$ gcc arg1.c
$ a.out Welcome to C Class
The words in the sentence are:
Total number of words: 4
No sentence given on command line

Sanfoundry Global Education & Learning Series – 1000 C Programs.


Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.