programming

Page 1

Operators and Conditionals by

Erol Seke

For the course “Introduction to Programming”

OSMANGAZI UNIVERSITY


Basic Branching With if

Condition satisfied?

Yes

No

<Do those>

Flow Diagram

≥ <Do these>

. . if(condition) Statement <else Statement > . . C Syntax


Example #include <stdio.h> int main(void){ int number; printf("Enter number :"); scanf("%d",&number); if(number>=0) printf("Dec-%d = Hex-%X\n",number,number); else printf("You have entered a negative number.\n"); return 0; }

output Enter number :8171553 Dec-8171553 = Hex-7CB021 Press any key to continue

Print text but do not move the cursor to the next line Wait for user input

This standard library function reads terminal input and stores the result into wherever the second argument says scanf("%d",&number);

store it to the memory address given Read a decimal number from input


Logical/Relational Operators and Expressions All logical expressions must yield either FALSE or TRUE values. Numerical values are treated as zero (=FALSE) or nonzero (=TRUE) if they are used as logical values > >= < <= == != ! && ||

: : : : : : : : :

Greater than Greater than or equal to Less than Less than or equal to Equal to Not equal to Not Logical AND Logical OR

Examples (A!=0)&&(B<100) (MyFunc(A)>100)||(!((B==C+D)||(K<=2*M))) counter=counter-1; if(!counter) printf("time is over\n");

this is equivalent to if(counter==0)‌


Arithmetic Operators and Precedence Precedence order table includes operators learned so far. () + - ! * / + < > <= >= == != && || =

: : : : : : : : :

Paranthesis Some unary operators Multiplicative Additive Relational Equality Logical AND Logical OR Assignment

error: left operand must be an L-value

Examples G=A+B-C/D*(E=F);

6

5

4

Operators on the same line have the same precedence. Compilers usually evaluate expressions starting from the left but may chose otherwise. Exception is = operator.

3

2

G=A+B-C/D*E=F;

1

compiler may decide to perform this summation first because it does not affect the final result

no error here A+B-C/D*(E=F);

≥

A=B=C=D;

C=D; B=C; A=B;

A=-(B=+C*D)/E; 7

5

1

4

2

3

6


Combined (Compound) Operators *= /= %= += –= : Combined arithmetic operators <<= >>= &= ^= |= : Combined bitwise operators (will be seen later) ?:

: Condition-expression operator

Precedence of compound operators are the same as of =‘s In general

A@=B;

is equivalent to

A=A@B;

Examples A+=B;

is equivalent to

A=A+B; /* assign the value of the A+B to A */

A+=B+(C*=D); /* C=C*D; A=A+B+C */

Condition ? Expression-1 : Expression-2; If the Condition evaluates to TRUE evaluate Expression-1 otherwise evaluate Expression-2 C=A>B?A-B:B-A;

is equivalent to

if(A>B) C=A-B; else C=B-A;


++ (increment) and -- (decrement) operators ++A;

--A; are equivalent to

A=A+1;

and

A++;

are equivalent to

A=A-1;

A--;

The difference between prefix (++A, --A) and postfix (A++, A--) is the evaluation order if they are used in another expression. They have the highest precedence. A=B++ +C; whereas

is equivalent to A=++B+C;

A=B+C; B=B+1; is equivalent to

B=B+1; A=B+C;

Examples int A, B=1, C=4; A=B+++C; printf("%d %d %d",A,B,C);

prints out

5 2 4

int A, B=1, C=4; A=++B+ ++C; printf("%d %d %d",A,B,C);

prints out

7 2 5

A=++B+++C; /* error */

A=B+++ ++C; /* C=C+1; A=B+C; B=B+1; */

Hint : Be wise, use parentheses and create simpler expressions


Example #include <stdio.h> /* Simple calculator */ int main(void){ int A,B; char op; printf("Enter A@B : "); scanf("%d%c%d", &A, &op, &B); if(op=='+') printf("%d\n",A+B); else if(op=='-') printf("%d\n",A-B); else if(op=='*') printf("%d\n",A*B); else if(op=='/') printf("%d\n",A/B); else printf("unknown operation %c\n",op); return 0; }

Sample runs Enter A@B : 273-290 -17 Press any key to continue Enter A@B : 4341*765 3320865 Press any key to continue

Homework : Enhance the program to handle double numbers and ‘division by zero’ error.


Bitwise Operators ++ -- (post) () ++ -- (pre) ! ~ - + (unary) (type) * / % + << >> < <= > >= == != & ^ | && || ?: = *= /= %= += -= <<= >>= &= ^= |= ,

Bitwise operators are the ones that work on bits decimal 41047

decimal 16049

int A=0xA057, B=0x3EB1, C; C=A&B; /* C is 0x2011 or 8209 now */ Bitwise left shift

1010000001010111 & 0011111010110001 0010000000010001

Bitwise right shift C=A|B;

/* C is 0xBEF7 or 48887 now

*/

C=A^B;

/* C is 0x9EE6 or 40678 now

*/

Bitwise AND Bitwise XOR Bitwise OR

C=A<<1; /* C is 0x140AE or 82094 now */ C=A>>2; /* C is 0x2815 or 10261 now

*/

C<<=2;

*/

/* C is 0xA054 or 41044 now

Compound bitwise operators

Homework: verify calculations, try other compound-bitwise expressions


Example : A naive hex to binary converter #include <stdio.h> int HexDigit2Bin(int X){ if(X==0x0) return 0; if(X==0x1) return 1; if(X==0x2) return 10; if(X==0x3) return 11; if(X==0x4) return 100; if(X==0x5) return 101; if(X==0x6) return 110; if(X==0x7) return 111; if(X==0x8) return 1000; if(X==0x9) return 1001; if(X==0xA) return 1010; if(X==0xB) return 1011; if(X==0xC) return 1100; if(X==0xD) return 1101; if(X==0xE) return 1110; if(X==0xF) return 1111; return 2222; }

Function actually returns an integer. That is 1101 is actually ‘one thousand one hundred and one’. we do not need else’s here because function returns anyway.

int main(void){ int i; looplabel: /* we usually avoid goto labels */ printf("Enter Hex digit : "); scanf("%X",&i); if((i<0)|(i>15)) return 0; printf("%d\n",HexDigit2Bin(i)); goto looplabel; /* we usually avoid this */ return 0; } goto is another C-keyword the programmers try to avoid

Homework : Display decimal numbers (not only digits) in binary. Hint-use bitwise operators. No loops.


The switch Keyword for a given integer X

X==X1?

Yes

No X==X2?

<Statements 1> Yes

No X==X3?

< Statements 2> Yes < Statements 3>

No

X==Xn?

Yes

No

This flow diagram is only to understand switch and may not exactly represent what is done internaly.

< Statements n>

. . switch(int_exp){ case int1: <statements 1> <case int2: <statements 2> case int3: <statements 3> . . . case intn: <statements n> <default: <statements>>> } . .

< Statements> may have early exit from switch block which is usually the case


The break Keyword

#include <stdio.h> int main(void){ int num; printf("Enter 1,2,3 or 4: "); scanf("%d",&num); switch(num){ case 1: printf("One " ); case 2: printf("Two "); case 3: printf("Three "); case 4: printf("Four\n"); break; default: printf("Invalid\n"); } return 0; }

Enter 1,2,3 or 4: 2 Two Three Four Press any key to continue

if no break is used after the statement(s) program flow continues to the next statement(s). (not to the end of switch) break causes the program flow to jump to the point right after the closing brace of the switch.

Enter 1,2,3 or 4: 3 Three Four Press any key to continue

Enter 1,2,3 or 4: 85 Invalid Press any key to continue


#include <stdio.h> int main(void){ int num; printf("Enter -10 to +10: "); scanf("%d",&num); switch(num){ case 1: printf("One " );break; case -1: printf("Two "); case -5: printf("Five"); printf("but negative\n");break; case 3:case 4: printf("Three or Four\n"); break; case 10-3: break; /* means 7 */ case 3: /* this is illegal */ case 6.5: /* error again */ default: /* this is optional */ if(num>0) printf("Other positive number\n"); } return 0; }

This will be printed only if num is something other than 1,3,4,7. (if two illegal lines were removed, of course ) A case label may include other switch(es)

As many statements as wished can be put in a case label, even a large portion of the program.

Labels can be empty. Example shows a case of “3 or 4�. case labels must evaluate to integers


#include <stdio.h> /* Simple calculator */

Since single characters are actually integers

int main(void){ double A,B,C=0; char op; printf("Enter A@B : "); scanf("%lf%c%lf", &A, &op, &B); switch(op){ case '+' : C=A+B; break; case '-' : C=A-B; break; case '*' : C=A*B; break; case '/' : if(B!=0) C=A/B; } printf("%lf\n",C); return 0; }

Homework: 1. Insert default case, 2. Handle the case of B=0

No need for break here since it would be the last statement in switch block anyway


END


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.