Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

you need to write a C function named start. The prototype is: int start(int argc

ID: 3593599 • Letter: Y

Question

you need to write a C function named start. The prototype is:

int start(int argc, char **argv);

The function accepts an argc and argv that are passed to main.
The return value is as follows:

if argc<>2, return -1
if argc==2, then return the following:

if argv[1] is not an integer, return -2
if argv[1] is an integer but is not positive, return -3
otherwise argv[1] is a positive integer: return its value

You must use sscanf (as usual). Be sure to check the return value from sscanf
to determine whether or not its argument represents an integer.

Write your own main test function to test your start function.

Explanation / Answer

#include<stdio.h>

/*

Here, different cases are:

Case 1: if argc<>2, return -1

Case 2: if argc==2, argv[1] is not an integer, return -2

Case 3: if argc==2, argv[1] is an integer but is not positive, return -3

Case 4: if argc==2, argv[1] is a positive integer: return its value

Following is the output of the program:

For Case1 : -1

For Case2 : -2

For Case3 : -3

For Case4 : 4

*/

int start(int argc, char **argv)

{

int n; //Variable to which the argv[1] will be assigned if it is an integer

if(argc==2)

{

if (sscanf(argv[1], "%d", &n) != 1) //If argv[1] is an integer, it is assigned to n, else -2 is returned

{

return -2;

}

else

{

if(n<0) //If argv[1] is negative integer, return -3

{

return -3;

}

else //Assuming 0 is positive integer, because there is no special case given in question

{

return n; //If argv[1] is positive integer, return the integer

}

}

}

else

{

return -1; //If argv[1] is <> 2, return -1

}

}

int main()

{

//Case 1: if argc<>2, return -1

char * argv_case1[2];

argv_case1[0] = "1";

argv_case1[1] = "2"; //This will be value of argv[1] in start function

int returned_value = start(1, argv_case1);

printf("For Case1 : %d ",returned_value);

//Case 2: if argc==2, argv[1] is not an integer, return -2

char * argv_case2[2];

argv_case2[0] = "1";

argv_case2[1] = "a"; //This will be value of argv[1] in start function

returned_value = start(2, argv_case2);

printf("For Case2 : %d ",returned_value);

//Case 3: if argc==2, argv[1] is an integer but is not positive, return -3

char * argv_case3[2];

argv_case3[0] = "1";

argv_case3[1] = "-1"; //This will be value of argv[1] in start function

returned_value = start(2, argv_case3);

printf("For Case3 : %d ",returned_value);

//Case 4: if argc==2, argv[1] is a positive integer: return its value

char * argv_case4[2];

argv_case4[0] = "1";

argv_case4[1] = "4"; //This will be value of argv[1] in start function

returned_value = start(2, argv_case4);

printf("For Case4 : %d ",returned_value);

return 0;

}