Write a program that finds either the largest or smallest of the ten numbers as
ID: 3812591 • Letter: W
Question
Write a program that finds either the largest or smallest of the ten numbers as command-line arguments. With –l for largest and –s for smallest number, if the user enters an invalid option, the program should display an error message. Example runs of the program: ./find_largest_smallest –l 5 2 92 424 53 42 8 12 23 41 output: The largest number is 424 ./find_largest_smallest –s 5 2 92 424 53 42 8 12 23 41 output: The smallest number is 2 1) Name your program numbers.c. 2) Use atoi function in to convert a string to integer form. 3) Generate the executable as find_largest_smallest.
Explanation / Answer
//Save in file numbers.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int findLargest(char *argv[], int n)
{
int i = 2;
int max = atoi(argv[i]);
for(i = 3; i < n+2; i++)
{
if (max < atoi(argv[i]))
{
max = atoi(argv[i]);
}
}
return max;
}
int findSmallest(char *argv[], int n)
{
int i = 2;
int min = atoi(argv[i]);
for(i = 3; i < n+2; i++)
{
if (min > atoi(argv[i]))
{
min = atoi(argv[i]);
}
}
return min;
}
int main(int argc, char *argv[])
{
if( argc != 12 ) {
printf("To find largest among 10 nmbers ");
printf("Usage ./find_largest_smallest -l <10 numbers seprated with sapce> ");
printf(" ");
printf("To find smallest among 10 nmbers ");
printf("Usage ./find_largest_smallest -s <10 numbers seprated with sapce> ");
return 1;
}
int result;
if (strcmp(argv[1], "-l") == 0)
{
result = findLargest(argv, 10);
printf("output: The largest number is %d ", result);
}
else
{
if (strcmp(argv[1], "-s") == 0)
{
result = findSmallest(argv, 10);
printf("output: The smallest number is %d " , result);
}
else
{
printf("incorrect option. Exiting...");
return 1;
}
}
return 0;
}
// compile using
// gcc numbers.c -o find_largest_smallest
// Sample run
$ ./find_largest_smallest -l 5 2 92 424 53 42 8 12 23 41
output: The largest number is 424
$ ./find_largest_smallest -s 5 2 92 424 53 42 8 12 23 41
output: The smallest number is 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.