C – The if-else Statement ”; Previous Next 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 − 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 don’t need curly brackets. if (marks<50) printf(“Result: Failn”); else printf(“Result: Passn”); 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 employee’s 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> int main() { int income = 5000; float tax; printf(“Income: %dn”, 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); } } 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> int main() { char ch=”7”; if (ch>=48 && ch<=57){ printf(“The character is a digit.”); } else{ printf(“The character is not a digit.”); } return 0; } 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> int main() { int amount = 50; float discount; printf(“Amount: %dn”, amount); if (amount >= 100) discount = amount * 10 / 100; printf(“Discount: %f n”, discount); else printf(“Discount not applicablen”); return 0; } 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> int main() { int amount = 50; float discount, nett; printf(“Amount: %dn”, amount); if (amount<100) printf(“Discount not applicablen”); else printf(“Discount applicable”); discount = amount*10/100; nett = amount – discount; printf(“Discount: %f Net payable: %f”, discount, nett); return 0; } Output The code doesn’t 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 applicablen”); } 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 } else if(another_condition){ // if the above condition was false // and this condition is true, // then run the code in this block }
Category: cprogramming
C – Continue Statement
Continue Statement in C ”; Previous Next The behaviour of continue statement in C is somewhat opposite to the break statement. Instead of forcing the termination of a loop, it forces the next iteration of the loop to take place, skipping the rest of the statements in the current iteration. What is Continue Statement in C? The continue statement is used to skip the execution of the rest of the statement within the loop in the current iteration and transfer it to the next loop iteration. It can be used with all the C language loop constructs (while, do while, and for). Continue Statement Syntax The continue statement is used as per the following structure − while (expr){ . . . . . . if (condition) continue; . . . } Continue Statement Flowchart The following flowchart represents how continue works − You must use the continue statement inside a loop. If you use a continue statement outside a loop, then it will result in compilation error. Unlike the break statement, continue is not used with the switch-case statement. Continue Statement with Nested Loops In case of nested loops, continue will continue the next iteration of the nearest loop. The continue statement is often used with if statements. Continue Statement Examples Example: Continue Statement with While Loop In this program the loop generates 1 to 10 values of the variable “i”. Whenever it is an even number, the next iteration starts, skipping the printf statement. Only the odd numbers are printed. #include <stdio.h> int main(){ int i = 0; while (i < 10){ i++; if(i%2 == 0) continue; printf(“i: %dn”, i); } } Output i: 1 i: 3 i: 5 i: 7 i: 9 Example: Continue Statement with For Loop The following program filters out all the vowels in a string − #include <stdio.h> #include <string.h> int main () { char string[] = “Welcome to TutorialsPoint C Tutorial”; int len = strlen(string); int i; printf(“Given string: %sn”, string); printf(“after removing the vowelsn”); for (i=0; i<len; i++){ if (string[i]==”a” || string[i]==”e” || string[i] == ”i” || string[i] == ”o” || string[i] == ”u”) continue; printf(“%c”, string[i]); } return 0; } Output Run the code and check its output − Given string: Welcome to TutorialsPoint C Tutorial after removing the vowels Wlcm t TtrlsPnt C Ttrl Example: Continue Statement with Nested Loops If a continue statement appears inside an inner loop, the program control jumps to the beginning of the corresponding loop. In the example below, there are three for loops one inside the other. These loops are controlled by the variables i, j, and k respectively. The innermost loop skips the printf statement if k is equal to either i or j, and goes to its next value of k. The second j loop executes the continue when it equals i. As a result, all the unique combinations of three digits 1, 2 and 3 are displayed. #include <stdio.h> int main (){ int i, j, k; for(i = 1; i <= 3; i++){ for(j = 1; j <= 3; j++){ if (i == j) continue; for (k=1; k <= 3; k++){ if (k == j || k == i) continue; printf(“%d %d %d n”, i,j,k); } } } return 0; } Output Run the code and check its output − 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Example: Removing Spaces Between Words in a String The following code detects the blankspaces between the words in a string, and prints each word on a different line. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(){ char string[] = “Welcome to TutorialsPoint C Tutorial”; int len = strlen(string); int i; printf(“Given string: %sn”, string); for (i = 0; i < len; i++){ if (string[i] == ” ”){ printf(“n”); continue; } printf(“%c”, string[i]); } return 0; } Output On executing this code, you will get the following output − Given string: Welcome to TutorialsPoint C Tutorial Welcome to TutorialsPoint C Tutorial Example: Finding Prime Factors of a Number One of the cases where the continue statement proves very effective is in the problem of writing a program to find prime factors of a given number. The algorithm of this program works like this − The given number is successively divided by numbers starting with 2. If the number is divisible, the given number is reduced to the division, and the resultant number is checked for divisibility with 2 until it is no longer divisible. If not by 2, the process is repeated for all the odd numbers starting with 3. The loop runs while the given number reduces to 1. Here’s the program to find the prime factors − #include <stdio.h> int main (){ int n = 64; int i, m = 2; printf(“Prime factors of %d: n”, n); while (n > 1){ if (n % m == 0){ n = n/m; printf(“%d “, m); continue; } if (m == 2) m++; else m = m+2; } return 0; } Output Here, the given number is 64. So, when you run this code, it will produce the following output − Prime factors of 64: 2 2 2 2 2 2 Change the number to 45 and then 90. Run the code again. Now you will get the following outputs − Prime factors of 45: 3 3 5 Prime factors of 90: 2 3 3 5 c_loops.htm
C – if statement
C – The If Statement ”; Previous Next 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 − 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> int main (){ /* 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 again printf(“Value of a is : %dn”, a); // check the boolean condition using if statement if(a < 20){ //if the condition is true, then print the following printf(“a is less than 20n” ); } return 0; } 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> int main () { /* 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); return 0; } 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> int main () { // local variable declaration int 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 >= 1000 && amount<5000){ discount=5; } if (amount >= 5000){ discount=10; } net = amount – amount*discount/100; printf(“Amount: %d Discount: %f Net payable: %f”, amount, discount, net); return 0; } 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> int main (){ /* local variable declaration */ int phy, maths; float avg; /*use different values of phy and maths to check conditional execution*/ //change to
C – Decision Making
C – Decision Making ”; Previous Next 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 − if, else, switch, case, default, goto, the ?: operator, break, 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 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 nested if statements You can use one if or else-if statement inside another if or else-if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You 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 − 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 if–else statement offers an alternative path when the condition isn”t met. 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. 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. 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 while, do–while and for statements are provided to form loops. The loop formed by while and do–while 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 switch–case constructs as well as in loops. When used inside a loop, it causes the repetition to be abandoned. The Continue Statement in C Programming In C, the continue statement causes the conditional test and increment portions of the loop to execute. 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 −
C – switch statement
Switch Statement in C ”; Previous Next A 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 Value1 case Value1: Statement1; Statement2; break; // if expr equals Value2 case Value2: Statement1; Statement2; break; . . // if expr is other than the specific values above default: Statement1; Statement2; } 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 doesn’t 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 − 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> int main(){ /* local variable definition */ char ch = ”e”; printf(“Time code: %cnn”, ch); if (ch == ”m”) printf(“Good Morning”); else if (ch == ”a”) printf(“Good Afternoon”); else printf(“Good Evening”); return 0; } The if-else logic in the above code is replaced by the switch-case construct in the code below − #include <stdio.h> int main (){ // local variable definition char ch = ”m”; printf(“Time code: %cnn”, ch); switch (ch){ case ”a”: printf(“Good Afternoonn”); break; case ”e”: printf(“Good Eveningn”); break; case ”m”: printf(“Good Morningn”); } return 0; } 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
C – Relational Operators
Relational Operators in C ”; Previous Next Relational operators in C are defined to perform comparison of two values. The familiar angular brackets < and > are the relational operators in addition to a few more as listed in the table below. These relational operators are used in Boolean expressions. All the relational operators evaluate to either True or False. C doesn’t have a Boolean data type. Instead, “0” is interpreted as False and any non-zero value is treated as True. Example 1 Here is a simple example of relational operator in C − #include <stdio.h> int main(){ int op1 = 5; int op2 = 3; printf(“op1: %d op2: %d op1 < op2: %dn”, op1, op2, op1 < op2); return 0; } Output Run the code and check its output − op1: 5 op2: 3 op1 < op2: 0 Relational operators have an important role to play in decision-control and looping statements in C. The following table lists all the relational operators in C − Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) All the relational operators are binary operators. Since they perform comparison, they need two operands on either side. We use the = symbol in C as the assignment operator. So, C uses the “==” (double equal) as the equality operator. The angular brackets > and < are used as the “greater than” and “less than” operators. When combined with the “=” symbol, they form the “>=” operator for “greater than or equal” and “<=” operator for “less than or equal” comparison. Finally, the “=” symbol prefixed with “!” (!=) is used as the inequality operator. Example 2 The following example shows all the relational operators in use. #include <stdio.h> int main(){ int a = 21; int b = 10; int c ; printf(“a: %d b: %dn”, a,b); if(a == b){ printf(“Line 1 – a is equal to bn” ); } else { printf(“Line 1 – a is not equal to bn” ); } if (a < b){ printf(“Line 2 – a is less than bn” ); } else { printf(“Line 2 – a is not less than bn” ); } if (a > b){ printf(“Line 3 – a is greater than bn” ); } else { printf(“Line 3 – a is not greater than b nn” ); } /* Lets change value of a and b */ a = 5; b = 20; printf(“a: %d b: %dn”, a,b); if (a <= b){ printf(“Line 4 – a is either less than or equal to bn” ); } if (b >= a){ printf(“Line 5 – b is either greater than or equal to bn” ); } if(a != b){ printf(“Line 6 – a is not equal to bn” ); } else { printf(“Line 6 – a is equal to bn” ); } return 0; } Output When you run this code, it will produce the following output − a: 21 b: 10 Line 1 – a is not equal to b Line 2 – a is not less than b Line 3 – a is greater than b a: 5 b: 20 Line 4 – a is either less than or equal to b Line 5 – b is either greater than or equal to b Line 6 – a is not equal to b Example 3 The == operator needs to be used with care. Remember that “=” is the assignment operator in C. If used by mistake in place of the equality operator, you get an incorrect output as follows − #include <stdio.h> int main(){ int a = 5; int b = 3; if (a = b){ printf(“a is equal to b”); } else { printf(“a is not equal to b”); } return 0; } Output The value of “b” is assigned to “a” which is non-zero, and hence the if expression returns true. a is equal to b Example 4 We can have “char” types too as the operand for all the relational operators, as the “char” type is a subset of “int” type. Take a look at this example − #include <stdio.h> int main(){ char a = ”B”; char b = ”d”; printf(“a: %c b: %cn”, a,b); if(a == b){ printf(“Line 1 – a is equal to b n”); } else { printf(“Line 1 – a is not equal to b n”); } if (a < b){ printf(“Line 2 – a is less than b n”); } else { printf(“Line 2 – a is
C – Logical Operators
Logical Operators in C ”; Previous Next Logical operators in C evaluate to either True or False. Logical operators are typically used with Boolean operands. The logical AND operator (&&) and the logical OR operator (||) are both binary in nature (require two operands). The logical NOT operator (!) is a unary operator. Since C treats “0” as False and any non-zero number as True, any operand to a logical operand is converted to a Boolean data. Here is a table showing the logical operators in C − Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A) The result of a logical operator follows the principle of Boolean algebra. The logical operators follow the following truth tables. Logical AND (&&) Operator The && operator in C acts as the logical AND operator. It has the following truth table − a b a&&b true true True true false False false true False false false False The above truth table shows that the result of && is True only if both the operands are True. Logical OR (||) Operator C uses the double pipe symbol (||) as the logical OR operator. It has the following truth table − a b a||b true true True true false True false true true false false false The above truth table shows that the result of || operator is True when either of the operands is True, and False if both operands are false. Logical NOT (!) Operator The logical NOT ! operator negates the value of a Boolean operand. True becomes False, and False becomes True. Here is its truth table − A !a True False False True Unlike the other two logical operators && and ||, the logical NOT operator ! is a unary operator. Example 1 The following example shows the usage of logical operators in C − #include <stdio.h> int main(){ int a = 5; int b = 20; if (a && b){ printf(“Line 1 – Condition is truen” ); } if (a || b){ printf(“Line 2 – Condition is truen” ); } /* lets change the value of a and b */ a = 0; b = 10; if (a && b){ printf(“Line 3 – Condition is truen” ); } else { printf(“Line 3 – Condition is not truen” ); } if (!(a && b)){ printf(“Line 4 – Condition is truen” ); } return 0; } Output Run the code and check its output − Line 1 – Condition is true Line 2 – Condition is true Line 3 – Condition is not true Line 4 – Condition is true Example 2 In C, a char type is a subset of int type. Hence, logical operators can work with char type too. #include <stdio.h> int main(){ char a = ”a”; char b = ””; // Null character if (a && b){ printf(“Line 1 – Condition is truen” ); } if (a || b){ printf(“Line 2 – Condition is truen” ); } return 0; } Output Run the code and check its output − Line 2 – Condition is true Logical operators are generally used to build a compound boolean expression. Along with relational operators, logical operators too are used in decision-control and looping statements in C. Example 3 The following example shows a compound Boolean expression in a C program − #include <stdio.h> int main(){ int phy = 50; int maths = 60; if (phy < 50 || maths < 50){ printf(“Result:Fail”); } else { printf(“Result:Pass”); } return 0; } Output Result:Pass Example 4 The similar logic can also be expressed using the && operator as follows − #include <stdio.h> int main(){ int phy = 50; int maths = 60; if (phy >= 50 && maths >= 50){ printf(“Result: Pass”); } else { printf(“Result: Fail”); } return 0; } Output Run the code and check its output − Result: Pass Example 5 The following C code employs the NOT operator in a while loop − #include <stdio.h> int main(){ int i = 0; while (!(i > 5)){ printf(“i = %dn”, i); i++; } return 0; } Output In the above code, the while loop continues to iterate till the expression “!(i > 5)” becomes false, which will be when the value of “i” becomes more than 5. i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 C has bitwise counterparts of the logical operators such as bitwise AND (&), bitwise OR (|), and binary NOT or complement (~) operator. c_operators.htm
C – Ternary Operator
Ternary Operator in C ”; Previous Next The ternary operator (?:) in C is a type of conditional operator. The term “ternary” implies that the operator has three operands. The ternary operator is often used to put multiple conditional (if-else) statements in a more compact manner. Syntax of Ternary Operator in C The ternary operator is used with the following syntax − exp1 ? exp2 : exp3 It uses three operands − exp1 − A Boolean expression evaluating to true or false exp2 − Returned by the ? operator when exp1 is true exp3 − Returned by the ? operator when exp1 is false Example 1: Ternary Operator in C The following C program uses the ternary operator to check if the value of a variable is even or odd. #include <stdio.h> int main(){ int a = 10; (a % 2 == 0) ? printf(“%d is Even n”, a) : printf(“%d is Odd n”, a); return 0; } Output When you run this code, it will produce the following 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 Example 2 The conditional operator is a compact representation of if–else construct. We can rewrite the logic of checking the odd/even number by the following code − #include <stdio.h> int main(){ int a = 10; if (a % 2 == 0){ printf(“%d is Evenn”, a); } else{ printf(“%d is Oddn”, a); } return 0; } Output Run the code and check its output − 10 is Even Example 3 The following program compares the two variables “a” and “b”, and assigns the one with the greater value to the variable “c”. #include <stdio.h> int main(){ int a = 100, b = 20, c; c = (a >= b) ? a : b; printf (“a: %d b: %d c: %dn”, a, b, c); return 0; } Output When you run this code, it will produce the following output − a: 100 b: 20 c: 100 Example 4 The corresponding code with if–else construct is as follows − #include <stdio.h> int main(){ int a = 100, b = 20, c; if (a >= b){ c = a; } else { c = b; } printf (“a: %d b: %d c: %dn”, a, b, c); return 0; } Output Run the code and check its output − a: 100 b: 20 c: 100 Example 5 If you need to put multiple statements in the true and/or false operand of the ternary operator, you must separate them by commas, as shown below − #include <stdio.h> int main(){ int a = 100, b = 20, c; c = (a >= b) ? printf (“a is larger “), c = a : printf(“b is larger “), c = b; printf (“a: %d b: %d c: %dn”, a, b, c); return 0; } Output In this code, the greater number is assigned to “c”, along with printing the appropriate message. a is larger a: 100 b: 20 c: 20 Example 6 The corresponding program with the use of if–else statements is as follows − #include <stdio.h> int main(){ int a = 100, b = 20, c; if(a >= b){ printf(“a is larger n”); c = a; } else{ printf(“b is larger n”); c = b; } printf (“a: %d b: %d c: %dn”, a, b, c); return 0; } Output Run the code and check its output − a is larger a: 100 b: 20 c: 100 Nested Ternary Operator Just as we can use nested if-else statements, we can use the ternary operator inside the True operand as well as the False operand. exp1 ? (exp2 ? expr3 : expr4) : (exp5 ? expr6: expr7) First C checks if expr1 is true. If so, it checks expr2. If it is true, the result is expr3; if false, the result is expr4. If expr1 turns false, it may check if expr5 is true and return expr6 or expr7. Example 1 Let us develop a C program to determine whether a number is divisible by 2 and 3, or by 2 but not 3, or 3 but not 2, or neither by 2 and 3. We will use nested condition operators for this purpose, as shown in the following code − #include <stdio.h> int main(){ int a = 15; printf(“a: %dn”, a); (a % 2 == 0) ? ( (a%3 == 0)? printf(“divisible by 2 and 3”) : printf(“divisible by 2 but not 3”)) : ( (a%3 == 0)? printf(“divisible by 3 but not 2”) : printf(“not divisible by 2, not divisible by 3”) ); return 0; } Output Check for different values − a: 15 divisible by 3 but not 2 a: 16 divisible by 2 but not 3 a: 17 not divisible by 2, not divisible by 3 a: 18 divisible by 2 and 3 Example 2 In this program, we have used nested if–else statements for the same purpose instead of conditional operators − #include <stdio.h> int main(){ int a = 15; printf(“a: %dn”, 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 %
Increment and Decrement Operators in C ”; Previous Next C – Increment and Decrement Operators The increment operator (++) increments the value of a variable by 1, while the decrement operator (–) decrements the value. Increment and decrement operators are frequently used in the construction of counted loops in C (with the for loop). They also have their application in the traversal of array and pointer arithmetic. The ++ and — operators are unary and can be used as a prefix or posfix to a variable. Example of Increment and Decrement Operators The following example contains multiple statements demonstrating the use of increment and decrement operators with different variations − #include <stdio.h> int main() { int a = 5, b = 5, c = 5, d = 5; a++; // postfix increment ++b; // prefix increment c–; // postfix decrement –d; // prefix decrement printf(“a = %dn”, a); printf(“b = %dn”, b); printf(“c = %dn”, c); printf(“d = %dn”, d); return 0; } Output When you run this code, it will produce the following output − a = 6 b = 6 c = 4 d = 4 Example Explanation In other words, “a++” has the same effect as “++a”, as both the expressions increment the value of variable “a” by 1. Similarly, “a–” has the same effect as “–a”. The expression “a++;” can be treated as the equivalent of the statement “a = a + 1;”. Here, the expression on the right adds 1 to “a” and the result is assigned back to 1, therby the value of “a” is incremented by 1. Similarly, “b–;” is equivalent to “b = b – 1;”. Types of Increment Operator There are two types of increment operators – pre increment and post increment. Pre (Prefix) Increment Operator In an expression, the pre-increment operator increases the value of a variable by 1 before the use of the value of the variable. Syntax ++variable_name; Example In the following example, we are using a pre-increment operator, where the value of “x” will be increased by 1, and then the increased value will be used in the expression. #include <stdio.h> int main() { int x = 10; int y = 10 + ++x; printf(“x = %d, y = %dn”, x, y); return 0; } When you run this code, it will produce the following output − x = 11, y = 21 Post (Postfix) Increment Operator In an expression, the post-increment operator increases the value of a variable by 1 after the use of the value of the variable. Syntax variable_name++; Example In the following example, we are using post-increment operator, where the value of “x” will be used in the expression and then it will be increased by 1. #include <stdio.h> int main() { int x = 10; int y = 10 + x++; printf(“x = %d, y = %dn”, x, y); return 0; } When you run this code, it will produce the following output − x = 11, y = 20 Types of Decrement Operator There are two types of decrement operators – pre decrement and post decrement. Pre (Prefix) decrement Operator In an expression, the pre-decrement operator decreases the value of a variable by 1 before the use of the value of the variable. Syntax –variable_name; Example In the following example, we are using a pre-decrement operator, where the value of “x” will be decreased by 1, and then the decreased value will be used in the expression. #include <stdio.h> int main() { int x = 10; int y = 10 + –x; printf(“x = %d, y = %dn”, x, y); return 0; } When you run this code, it will produce the following output − x = 9, y = 19 Post (Postfix) Decrement Operator In an expression, the post-decrement operator decreases the value of a variable by 1 after the use of the value of the variable. Syntax variable_name–; Example In the following example, we are using post-decrement operator, where the value of “x” will be used in the expression and then it will be decreased by 1. #include <stdio.h> int main() { int x = 10; int y = 10 + x–; printf(“x = %d, y = %dn”, x, y); return 0; } When you run this code, it will produce the following output − x = 9, y = 20 More Examples of Increment and Decrement Operators Example 1 The following example highlights the use of prefix/postfix increment/decrement − #include <stdio.h> int main(){ char a = ”a”, b = ”M”; int x = 5, y = 23; printf(“a: %c b: %cn”, a, b); a++; printf(“postfix increment a: %cn”, a); ++b; printf(“prefix increment b: %cn”, b); printf(“x: %d y: %dn”, x, y); x–; printf(“postfix decrement x : %dn”, x); –y; printf(“prefix decrement y : %dn”, y); return 0; } Output When you run this code, it will produce the following output − a: a b: M postfix increment a: b prefix increment b: N x: 5 y: 23 postfix decrement x: 4 prefix decrement y: 22 The above example shows that the prefix as well as postfix operators have the same effect on the value of the operand variable. However, when these “++” or “–” operators appear along with the other operators in an expression, they behave differently. Example 2 In the
C – Unary Operators
Unary Operators in C ”; Previous Next While most of the operators in C are binary in nature, there are a few unary operators as well. An operator is said to be unary if it takes just a single operand, unlike a binary operator which needs two operands. Some operators in C are binary as well as unary in their usage. Examples of unary operators in C include ++, —, !, etc. The Increment Operator in C The increment operator (++) adds 1 to the value of its operand variable and assigns it back to the variable. The statement a++ is equivalent to writing “a = a + 1.” The “++” operator can appear before or after the operand and it will have the same effect. Hence, a++ is equivalent to ++a. However, when the increment operator appears along with other operators in an expression, its effect is not the same. The precedence of “prefix ++” is more than “postfix ++”. Hence, “b = a++;” is not the same as “b = ++a;“ In the former case, “a” is assigned to “b” before the incrementation; while in the latter case, the incrementation is performed before the assignment. The Decrement Operator in C The decrement operator (–) subtracts 1 from the value of its operand variable and assigns it back to the variable. The statement “a–;” is equivalent to writing “a = a – 1;“ The “–” operator can appear before or after the operand and in either case, it will have the same effect. Hence, “a–” is equivalent to “–a“. However, when the decrement operator appears along with other operators in an expression, its effect is not the same. The precedence of “prefix –” is more than “postfix –“. Hence, “b = a–” is not the same as “b = –a“. In the former case, “a” is assigned to “b” before the decrementation; while in the latter case, the decrementation is performed before the assignment. The Unary “+” Operator in C The “+” and “–” operators are well known as binary addition and subtraction operators. However, they can also be used in unary fashion. When used as unary, they are prefixed to the operand variable. The “+” operator is present implicitly whenever a positive value is assigned to any numeric variable. The statement “int x = 5;” is same as “int x = +5;“. The same logic applies to float and char variable too. Example Take a look at the following example − #include <stdio.h> int main(){ char x = ”A”; char y = +x; float a = 1.55; float b = +a; printf (“x: %c y: %cn”, x,y); printf (“a: %f y: %fn”, a,b); return 0; } Output When you run this code, it will produce the following output − x: A y: A a: 1.550000 y: 1.550000 The Unary “−” Operator in C The “−” symbol, that normally represents the subtraction operator, also acts the unary negation operator in C. The following code shows how you can use the unary negation operator in C. Example In this code, the unary negation operator returns the negative value of “x” and assigns the same to another variable “y”. #include <stdio.h> int main(){ int x = 5; int y = -x; printf(“x: %d y: %dn”, x, y); return 0; } Output Run the code and check its output − x: 5 y: -5 The Address-of Operator (&) in C We use the & symbol in C as the binary AND operator. However, we also use the same & symbol in unary manner as the “address-of” operator. Example The & operator returns the memory address of its variable operand. Take a look at the following example − #include <stdio.h> int main(){ char x = ”A”; printf (“Address of x: %dn”, &x); return 0; } Output Run the code and check its output − Address of x: 6422047 Note: The C compiler assigns a random memory address whenever a variable is declared. Hence, the result may vary every time the address is printed. The format specifier %p is used to get a hexadecimal representation of the memory address. char x = ”A”; printf (“Address of x: %pn”, &x); This prints the address of “x” in hexadecimal format − Address of x: 000000000061FE1F The address of a variable is usually stored in a “pointer variable”. The pointer variable is declared with a “*” prefix. In the code snippet below, “x” is a normal integer variable while “y” is a pointer variable. int x = 10; int *y = &x; The Dereference Operator (*) in C We normally use the “*” symbol as the multiplication operator. However, it is also used as the “dereference operator” in C. When you want to store the memory address of a variable, the variable should be declared with an asterisk (*) prefixed to it. int x = 10; int *y = &x; Here the variable “y” stores the address of “x”, hence “y” acts as a pointer to “x”. To access the value of “x” with the help of its pointer, use the dereference operator (*). Example 1 Take a look at the following example − #include <stdio.h> int main(){ int x = 10; int *y = &x; printf (“x: %d Address of x: %dn”, x, &x); printf(“Value at x with Dereference: %d”, *y); return 0; } Output Run the code and check its output − x: 10 Address of x: 6422036 Value at x with Dereference: 10