Multiple if-else branches

If-else statement: Fix errors.

Re type the code and fix any errors. The code should convert negative numbers to 0.

if (userNum >= 0)
   printf("Non-negative\n");
else
   printf("Negative; converting to 0\n");
   userNum = 0;
 
printf("Final: %d\n", userNum);

solution

#include <stdio.h>

int main(void) {
 int userNum = 0;


 if (userNum >= 0){
 printf("Non-negative\n");
}
else{
 printf("Negative; converting to 0\n");
 userNum = 0;
 }
 printf("Final: %d\n", userNum);

return 0;
}

Multiple branch If-else statement: Print century.

Write an if-else statement with multiple branches. If givenYear is 2100 or greater, print “Distant future” (without quotes). Else, if givenYear is 2000 or greater (2000-2099), print “21st century”. Else, if givenYear is 1900 or greater (1900-1999), print “20th century”. Else (1899 or earlier), print “Long ago”. Do NOT end with newline.

#include <stdio.h>

int main(void) {
 int givenYear = 0;

givenYear = 1776;

if(givenYear >= 2100){printf("Distant future"); } 
else if(givenYear >= 2000){printf("21st century"); } 
else if(givenYear >= 1900){printf("20th century"); }
else {printf("Long ago"); }

return 0;
}

Multiple if statements: Print car info.

 Write multiple if statements. If carYear is 1969 or earlier, print “Probably has few safety features.” If 1970 or higher, print “Probably has seat belts.” If 1990 or higher, print “Probably has anti-lock brakes.” If 2000 or higher, print “Probably has air bags.” End each phrase with period and newline. Ex: carYear = 1995 prints:

 

Probably has seat belts.
Probably has anti-lock brakes.
#include <stdio.h>

int main(void) {
 int carYear = 0;

carYear = 1940;

if(carYear <= 1969){printf("Probably has few safety features.\n"); } 
if(carYear >= 1970){printf("Probably has seat belts.\n"); } 
if(carYear >= 1990){printf("Probably has anti-lock brakes.\n"); }
if(carYear >= 2000){printf("Probably has air bags.\n"); }

return 0;
}