Chapter 5: Tackling Typecasting, Decision Control in C

Decision Control
Decision Control

Type Conversion

    Type conversion, also known as type coercion, is an automatic process performed by the compiler (or programming language) to convert one data type into another without explicit instructions from the programmer. The purpose of type conversion is to facilitate operations between different data types and ensure compatibility.
For Example, Consider the code below:  

int num1 = 10;
float num2 = 3.14;
float sum = num1 + num2; 

  • The code declares three variables: num1 (an integer), num2 (a float), and sum (a float). 
  • The variable num1 is initialized with the value 10, and num2 is initialized with 3.14.
  • The expression num1 + num2 performs addition between an integer and a float. 
  • During this operation, the compiler automatically converts the num1 integer value to a float. 
  • This conversion, also known as type coercion, enables us to add different data types together.
  • The result of the addition is 13.14, which is then stored in the sum variable, a float.

Type Casting

    Type casting in C is a process where the programmer explicitly instructs the compiler to convert a value from one data type to another. It allows us to control how data is converted and used in expressions.

For example, consider the code below that involves type casting for addition:

#include <stdio.h>

int main() {
    int num1 = 10;
    float num2 = 3.14;
    
    // Type casting num1 from int to float before addition
    float sum = (float)num1 + num2;

    printf("The sum is: %f\n", sum);
    return 0;
}

  • Here we have an integer variable num1 and a float variable num2.
  • Before performing the addition operation, we explicitly use type casting (float) to convert num1 from an integer to a float.
  • The result of the addition is stored in the sum variable, and we print the final result using printf.
  • Note that in C, the (float) notation indicates type casting.
  • It instructs the compiler to convert the value of num1 from an integer to a float, allowing the addition operation to be performed between an integer and a float.
Refer Previous Topics : Click Here

Decision Control

    In C, control statements enable the computer to make decisions and control the flow of execution based on specific conditions. They help the program execute logical statements and determine whether to proceed with certain sets of code or not. Control statements direct how the program behaves under different situations.

if-statement:

  • The primary purpose of if-statements is to introduce flexibility and efficiency to your programs. 
  • They enable you to create dynamic behavior, allowing your code to adapt to different scenarios. 
  • With if-statements, you can execute specific actions based on specific conditions, making your program more intelligent and responsive.

Syntax & Flow-Chart

IF-Statement
IF-Statement
Example
#include <stdio.h>

int main() {
    int number;

    // Get input from the user
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is even or odd
    if (number % 2 == 0) {
        // Code to execute if the number is even
        printf("%d is an even number.\n", number);
    } else {
        // Code to execute if the number is odd
        printf("%d is an odd number.\n", number);
    }

    return 0;
}

if-else statement:

  • The if-else statement is a core tool in C programming that adds adaptability and intelligence to your code, allowing it to handle different situations effectively.
  • By using the if-else statement, your code gains the ability to make decisions based on conditions. This means your program can take specific actions depending on whether certain conditions are met.
  • When you incorporate an if-else statement, your code can take two different paths. If the condition specified in the if-statement is true, a designated block of code is executed. If the condition is false, an alternate block of code within the else-statement is executed.
  • Through if-else statements, your program makes informed choices. For instance, it can display tailored messages based on weather conditions or user preferences, showcasing intelligent decision-making.

Syntax & Flow-Chart

IF-ELSE Statement
IF-ELSE Statement
Example
#include <stdio.h>

int main() {
    int age;

    // Get user input for age
    printf("Please enter your age: ");
    scanf("%d", &age);

    // Check if the user is eligible to vote
    if (age >= 18) {
        // If the age is 18 or above, the user can vote
        printf("You are eligible to vote. Make your voice count!\n");
    } else {
        // If the age is below 18, the user cannot vote
        printf("Sorry, you are not eligible to vote yet. Wait a few more years!\n");
    }

    return 0;
}
  • In the main function, an integer variable age is declared to hold the user's age.
  • The program prompts the user to enter their age using the printf function and receives the input using the scanf function.
  • The if-else statement evaluates whether the user's age is greater than or equal to 18, which is the legal voting age in many countries.
  • If the condition is true (age is 18 or above), the program prints a message indicating that the user is eligible to vote.
  • If the condition is false (age is below 18), the program prints a message indicating that the user is not eligible to vote.
  • Finally, the program returns 0 to indicate successful completion.

Nested-if-else statement:

  • Nested if-statements in C programming introduce a higher level of logic flexibility to your code, allowing you to make intricate decisions.
  • With nested if-statements, you can address multiple conditions in a granular manner. Each nested if-statement operates within the context of the outer condition, enabling you to handle specific cases precisely.
  • Nested if-statements are your allies when dealing with multifaceted problems. As you break down intricate challenges into smaller parts using nested conditions, you develop a systematic approach to problem-solving.
  • By utilizing nested if-statements, you're empowered to craft software that offers a positive user experience.

Syntax

NESTED-IF Statement
NESTED-IF Statement

Example

#include <stdio.h>

int main() {
    int age;
    char gender;

    // Get user input for age and gender
    printf("Please enter your age: ");
    scanf("%d", &age);

    printf("Please enter your gender (M/F): ");
    scanf(" %c", &gender);

    // Check eligibility for voting
    if (age >= 18) {
        if (gender == 'M') {
            printf("Hello, Sir! You are eligible to vote.\n");
        } else if (gender == 'F') {
            printf("Hello, Madam! You are eligible to vote.\n");
        } else {
            printf("Invalid gender input.\n");
        }
    } else {
        printf("Sorry, you are not eligible to vote.\n");
    }

    return 0;
}
  • In the main function, integer variable age and character variable gender are declared to hold user inputs.
  • The program prompts the user to enter their age and gender using the printf function and reads the inputs using the scanf function.
  • The nested if-statement begins by checking if the user's age is greater than or equal to 18.
  • If the condition is true, the program enters the nested if-block.
  • The nested if-block checks the user's gender using another if-else statement.
  • If the gender is 'M', a message addressing the user as "Sir" is printed.
  • If the gender is 'F', a message addressing the user as "Madam" is printed.
  • If the gender is neither 'M' nor 'F', an "Invalid gender input" message is printed.
  • If the initial age condition is false, the program prints a message indicating that the user is not eligible to vote.
  • Finally, the program returns 0 to indicate successful completion.
Refer Previous Topics : Click Here

Switch statement:

  • The switch statement in C programming is your dynamic decision wizard. Imagine it as a versatile tool that evaluates a value and magically directs your program to specific actions based on that value. 
  • Picture the switch statement as a roadmap with multiple routes. When your program reaches the switch statement, it quickly identifies the value you're evaluating.
  • The switch statement is your coding elegance enhancer. It's perfect when you have a series of cases, like days of the week or menu choices. Instead of multiple if-else blocks, you get a clean and compact structure that's easy to read, write, and maintain.
  • Introducing the "default" case - your safety net in the switch statement. If none of the cases match the evaluated value, the default case takes the stage. Think of it as your code's elegant fallback plan, ensuring that no matter what, your program will always have a response.
  • The switch statement isn't just about selecting the right path; it's about avoiding the wrong ones. Each case is like a room with an exit. But watch out for "fall-through"! Use the "break" command to ensure you exit the room after making a choice, preventing unintended actions in the subsequent cases.

Syntax & Flow-Chart

Switch Statement
Switch Statement
Example
#include <stdio.h>

int main() {
    int score;

    // Get user input for score (0-100)
    printf("Enter your score: ");
    scanf("%d", &score);

    switch (score / 10) {
        case 10:
        case 9:
            printf("Your grade is A!\n");
            break;
        case 8:
            printf("Your grade is B!\n");
            break;
        case 7:
            printf("Your grade is C!\n");
            break;
        case 6:
            printf("Your grade is D!\n");
            break;
        default:
            printf("Your grade is F.\n");
    }

    return 0;
}

  • The main function initializes an integer variable score to hold the user's input.
  • The user is prompted to enter a score between 0 and 100.
  • The switch statement evaluates the value of score / 10. This calculation groups scores into ranges that correspond to letter grades.
  • Depending on the calculated value, the program enters the corresponding case and prints the associated grade.
  • The break statements ensure that only the code block of the matching case is executed.
  • Since multiple cases can lead to the same grade (e.g., A and B for scores 90-100 and 80-89), they are grouped together without needing separate code blocks.
  • If the calculated value doesn't match any of the cases, the code within the default case is executed, indicating a failing grade.
  • Finally, the program returns 0 to indicate successful completion.
Discover the dynamic world of typecasting and decision control in C, empowering your code to handle diverse scenarios with finesse. With the ability to manipulate data types and make informed choices, your programming journey becomes versatile and powerful. Embrace the art of crafting adaptable solutions and unleash the potential of your code. Happy coding!

Thank you for reading this blog post! To explore more chapters, click the button below:Master C Programming Index

Comments

Popular posts from this blog

Chapter 2: Unlocking the World of C

Chapter: 1 Programming..? What is it.?