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

Advertisements
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.

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

If you wish to look at programming examples on all topics, go to C Programming Examples.
Advertisements
Subscribe Newsletter & Posts

Manish Bhojasia, a technology veteran with 17+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer and SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage & Cluster Administration, Advanced C Programming, SAN Storage Technologies, SCSI Internals and Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him below.

Practice Interview Questions & Answers, Quizzes, Objective, Multiple Choice Aptitude Tests for Freshers and Experienced People in these topics - Learn C, C++, Java and C# Programming with coding example on Simple problems as well as tough Algorithms and Data-structures along with runtime output: - C Programs, Data-Structures and Algorithms, C++ Algorithms, Java Algorithms, C# Programs, Android Programs in Java

C Tutorials and Linux Commands Tutorial - C Tutorials, Linux Commands

Career Mentoring with our Founder / CTO - Read More
Advertisements

Follow Manish & Sanfoundry