Spread the love

 Conditional Statements

VIDEO CREDIT:- CODE WITH HARRY 

In the previous examples, you’ve seen programs execute sequentially, line by line, from top to bottom. However, such programs lack flexibility and do not adapt to different situations or user behaviors.

In this chapter, you’ll learn how to make decisions and control the flow of a program using conditional statements. These statements allow you to set the rules for what happens next, based on specific conditions.

Conditional statements perform actions based on the results of comparisons. The program will decide the next steps depending on whether these conditions are met. Consequently, certain parts of the program may not run depending on the results or specific user inputs, leading to different paths or “forks in the road” during the program’s execution.

You’ll start by learning about the if statement, the foundational building block of decision-making in C. Then, you’ll explore the else if and else statements, which add more flexibility to the if statement. Finally, you’ll learn about the ternary operator, which allows you to condense decision-making logic into a single line of code, enhancing the readability of your program.

Creating an if Statement in C

The most basic conditional statement in C is the if statement. It makes a decision based on a condition. If the condition evaluates to true, the code inside the if block is executed. If the condition evaluates to false, the code inside the if block is ignored.

The general syntax for an if statement in C is as follows:

if (condition) {
// run this code if condition is true
}
Let’s look at an example:
#include <stdio.h>

int main(void) {

    // variable age
   int age;

   // prompt user to enter their age
   printf("Please enter your age: ");

   // store user's answer in the variable
   scanf("%i", &age);

    // check if age is less than 18
    // if it is, then and only then, print a message to the console

   if (age < 18) {
       printf("You need to be over 18 years old to continue\\n");
   }
}
  1. Create a variable named age to hold an integer value.
  2. Prompt the user to enter their age and store the answer in the variable age.
  3. Create a condition to check if the value of age is less than 18.
  4. If the condition is true, print a message to the console informing the user that they must be at least 18 years old to proceed.

If the user is asked for their age and they enter 16, the output should be:

“You must be at least 17 years old to proceed.”

How to Create an if else statement in C

To create an if-else statement in C, follow these steps:

  1. Declare and initialize the variable you want to check.
  2. Use the if keyword to start the conditional statement.
  3. Inside the parentheses, write the condition you want to check.
  4. If the condition is true, the code inside the braces {} following the if statement will execute.
  5. Use the else keyword to specify the block of code that will execute if the condition is false.

Here is an example:

#include <stdio.h>
int main() {
// Declare a variable to hold the age

int age;
// Prompt the user to enter their age

printf("Please enter your age: ");
scanf("%d", &age);
// Create an if-else statement to check the age

if (age < 18) {
// If the age is less than 18, print this message

printf("You must be at least 18 years old to proceed.\n");
} else {
// If the age is 18 or greater, print this message

printf("You are old enough to proceed.\n");
}
return 0;
}

Explanation:

  1. Include the necessary header: #include <stdio.h> is included to use the standard input/output functions.
  2. Declare a variable: int age; declares a variable named age to store the user’s age.
  3. Prompt the user: printf("Please enter your age: "); prints a message asking the user to enter their age.
  4. Read the user’s input: scanf("%d", &age); reads an integer from the user and stores it in the variable age.
  5. If-else statement:
    • if (age < 18) checks if the age is less than 18.
    • printf("You must be at least 18 years old to proceed.\n"); prints a message if the condition is true.
    • else provides an alternative action if the condition is false.
    • printf("You are old enough to proceed.\n"); prints a message if the age is 18 or greater.
  6. Return statement: return 0; indicates that the program ended successfully.

How to Create an else if statement in C

To create an else if statement in C, follow these steps:

  1. Declare and initialize the variable you want to check.
  2. Use the if keyword to start the first conditional statement.
  3. Inside the parentheses, write the first condition you want to check.
  4. If the first condition is true, the code inside the braces {} following the if statement will execute.
  5. Use the else if keyword to specify an additional condition to check if the first condition is false.
  6. Inside the parentheses, write the additional condition you want to check.
  7. If the additional condition is true, the code inside the braces {} following the else if statement will execute.
  8. You can include multiple else if statements for additional conditions.
  9. Optionally, use the else keyword to specify a block of code that will execute if all previous conditions are false.

Here is an example:

#include <stdio.h>
int main() {
// Declare a variable to hold the age
int age;
// Prompt the user to enter their age

printf("Please enter your age: ");
scanf("%d", &age);
// Create an if-else if-else statement to check the age

if (age < 13) {
// If the age is less than 13, print this message

printf("You are a child.\n");
}
else if (age >= 13 && age < 18) {
// If the age is between 13 and 17, print this message

printf("You are a teenager.\n");
} else if (age >= 18 && age < 65) {
// If the age is between 18 and 64, print this message

printf("You are an adult.\n");
} else {
// If none of the above conditions are met, print this message

printf("You are a senior.\n");
}
return 0;
}

Explanation:

  1. Include the necessary header: #include <stdio.h> is included to use the standard input/output functions.
  2. Declare a variable: int age; declares a variable named age to store the user’s age.
  3. Prompt the user: printf("Please enter your age: "); prints a message asking the user to enter their age.
  4. Read the user’s input: scanf("%d", &age); reads an integer from the user and stores it in the variable age.
  5. If-else if-else statement:
    • if (age < 13) checks if the age is less than 13.
    • printf("You are a child.\n"); prints a message if the first condition is true.
    • else if (age >= 13 && age < 18) checks if the age is between 13 and 17.
    • printf("You are a teenager.\n"); prints a message if the second condition is true.
    • else if (age >= 18 && age < 65) checks if the age is between 18 and 64.
    • printf("You are an adult.\n"); prints a message if the third condition is true.
    • else provides an alternative action if none of the previous conditions are true.
    • printf("You are a senior.\n"); prints a message if all other conditions are false.
  6. Return statement: return 0; indicates that the program ended successfully.

How to Use the Ternary Operator in C

The ternary operator in C, also known as the conditional operator, provides a way to perform inline conditional checks and return a value based on the result. It’s a shorthand for the if-else statement and can make code more concise and readable when used appropriately.

The syntax for the ternary operator is:

condition ? expression_if_true : expression_if_false;

Here’s a breakdown of its components:

  • condition: This is the expression that is evaluated. If it evaluates to true (non-zero), expression_if_true is executed. If it evaluates to false (zero), expression_if_false is executed.
  • ? and :: These symbols are part of the syntax, separating the condition from the true and false expressions.

Examples

Example 1: Basic Usage

Let’s consider a simple example where we want to assign the minimum of two integers to a variable:

#include <stdio.h>

int main() {

int a = 10;
int b = 20;
int min;
min = (a < b) ? a : b;
printf("The minimum value is %d\n", min);
return 0;
}

In this example, the condition (a < b) is checked:

  • If a is less than b, min is assigned the value of a.
  • Otherwise, min is assigned the value of b.

Example 2: Inline Output

The ternary operator can also be used directly in function calls or other expressions:

#include <stdio.h>

int main() {

int number = 5;
printf("%s\n", (number % 2 == 0) ? "Even" : "Odd");
return 0;
}

Here, (number % 2 == 0) checks if the number is even:

  • If true, the string “Even” is printed.
  • If false, the string “Odd” is printed.

Considerations

  1. Readability: While the ternary operator can make code shorter, it can also reduce readability if overused or used in complex expressions. It’s best suited for simple conditions.
  2. Nested Ternary Operators: Nesting ternary operators can quickly become confusing. It’s generally better to use if-else statements in such cases for clarity.
  3. Side Effects: Be cautious about using the ternary operator with expressions that have side effects, as it can lead to unexpected behavior.
Categories: C

techbloggerworld.com

Nagendra Kumar Sharma I Am Software engineer

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *