Please i need help to fix my code. This is a C code and it compiles, some of the
ID: 3668352 • Letter: P
Question
Please i need help to fix my code. This is a C code and it compiles, some of the error checking works but it doesnt return the correct result The program is supposed to compare 3 integers and return the maximum number, I don't know what i did wrong.........This for a system programming class
Instructions:
Write a program, named max, that reads three integers from standard input and returns the max integer on the standard output screen, For instance,
>max 3 5 7
>The maximum value is 7.
>max 4 0 9
>The maximum value is 9
>max 1 p 9
>max: invalid input p.
>max
>usage: max num1 num2 num3!
#include <stdio.h>
#include <stdlib.h> //atoi()
#include <string.h> //strcmp()
main(int argc, char * argv[])
{
//step1: error checking
//step1-1: format check, check the number of arguments. If the format is wrong, print out the message
if (argc != 3)
{
printf("usage: max num1 num2 num3! ");
exit(1);
}
//step1-2: input check, check if the input numbers are invalid. Use atoi() function
//be noted that the command line arguments are strings
int a, b, c;
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
//This atoi() returns the converted integral number as an int value.
//If no valid conversion could be performed, it returns zero.
//use strcmp() to verify when converted number is equal zero
if (a == 0 && strcmp(argv[1], "0") !=0) //invalid input case
{
printf("max: invalid integer number %s ", argv[1]);
exit(1); //failure return
}
if (b == 0 && strcmp(argv[2], "0") !=0) //invalid input case
{
printf("max: invalid integer number %s ", argv[2]);
exit(1); //failure return
}
if (c == 0 && strcmp(argv[3], "0") !=0) //invalid input case
{
printf("max: invalid integer number %s ", argv[3]);
exit(1); //failure return
}
//Step2: perform addition operation
int max (int a,int b,int c) //maximum should have type int.
{
if(a>b)
{
if(a>c)
{
return a;
}
}// You were missing a } here
else if(b>a) //You had elsif, that doesn't mean anything
{
if(b>c)
{
return b; // return instead of cout
}
}
else if(c>b)
{
if(c>a)
{
return c;
}
}
}
//step3: output
printf("The maximum of %d and %d is %d ", a, b, c, max);
}
}
Explanation / Answer
#include<stdio.h>
int main(){
int n,num,i;
int big;
printf("Enter the values of n: ");
scanf("%d",&n);
printf("Number %d",1);
scanf("%d",&big);
for(i=2;i<=n;i++){
printf("Number %d: ",i);
scanf("%d",&num);
if(big<num)
big=num;
}
printf("Largest number is: %d",big);
return 0;
}
Sample Output:
Enter the values of n:
Number 1: 12
Number 2: 32
Number 3: 35
Largest number is: 35