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>
  6.  
  7. int main(int argc, char *argv[])
  8. {
  9.     int i = 0;
  10.  
  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:
Welcome
to
C
Class
 
Total number of words: 4
 
a.out
 
No sentence given on command line

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

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.

advertisement
advertisement
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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.