111k views
3 votes
C programming question:

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002. Given an int variable modelYear and an array of chars representing a string modelName write a statement that prints the message "RECALL" to standard output if the values of modelYear and modelName match the recall details.

Is the answer :

if (modelName == "Extravagant" && modelYear >= 1999 && modelYear <= 2002)
printf("%s\\","RECALL");

?? or I'm wondering if I should do this instead:

if (0==strcmp(modelName,"Extravagant") && modelYear >= 1999 && modelYear <= 2002)
printf("%s\\","RECALL");

User Chakrapani
by
4.7k points

1 Answer

4 votes

Answer:

You should do this:

if (0==strcmp(modelName,"Extravagant") && modelYear >= 1999 && modelYear <= 2002)

printf("%s\\","RECALL");

Step-by-step explanation:

Lets consider this program and analyze the output.

int main()

{

int modelYear;

char modelName[30];

printf("enter the year");

scanf("%d",&modelYear);

printf("enter the modelname");

scanf("%s",modelName);

if (0==strcmp(modelName,"Extravagant") && modelYear >= 1999 && modelYear <= 2002)

printf("%s\\","RECALL"); }

if (0==strcmp(modelName,"Extravagant") && modelYear >= 1999 && modelYear <= 2002)

This statement has a function strcmp which is used to compare two strings.

If the user enters Extravagant as model name then this input will be compared by the string stored in modelName i.e. Extravagant, character by character. If the string entered by the user matches the string stored in modelName this means this part of the if condition evaluates to true. 0==strcmp means that both the strings should be equal.

The next part of the if statement checks if the model year entered is greater than or equal to 1999 AND less than or equal to 2002. This means that the model year should be between 1999 and 2002 (inclusive).

&& is the logical operator between both the parts of if statement which means that both should evaluate to true in order to display RECALL.

This is correct way to use because the if (modelName == "Extravagant" && modelYear >= 1999 && modelYear <= 2002) printf("%s\\","RECALL"); statement will not display RECALL. After entering the model name and model year it will move to the next line and exit.

So in if (0==strcmp(modelName,"Extravagant") && modelYear >= 1999 && modelYear <= 2002)

printf("%s\\","RECALL"); statement when the if condition evaluates to true, then RECALL is displayed in the output.

User Massimobio
by
4.2k points