Command line programs are an essential part of any developer’s toolkit. They provide efficient ways to execute tasks, automate processes, and interact with the system using minimal resources. In this article, we’ll walk through five essential C programs that you can run via the command line. These programs include:
Each program is structured to accept input from the command line, making them highly versatile and useful in real-world scenarios.
This program generates the Fibonacci series up to a given number of terms.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n, first = 0, second = 1, next, c;
if (argc < 2) {
printf("Usage: %s <number_of_terms>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
printf("First %d terms of Fibonacci series:\n", n);
for (c = 0; c < n; c++) {
if (c <= 1)
next = c;
else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
printf("\n");
return 0;
}
./fibonacci 10
This program finds the greatest number among multiple command-line arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <num1> <num2> ...\n", argv[0]);
return 1;
}
int i, greatest = atoi(argv[1]);
for (i = 2; i < argc; i++) {
int num = atoi(argv[i]);
if (num > greatest) {
greatest = num;
}
}
printf("Greatest number is: %d\n", greatest);
return 0;
}
./greatest 12 45 67 89 23
This program calculates the factorial of a given number.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
int n = atoi(argv[1]);
unsigned long long factorial = 1;
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", n, factorial);
return 0;
}
./factorial 5
This program reverses a given string input via command line arguments.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <string>\n", argv[0]);
return 1;
}
char *str = argv[1];
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
printf("Reversed string: %s\n", str);
return 0;
}
./reverse hello
This program swaps two numbers entered as command-line arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <num1> <num2>\n", argv[0]);
return 1;
}
double first = atof(argv[1]);
double second = atof(argv[2]);
double temp = first;
first = second;
second = temp;
printf("After swapping: First Number = %.2lf, Second Number = %.2lf\n", first, second);
return 0;
}
./swap 10 20
These command-line C programs provide a solid foundation for learning and implementing problem-solving techniques in programming. Each program demonstrates a fundamental concept, including loops, conditionals, and string manipulation, making them great exercises for beginners and professionals alike.