Tutorial 04
Tutorial 04
1) What is wrong with the following if statement (there are at least 3 errors). The
Indentation indicates the desired behavior.
if numNeighbors >= 3 || numNeighbors = 4
++numNeighbors;
printf("You are dead! \n " );
else
--numNeighbors;
if (doesSignificantWork) {
if (makesBreakthrough)
nobelPrizeCandidate = true;
else
nobelPrizeCandidate = false;
}
else if (!doesSignificantWork)
nobelPrizeCandidate = false;
1. If character variable taxCode is ’T’, increase price by adding the taxRate percentage
of price to it.
if (taxCode == 'T') { price += (taxRate / 100) * price;
}
2. If integer variable opCode has the value 1, read in double values for X and Y and
calculate and print their sum.
if (opCode == 1) {
double X, Y;
printf("Enter value for X: ");
scanf("%lf", &X);
printf("Enter value for Y: ");
scanf("%lf", &Y);
double sum = X + Y;
printf("The sum of X and Y is: %.2lf\n", sum);
}
3. If integer variable currentNumber is odd, change its value so that it is now 3 times
currentNumber plus 1, otherwise change its value so that it is now half of
currentNumber (rounded down when currentNumber is odd).
if (currentNumber % 2 != 0) {
currentNumber = (3 * currentNumber) + 1;
} else {
currentNumber = currentNumber / 2;
}
4. Assign true to the boolean variable leapYear if the integer variable year is a leap
year. (A leap year is a multiple of 4, and if it is a multiple of 100, it must also be a
multiple of 400.)
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
leapYear = 1;
} else {
leapYear = 0;
}
5. Assign a value to double variable cost depending on the value of integer variable
distance as follows:
if (distance <= 100) {
cost = 5.00;
} else if (distance <= 500) {
cost = 8.00;
} else if (distance < 1000) {
cost = 10.00;
} else {
cost = 12.00;
}
Distance Cost
----------------------------------- ----------
0 through 100 5.00
More than 100 but not more than 500 8.00
More than 500 but less than 1,000 10.00
1,000 or more 12.00