Author: saqibkhan

  • Switch Case Using Range

    In C, a switch case is a control flow statement used to compare a variable with specific values and execute different blocks of code depending on which value matches. For example −

    switch(num){case1:printf("One");break;case2:printf("Two");break;default:printf("Other");}

    Here, the switch case checks exact matches only. But sometimes, we want to check if a value falls within a range, like 1-5 or ‘A’-‘Z’. Instead of writing a separate case for each value, we can define a range of values in a single case. This is called a switch case with ranges. For exmaple −

    switch(num){case1...5:printf("Between 1 and 5");break;case6...10:printf("Between 6 and 10");break;default:printf("Other");}

    Switch Case Using Range

    switch case using ranges handles multiple consecutive values in one case. Instead of writing a separate case for each number or character, we define a range and the same block of statements runs for all values in that range.

    We cannot use ranges in standard C, but the GNU C compiler provides this feature as a case range extension.

    Syntax for Switch Case Using Range

    Following is the syntax for using ranges in a switch case statement.

    switch(value){case lower_range ... higher_range:// code blockbreak;default:// code block}

    Here, lower_range is the starting value and higher_range is the ending value. We must put spaces around the ellipsis () to make a valid syntax.

    Steps to Implement Range Handling

    To implement switch case with range handling, we first group the variable into categories and then use the switch to check which category it belongs to. Here’s how we handle ranges-

    • First, we use if statements to check which range the value belongs to, like 1-10, 11-20, or 21-30.
    • Then, we assign each range a number, such as 1, 2, or 3, to represent it.
    • Next, pass this number to the switch case where each case corresponds to one range.
    • The switch case checks the number and runs the code for that range.
    • Finally, we add a default case to handle values outside the defined ranges.

    Example: Simple Range Check

    Let’s see a simple example where we will use two ranges inside the switch case and check if a number belongs to the range 1-5 or 6-10. If it does not belong to any of these ranges, then the default statement will get printed.

    #include <stdio.h>intmain(){int number =7;// You can change the value to test different casesswitch(number){case1...5:printf("The number is between 1 and 5.\n");break;case6...10:printf("The number is between 6 and 10.\n");break;default:printf("The number is outside the range 1 to 10.\n");}return0;}

    Following is the output of the above program −

    The number is between 6 and 10.
    

    Example: Using if-else for Ranges with Switch Case

    In this example, we check which range a number belongs to and display a message. We first use if-else statements to assign the number to a range such as 1-1011-2021-30, or out of range, and then the switch case prints the message corresponding to that range.

    #include <stdio.h>intmain(){int number =17;// Set the number directly// Normalize the number into a rangeint range;if(number >=1&& number <=10){
    
      range =1;// Range 1-10}elseif(number &gt;=11&amp;&amp; number &lt;=20){
      range =2;// Range 11-20}elseif(number &gt;=21&amp;&amp; number &lt;=30){
      range =3;// Range 21-30}else{
      range =4;// Out of range}// Use switch to handle the different rangesswitch(range){case1:printf("The number is between 1 and 10\n");break;case2:printf("The number is between 11 and 20\n");break;case3:printf("The number is between 21 and 30\n");break;default:printf("The number is out of range\n");}return0;}</code></pre>

    Following is the output of the above program, showing which range the given number belongs to.

    The number is between 11 and 20
    

    Example: Handling Character Ranges in Switch Case

    In this example, we check what type of character a variable contains. The switch case checks whether the character is a lowercase letter, an uppercase letter, or a digit, and prints the corresponding message. Any character outside these ranges is handled by the default case.

    #include <stdio.h>intmain(){char ch ='G';// Set the character directly// Switch-case with rangesswitch(ch){case'a'...'z':// Lowercase letters rangeprintf("%c is a lowercase alphabet\n", ch);break;case'A'...'Z':// Uppercase letters rangeprintf("%c is an uppercase alphabet\n", ch);break;case'0'...'9':// Digits rangeprintf("%c is a digit\n", ch);break;default:printf("%c is a non-alphanumeric character\n", ch);}return0;}

    Below is the output of the above program where it shows the type of the given character.

    G is an uppercase alphabet
    

    Example: Using Category Mapping with Switch Case

    In this example, we group marks into categories by dividing them by 10. For example, marks from 90 to 100 fall into category 9 or 10, marks from 80 to 89 fall into category 8, and so on. Then, the switch case prints the message for that category.

    #include <stdio.h>intmain(){int marks =87;// Set the marks directly// Convert marks into categories (divide by 10)int category = marks /10;// Handle ranges using switchswitch(category){case10:// For 100case9:// For 90-99printf("Excellent! Grade A\n");break;case8:// For 80-89printf("Very Good! Grade B\n");break;case7:// For 70-79printf("Good! Grade C\n");break;case6:// For 60-69printf("Satisfactory! Grade D\n");break;default:// For below 60printf("Needs Improvement! Grade F\n");}return0;}

    Below is the output of the program, which divides the given marks and shows their category.

    Very Good! Grade B
    

    Errors in Switch Case Using Ranges

    When using ranges in switch case, there are a few important things to keep in mind −

    Invalid Range (low > high): If the low value is greater than the high value, the compiler will give an error.

    Example of incorrect range −

    case5...1:// This will cause an error

    Overlapping Ranges: If you try to define multiple case ranges that overlap, the compiler will give an error.

    Example of incorrect overlapping ranges −

    case1...5:case3...7:// Overlap error

    In this chapter, we learned how to use ranges with switch cases to handle multiple consecutive values together. We covered this for both numbers and characters, and also looked at situations where errors can occur.

  • Nested Switch Statements

    It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

    Syntax

    The syntax for a nested switch statement is as follows −

    switch(ch1){case'A':printf("This A is part of outer switch");switch(ch2){case'A':printf("This A is part of inner switch");break;case'B':/* case code */}break;case'B':/* case code */}

    Example

    Take a look at the following example −

    #include <stdio.h>intmain(){/* local variable definition */int a =100;int b =200;switch(a){case100:printf("This is part of outer switch\n", a);switch(b){case200:printf("This is part of inner switch\n", a);}}printf("Exact value of a is: %d\n", a);printf("Exact value of b is: %d\n", b);return0;}

    Output

    When the above code is compiled and executed, it produces the following output −

    This is part of outer switch
    This is part of inner switch
    Exact value of a is : 100
    Exact value of b is : 200
    

    Nested Switch-Case Statements in C

    Just like nested ifelse, you can have nested switch-case constructs. You may have a different switch-case construct each inside the code block of one or more case labels of the outer switch scope.

    The nesting of switch-case can be done as follows −

    switch(exp1){case val1:switch(exp2){case val_a:
    
         stmts;break;case val_b:
         stmts;break;}case val2:switch(expr2){case val_c:
         stmts;break;case val_d:
         stmts;break;}}</code></pre>

    Example

    Here is a simple program to demonstrate the syntax of Nested Switch Statements in C −

    #include <stdio.h>intmain(){int x =1, y ='b', z='X';// Outer Switchswitch(x){case1:printf("Case 1 \n");switch(y){case'a':printf("Case a \n");break;case'b':printf("Case b \n");break;}break;case2:printf("Case 2 \n");switch(z){case'X':printf("Case X \n");break;case'Y':printf("Case Y \n");break;}}return0;}

    Output

    When you run this code, it will produce the following output −

    Case 1 
    Case b
    

    Change the values of the variables (xy, and z) and check the output again. The output depends on the values of these three variables.

  • Switch Statement

    switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

    C switch-case Statement

    The switch-case statement is a decision-making statement in C. The if-else statement provides two alternative actions to be performed, whereas the switch-case construct is a multi-way branching statement. A switch statement in C simplifies multi-way choices by evaluating a single variable against multiple values, executing specific code based on the match. It allows a variable to be tested for equality against a list of values.

    Syntax of switch-case Statement

    The flow of the program can switch the line execution to a branch that satisfies a given case. The schematic representation of the usage of switch-case construct is as follows −

    switch(Expression){// if expr equals Value1case Value1: 
    
      Statement1;
      Statement2;break;// if expr equals Value2case Value2: 
      Statement1;
      Statement2;break;..// if expr is other than the specific values abovedefault:
      Statement1;
      Statement2;}</code></pre>

    How switch-case Statement Work?

    The parenthesis in front of the switch keyword holds an expression. The expression should evaluate to an integer or a character. Inside the curly brackets after the parenthesis, different possible values of the expression form the case labels.

    One or more statements after a colon(:) in front of the case label forms a block to be executed when the expression equals the value of the label.

    You can literally translate a switch-case as "in case the expression equals value1, execute the block1", and so on.

    C checks the expression with each label value, and executes the block in front of the first match. Each case block has a break as the last statement. The break statement takes the control out of the scope of the switch construct.

    You can also define a default case as the last option in the switch construct. The default case block is executed when the expression doesnt match with any of the earlier case values.

    Flowchart of switch-case Statement

    The flowchart that represents the switch-case construct in C is as follows −

    switch statement in C

    Rules for Using the switch-case Statement

    The following rules apply to a switch statement −

    • The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
    • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
    • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
    • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
    • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
    • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
    • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

    The switch-case statement acts as a compact alternative to cascade of if-else statements, particularly when the Boolean expression in "if" is based on the "=" operator.

    If there are more than one statements in an if (or else) block, you must put them inside curly brackets. Hence, if your code has many if and else statements, the code with that many opening and closing curly brackets appears clumsy. The switch-case alternative is a compact and clutter-free solution.

    C switch-case Statement Examples

    Practice the following examples to learn the switch case statements in C programming language −

    Example 1

    In the following code, a series of if-else statements print three different greeting messages based on the value of a "ch" variable ("m", "a" or "e" for morning, afternoon or evening).

    #include <stdio.h>intmain(){/* local variable definition */char ch ='e';printf("Time code: %c\n\n", ch);if(ch =='m')printf("Good Morning");elseif(ch =='a')printf("Good Afternoon");elseprintf("Good Evening");return0;}

    The if-else logic in the above code is replaced by the switch-case construct in the code below −

    #include <stdio.h>intmain(){// local variable definitionchar ch ='m';printf("Time code: %c\n\n", ch);switch(ch){case'a':printf("Good Afternoon\n");break;case'e':printf("Good Evening\n");break;case'm':printf("Good Morning\n");}return0;}

    Output

    Change the value of "ch" variable and check the output. For ch = 'm', we get the following output −

    Time code: m
    
    Good Morning
    

    The use of break is very important here. The block of statements corresponding to each case ends with a break statement. What if the break statement is not used?

    The switch-case works like this: As the program enters the switch construct, it starts comparing the value of switching expression with the cases, and executes the block of its first match. The break causes the control to go out of the switch scope. If break is not found, the subsequent block also gets executed, leading to incorrect result.

    Example 2: Switch Statement without using Break

    Let us comment out all the break statements in the above code.

    #include <stdio.h>intmain(){/* local variable definition */char ch ='a';printf("Time code: %c\n\n", ch);switch(ch){case'a':printf("Good Afternoon\n");// break;case'e':printf("Good Evening\n");// break;case'm':printf("Good Morning\n");}return0;}

    Output

    You expect the "Good Morning" message to be printed, but you find all the three messages printed!

    Time code: a
    
    Good Afternoon
    Good Evening
    Good Morning
    

    This is because C falls through the subsequent case blocks in the absence of break statements at the end of the blocks.

    Example 3: Grade Checker Program using Switch Statement

    In the following program, "grade" is the switching variable. For different cases of grades, the corresponding result messages will be printed.

    #include <stdio.h>intmain(){/* local variable definition */char grade ='B';switch(grade){case'A':printf("Outstanding!\n");break;case'B':printf("Excellent!\n");break;case'C':printf("Well Done\n");break;case'D':printf("You passed\n");break;case'F':printf("Better try again\n");break;default:printf("Invalid grade\n");}printf("Your grade is  %c\n", grade);return0;}

    Output

    Run the code and check its output −

    Excellent!
    Your grade is  B
    

    Now change the value of "grade" (it is a "char" variable) and check the outputs.

    Example 4: Menu-based Calculator for Arithmetic Operations using Switch

    The following example displays a menu for arithmetic operations. Based on the value of the operator code (1, 2, 3, or 4), addition, subtraction, multiplication or division of two values is done. If the operation code is something else, the default case is executed.

    #include <stdio.h>intmain(){// local variable definitionint a =10, b =5;// Run the program with other values 2, 3, 4, 5int op =1;float result;printf("1: addition\n");printf("2: subtraction\n");printf("3: multiplication\n");printf("4: division\n");printf("\na: %d b: %d : op: %d\n", a, b, op);switch(op){case1:
    
         result = a + b;break;case2:
         result = a - b;break;case3:
         result = a * b;break;case4:
         result = a / b;break;default:printf("Invalid operation\n");}if(op &gt;=1&amp;&amp; op &lt;=4)printf("Result: %6.2f", result);return0;}</code></pre>

    Output

    1: addition
    2: subtraction
    3: multiplication
    4: division
    
    a: 10 b: 5 : op: 1
    Result:  15.00
    

    For other values of "op" (2, 3, and 4), you will get the following outputs −

    a: 10 b: 5 : op: 2
    Result:   5.00
    
    a: 10 b: 5 : op: 3
    Result:  50.00
    
    a: 10 b: 5 : op: 4
    Result:   2.00
    
    a: 10 b: 5 : op: 5
    Invalid operation
    

    Switch Statement by Combining Multiple Cases

    Multiple cases can be written together to execute one block of code. When any of them case value matches, the body of these combined cases executes. If you have a situation where the same code block is to be executed for more than one case labels of an expression, you can combine them by putting the two cases one below the other, as shown below −

    Syntax

    switch(exp){case1:case2:
    
      statements;break;case3:
      statements;break;default:printf("%c is a non-alphanumeric character\n", ch);}</code></pre>

    You can also use the ellipsis () to combine a range of values for an expression. For example, to match the value of switching variable with any number between 1 to 10, you can use "case 1 10"

    Example 1

    #include <stdio.h>intmain(){// local variable definitionint number =5;switch(number){case1...10:printf("The number is between 1 and 10\n");break;default:printf("The number is not between 1 and 10\n");}return0;}

    Output

    Run the code and check its output. For "number = 5", we get the following output −

    The number is between 1 and 10
    

    Example 2

    The following program checks whether the value of the given char variable stores a lowercase alphabet, an uppercase alphabet, a digit, or any other key.

    #include <stdio.h>intmain(){char ch ='g';switch(ch){case'a'...'z':printf("%c is a lowercase alphabet\n", ch);break;case'A'...'Z':printf("%c is an uppercase alphabet\n", ch);break;case48...57:printf("%c is a digit\n", ch);break;default:printf("%c is a non-alphanumeric character\n", ch);}return0;}

    Output

    For ch = 'g', we get the following output −

    g is a lowercase alphabet
    

    Test the code output with different values of "ch".

  • Nested If Statements

    It is always legal in C programming to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement(s).

    In the programming context, the term “nesting” refers to enclosing a particular programming element inside another similar element. For example, nested loops, nested structures, nested conditional statements, etc. If an if statement in C is employed inside another if statement, then we call it as a nested if statement in C.

    Syntax

    The syntax of nested if statements is as follows −

    if(expr1){if(expr2){
    
      block to be executed when 
      expr1 and expr2 are true
    }else{
      block to be executed when 
      expr1 is true but expr2 is false
    }}

    The following flowchart represents the nesting of if statements −

    Nested Condition

    You can compound the Boolean expressions with && or || to get the same effect. However, for more complex algorithms, where there are different combinations of multiple Boolean expressions, it becomes difficult to form the compound conditions. Instead, it is recommended to use nested structures.

    Another if statement can appear inside a top-level if block, or its else block, or inside both.

    Example 1

    Let us take an example, where the program needs to determine if a given number is less than 100, between 100 to 200, or above 200. We can express this logic with the following compound Boolean expression −

    #include <stdio.h>intmain(){// local variable definitionint a =274;printf("Value of a is : %d\n", a);if(a <100){printf("Value of a is less than 100\n");}if(a >=100&& a <200){printf("Value of a is between 100 and 200\n");}if(a >=200){printf("Value of a is more than 200\n");}}

    Output

    Run the code and check its output. Here, we have intialized the value of “a” as 274. Change this value and run the code again. If the supplied value is less than 100, then you will get a different output. Similarly, the output will change again if the supplied number is in between 100 and 200.

    Value of a is : 274
    Value of a is more than 200
    

    Example 2

    Now let’s use nested conditions for the same problem. It will make the solution more understandable when we use nested conditions.

    First, check if “a >= 100”. Inside the true part of the if statement, check if it is <200 to decide if the number lies between 100-200, or it is >200. If the first condition (a >= 100) is false, it indicates that the number is less than 100.

    #include <stdio.h>intmain(){// local variable definition// check with different values 120, 250 and 74int a =120;printf("value of a is : %d\n", a );// check the boolean conditionif(a >=100){// this will check if a is between 100-200if(a <200){// if the condition is true, then print the followingprintf("Value of a is between 100 and 200\n");}else{printf("Value of a is more than 200\n");}}else{// executed if a < 100printf("Value of a is less than 100\n");}return0;}

    Output

    Run the code and check its output. You will get different outputs for different input values of “a” −

    Value of a is : 120
    Value of a is between 100 and 200
    

    Example 3

    The following program uses nested if statements to determine if a number is divisible by 2 and 3, divisible by 2 but not 3, divisible by 3 but not 2, and not divisible by both 2 and 3.

    #include <stdio.h>intmain(){int a =15;printf("a: %d\n", a);if(a %2==0){if(a %3==0){printf("Divisible by 2 and 3");}else{printf("Divisible by 2 but not 3");}}else{if(a %3==0){printf("Divisible by 3 but not 2");}else{printf("Not divisible by 2, not divisible by 3");}}return0;}

    Output

    Run the code and check its output −

    a: 15
    Divisible by 3 but not 2
    

    For different values of “a”, you will get different outputs.

    Example 4

    Given below is a C program to check if a given year is a leap year or not. Whether the year is a leap year or not is determined by the following rules −

    • Is the year divisible by 4?
    • If yes, is it a century year (divisible by 100)?
    • If yes, is it divisible by 400? If yes, it is a leap year, otherwise not.
    • If it is divisible by 4 and not a century year, it is a leap year.
    • If it is not divisible by 4, it is not a leap year.

    Here is the C code −

    #include <stdio.h>intmain(){// Test the program with the values 1900, 2023, 2000, 2012int year =1900;printf("year: %d\n", year);// is divisible by 4?if(year %4==0){// is divisible by 100?if(year %100==0){// is divisible by 400?if(year %400==0){printf("%d is a Leap Year\n", year);}else{printf("%d is not a Leap Year\n", year);}}else{printf("%d is not a Leap Year\n", year);}}else{printf("%d is a Leap Year\n", year);}}

    Output

    Run the code and check its output −

    year: 1900
    1900 is not a Leap Year
    

    Test the program with different values for the variable “year” such as 1900, 2023, 2000, 2012.

    The same result can be achieved by using the compound Boolean expressions instead of nested if statements, as shown below −

    If(year %4==0&&(year %400==0|| year %100!=0)){printf("%d is a leap year", year);}else{printf("%d is not a leap year", year);}

    With nested if statements in C, we can write structured and multi-level decision-making algorithms. They simplify coding the complex discriminatory logical situations. Nesting too makes the program more readable, and easy to understand.

  • if…else if Ladder in C

    The if-else-if ladder in C is an extension of the simple if-else statement that is used to test multiple conditions sequentially. It executes a block of code associated with the first condition that evaluates to true.

    Syntax of if…else if Ladder in C

    The syntax of if…else if ladder in C is as follows −

    if(condition1){// Code to be executed if condition1 is true}elseif(condition2){// Code to be executed if condition1 is false and condition2 is true}elseif(condition3){// Code to be executed if all previous are false, and condition3 is true}// ...else{// Code to be executed if all preceding conditions are false}

    In an if…else if ladder, each condition is evaluated sequentially, but only if all the previous conditions are false. As soon as a condition evaluates to true, its corresponding code block executes, and the ladder terminates without checking the remaining conditions.

    Example

    Let’s understand the if…else if ladder in C with an example to see how the code executes and how the flow runs step by step.

    #include <stdio.h>intmain(){int items =72;if(items >=90){printf("Store is full");}elseif(items >=80){printf("Need few more items");}elseif(items >=70){printf("Store is partially full");}elseif(items >=50){printf("Sore is half full");}else{printf("Store is empty");}return0;}

    When you run this code, it will produce the following output −

    Store is partially full
    

    Explanation − In this example, there are 72 items. The condition “items >= 90” evaluates to false, so the control moves to “items >= 80”, which is also false.

    Next, it checks the condition “items >= 70”, which evaluates to true. Therefore, the statement “Store is partially full” is printed, and the remaining conditions in the ladder are skipped.

    Components of if…else if Ladder

    Let’s look at the components of an if…else if ladder in C programming −

    If statement

    The if statement first statement in the if…else if ladder. The if block contains a condition and a code block, which executes if the condition evaluates to true; otherwise, the control passes to the next statement.

    else if statement

    The else-if statement always comes after the if statement. An if…else if ladder can have multiple else if statements, each containing a condition to be tested. If a condition evaluates to true, its corresponding code block executes; otherwise, the control moves to the next statement.

    else statement

    The else statement is the last statement in an if…else if ladder. The else statement does not contain any condition, however it contains a code block which is executed if all the conditions mentioned in the above if and else if statements evaluate to false.

    Working of if…else if Ladder

    The working of the if…else if ladder in C can be understood using the following flowchart −

    Working of if…else if Ladder

    This is how the control flow moves −

    • If condition 1 is true, Statement 1 executes, and the remaining else-if and else conditions are skipped.
    • If condition 1 is false, condition 2 is evaluated. If condition 2 is true, Statement 2 executes, and the else block is skipped.
    • If condition 2 is also false, the else block executes.
    • After the if…else if ladder finishes, the statement immediately following the ladder executes.

    Example 1

    In this C example, we have used an if…else if ladder to display the day names based on their designated numbers −

    #include <stdio.h>intmain(){int day =5;printf("Day Number: %d\n", day);if(day ==1){printf("Day Name: Monday\n");}elseif(day ==2){printf("Day Name: Tuesday\n");}elseif(day ==3){printf("Day Name: Wednesday\n");}elseif(day ==4){printf("Day Name: Thursday\n");}elseif(day ==5){printf("Day Name: Friday\n");}elseif(day ==6){printf("Day Name: Saturday\n");}elseif(day ==7){printf("Day Name: Sunday\n");}else{printf("Invalid day Number\n");}return0;}

    Run this code and check its output. When you enter the number “5”, the program will print “Friday” on the console −

    Day Number: 5
    Day Name: Friday
    

    Example 2

    The following C Program uses an if…else if ladder to check whether a given number is even, odd, even & prime, or odd & prime −

    #include <stdio.h>#include <stdbool.h>// Function to check prime number
    bool isPrime(int num){if(num <=1){return false;}for(int i =2; i * i <= num; i++){if(num % i ==0){return false;}}return true;}intmain(){int num =5;// if...else if ladderif(num %2==0&&isPrime(num)){printf("%d is Even and Prime.\n", num);}elseif(num %2!=0&&isPrime(num)){printf("%d is Odd and Prime.\n", num);}elseif(num %2==0){printf("%d is Even.\n", num);}elseif(num %2!=0){printf("%d is Odd.\n", num);}else{printf("Invalid input.\n");}return0;}

    When you run this code, it will produce the following output −

    5 is Odd and Prime.
    
  • The if-else Statement

    The if-else statement is one of the frequently used decision-making statements in C. The if-else statement offers an alternative path when the condition isn’t met.

    The else keyword helps you to provide an alternative course of action to be taken when the Boolean expression in the if statement turns out to be false. The use of else keyword is optional; it’s up to you whether you want to use it or not.

    Syntax of if-else Statement

    Here is the syntax of if-else clause −

    if(Boolean expr){
       Expression;...}else{
       Expression;...}

    The C compiler evaluates the condition, and executes a statement or a block of statements following the if statement if it is true.

    If the programming logic needs the computer to execute some other instructions when the condition is false, they are put as a part of the else clause.

    An if statement is followed by an optional else statement, which executes when the Boolean expression is false.

    Flowchart of if-else Statement

    The following flowchart represents how the if-else clause works in C −

    C if...else statement

    Note that the curly brackets in the if as well as the else clause are necessary if you have more than one statements to be executed. For example, in the following code, we dont need curly brackets.

    if(marks<50)printf("Result: Fail\n");elseprintf("Result: Pass\n");

    However, when there are more than one statements, either in the if or in the else part, you need to tell the compiler that they need to be treated as a compound statement.

    C if-else Statement Examples

    Example: Tax Calculation Using if-else Statement

    In the code given below, the tax on employees income is computed. If the income is below 10000, the tax is applicable at 10%. For the income above 10000, the excess income is charged at 15%.

    #include <stdio.h>intmain(){int income =5000;float tax;printf("Income: %d\n", income);if(income<10000){
    
      tax =(float)(income *10/100);printf("tax: %f \n", tax);}else{
      tax=(float)(1000+(income-10000)*15/100);printf("tax: %f", tax);}}</code></pre>

    Output

    Run the code and check its output −

    Income: 5000
    tax: 500.000000
    

    Set the income variable to 15000, and run the program again.

    Income: 15000
    tax: 1750.000000
    

    Example: Checking Digit Using if-else Statement

    The following program checks if a char variable stores a digit or a non-digit character.

    #include <stdio.h>intmain(){char ch='7';if(ch>=48&& ch<=57){printf("The character is a digit.");}else{printf("The character is not a digit.");}return0;}

    Output

    Run the code and check its output −

    The character is a digit.
    

    Assign any other character such as "*" to "ch" and see the result.

    The character is not a digit.
    

    Example: if-else Statement Without Curly Braces

    Consider the following code. It intends to calculate the discount at 10% if the amount is greater than 100, and no discount otherwise.

    #include <stdio.h>intmain(){int amount =50;float discount;printf("Amount: %d\n", amount);if(amount >=100)
    
      discount = amount *10/100;printf("Discount: %f \n", discount);elseprintf("Discount not applicable\n");return0;}</code></pre>

    Output

    The program shows the following errors during the compilation −

    error: 'else' without a previous 'if'
    

    The compiler will execute the first statement after the if clause and assumes that since the next statement is not else (it is optional anyway), the subsequent printf() statement is unconditional. However, the next else is not connected to any if statement, hence the error.

    Example: if-else Statement Without Curly Braces

    Consider the following code too −

    #include <stdio.h>intmain(){int amount =50;float discount, nett;printf("Amount: %d\n", amount);if(amount<100)printf("Discount not applicable\n");elseprintf("Discount applicable");
    
      discount = amount*10/100;
      nett = amount - discount;printf("Discount: %f Net payable: %f", discount, nett);return0;}</code></pre>

    Output

    The code doesnt give any compiler error, but gives incorrect output −

    Amount: 50
    Discount not applicable
    Discount: 5.000000 Net payable: 45.000000
    

    It produces an incorrect output because the compiler assumes that there is only one statement in the else clause, and the rest of the statements are unconditional.

    The above two code examples emphasize the fact that when there are more than one statements in the if or else else, they must be put in curly brackets.

    To be safe, it is always better to use curly brackets even for a single statement. In fact, it improves the readability of the code.

    The correct solution for the above problem is shown below −

    if(amount >=100){
       discount = amount *10/100;printf("Discount: %f \n", discount);}else{printf("Discount not applicable\n");}

    The else-if Statement in C

    C also allows you to use else-if in the programs. Let's see where you may have to use an else-if clause.

    Let's suppose you have a situation like this. If a condition is true, run the given block that follows. If it isn't, run the next block instead. However, if none of the above is true and all else fails, finally run another block. In such cases, you would use an else-if clause.

    Syntax of else-if Statement

    Here is the syntax of the else-if clause −

    if(condition){// if the condition is true, // then run this code}elseif(another_condition){// if the above condition was false // and this condition is true,// then run the code in this block}else{// if both the above conditions are false,// then run this code}

    Example of else-if Statement

    Take a look at the following example −

    #include <stdio.h>intmain(void){int age =15;if(age <18){printf("You need to be over 18 years old to continue\n");}elseif(age <21){printf("You need to be over 21\n");}else{printf("You are over 18 and older than 21 so you can continue \n");}}

    Output

    Run the code and check its output −

    You need to be over 18 years old to continue
    

    Now, supply a different value for the variable "age" and run the code again. You will get a different output if the supplied value is less than 18.

  • The If Statement

    Conditional execution of instructions is the basic requirement of a computer program. The if statement in C is the primary conditional statement. C allows an optional else keyword to specify the statements to be executed if the if condition is false.

    C – if Statement

    The if statement is a fundamental decision control statement in C programming. One or more statements in a block will get executed depending on whether the Boolean condition in the if statement is true or false.

    Syntax of if Statement

    The if statement is written with the following syntax −

    if(boolean_expression){/* statement(s) will execute if the boolean expression is true */}

    How if Statement Works?

    C uses a pair of curly brackets to form a code block. If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed.

    If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.

    C programming treats any non-zero and non-null values as true. And if the values are either zero or null, then they are treated as false values.

    Flowchart of if Statement

    The behaviour of the if statement is expressed by the following flowchart −

    C if statement

    Flowchart Explained

    When the program control comes across the if statement, the condition is evaluated.

    If the condition is true, the statements inside the if block are executed.

    If the condition is false, the program flow bypasses the conditional block.

    Statements after the if block are executed to continue the program flow.

    Example of if Statement in C

    This example demonstrates the simplest use-case of if statement. It determines and tells the user if the value of a variable is less than 20.

    #include <stdio.h>intmain(){/* local variable declaration */int a;// run the program for different values of "a" // Assign 12 first and 40 afterwards
       
       a =12;//change to 40 and run againprintf("Value of a is : %d\n", a);// check the boolean condition using if statementif(a <20){//if the condition is true, then print the followingprintf("a is less than 20\n");}return0;}

    Output

    Run the above program and check its ouput −

    Value of a is : 12
    a is less than 20
    

    Now assign a number greater than 20. The if condition is not executed.

    Value of a is: 40
    

    if Statement with Logical Operations

    You can put a compound boolean expression with the use of && or || operators in the parenthesis in the if statement.

    Example

    In the following example, three variables “a”, “b” and “c” are compared. The if block will be executed when “a” is greater than both “b” and “c”.

    #include <stdio.h>intmain(){/* local variable declaration */int a, b, c;/*use different values for a, b and c as
       10, 5, 7
       10, 20, 15
       */// change to 10,20,15 respectively next time
       a =10; b =5; c =7;if(a>=b && a>=c){printf("a is greater than b and c \n");}printf("a: %d b:%d c:%d", a, b, c);return0;}

    Output

    Run the code and check its output −

    //when values for a, b and c are 10 5 7
    a is greater than b and c 
    a: 10 b:5 c:7
    
    //when values for a, b and c are 10 20 15
    a: 10 b:20 c:15
    

    Note that the statement following the conditional block is executed after the block is executed. If the condition is false, the program jumps directly to the statement after the block.

    Multiple if Statements

    If you have multiple conditions to check, you can use the if statement multiple times.

    Example

    In this example, the net payable amount is calculated by applying discount on the bill amount.

    The discount applicable is 5 percent if the amount is between 1000 to 5000, and 10 percent if the amount is above 5000. No discount is applicable for purchases below 1000.

    #include <stdio.h>intmain(){// local variable declarationint amount;float discount, net;/*Run the program for different values 
       of amount  500, 2250 and 5200. Blocks in 
       respective conditions will be executed*/// change to 2250 and 5200 and run again
       amount =500;if(amount <1000){
    
      discount=0;}if(amount &gt;=1000&amp;&amp; amount&lt;5000){
      discount=5;}if(amount &gt;=5000){
      discount=10;}
    net = amount - amount*discount/100;printf("Amount: %d Discount: %f Net payable: %f", amount, discount, net);return0;}

    Output

    //when the bill amount is 500
    Amount: 500 Discount: 0.000000 Net payable: 500.000000
    
    //when the bill amount is 2250
    Amount: 2250 Discount: 5.000000 Net payable: 2137.500000
    
    //when the bill amount is 5200
    Amount: 5200 Discount: 10.000000 Net payable: 4680.000000
    

    Checking Multiple Conditions With if Statement

    You can also check multiple conditions using the logical operators in a single if statement.

    Example

    In this program, a student is declared as passed only if the average of “phy” and “maths” marks is greater than equal to 50. Also, the student should have secured more than 35 marks in both the subjects. Otherwise, the student is declared as failed.

    #include <stdio.h>intmain(){/* local variable declaration */int phy, maths;float avg;/*use different values of phy and maths 
       to check conditional execution*///change to 40, 40 and 80, 40
       phy =50; maths =50; 
       avg =(float)(phy + maths)/2;printf("Phy: %d Maths: %d Avg: %f\n", phy, maths, avg);if(avg >=50&&(maths >=35&& phy >=35)){printf("Result: Pass");}if(avg<50){printf("Result: Fail\n");}return0;}

    Output

    Run the code and check its output −

    //when marks in Phy and Maths - 50 50
    Phy: 50 Maths: 50 Avg: 50.000000
    Result: Pass
    
    //when marks in Phy and Maths - 40 40
    Phy: 40 Maths: 40 Avg: 40.000000
    Result: Fail
    
    //when marks in Phy and Maths - 80 40
    Phy: 80 Maths: 40 Avg: 60.000000
    Result: Pass
    
  • Decision Making

    Every programming language including C has decision-making statements to support conditional logic. C has a number of alternatives to add decision-making in the code.

    Any process is a combination of three types of logic −

    • Sequential logic
    • Decision or branching
    • Repetition or iteration

    A computer program is sequential in nature and runs from top to bottom by default. The decision-making statements in C provide an alternative line of execution. You can ask a group of statements to be repeatedly executed till a condition is satisfied.

    The decision-making structures control the program flow based on conditions. They are important tools for designing complex algorithms.

    We use the following keywords and operators in the decision-making statements of a C program − ifelseswitchcasedefaultgotothe ?: operatorbreak, and continue statements.

    In programming, we come across situations when we need to make some decisions. Based on these decisions, we decide what should we do next. Similar situations arise in algorithms too where we need to make some decisions and based on these decisions, we will execute the next block of code.

    The next instruction depends on a Boolean expression, whether the condition is determined to be True or False. C programming language assumes any non-zero and non-null values as True, and if it is either zero or null, then it is assumed as a False value.

    C programming language provides the following types of decision making statements.

    Sr.No.Statement & Description
    1if statementAn if statement consists of a boolean expression followed by one or more statements.
    2if…else statementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
    3nested if statementsYou can use one if or else-if statement inside another if or else-if statement(s).
    4switch statementswitch statement allows a variable to be tested for equality against a list of values.
    5nested switch statementsYou can use one switch statement inside another switch statement(s).

    If Statement in C Programming

    The if statement is used for deciding between two paths based on a True or False outcome. It is represented by the following flowchart −

    Decision making statements in C

    Syntax

    if(Boolean expr){
       expression;...}

    An if statement consists of a boolean expression followed by one or more statements.

    If…else Statement in C Programming

    The ifelse statement offers an alternative path when the condition isn’t met.

    C if...else statement

    Syntax

    if(Boolean expr){
       expression;...}else{
       expression;...}

    An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

    Nested If Statements in C Programming

    Nested if statements are required to build intricate decision trees, evaluating multiple nested conditions for nuanced program flow.

    nested if statements

    You can use one if or else-if statement inside another if or else-if statement(s).

    Switch Statement in C Programming

    A switch statement simplifies multi-way choices by evaluating a single variable against multiple values, executing specific code based on the match. It allows a variable to be tested for equality against a list of values.

    switch statement in C

    Syntax

    switch(expression){case constant-expression  :statement(s);break;/* optional */case constant-expression  :statement(s);break;/* optional *//* you can have any number of case statements */default:/* Optional */statement(s);}

    As in if statements, you can use one switch statement inside another switch statement(s).

    The ?: Operator in C Programming

    We have covered the conditional operator (?:) in the previous chapter which can be used to replace if-else statements. It condenses an if-else statement into a single expression, offering compact and readable code.

    It has the following general form −

    Exp1 ? Exp2 : Exp3;

    Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon (:). The value of a “?” expression is determined like this −

    Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.

    If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the : expression.

    You can simulate nested if statements with the ? operator. You can use another ternary operator in true and/or false operand of an existing ? operator.

    An algorithm can also have an iteration logic. In C, the whiledowhile and for statements are provided to form loops.

    The loop formed by while and dowhile are conditional loops, whereas the for statement forms a counted loop.

    The loops are also controlled by the Boolean expressions. The C compiler decides whether the looping block is to be repeated again, based on a condition.

    The program flow in a loop is also controlled by different jumping statements. The break and continue keywords cause the loop to terminate or perform the next iteration.

    The Break Statement in C Programming

    In C, the break statement is used in switchcase constructs as well as in loops. When used inside a loop, it causes the repetition to be abandoned.

    c break statement

    The Continue Statement in C Programming

    In C, the continue statement causes the conditional test and increment portions of the loop to execute.

    C continue statement

    The goto Statement in C Programming

    C also has a goto keyword. You can redirect the program flow to any labelled instruction in the program.

    Here is the syntax of the goto statement in C −

    goto label;...
    label: statement;
    C goto statement

    With the goto statement, the flow can be directed to any previous step or any subsequent step.

    In this chapter, we had a brief overview of the decision-making statements in C. In the subsequent chapters, we will have an elaborate explanation on each of these decision-making statements, with suitable examples.

  • Misc Operators

    Besides the main categories of operators (arithmetic, logical, assignment, etc.), C uses the following operators that are equally important. Let us discuss the operators classified under this category.

    The “&” symbol, already defined in C as the Binary AND Operator copies a bit to the result if it exists in both operands. The “&” symbol is also defined as the address−of operator.

    The “*” symbol − A well−known arithmetic operator for multiplication, it can also be used as a dereference operator.

    C uses the “>” symbol, defined as a ternary operator, used to evaluate a conditional expression.

    In C, the dot “.” symbol is used as the member access operator in connection with a struct or union type.

    C also uses the arrow “” symbol as an indirection operator, used especially with the pointer to the struct variable.

    OperatorDescriptionExample
    sizeof()Returns the size of a variable.sizeof(a), where a is integer, will return 4.
    &Returns the address of a variable.&a; returns the actual address of the variable.
    *Pointer to a variable.*a;
    ?:Conditional Expression.If Condition is true ? then value X, else value Y
    .Member access operatorvar.member
    −>Access members of a struct variable with pointerptr −> member;

    The sizeof Operator in C

    The sizeof operator is a compile−time unary operator. It is used to compute the size of its operand, which may be a data type or a variable. It returns the size in number of bytes. It can be applied to any data type, float type, or pointer type variables.

    sizeof(type or var);

    When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32−bit system can show different output while a 64−bit system can show different of the same data types.

    Example

    Here is an example in C language

    #include <stdio.h>intmain(){int a =16;printf("Size of variable a : %d\n",sizeof(a));printf("Size of int data type : %d\n",sizeof(int));printf("Size of char data type : %d\n",sizeof(char));printf("Size of float data type : %d\n",sizeof(float));printf("Size of double data type : %d\n",sizeof(double));return0;}

    Output

    When you run this code, it will produce the following output −

    Size of variable a: 4
    Size of int data type: 4
    Size of char data type: 1
    Size of float data type: 4
    Size of double data type: 8
    

    Address-of Operator in C

    The “&” operator returns the address of an existing variable. We can assign it to a pointer variable −

    int a;

    Assuming that the compiler creates the variable at the address 1000 and “x” at the address 2000, then the address of “a” is stored in “x“.

    Header Files

    Example

    Let us understand this with the help of an example. Here, we have declared an int variable. Then, we print its value and address −

    #include <stdio.h>intmain(){int var =100;printf("var: %d address: %d", var,&var);return0;}

    Output

    Run the code and check its output −

    var: 100 address: 931055924
    

    The Dereference Operator in C

    To declare a pointer variable, the following syntax is to be used −

    type *var;

    The name of the variable must be prefixed with an asterisk (*). The data type indicates it can store the address of which data type. For example −

    int*x;

    In this case, the variable x is meant to store the address of another int variable.

    float*y;

    The “y” variable is a pointer that stores the memory location of a float variable.

    The “&” operator returns the address of an existing variable. We can assign it to the pointer variable −

    int a;int*x =&a;

    We can see that the address of this variable (any type of variable for that matter) is an integer. So, if we try to store it in a pointer variable of int type, see what happens −

    float var1 =10.55;int*intptr =&var1;

    The compiler doesnt accept this, and reports the following error −

    initialization of 'int *' from incompatible pointer type 'float *'[-Wincompatible-pointer-types]

    It indicates that the type of a variable and the type of its pointer must be the same.

    In C, variables have specific data types that define their size and how they store values. Declaring a pointer with a matching type (e.g., “float *”) enforces type compatibility between the pointer and the data it points to.

    Different data types occupy different amounts of memory in C. For example, an int typically takes 4 bytes, while a float might take 4 or 8 bytes depending on the system.

    Adding or subtracting integers from pointers moves them in memory based on the size of the data they point to.

    Hence, we declare the floatptr variable of float * type.

    Example 1

    Take a look at the following example −

    #include <stdio.h>intmain(){float var1 =10.55;float*floatptr =&var1;printf("var1: %f \naddress of var1: %d \n\nfloatptr: %d \naddress of floatptr: %d", var1,&var1, floatptr,&floatptr);return0;}

    Output

    var1: 10.550000 
    address of var1: 6422044 
    
    floatptr: 6422044 
    address of floatptr: 6422032
    

    Example 2

    The * operator is called the Dereference operator. It returns the value stored in the address which is stored in the pointer, i.e., the value of the variable it is pointing to. Take a look at the following example −

    #include <stdio.h>intmain(){float var1 =10.55;float*floatptr =&var1;printf("var1: %f address of var1: %d\n",var1,&var1);printf("floatptr: %d address of floatptr: %d\n", floatptr,&floatptr);printf("var1: %f value at floatptr: %f", var1,*floatptr);return0;}

    Output

    On running this code, you will get the following output −

    var1: 10.550000 address of var1: 6422044
    floatptr: 6422044 address of floatptr: 6422032
    var1: 10.550000 value at floatptr: 10.550000
    

    The Ternary Operator in C

    In C language, the “?” character is used as the ternary operator. It is also known as a conditional operator.

    The term “ternary” implies that the operator has three operands. The ternary operator is often used to put conditional (if−else) statements in a compact way.

    The ? operator is used with the following syntax −

    exp1 ? exp2 : exp3
    

    It has the following three operands −

    • exp1 − a Boolean expression that evaluates to True or False
    • exp2 − returned by the ? operator when exp1 is true
    • exp3 − returned by the ? operator when exp1 is false

    Example

    The following C program uses the ? operator to check if the value of a is even or odd.

    #include <stdio.h>intmain(){int a =10;(a %2==0)?printf("%d is Even\n", a):printf("%d is Odd\n", a);return0;}

    Output

    10 is Even
    

    Change the value of “a” to 15 and run the code again. Now you will get the following output −

    15 is Odd
    

    The conditional operator is a compact representation of if − else construct.

    The Dot (.) Operator in C

    In C language, you can define a derived data type with struct and union keywords. A derived or user−defined data type that groups together member elements of different types.

    The dot operator is a member selection operator, when used with the struct or union variable. The dot (.) operator has the highest operator precedence in C Language and its associativity is from left to right.

    Take a look at its syntax −

    var.member;

    Here, var is a variable of a certain struct or a union type, and member is one of the elements defined while creating structure or union.

    A new derived data type is defined with struct keyword as following syntax −

    structnewtype{
       type elem1;
       type elem2;
       type elem3;......};

    You can then declare a variable of this derived data type as −

    structnewtype var;

    To access a certain member,

    var.elem1;

    Example

    Let us declare a struct type named book, declare a struct variable. The following example shows the use of “.” operator to access the members in the book structure.

    #include <stdio.h>structbook{char title[10];double price;int pages;};intmain(){structbook b1 ={"Learn C",675.50,325};printf("Title: %s\n", b1.title);printf("Price: %lf\n", b1.price);printf("No of Pages: %d\n", b1.pages);printf("size of book struct: %d",sizeof(structbook));return0;}

    Output

    On running this code, you will get the following output −

    Title: Learn C
    Price: 675.500000
    No of Pages: 325
    size of book struct: 32
    

    The Indirection Operator in C

    A structure is a derived data type in C. In C, the struct keyword has been provided to define a custom data type.

    A new derived data type is defined with a struct keyword as the following syntax −

    structtype{
       type var1;
       type var2;
       type var3;......};

    You can then declare a variable of this derived data type as −

    structtype= var;

    Usually, a struct is declared before the first function is defined in the program, after the include statements. That way, the derived type can be used for declaring its variable inside any function.

    Let us declare a struct type named book as follows −

    structbook{char title[10];double price;int pages;};

    To declare a variable of this type, use the following syntax −

    structbook b1;

    The initialization of a struct variable is done by placing value of each element inside curly brackets.

    structbook b1 ={"Learn C",675.50,325};

    You can also store the address of a struct variable in the struct pointer variable.

    structbook*strptr;

    To store the address, use the “&” operator.

    strptr =&b1;

    C defines the arrow () symbol to be used with struct pointer as indirection operator (also called struct dereference operator). It helps to access the elements of the struct variable to which the pointer reference to.

    Example

    In this example, strptr is a pointer to struct book b1 variable. Hence, strrptr−>title returns the title, similar to b1.title does.

    #include <stdio.h>#include <string.h>structbook{char title[10];double price;int pages;};intmain(){structbook b1 ={"Learn C",675.50,325};structbook*strptr;
       strptr =&b1;printf("Title: %s\n", strptr->title);printf("Price: %lf\n", strptr->price);printf("No of Pages: %d\n", strptr->pages);return0;}

    Output

    Run the code and check its output −

    Title: Learn C
    Price: 675.500000
    No of Pages: 325
    
  • Operator Precedence

    A single expression in C may have multiple operators of different types. The C compiler evaluates its value based on the operator precedence and associativity of operators.

    The precedence of operators determines the order in which they are evaluated in an expression. Operators with higher precedence are evaluated first.

    For example, take a look at this expression −

    x =7+3*2;

    Here, the multiplication operator “*” has a higher precedence than the addition operator “+”. So, the multiplication 3*2 is performed first and then adds into 7, resulting in “x = 13”.

    The following table lists the order of precedence of operators in C. Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom.

    CategoryOperatorAssociativity
    Postfix() [] -> . ++ – –Left to right
    Unary+ – ! ~ ++ – – (type)* & sizeofRight to left
    Multiplicative* / %Left to right
    Additive+ –Left to right
    Shift<< >>Left to right
    Relational< <= > >=Left to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
    Comma,Left to right

    Within an expression, higher precedence operators will be evaluated first.

    Operator Associativity

    In C, the associativity of operators refers to the direction (left to right or right to left) an expression is evaluated within a program. Operator associativity is used when two operators of the same precedence appear in an expression.

    In the following example −

    15/5*2

    Both the “/” (division) and “*” (multiplication) operators have the same precedence, so the order of evaluation will be decided by associativity.

    As per the above table, the associativity of the multiplicative operators is from Left to Right. So, the expression is evaluated as −

    (15/5)*2

    It evaluates to −

    3*2=6

    Example 1

    In the following code, the multiplication and division operators have higher precedence than the addition operator.

    The left−to−right associativity of multiplicative operator results in multiplication of “b” and “c” divided by “e“. The result then adds up to the value of “a“.

    #include <stdio.h>intmain(){int a =20;int b =10;int c =15;int d =5;int e;
       e = a + b * c / d;printf("e : %d\n",  e );return0;}

    Output

    When you run this code, it will produce the following output −

    e: 50
    

    Example 2

    We can use parenthesis to change the order of evaluation. Parenthesis () got the highest priority among all the C operators.

    #include <stdio.h>intmain(){int a =20;int b =10;int c =15;int d =5;int e;
    
       e =(a + b)* c / d;printf("e:  %d\n",  e);return0;}

    Output

    Run the code and check its output −

    e: 90
    

    In this expression, the addition of a and b in parenthesis is first. The result is multiplied by c and then the division by d takes place.

    Example 3

    In the expression that calculates e, we have placed a+b in one parenthesis, and c/d in another, multiplying the result of the two.

    #include <stdio.h>intmain(){int a =20;int b =10;int c =15;int d =5;int e;
       e =(a + b)*(c / d);printf("e: %d\n",  e );return0;}

    Output

    On running this code, you will get the following output −

    e: 90
    

    Precedence of Post / Prefix Increment / Decrement Operators

    The “++” and “− −” operators act as increment and decrement operators, respectively. They are unary in nature and can be used as a prefix or postfix to a variable.

    When used as a standalone, using these operators in a prefix or post−fix manner has the same effect. In other words, “a++” has the same effect as “++a”. However, when these “++” or “− −” operators appear along with other operators in an expression, they behave differently.

    Postfix increment and decrement operators have higher precedence than prefix increment and decrement operators.

    Example

    The following example shows how you can use the increment and decrement operators in a C program −

    #include <stdio.h>intmain(){int x =5, y =5, z;printf("x: %d \n", x);
    
       z = x++;printf("Postfix increment: x: %d z: %d\n", x, z);
    
       z =++y;printf("Prefix increment. y: %d z: %d\n", y ,z);return0;}

    Output

    Run the code and check its output −

    x: 5 
    Postfix increment: x: 6 z: 5
    Prefix increment. y: 6 z: 6
    

    Logical operators have left−to−right associativity. However, the compiler evaluates the least number of operands needed to determine the result of the expression. As a result, some operands of the expression may not be evaluated.

    For example, take a look at the following expression −

    x >50&& y >50

    Here the second operand “y > 50” is evaluated only if the first expression evaluates to True.