🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

Shyamsir C++ 78 74 39 11 91 2.1 Operators & Expression Operators are the symbols that instruct to perform some mathematical or logical operations. Operators operate on certain data types called operands, and they form a part of the mathematical o...

Shyamsir C++ 78 74 39 11 91 2.1 Operators & Expression Operators are the symbols that instruct to perform some mathematical or logical operations. Operators operate on certain data types called operands, and they form a part of the mathematical or logical expressions. More complex expression use operators. Example# + - X / && There are three categories of operators. Expression means whose evaluation yields numeric value. Expression contains constant, variable and operators. In C, every expression evaluates to a value. C language supports rich set of Operators. Like arithmetic, logical, relational etc. Example# a+b-c www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 2.1.1 Operators Arithmetic Operators Increment and Decrement Operators Assignment Operators Relational Operators Logical Operators Conditional Operators Bitwise Operators Special Operators 2.1.1.1 Arithmetic operators These operators are used to perform some basic operations like addition, substation, division, multiplication and modulo. These requires two operands to perform its operation hence they are also called binary operators. They are also knowing as mathematical operators. Operator Meaning Example + To perform addition operation. a+b - To perform subtraction operation. a-b * To perform multiplication operation. a*b / To perform division operation. a/b % Modulus: To gives remainder of the a%b division operation. Example# #include #include main() { int a,b; clrscr(); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 a=22; b=2; printf("\nAdd = %d",a+b); printf("\nSub = %d",a-b); printf("\nMul = %d",a*b); printf("\nDiv = %d",a/b); printf("\nModuls = %d",a%b); getch(); } Output: Add = 24 Sub = 20 Mul = 44 Div = 11 Moduls = 0 2.1.1.2 Increment & Decrement These operators operate on one operand only. They are also known as unary operators. Examples are increment (++), Decrement (--). These operators are used with variable only. Symbol Meaning Example ++ To increment value by one in the a++,++a operand. -- To decrement value by one in the a--,--a operand. Two type of notation are used with these operators: postfix and prefix Postfix notation Syntax# operand symbol Here symbol is used after the operand means operator modify operand after it is used. Example# a=5; a=5; b=a++; b=a--; After these two operations are After these two operations are executed, a variable has a 6 and b has executed, a variable has a 4 and b has 5. 5. www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Prefix notation Syntax# symbol operand Here symbol is used before the operand means operators modify operand first then after it is used. Example# a=5; a=5; b=++a; b=--a; After these two operations are After these two operations are executed, a variable has a 6 and b has executed, a variable has a 4 and b has 6. 4. 2.1.1.3 Assignment operators Assignment operator are used to assign value to any variable. It is denoted by ‘=’ sign. Assignment operator is a binary operator i.e. it operates on two values. It has the lowest precedence Operator Meaning Example Equivalent to = Assign value to operand A=5; += Add given value to operand a+=5; a=a+5; value -= Subtract the given value from a-=5; a=a-5; operand value *= Multiply operands value from a*=5; a=a*5; the given value /= Divides the operands value by a/=5; a=a/5; the given value %= Assign remainder of operators a%=5; a=a%5; value by given value Example# #include #include void main() { clrscr(); int a; a=50; printf("\na=%d",a); a+=5; printf("\na=%d",a); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 a-=10; printf("\na=%d",a); a*=2; printf("\na=%d",a); a/=2; printf("\na=%d",a); a%=5; printf("\na=%d",a); getch(); } Output: a =50 a =55 a =45 a =90 a =45 a =0 2.1.1.4 Relational operators It returns Boolean value only. Relational operators are used to compare between two operands and evaluate as either true or false. For example,# 1 or 0. If the condition is true than return 1 otherwise return 0. They are used in conjunction with logical operators and conditional & looping statements. Operator Meaning Example < Less than a Greater than a>b >= Greater than or equal to. a>=b c); printf("\na=1 && a"); scanf("%d",&a); a%2==0?printf("\n%d is even",a):printf("\n%d is odd",a); getch(); } Output Enter value of a=>3 3 is odd 2.1.1.8 Comma operator The comma operator can be used to link the related expressions together. It allows evaluating two or more distinct expressions together. A comma-linked list of expressions is evaluated left to right and the value of the right-most expression is the value of the combined expression. For example, the statement Value = (x = 2, y = 3, x +y); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 First 2 is assigned to x, then 3 is assigned to y and then finally x+y(2+3) is executed and assigned to Value. Since comma operator has the lowest precedence of all operators, the parentheses are necessary. 2.1.1.9 sizeof() operator sizeof() is a unary operator which returns the size of the variable passed as an argument. Example# #include #include void main() { clrscr(); printf(“\nint=%d”,sizeof(int)); printf(“\nchar=%d”,sizeof(char)); printf(“\nlong=%d”,sizeof(long)); printf(“\nfloat=%d”,sizeof(float)); getch(); } Output: int=2 char=1 long=4 float=4 2.1.2 Expression, Precedence & Associativity In programming, an expression is any legal combination of symbols that represents a value. Example# a+b-c In c language expression evaluation is mainly depends on priority and associativity. C Programming provides its own rules of Expression. Every expression contains at least one operand and can contain any number of operators. Operands refer to the values and operator are symbol that represent particular action. www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Precedence This represents the evaluation of expression starts from "what" operator. Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence. Example# 5 + 10 * 20 is calculated as 5 + (10 * 20) and not as (5 + 10) * 20. Associativity Associativity is only used when there are two or more operators of same precedence. Operator Precedence Associativity {}, (), [] 1 Left to right ++, --, ! 2 Right to left *, /, % 3 Left to right +, - 4 Left to right =, ==, != 5 Left to right && 6 Left to right || 7 Left to right ?: 8 Right to left =, +=, -=, *=, /=, %= 9 Right to left Example# www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 2.2 Console based I/O and related built-in I/O function 2.2.1 printf() printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen. printf is a predefined function in "stdio.h" header file, by using this function, we can print the data or user defined message on console/monitor. While working with printf(), it can take any number of arguments but first argument must be written within double cotes (" ") and every argument should be separated by comma ( , ). Within the double cotes, whatever we pass, compiler prints it as it is on the output screen. Syntax# printf("format specifers",value1,value2,..); Example# #include #include main() { char ch = 'A'; char siteName = "www.shyamsir.com"; float rsFloat = 22.778; int rollno = 21; double meterDbl = 33.7777889; clrscr(); printf("Character is %c \n", ch); printf("String is %s \n" , siteName); printf("Float value is %f \n", rsFloat); printf("Integer value is %d\n" , rollno); printf("Double value is %lf \n", meterDbl); printf("Octal value is %o \n", rollno); printf("Hexadecimal value is %x \n", rollno); getch(); } Output Character is A www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 String is www.shyamsir.com Float value is 22.778000 Integer value is 21 Double value is 33.777789 Octal value is 25 Hexadecimal value is 15 2.2.2 scanf() scanf() is a predefined function in "stdio.h" header file. It is used for taking input from the user. scanf() function is used to read character, string, numeric data from keyboard Syntax# scanf("format specifiers",&value1,&value2,.....); Format specifier Type of value %d Integer %f Float %lf Double %c Single character %s String %u Unsigned int %ld Long int %lf Long double Example# #include #include main() { char ch; char siteName; float rsFloat; int rollno; double meterDbl; clrscr(); printf("\nEnter character =>"); scanf("%c",&ch); printf("\nEnter site Name =>"); scanf("%s",&siteName); printf("\nEnter float value =>"); scanf("%f",&rsFloat); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 printf("\nEnter roll no =>"); scanf("%d",&rollno); printf("\nEnter Double value =>"); scanf("%lf",&meterDbl); printf("\nCharacter is %c \n", ch); printf("String is %s \n" , siteName); printf("Float value is %f \n", rsFloat); printf("Integer value is %d\n" , rollno); printf("Double value is %lf \n", meterDbl); getch(); } Output: Enter character =>a Enter site Name =>www.shyamsir.com Enter float value =>23.44567 Enter roll no =>21 Enter Double value =>12.888345 Character is a String is www.shyamsir.com Float value is 23.445669 Integer value is 21 Double value is 12.888345 2.2.3 getch() getch() is a inbuilt function which is stored in “conio.h” header file. getch() takes a character input but does not display the character which is entered. Example# #include #include void main() { clrscr(); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 char a; printf(“Enter value of a: ”); a=getch(); printf(“a=%d”,a); getch(); } Output Enter value of a: a=c 2.2.4 getchar() getchar() is a inbuilt function which is stored in “stdio.h” header file and it does the same function as getch() the difference between both of them is that getchar() gives the output of the entered character while getch() doesn’t. Example# #include #include void main() { clrscr(); char a; printf(“Enter value of a: ”); a=getchar(); printf(“a=%d”,a); getch(); } Output Enter value of a: c a=c 2.2.5 putchar() putchar() is an in built function which is used to print a character on the console screen. Example# #include #include void main() { www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 clrscr(); char a; printf(“Enter value of a: ”); a=getchar(); putchar(a); getch(); } Output Enter value of a:c c 2.3 Header File A header file in C programming language is a file with.h extension which contains a set of common function declarations and macro definitions which can be shared across multiple program files. There are 32 numbers of header file. Each header file contains information (or declarations) for a particular group of functions. Example# stdio.h header file contains standard Input and Output functions. ctype.h header file contains character handling functions string.h header file contains string handling functions. There are two types of header files User Define Header file The files that the programmer writes and store with.h extension means user define Inbuilt Header file The files that comes with our compiler means in built and extension with.h www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 #include We can include header file in our program by including it with the C preprocessing directive #include #include Preprocessor Directives is used to include both system header files and user defined header files in C Program. Syntax# #include or #include "headerfileName.h" The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current source file. Including a header file in a c program is equivalent to copying the content of the header file in your program. Some of the header file of C: stdio.h string.h math.h stdlib.h floats.h conio.h time.h limits.h graphic.h ctype.h malloc.h calloc.h sound.h 2.3.1 Steps to create our own header file 1. Open a text editor and type a functions definition, like we define a new function in C program. int Add(int a,int b) { return a+b; } int Sub(int a,int b) { return a-b; } 2. Save this file with.h extension. Lets assume we saved this file as myCalc.h. 3. Copy myCalc.h header file to the same directory where other inbuilt header files are stored.(Usually in c:\tc\bin) 4. To Include your new header file in a c program used #include preprocessor directive. #include "myCalc.h" 5. Create new file and add "myCalc.h" header file. www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 #include #include #include "myCalc.h" main() { int sumans,subans; clrscr(); sumans=Add(5,2); subans=Sub(5,2); printf("\nAdd = %d",sumans); printf("\nSub = %d",subans); getch(); } Output Add = 7 Sub = 3 2.4 PreProcessor The C preprocessor is a macro preprocessor that transforms your program before it is compiled. Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. All preprocessing directives begins with a # symbol. For example, #include #define PI 3.14 #ifdef TURBOC #define INT_SIZE 16 #else #define INT_SIZE 32 #endif Some of the common uses of C preprocessor are: Processor Meaning #define Substitutes a preprocessor macro. #include Inserts a particular header from another file. #undef Undefines a preprocessor macro. www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 #ifdef Returns true if this macro is defined. #ifndef Returns true if this macro is not defined. #if Tests if a compile time condition is true. #else The alternative for #if. #elif #else and #if in one statement. #endif Ends preprocessor conditional. #error Prints error message on stderr. #pragma Issues special commands to the compiler, using a standardized method. 2.4.1 #define Preprocessor The #define directive takes two forms: 2.4.2 Defining a Constant using #define Syntax# #define token [value] Example# #define PI 3.14 #define N 200 It has no type. It is a simple text substitution. The text 3.14 or 200 will be dropped in place wherever PI and N appears as a token. 2.4.3 Creating a macro function using #define Syntax# #define token( [, s... ]) statement Example# #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define SQR(a)(a*a) It has no type. Macro can be type-neutral means it works with any data type. It's inlined directly into the code, so there isn't any function call overhead. www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Example# #define preprocessor #include #include #define PI 3.14 #define Max(a,b)(a>b?a:b) main() { float r=10; clrscr(); printf("\nArea of Rect = %.2f",PI*r*r); printf("\nMax = %d",Max(5,2)); getch(); } Output Area of Rect = 314.00 Max = 5 www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Decision Making Structure 2.5 Control statement We can control the order of execution of the program with the help of control statement, based on logic and values. In the sequential flow of control, statements are executed line by line but in the case of conditional program the order of execution is based on data values and conditional logic. Conditional statements cause variable flow of execution of the same program based on certain condition to be true or false, evertime when a program is executed The control statments can be classified into three groups: Decision making statements , Looping statements and Jumping statements. 2.5.1 Decision making statement Decision making statement are also known as Selection statement. There are two ways to take decision, 2.5.1.1 if In some situation, we would like to execute some logic when a condition is TRUE, and some other logic when the condition is FALSE and this can be done by using if statement. The condition’s result comes from the comparison of two values. Condition is an expression that is made up by using relational operators (>,=,0) { printf("\n No is pos"); } else { printf("\n No is neg"); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 } getch(); } Output: Enter the value of a=4 No is pos 2.5.1.1.1.3 Nested If…else If within If is known as a Nested If…else In some cases we would like to execute some more condition when a condition is TRUE, and some other condition logic when the condition is FALSE. The most general way of doing this is by using the else if variant on then if statement. This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed. Syntax# if(condition) { if(condition) { } } else { if(condition) { } else { } } Example# To find the maximum number out of three numbers #include #include void main() { www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 int a,b,c; clrscr(); printf("\n Enter value of a="); scanf("%d",&a); printf("\n Enter value of b="); scanf("%d",&b); printf("\n Enter value of c="); scanf("%d",&c); if(a>b) { if(a>c) { printf("\n%d is max",a); } else { printf(“\n%d is max”,c); } } else { if(b>c) { printf("\n%d is max",b); } else { printf(“\n%d is max”,c); } } getch(); } Output: Enter value of a=4 Enter value of b=3 Enter value of c=6 6 is max 2.5.1.1.1.4 if…else if…else www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 There are cases when we would like to execute some more condition when a condition is TRUE, and some other condition logic when the condition is FALSE. We can write multiple else if condition with if statement. Syntax# if(condition) { } else if(condition) { } else { } Example# To check wether a number is odd even or zero #include #include void main() { int a; clrscr(); printf("\n Enter the value of a="); scanf("%d",&a); if(a%2==0) { printf("No is even"); } else if(a%2!=0) { printf("No is odd"); } else { printf(“No is zero”); } getch(); } Output: Enter the value of a=6 No is even www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Example# To find total and grade of a student #include #include void main() { int a,b,c,t; clrscr(); printf("\nEnter marks in science=>"); scanf("%d",&a); printf("\nEnter marks in maths=>"); scanf("%d",&b); printf("\nEnter marks in computer=>"); scanf("%d",&c); printf("\nTotal=%d",a+b+c); t=a+b+c; if(t66 Enter marks in computer=>75 Total=201 A grade Properties of If..else Statement www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 It’s not compulsory to write else block. We cannot write multiple if or else. Usually we have to write {} braces. We cannot write condition with else. We can use logical and relational operator in condition expression. if(a>b) , if(a>b && a>c) 2.5.1.2 Switch-case When you are comparing the same expression to several different values it gets complicated with if…else if…else so we can use the switch-case statements as an alternative to the if-else statements. It executes one of several groups of statements depending on the value of an expression. If-else block executes different condition or expression in each statement on the other hand the switch statement evaluates a single expression and compares it for every comparison. If any case statement is satisfied, then the logic of that case will be executed and then the control will come out of switch block. This one will not happen with if-else block. Remember that switch block use break statement at the end of each case. C simply requires that we leave the block before it ends. If-else block are time consuming then switch case block. 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. Syntax# switch(testexpression) { case expression1: Logic.. break; case expression2: Logic.. break; case expression N: Logic.. break; default: www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 break; } Example# Switch case demo #include #include void main() { int a; clrscr(); printf("\nEnter option=>"); scanf("%d",&a); switch(a) { case 1: { printf("\n jan"); break; } case 2: { printf("\n feb"); break; } case 3: { printf("\n March"); break; } case 4: { printf("\n April"); break; } case 5: { printf("\n May"); break; } default: { printf("\nWrong opt"); } } getch(); } www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 Output: Enter option=>4 April Example# Add, substract, multipy or divide bsaed on user choice using switch statement #include #include void main() { int a,b; char op; clrscr(); printf("\n Enter no1:"); scanf("%d",&a); printf("\n Enter no2:"); scanf("%d",&b); fflush(stdin); printf("\n Enter option A,M,S,D=>"); scanf("%c",&op); switch(op) { case 'A': { printf("\n Add=%d",a+b); break; } case 'M': { printf("\n Multi=%d",a*b); break; } case 'S': { printf("\n Sub=%d",a-b); break; } case 'D': { printf("\n Div=%d",a/b); break; } default: { printf("Wrong option"); www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 } } getch(); } Output: Enter no1:4 Enter no2:6 Enter option A,M,S,D=>A Add=10 2.5.1.2.1 Properties of Switch statmements We don't use those expressions to evaluate switch case, which may return floating point values or strings. The case label values must be unique. The case label must end with a colon(:) The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. It isn't necessary to use break after each block, but if you do not use it, then all the consecutive block of codes will get executed after the matching block. The default case is optional, but it is wise to include it as it handles any unexpected cases.Usually default case is executed when none of the mentioned cases matches the switch expression. 2.5.1.3 Difference between if and switch If Switch Which statement will be executed Which statement will be executed is depend upon the output of the decided by user. expression inside if statement. if-else statement test for equality as switch statement test only for well as for logical expression. equality. if statements can evaluate float switch statements cannot evaluate conditions. float conditions. If the condition inside if statements is If the condition inside switch false, then by default the else statements does not match with any statement is executed if created. of cases, for that instance the default statements is executed if created www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 2.5.2 Loop Control Structure Iteration statements are also known as Looping statements. Looping statements are used when a group of statements is to be executed repeatedly, till a condition is TRUE or until a condition is FALSE. The following illustration shows a loop structure that runs a set of statements until a condition becomes true. Entry controlled loop and Exit controlled loop In entry controlled loop, where test condition is checked before entering the loop body, known as Entry Controlled Loop. Example# for and while loops are known as entry controlled loop While in exit controlled loop the body of loop will be executed first and at the end the test condition is checked, if condition is satisfied than body of loop will be executed again. Example# do while loop is known as exit controlled loop www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 2.5.2.1 For loop The for loop executes a block of statements a specified number of times. It is the most commonly and most popular loop used in any programming language. For loop is an entry controlled loop i.e. the condition is checked before entering into the loop. So, if the condition is false for the first time, the statements inside for loop may not be executed at all. Syntax# for(initialization; condition; increment/decrement) { Logic…. } Step 1: Initialization Evaluates the initialization code means from where to start. The variable initialization allows us to declare a variable and gives it a starting value. The initialization statement is executed only once. This part is optional and may be absent. Example# for(i=0 ; condition; increment/decrement) for(i=20 ; condition; increment/decrement) for(i=strlen(name) ; condition; increment/decrement) for( ; condition; increment/decrement) // initialization is absent Keep in mind that a semicolon separates each of these sections. Step 2: Condition The condition expression is evaluated. If the test expression is false, for loop is terminated at that time. But if the test expression is true , logic inside the body of for loop is executed and the update expression is updated. The condition is checked after the execution of increment/decrement statement. This process repeats until the test expression is false. Usually condition is combination of Relational operator. Example# www.Shyamsir.com Shyamsir C++ 78 74 39 11 91 for(intialization ; i X; increment/decrement) for(intialization ; i < strlen(name); increment/decrement) Step 3: Increment/Decrement Then it evaluates the increment/decrement condition and again follows from step 2. When the condition expression becomes false, it exits the loop. The variable increment/decrement section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, x-- Example# for(intialization ; condition ; i=i+1) for(intialization ; condition ; i++) for(intialization ; condition ; i--) for(intialization ; condition ; i=i+10) Example# for loop demo #include #include void main() { int i,n; clrscr(); printf("\n Enter a number="); scanf("%d",&n); for(i=1;i

Tags

C++ programming operators expressions
Use Quizgecko on...
Browser
Browser