PPS Unit 2 Notes PDF

Document Details

UnforgettableHappiness6709

Uploaded by UnforgettableHappiness6709

Tags

C programming arithmetic operators programming operators computer science

Summary

This document provides notes on arithmetic operators in C programming. It covers binary and unary operators, including examples and explanations. The notes also cover relational operators.

Full Transcript

Session 2024-2025 Subject: Programming For Problem Solving Unit-II: Operator & Expression  Arithmetic Operator Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C program. They...

Session 2024-2025 Subject: Programming For Problem Solving Unit-II: Operator & Expression  Arithmetic Operator Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C program. They can be used in programs to define expressions and mathematical formulas.The Arithmetic operators are the symbols that are used to perform mathematical operations on operands. There are a total of 9 arithmetic operators in C to provide the basic arithmetic operations such as addition, subtraction, multiplication, etc. Types of Arithmetic Operators in C The C Arithmetic Operators are of two types based on the number of operands they work. These are as follows: 1. Binary Arithmetic Operators 2. Unary Arithmetic Operators 1. Binary Arithmetic Operators in C The C binary arithmetic operators operate or work on two operands. C provides 5 Binary Arithmetic Operators for performing arithmetic functions which are as follows: Let us assume that variable A has a value of 5, and variable B has a value of 10. Then: Operator Description Example + Addition of two operands var = A + B = 15 – Subtraction of the second variable from the var = A - B = -5 first one / Division of the numerator by the de- var = B / A = 2 numerator * Multiplication of both the operands var = A * B = 50 1 % The modulus operator and the remainder var = B % A = 0 after the division of an integer // C program to demonstrate syntax of binary arithmetic // operators #include int main() { int a = 10, b = 4, res; // printing a and b printf("a is %d and b is %d\n", a, b); res = a + b; // addition printf("a + b is %d\n", res); res = a - b; // subtraction printf("a - b is %d\n", res); res = a * b; // multiplication printf("a * b is %d\n", res); res = a / b; // division printf("a / b is %d\n", res); res = a % b; // modulus printf("a %% b is %d\n", res); return 0; } Output a is 10 and b is 4 a + b is 14 a - b is 6 a * b is 40 a / b is 2 a % b is 2 2. Unary Arithmetic Operators in C The unary arithmetic operators operate or work with a single operand. In C, we have two unary arithmetic operators which are as follows: Operator Symbol Operation Implementation Decrement Decreases the integer value of the — –h or h– Operator variable by one. 2 Operator Symbol Operation Implementation Increment Increases the integer value of the ++ ++h or h++ Operator variable by one. Unary Plus + Returns the value of its operand. +h Operator Unary Minus Returns the negative of the value of its – -h Operator operand.  Relational Operator The relational operators are used to compare two of the available values to understand what relationship the pairs of values share. For example, equal to, greater than, less than, etc. Here is a list of all the relational operators used in the C language: Here is a table that discusses, in brief, all the Relational operators that the C language supports. If P=5 and Q=3, then: Meaning Operator Details Example Equal to (P == Q) is not true 4 == 5 gets evaluated to 0 == 4 == 4 gets evaluated to 1 Not equal to (P != Q) is true 4 != 5 gets evaluated to 1 != 4 != 4 gets evaluated to 0 Less than (P < Q) is not true 4 < 2 gets evaluated to 0 < 4 < 6 gets evaluated to 1 Greater than (P > Q) is true 4 > 2 gets evaluated to 1 > 4 > 9 gets evaluated to 0 Less than or (P 5 && y < 10) {... } will execute the code inside the curly braces only if both x is greater than 5 and y is less than 10.Logical operators in C are used to perform logical operations on Boolean values (i.e., true or false). There are three logical operators in C: [&& (logical AND)], [|| logical OR)], [and ! (logical NOT)]. 7 Types of Logical Operators in C We have three major logical operators in the C language: 1. Logical AND (&&) X Y X && Y 2. Logical OR (||) 3. Logical NOT (!) 1 1 1 1 0 0 0 1 0 0 0 0 1. Logical AND (&&) This type of operator returns true when both the conditions that are under consideration happen to be satisfied. In any other case, it is bound to return false. For instance, the X && Y will return true when both- X and Y are true 1. Example #include #include int main() { int x = 22, y = 33; clrscr(); if (x > 20 && y > 23) { printf("Both values are greater than 0\n"); } else { printf("Both values are less than 0\n"); } getch(); return 0; } 8 2. Logical OR(||) This type of operator returns true even when one of the conditions that are under consideration are satisfied. In any other case, it is bound to return false. For Example, the X || Y will return true when both or one of p and q are true. It also returns to be true when X and Y are true. X Y X || Y 1 1 1 1 0 1 0 1 1 0 0 0 #include #include int main() { int x = 22, y = 33; clrscr(); if (x >200 || y > 23) { printf(" Any of the GivenValues are greater than 0\n"); } else { printf("Both values are less than 0\n"); } getch(); return 0; } 3. Logical NOT (!) This type of operator returns true whenever the conditions that are under consideration are not at all satisfied. In any other case, it is bound to return false. For instance, the !p will return true if p is false, meaning, when p = 0. X !X 0 1 1 0 Example #include 9 #include int main() { int x=10; clrscr(); if (x!=20) { printf(" X is Not Equal to 20\n"); } else { printf("X is Equal to 20\n"); } getch(); return 0; }  Assignment Operator:- Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below: 1 “=” : This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. For example: 1 a = 10; 2 b = 20; 3 ch = 'y'; 2 “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11. 3 “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. Example: (a -= b) can be written as (a = a - b) If initially value stored in a is 8. Then (a -= 6) = 2. 10 4 “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30. 5 “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: (a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3. Below example illustrates the various Assignment Operators: // C program to demonstrate // working of Assignment operators #include int main() { int a = 10; printf("Value of a is %d\n", a); a += 10; printf("Value of a is %d\n", a); a -= 10; printf("Value of a is %d\n", a); a *= 10; printf("Value of a is %d\n", a); a /= 10; printf("Value of a is %d\n", a); return 0; }  Increment & Decrement Operator The increment ( ++ ) and decrement ( — ) operators in C are unary operators for incrementing and decrementing the numeric values by 1 respectively. The incrementation and decrementation are one of the most frequently used operations in programming for looping, array traversal, pointer arithmetic, and many more. 1. Increment operator ( ++ ) 11 The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1. It can be used on variables of the numeric type such as integer, float, character, pointers, etc. Syntax of Increment Operator Increment Operator can be used in two ways which are as follows: // AS PREFIX ++m // AS POSTFIX m++ where m is variable. How to use the increment operator? Both pre-increment and post-increment increase the value of the variable but there is a little difference in how they work. 1. Pre-Increment In pre-increment, the increment operator is used as the prefix. Also known as prefix increment, the value is incremented first according to the precedence and then the less priority operations are done. Example result = ++var1; The above expression can be expanded as var = var + 1; result = var; 2. Post-Increment In post-increment, the increment operator is used as the suffix of the operand. The increment operation is performed after all the other operations are done. It is also known as postfix increment. Example result = var1++; The above expression is equivalent result = var; var = var + 1; 2. Decrement Operator in C 12 The decrement operator is used to decrement the value of a variable in an expression. In the Pre-Decrement, the value is first decremented and then used inside the expression. Whereas in the Post-Decrement, the value is first used inside the expression and then decremented. Syntax Just like the increment operator, the decrement operator can also be used in two ways: // AS PREFIX --m // AS POSTFIX m-- where m is variable. 1. Pre-Decrement Operator The pre-decrement operator decreases the value of the variable immediately when encountered. It is also known as prefix decrement as the decrement operator is used as the prefix of the operand. Example result = --m; which can be expanded to m = m - 1; result = m; 2. Post-Decrement Operator The post-decrement happens when the decrement operator is used as the suffix of the variable. In this case, the decrement operation is performed after all the other operators are evaluated. Example result = m--; The above expression can be expanded as result = m; m = m-1;  Conditional Operator in C The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'. As conditional operator works on three operands, so it is also known as the ternary operator. The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement. 13 Syntax of a conditional operator Expression1? expression2: expression3; Example #include int main() { int age; // variable declaration printf("Enter your age"); scanf("%d",&age); // taking user input for age variable (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator return 0; }  Bitwise Operator The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C programming language. The following is the list of the bitwise operators: Operator Meaning of operator & Bitwise AND operator | Bitwise OR operator ^ Bitwise exclusive OR operator ~ One's complement operator (unary operator) > Right shift operator Let's look at the truth table of the bitwise operators. X Y X&Y X|Y X^Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 14 1. Bitwise AND operator (&) Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. For example, We have two variables a and b. a =6; b=4; The binary representation of the above two variables are given below: a = 0110 b = 0100 When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output would be: Result = 0100 As we can observe from the above result that bits of both the variables are compared one by one. If the bit of both the variables is 1 then the output would be 1, otherwise 0. Let's understand the bitwise AND operator through the program. #include int main() { int a=6, b=14; // variable declarations printf("The output of the Bitwise AND operator a&b is %d",a&b); return 0; } 2. Bitwise OR operator (|) The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0. For example, We consider two variables, a = 23; b = 10; The binary representation of the above two variables would be: a = 0001 0111 b = 0000 1010 When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output would be: Result = 0001 1111 15 As we can observe from the above result that the bits of both the operands are compared one by one; if the value of either bit is 1, then the output would be 1 otherwise 0. Let's understand the bitwise OR operator through a program. #include int main() { int a=23,b=10; // variable declarations printf("The output of the Bitwise OR operator a|b is %d",a|b); return 0; } 3. Bitwise exclusive OR operator (^) Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0. For example,We consider two variables a and b, a = 12; b = 10; The binary representation of the above two variables would be: a = 0000 1100 b = 0000 1010 When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the result wou ld be: Result = 0000 1110 As we can observe from the above result that the bits of both the operands are compared one by one; if the corresponding bit value of any of the operand is 1, then the output would be 1 otherwise 0. Let's understand the bitwise exclusive OR operator through a program. #include int main() { I nt a=12,b=10; // variable declarations printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b); return 0; } 4. Bitwise complement operator(~) 16 The bitwise complement operator is also known as one's complement operator. It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0. For example, If we have a variable named 'a', a = 8; The binary representation of the above variable is given below: a = 1000 When we apply the bitwise complement operator to the operand, then the output would be: Result = 0111 As we can observe from the above result that if the bit is 1, then it gets changed to 0 else 1. Let's understand the complement operator through a program. #include int main() { int a=8; // variable declarations printf("The output of the Bitwise complement operator ~a is %d",~a); return 0; } 5. Bitwise shift operators Two types of bitwise shift operators exist in C programming. The bitwise shift operators will shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift operator is divided into two categories: 1. Left-shift operator 2. Right-shift operator 1. Left-shift operator It is an operator that shifts the number of bits to the left-side. Syntax of the left-shift operator is given below: Operand >2); return 0; }  sizeof() operator in C The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.  Need of sizeof() operator Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator: int *ptr=malloc(10*sizeof(int));  When operand is a data type. #include int main() { int x=89; // variable declaration. printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable. printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integer data type. printf("\nsize of the character data type is %d",sizeof(char)); //Displaying the size of character data t ype. printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of floating data typ e. return 0; } In the above code, we are printing the size of different data types such as int, char, float with the help of sizeof() operator. 19  Arithmetic Expression in C An Arithmetic Expression is a combination of operands and Arithmetic operators, such as addition, subtraction, and so on. These combinations of operands and operators should be mathematically meaningful, otherwise, they can not be considered as an Arithmetic expression in C. The below table lists the different arithmetic operators available in the C programming language, along with a small description. Symbol Unary / Description Binary + unary denotes that the number is a positive integer. - Unary denotes that the number is a negative integer. ++ Unary Increments the value of the variable by 1 -- Unary Decreases the value of the variable by 1 + Binary performs the mathematical addition of the two given operands. - Binary performs the mathematical subtraction of the two given operands. * Binary performs the mathematical multiplication of the two given operands. \ Binary performs the mathematical division of the two given operands and returns the quotient. % Binary performs the mathematical division of the two given operands and returns the remainder as the result. The below table consists of some valid and invalid arithmetic expressions in C, with the explanation for all the invalid expressions.  Expression Evaluation While knowing about expression evaluation we must understand what is an expression in C and what is an expression means. An expression in C is defined as 2 or more operands are connected by one operator and which can also be said to a formula to perform any operation. An operand is a function reference, an array element, a variable, or any constant. An operator is symbols like “+”, “-“, “/”, “*” etc. Now expression evaluation is nothing but operator precedence and associativity. Expression precedence in C tells you which operator is performed first, next, and so on in an expression with more than one operator with different precedence. This plays a crucial role while we are performing day to day arithmetic operations. If we get 2 same precedences appear in an expression, then it is said to be “Associativity”. Now in this case we can calculate this statement either from Left to right or right to left because this both are having the same precedence. 1. Arithmetic expression Evaluation Addition (+), Subtraction(-), Multiplication(*), Division(/), Modulus(%), Increment(++) and Decrement(–) operators are said to “Arithmetic expressions”. These operators work in between operands. like A+B, A-B, A–, A++ etc. While we perform the operation with these operators based on specified precedence order as like below image. 20 A+B*C/D-E%F Arithmetic Expression evaluation order: 2. Relational expression evaluation == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), B, AB)?”A is Big”:”B is Big”. While we perform the operation with these operators based on specified precedence order as like the below image. (X+2=10)?’true’:’false’; Conditional expression Evaluation order:  Programming Basics Main components of C language – 1. Character set 2. Identifiers 21 3. Variables 4. Keyword 5. Constants 6. Datatype  Standard I/O in C:- The scanf() and printf() Functions: Input:- scanf() function takes the input from the user and scans that input according to the format provided. e.g: scanf(“_format specifier “, variable); Output:-The int printf(const char *format,...) function writes the output to the standard output stream stdout and produces the output according to the format provided. e.g: printf(“statement….. “, variable);  Format specifier The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different data types such as %d for int, %c for char, etc. In this article, we will discuss some commonly used format specifiers and how to use them. List of Format Specifiers in C Format Description Specifier %c For b type. %d For signed integer type. %e or For scientific notation of %E floats. %f For float type. 22 The below table contains the most commonly used %g or For float type with the format specifiers in C %G current precision. Format %i Unsigned integer Specifier Description %ld or %lli or Long Long long %li %lld %lf Double %llu Unsigned long long %Lf Long double %o Octal representation Unsigned int or unsigned %p Pointer %lu long %s String %u Unsigned int %x or Hexadecimal representation %X %n Prints nothing %% Prints % character 23 Syntax and Logical Errors in Compilation: Synt ax errors are caused by violating the language 's grammar rules and can bedetected by the compiler. Logical errors are more subtle and a re caused by incorrect program logic, ofte nleading to unexpected results. Object and Executable Code: Obje ct code is the compiled code generated by the compiler, usually in the formof.o or.obj files. Executable code is the final program that can be run by the user. It's created bylinking object files. 24

Use Quizgecko on...
Browser
Browser