I am writing a program that finds if either -l
for find largest or -s
for find smallest appears when the user inputs the string into the command line. For example ./a.out -l 2 4 6
would find the largest of the users input. In my program I am unsure if I should use atoi
or if I can get by without. Also am I able to use the a pointer for the first part of my program and user the actual array in the second half to find the smallest or largest number? Since the ./a.out
and -l
is stored in array[0]
and array [1]
can I skip those and still find the largest and smallest numbers? I have written the code to find the largest and smallest number in an array but I am unsure if it is compatible. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int x,i;
for(; *argv != '\0'; argv++){ //checks to see if -l is in string
if (strcmp(*argv,"-l") == 0){
x = 1; //easier to use x value than nested fors and ifs
break;
}
if(strcmp(*argv,"-s") == 0){ //checks if -s is in string
x = 2;
break;
}
else{ //if neither
printf("Error invalid option");
break;
}
}
if(x == 1){ //is going to find the largest element
for(i=2;i<argc;++i){
if(argv[2]<argv[i])
argv[2]=argv[i];
}
printf("Largest element is %d", argv[2]);
}
if( x == 2){ //find smallest element
for(i=2;i<argc;++i){
if(argv[2]>argv[i])
argv[2]=argv[i];
}
printf("Smallest element is %d", argv[2]);
}
return 0;
}