HomeC ProgrammingC Program to Print the Program Name and All its Arguments

C Program to Print the Program Name and All its Arguments

This C program prints the name of the program and all its command-line arguments.

In C programming, command-line arguments allow us to pass inputs to a program when it is executed. These arguments can provide additional information or parameters to control the behavior of the program. In this context, we will develop a C program that prints the program name and all the arguments passed to it.

Problem statement

Write a C program that accepts command-line arguments and prints the program name followed by each argument, along with their respective indices.

C Program to Print the Program Name and All its Arguments

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Program Name: %s\n", argv[0]);

    printf("Arguments:\n");
    for (int i = 1; i < argc; i++) {
        printf("%d: %s\n", i, argv[i]);
    }

    return 0;
}

How it works

  1. The program starts by including the necessary header file stdio.h for input and output operations.
  2. The main function is the entry point of the program and accepts two parameters: argc and argv. argc represents the number of command-line arguments, while argv is an array of strings containing those arguments.
  3. The program uses the printf function to display the program name (argv[0]) using the format specifier %s.
  4. It then prints the header “Arguments:” to indicate the list of command-line arguments.
  5. A for loop is used to iterate over the command-line arguments starting from index 1 (since argv[0] contains the program name).
  6. Within the loop, the program uses printf to display the index of each argument (i) along with the argument itself (argv[i]).
  7. Finally, the return 0; statement signifies the successful execution of the program.

Input/output

C Program to Print the Program Name and All its Arguments

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...