0% found this document useful (0 votes)
6 views

ch03 Expressions

The chapter discusses expressions and various operators in C including arithmetic, relational, logical, and assignment operators. It provides examples of expressions and operator precedence. Standard libraries and I/O functions like getchar() and putchar() are also introduced. The chapter summarizes expressions, operators, and provides exercises for practice.

Uploaded by

Vikrant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ch03 Expressions

The chapter discusses expressions and various operators in C including arithmetic, relational, logical, and assignment operators. It provides examples of expressions and operator precedence. Standard libraries and I/O functions like getchar() and putchar() are also introduced. The chapter summarizes expressions, operators, and provides exercises for practice.

Uploaded by

Vikrant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter 3- Operators and Expressions

Chapter Contents
Expressions
Operators:
◦ Arithmetic operators
◦ Assignment operator and its compressed form
◦ Increment and decrement operators
◦ sizeof operator
◦ Relational operators
◦ Logical operators
Some standard libraries
I/O - getchar(), putchar()
Random numbers
Summary
Exercises
 Expressions
An expression consists of a combination of operators and operands.
 Operand may be a variable, constant value.
 The simplest expression is a lone operand.
 Here are some expressions:
6

-45

4+54

D * ( b / a + d)

A=2+b

A>b
Expressions – cont’d
 An important property of C is that every expression has :
◦ a type
◦ a value:

Expression Value Explanation


Arithmetic expressions
-5+12 7
have the value of the result.
Assignments has the same
a=3+1 4
value as its left side variable.
5>7 0 False expression results in 0.
5<7 1 True expression results in 1.
2+(c=2+3) 7 Combination of the above.
Arithmetic Operators

+ plus (unary & binary)


- minus (unary & binary)
* multiplication
/ division
% remainder of division

The precedence of the *, / and % operators,


is higher than that of + and -.
Assignment Operator
 In C, the equal sign is used to assign a value to a variable.

int x; assigning the value 5 to a


x=5; variable named x.

 The value of the expression on the right hand side


is assigned to the variable on the left hand side.

x=x+1;
is perfectly legal. First x+1 is evaluated,
and then the result is assigned to x.

 The value and the type of the expression are the value and the type of the lvalue (left
hand side).
int x,y,z;
 That is why x=y=z=5; is perfectly legal.

 Action starts from right: z=5 returns the value 5, and we


are left with x=y=5.
Assignment Operators – The Compressed Form

The statement x = x + 2;
may be written in the form x += 2;

◦ The syntax of this assignment operation is


variable op= expression;

◦ Which is identical to
variable = variable op expression;
◦ op may be one of the arithmetic or bitwise
operators.
Increment and Decrement Operators
 C provides two unusual unary operators for incrementing and
decrementing variables by one (1).
 Prefix Increment and Decrement Operators: ++, --
unary-expression :
++ unary-expression
-- unary-expression
 When the prefix operators are being used, the operand is incremented or
decremented and its new value is the result of the expression.
 Example:
i = 5;
printf(“i ==> %d\n”, ++i); /* i ==> 6 */
printf(“i ==> %d\n”, --i); /* i ==> 5 */
printf(“i ==> %d\n”, i); /* i ==> 5 */
Increment and Decrement Operators –
cont’d
 Postfix Increment and Decrement Operators: ++, --
postfix-expression :
postfix-expression ++
postfix-expression --
 The result of the postfix increment or decrement operation is the value of
the postfix-expression before the increment or decrement operator is
applied.

 Example:
i = 5;
printf(“i ==> %d\n”, i++); /* i ==> 5
*/
printf(“i ==> %d\n”, i--); /* i ==> 6
*/
printf(“i ==> %d\n”, i); /* i ==> 5
*/
sizeof()
 sizeof() is an operator (unary operator - not a
function) that evaluates the size (in bytes) of:

◦ Type.
◦ Constant.
◦ Variable.

 Ifthe operand is a type, it must be enclosed in


parentheses.
Enclosing constants and variables is optional.
 The sizeof() operator is evaluated at compilation
time.
Example: sizeof.c
/* sizeof.c This program illustrates the unary operator
sizeof(). */
#include <stdio.h>
void main()
{
int n;
double d;
printf("size of type int is: %d\n", sizeof(int) );
printf("size of type double is: %d\n",sizeof(double));
printf("size of variable n is: %d\n" ,sizeof (n));
/* with () */
printf("size of variable d is: %d\n", sizeof d );
/* without () */
printf("size of int costant %d is: %d\n",
-32555, sizeof(-32555) );
printf("size of double costant %f: is %d\n",
2.3, sizeof 2.3 );
printf("size of float costant %fF: is %d\n",
2.3, sizeof 2.3F );
}
Relational
>
Operators
greater than
>= greater or equal
< less than
<= less or equal
== equal
!= not equal

 == and != have lower precedence than others, and all of them


have lower precedence than arithmetic operators.

 Ifthe relation is:


◦ true - expression returns 1.
◦ false - the relation returns 0.

Relational Operators – cont’d
Examples:

◦ i < j + 1 is the same as i < (j + 1), since

◦ operator + has a T/F  1/0


higher precedence than operator <.

◦ (i < j ) + 1

(T/F) + 1  (1/0) + 1  2/1


Logical Operators
 Expressions build up more complex expressions.
 a,b are expressions
a b a||b a&&b !a
a||b a or b
T T T T F
a&&b a and b
T F T F F
!a not a
F T T F T
F F F F T
 If the first (left) operand of a logical-AND operation is equal to 0,
the second (right) operand is not evaluated.

 If the first (left) operand of a logical-OR operation is equal to 1,


the second (right) operand is not evaluated.
1
Example: log-opr.c
/* log-opr.c
2 illustrating logical operators.
3 Why doesn’t line 18 compile ?
4 use the precedence table in the next page to find out) */
5 #include <stdio.h>
6 void main(void)
7 {
8 int x=7, y=3;
9 int and, or1, or2;
10

11 and = ( x > 5 && y <= 3 );


12 printf("x = %d y = %d and = %d\n", x, y, and);
13

14 or1 = ( x < 5 || y <= 3);


15 printf("x = %d y = %d or1 = %d\n", x, y, or1);
16

17 or2 = ( x != 2 || x = y < 2 );
18 printf("x = %d y = %d or2 = %d\n", x, y, or2);
19 }
Precedence Table

Symb Meaning Directio


ol n
++ Post-increment
-- Post-decrement
() Function call
[] Array element Left to
-> Pointer to structure right
member
. Structure or union
member
Precedence
Symbol Meaning
Table – cont’d
Direction
++ pre-increment
-- Pre-decrement
! Logical NOT
~ Bitwise NOT
- Unary minus
Right to left
+ Unary plus
& Address
* Indirection
sizeof Size in bytes
(type) Type cast [example: (float) i]
Precedence Table – cont’d
Symbol Meaning Direction
* Multiply Left to
/ Divide right
% Remainder
+ add Left to
- subtract right
<< Left shift Left to
>> Right shift right
Precedence Table – cont’d
Symb Meaning Directi
ol on
< Less than
<= Less than or equal to Left to
> Greater than right
>= Greater than or equal
to

== Equal Left to
!= Not equal right
Precedence Table – cont’d
& Bitwise AND Left to
right
^ Bitwise exclusive OR – Left to
(XOR) right
| Bitwise OR Left to
right
&& Logical AND Left to
right
|| Logical OR Left to
right
?: Conditional (ternary) Right to
left
= Assignment Right to
left
Precedence Table – cont’d
*=
/=
%=
+=
-
= Compound assignment
<<=
>>=
&=
^=
,|= Comma Left to
right
Standard Libraries
 What is a Library?
◦ The libraries are supplied with the compiler.
◦ C is small and compact.
libraries

 Provide facilities that are not part of the C language.


 Wrap the operating system.

 For example, if a program only uses I/O facilities, it would include


the header file <stdio.h> only, but not any other header file –
this keeps the program small and compact.

 The compiler is responsible for connecting the library functions


with our code.
Libraries and Header Files
#include stdio.h
<stdio.h> __________
void main(void) printf()……
{ __________
printf("hi");
compile printf() is
}
declared here…

Object file

Object file
link of
Executable Library
module function
printf()
Math Library
 Mathematical library:
Provides functions for mathematical calculations.
For example : sqrt(), sin() etc.

#include <stdio.h>
#include <math.h>

void main(void)
{
float a,b;

scanf("%f", &a);
b = sqrt(a);
printf("The sqrt of %f is %f\n", a,b);
}
Standard Libraries – Explanation
 Topass compilation with no warning messages we
need to include header files, where functions are
declared.

 The compiler checks correctness of functions usage.


 The linker stage links our program’s object files with
the object files of the relevant libraries and produces
one executable file.
 Now,
when executing the program, the statement
sqrt(a) invokes the function sqrt() which is
known, and is executed to produce some results.
Mathematical Functions
 Declaration
in <math.h> header file
 Commonly used functions are:

abs(a) Absolute value of integer a and double argument b.


fabs(b)
acos(a)
asin(a) arccosine, arcsine and arctangent of double
atan(a) argument a.

cos(a)
sin(a) cosine, sine and tangent of double argument a.
tan(a)
exp(a) Exponent, natural logarithm, and logarithm to base
log(a) 10 of double argument a.
log10(a)
Mathematical Functions – cont’d
sqrt(a) Square root of double argument a.

pow(a,b) Gives “a to the power of b” , where a,b are double.

ceil(a) Closest integer that is greater/less than or equal


floor(a) to that of a double argument a.

hypot(a,b) Hypotenuse of a right triangle with two other


sides given as arguments.
I/O getchar(), putchar()
 The standard C library provides several functions for reading
and writing one character at a time.

 getchar() and putchar() are used for interactive input


from
the standard input file (usually keyboard) and output to the
standard output file (usually screen).

 Each time getchar() is called , it reads the next character


from the keyboard’s buffer, and returns its ASCII code.
If CTRL/Z was entered, getchar() returns EOF.

 putchar(c) writes the character c (the function’s


parameter) to the screen.
I/O getchar(), putchar() - Examples
 First Example:
void main(void)
{
char c;
printf("Press a key and then press ENTER => ");
c = getchar( );
printf("You entered the character ");
putchar(c);
}

 Second Example:
printf("\n"); and putchar('\n'); are equivalent.

You will learn later the difference between a double


quote (") and a single quote (').
Example - getchar.c
1 /* getchar.c:
2 This program illustrates the use of getchar()
3 and conversion from a digit character to a digit number */
4
5 #include <stdio.h>
6
7 void main(void)
8 {
9 int i, c;
10
11 printf("Enter a digit => ");
12 c = getchar(); /* read one character from the keyboard
*/
13 i = c -'0'; /* turn the character into a number */
14
15 printf("The ASCII code of the digit is %d \n", c);
16 printf("The value of the digit is : %d \n", i);
17 }
Explanation getchar()
 Explanation:

◦ c = getchar();
c is assigned the ASCII of the next character from the
standard input. If it is a digit, its value is between 48
and 57.

◦ i = c-’0’;
‘0’ is the ASCII of the digit 0, which is 48. c-’0’ is the
“distance” between the typed character and the
character ‘0’.

◦ In the ASCII table , the digits are grouped together, and


so are the letters.
I/O Streaming Functions
– Buffering
 We have learned that the functions scanf and getchar get buffered input. This can be
disadvantageous at times. Take the following example:
1. /*scanf0.c*/
2. #include <stdio.h>
3. void main()
4. {
5. char string1[30], string2[30];
6. printf ("Input a string: ");
7. scanf("%s", string1);
8. printf ("\nInput another string: ");
9. scanf ("%s", string2);
10. printf("\nThe first string you entered was \"%s\""
11. " and the second was \"%s\"\n",
12. string1,string2);
13.}

 Here, if the first string contains two words or more, only the first word is entered. The
remaining word stays in the buffer, and is retrieved by the next scanf.
I/O Streaming Functions – fflush
We would obviously like to prevent the second
word staying in the buffer – to clean the buffer
of remaining data.
The fflush() function provides a convenient
answer.
int fflush (FILE *stream);

 stream– We will use the fflush in order to clean


the buffers of the standard files: stdin, stdout,
stderr.
scanf1.c
Our example will now appear like this:
1. /*scanf1.c*/
2. #include <stdio.h>
3. void main()
4. {
5. char string1[30], string2[30];
6. printf ("Input a string: ");
7. scanf("%s", string1);
8. fflush (stdin); /* the ONLY difference */
9. printf ("\nInput another string: ");
10. scanf ("%s", string2);
11. printf("\nThe first string you entered was \"%s\""
12. " and the second was \"%s\"\n",
13. string1,string2);
14.}
Summary
Expressions consist of a combination of operators and
operands.

Every expression in C has a type and a value.

The operators perform some action on the operands.

Inthis chapter we saw the Assignment operator, Arithmetic


operators, Increment/Decrement operators, sizeof operator,
Relational operators and Logical operators.

Libraries provide us with facilities that the language does not


support. They also wrap the Operating System, by being
implemented differently in each OS.
Summary
The “include” allows the compiler to
recognizes the library functions used. The
linking stage links the library functions
themselves to our object module.

getchar() and putchar() are library


functions for getting/putting a single character
to/from stdin/stdout.

getchar() is for buffered input.

You might also like