# Conditional Expressions and Input in C

We can extend the if statement with the if-else statement, giving us an either-or situation.

In the following program, we will prompt the user for input. If the user enters a value larger than 10, we will apply a discount to the price calculation. Otherwise, no discount will be provided.

#include <stdio.h>

int main(void){

const double itemPrice = 4.99;

int quantity = 0;

printf("Please enter the number of items you'd like to purchase:\n");

scanf(" %d", &quantity);

if(quantity > 10){
printf("The original price is %.2f\n", itemPrice*quantity);
printf("With a 5\% discount that is: %.2f\n",
itemPrice*quantity-(itemPrice*quantity*.05));
} else {
//no discount
printf("The price for %d is %.2f\n", quantity, itemPrice*quantity);
}

return 0;

}

As we have seen earlier, blocks of statements are enclosed between curly braces, meaning we can provide a multitude of instructions to the computer after resolving the value of a conditional expression simply by enclosing them in curly braces after the if statement. Likewise, we can nest if statements within the conditionally executed blocks of code associated with another if statement.

The following program makes use of the INT_MAX definition from the <limits.h> header file that specifies the maximum value of an int data type.

#include <stdio.h>
#include <limits.h>
#include <math.h>

int main(void){

int num;
printf("Please enter a number less than %d\n", INT_MAX);

scanf(" %d", &num);

printf("You entered %d\n", num);

if(num%2==0){
printf("That number is even.\n");
if(sqrt(num)*sqrt(num)==num){
printf("It is also a perfect square.\n");
}
} else {
printf("That number is odd.\n");
}

return 0;

}

Three additional relational operators worth looking at are greater than or equal to, >=; less than or equal to, <=; and not equal to, !=.

Remember, a char value can be expressed either as an integer or as a single keyboard character. This means that we can use comparison operators on char values the same as we would with int values.

#include <stdio.h>

int main(void){

char a = 'z';
char b = 'Z';

if(a != b){
printf("%c [%d] does not equal %c [%d]\n\n",
a, a, b, b);
}

if(a>b){
printf("%c is greater than %c", a, b);
} else {
printf("%c is greater than %c", b, a);
}

printf("\nThe difference between %c and %c is %d\n",
a, b, a-b);

return 0;
}

Note that in ASCII code lowercase letters are greater than their uppercase equivalents by the constant value of 32.

Buy my book on Standard C, it contains 100% unique tutorial programs not available on this blog: http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M