If else

Basic if-else expression.

Write an expression that will cause the following code to print “less than 18” if the value of userAge is less than 18.
#include <stdio.h>

int main(void) {
 int userAge;

scanf("%d", &userAge); // Program will be tested with values: 16, 17, 18, 19.

if (userAge < 18) {
 printf("less than 18\n");
 }
 else {
 printf("18 or more\n");
 }
 return 0;
}

Write an expression that will cause the following code to print “greater than -10” if the value of userNum is greater than -10.

#include <stdio.h>

int main() {
 int userNum;

scanf("%d", &userNum); // Program will be tested with values: -8, -9, -10, -11.

if (userNum > - 10) {
 printf("greater than -10\n");
 }
 else {
 printf("-10 or less\n");
 }
 return 0;
}

Write an expression that will cause the following code to print “I am a teenager” if the value of userAge is less than 20.

#include <stdio.h>

int main() {
 int userAge;

scanf("%d", &userAge); // Program will be tested with values: 18, 19, 20, 21.

if (userAge >= 20) {
 printf("I am an adult\n");
 }
 else {
 printf("I am a teenager\n");
 }
 return 0;
}

Basic if-else.

Write an if-else statement for the following:
If userTickets is less than 5, execute awardPoints = 1. Else, execute awardPoints = userTickets.

Ex: If userTickets is 3, then awardPoints = 1.

#include <stdio.h>

int main(void) {
 int awardPoints;
 int userTickets;

scanf("%d", &userTickets); // Program will be tested with values: 3, 4, 5, 6.

if(userTickets < 5){
 awardPoints = 1;
 }

 else{
 awardPoints = userTickets;
 }

printf("%d\n", awardPoints);
 return 0;
}

 

Write an if-else statement for the following:
If numDifference is less than -20, execute totalDifference = -25. Else, execute totalDifference = numDifference.
#include <stdio.h>

int main() {
 int totalDifference;
 int numDifference;

scanf("%d", &numDifference); // Program will be tested with values: -19, -20, -21, -22.

if(numDifference < -20){
 totalDifference = -25;
 }
 
 else{
 totalDifference = numDifference;
 }

printf("%d", totalDifference);
 return 0;
}

 If-else statement: Fix errors.

Re-type the code and fix any errors. The code should convert non-positive numbers to 1.
if (userNum > 0)
   printf("Positive.\n");
else
   printf("Non-positive, converting to 1.\n");
   userNum = 1;
 
printf("Final: %d\n", userNum);

solution

#include <stdio.h>

int main(void) {
 int userNum;

userNum = -5;


 if (userNum > 0) { //was missing curly brackets
 printf("Positive.\n");
}

else { //was missing curly brackets
 printf("Non-positive, converting to 1.\n");
 userNum = 1;
 }
 
 printf("Final: %d\n", userNum);


 return 0;
}