Download presentation
Presentation is loading. Please wait.
1
INC 161 , CPE 100 Computer Programming
Lecture 3 Operator & Expression
2
Topics CPU Expression Operation Data type: int float char Flow Control
if for while Function Data type: int float char Array Pointer Structure CPU Input Output Command
3
Command Compiler translates a language to machine code.
Add Subtract Compiler Learn this format
4
Operator & Expression Operator: =, + ,- , < , etc.
Expression: 12, a+b, a-3, etc.
5
The Assignment Operator =
The regular assignment operator ‘=‘. It will calculate the right side of = and assign the right variable to the calculated value. When a floating-point number is assigned to an integer variable, the fractional part will be discarded. > int i; > float d = ; > i = d; (i = 10) > i = d + 0.5; (i = 11)
6
Arithmetic Operators There are five arithmetic operators:
Addition Subtraction * Multiplication / Division % Modulus The multiplication operator * is needed for multiplication. The result of the % operator is the remainder. If the value of the second operand is zero, the behavior is undefined. The operands of the % operator shall have integer type.
7
> int i = 10; > i = 5*i; (i = 50) > i = i / 11; (i = 4) > i = 50 % 11; (i = 6)
8
More Data Type Example from a 32-bit OS char - 8 bit short – 16 bit
int – 32 bit float – 32 bit double – 64 bit long double – 128 bit Low order High order
9
The algorithms and resultant data types of operations depend on the data types of the operand.
For binary operations, such as addition, subtraction, multiplication, and division, the resultant data type will take the higher order data type of two operands. For example, the addition of two float numbers will result in a float, while the addition of a float and a double will result in a double. 2 / 3 int / int -> int 0 2.0 / 3 float / int -> float
10
Precedence and Associativity of Operators
The list of operators are shown on right. Operators at the higher level has precedence over operators at the lower level.
12
Precedence and Associativity of Operators
Example: the order of the precedence for operators *, +, and =. Operator * is the highest, operator = the lowest in the expression i = *4 > int i; > i = 2+3*4; (i = 14)
13
Mathematical Function
Many mathematical functions are defined in <math.h> sqrt square root pow power sin cos tan trigonometry function abs absolute
14
Note: there is no exponential operator in C. Mathematical
function pow(x, y) can be used to calculate the exponential expression xy. These functions are declared inside the header file math.h /* File: powsqrt.c */ #include <stdio.h> #include <math.h> /* for pow() and sqrt() */ main() { double p, x = 2.0, y = 3.0; p = pow(x,y); printf("pow(2,3) = %f\n", p); printf("sqrt(2) = %f\n", sqrt(x)); } Example: Output: pow(2,3) = sqrt(2) =
15
Relational Operators The relational operators are listed below.
Description < less than comparison <= less or equal comparison == equal comparison >= greater or equal comparison > greater comparison != not equal comparison
16
Examples: True = 1 False = 0 > int i = 5, j = 3 > i < j
> j == j 1 // true > i > j > i >= j > i != j > i != i Examples: True = 1 False = 0
17
Logical Operators There are three logical operators in C:
1) ! logical negation 2) && --- logical AND 3) || local inclusive OR x y !x x && y x || y 1
18
Compound Assignment Operators
Besides the regular assignment operator, there are ten additional compound assignment operators: 1) += 2) -= 3) *= 4) /= 5) %= 6) &= 7) |= 8) ^= 9) <<= 10) >>= An lvalue is any object that occurs on the left hand side of an assignment statement. It refers to a memory such as a variable or pointer, not a function or constant. The expression lvalue op= rvalue is defined as lvalue = lvalue op rvalue, where lvalue is any valid lvalue. For example, i += 3; is equivalent to i = i+3;
19
Increment and Decrement Operators
The increment operator ++ adds 1 to its operand, and the decrement operator - - subtracts 1. If either is used as a prefix operator, the expression increments or decrements the operand before its value is used. If either is used as a postfix operator, the increment and decrement operation will be performed after its value has been used. Example: i = 5; i++; // i = i+1 i becomes 6 j = ++i; // i = i+1; j = i; i becomes 7 and j is 7 j = i++; // j = i; i = i+1; j is 7 and i becomes 8
20
Cast Operators (type)expr;
Used to convert a value of one type explicitly to a value of another type. C cast operation (type)expr; where expr is an expression and type is a data type of a single object such as char, int, float, double, or and pointer declaration such as char *. Example: > int i = 2, j = 3; > double d; > i/j > 2/3 > d = (double)i/j; // d = /3 0.6667
21
Comma Operator The comma operator ‘,’ introduces comma expression.
The comma expression consists of two expressions separated by a comma. For example, a = 1, b=2; This is useful for a for-loop to be described in next chapter. The comma operator is syntactically left-associative. The following expression a = 1, ++a, a + 10; is equivalent to ((a = 1), ++a), a + 10; The left operand of a comma operator is evaluated as a void expression first. Then the right operand is evaluated; the result has its type and value. For example, > a = 1, ++a, a + 10 12 > a 2
22
The comma operator cannot appear in contexts where a comma is used as a separate item such as the argument list of a function. In these cases, it can be used within parenthesis. For example, the exponential function pow(x,y) defined in the header file math.h for the mathematical expression xy has two arguments. It can be evaluated as shown below. > double x= 2, y = 3 > pow(x,y) // pow(2,3) 8.0000 > pow((x=2, x+3), y) // pow(5,3)
23
Bitwise Operators There are six bitwise operators: Operator Name
Description & bitwise AND The bit is set to 1 if the corresponding bits in the two operands are both 1. | bitwise OR The bit is set to 1 if at least one of the corresponding bits in the two operands is 1. ^ bitwise exclusive OR The bit is set to 1 if exactly one of the corresponding bits in the two operands is 1. << left shift Shift the bits of the first operand left by the number of bits specified by the second operand; fill from right with 0 bits. >> right shift Shift the bits of the first operand right by the number of bits specified by the second operand; filling from the left is implementation dependent. ~ One’s complement Set all 0 bits to 1, and all 1 bits to 0.
24
Example: a b a & b a | b a ^ b b << 1 a >> 1 ~a 3&5 = 011 & 101 = 001 = 1 4|5 = 100 | 101 = 101 = 5
25
Input & Output Human Interface Input: Keyboard Mouse Output: Monitor
Speaker
26
Sample Program The CPU computes but you see nothing
main () { int i; i = 0; i = i+2; i = i *3; i = i -1; } The CPU computes but you see nothing because you did not tell it to show you
27
How to show a character on screen?
Know where memory of the screen is Know how to send command to the monitor Select the mode of the screen Select the font Fill the pixels correspond to the character Too complicate !
28
It takes lots of CPU commands to show a character on screen.
It also requires knowledge of hardware. OS has a collection of frequent used CPU instructions, wrap them in a single command for easy use.
29
Library Library is a collection of useful complex commands.
CPU commands is native to the compiler. Complex commands are composed on several CPU commands. They are located in a library.
30
Standard Input/Output library
stdio.h is a library that collects input/output related commands. There are many commands, but we will initially cover two commands: printf() - print a set of characters on the screen scanf() - receive input from keyboard
31
How to use the library? Tell the program to load the library
#include <stdio.h> main () { int i = 0; i = i+2; printf(“Hello World”); } Use commands in the library
32
Introduction to Formatted Input and Output
Function printf() Precisely formatted output is accomplished using the output function printf. The printf function has following form printf( format-control-string, arguments ); Format-control-string: Using specifications to describe output format. Each specification begins with a percent sign (%), ends with conversion specified and is enclosed in quotation marks “ “. arguments: correspond to each conversion specification in format-control-string. The printf command is an extra function located in <stdio.h> library.
33
Format-Control-String
Table below lists the format-control-string of different argument types for function printf(). Argument Type Format-Control-String char “%c” signed char, short, int “%d” unsigned char, short, int “%u” octal number “%o” hexadecimal number “%x” float “%f” double “%f” or “%lf” string “%s” pointer “%p”
34
The program will replace %d with the value of i and print out
Double quote argument int i = 12; printf(“The distance is %d meters”, i); The program will replace %d with the value of i and print out The distance is 12 meters
35
Example: > printf(“%d”, 4261) // decimal integer 4261
> printf(“%ld”, 4261); // decimal long long integer > printf(“%o”, 4261); // octal number 10245 > printf(“%x”, 4261); // hexadecimal number 10a5 > printf(“%f”, 15.0F); // print out a float > printf(“%f”, 15.0); // print out a double float > printf(“%lf”, 15.0); > printf(“%c”, ‘a’); a > printf(“%s”, “This is a string.”); This is a string.
36
Special Characters
37
Printing Multiple Numerical Values in a Single Printing Statement
Use multiple format specifiers. Each format specifier corresponds to an argument. > printf(”integer is %d, floating-point number is %f”, 10, 12.34) integer is 10, floating-point number is
38
Precision of Floating-Point Numbers
The precision of a floating-point number specifies the number of digits after the decimal point character. The precision typically takes the form of a period (.) followed by an decimal integer. For example, the format “%.2f” specifies the precision with 2 digits after the decimal point. > printf(”%.2f”, ) 12.12 > printf(”%.2f”, ) 12.57 > printf(”%.20f”, 0.2) The fractional part after the specified precision number is rounded up. A floating-point number may not be represented exactly.
39
Program 1: Calculate the acceleration.
/* File: accelvar.c */ #include <stdio.h> main() { /* declare variables */ double a, /* acceleration */ mu, /* friction coefficient */ m, /* mass */ p; /* external force */ /* Initialize variables */ mu = 0.2; m = 5.0; p = 20.0; /* Calculate the acceleration */ a = (p-mu*m*9.81)/m; /* display output */ printf("Acceleration a = %f (m/s^2)\n", a); } Output: Acceleration a = (m/s^2)
40
Function scanf() Precise formatting input is accomplished using the input function scanf. The scanf function has following form scanf( format-control-string, arguments ); Format-control-string: Using specifications to describe input format. Each specification begins with a percent sign(%), ends with conversion specifier and is enclosed in quotation marks. The format-control-string is similar to format-control-string discussed in printf function. arguments: pointers to variables in which the input value will be stored (a variable name preceded with &).
41
Format-Control-String
Table below lists the format-control-string of different argument types for function scanf(). Argument Type Format-Control-String char “%c” int “%d” unsigned int “%u” float “%f” double “%lf” string “%s” pointer “%p”
42
Double quote & (indicate pointer)
int i; scanf(“%d”, &i); The program will receive keyboard and try to match the keyboard input to the control string.
43
Example: > int i > float f > double d > char c
> scanf(“%d”, &i); 10 > i > scanf(“%f”, &f); 10.2 > f 10.20 > scanf(“%lf”, &d); 15 > d > scanf(“%c”, &c); a > c
44
Example: > int i > scanf(“%d”, &i); // input number in decimal
4261 > i > scanf(“%o”, &i); // input number in octal // or ‘010245’ > scanf(“%x”, &i); // input number in hexadecimal 10A5 // or ‘0x10A5’ or ‘0X10A5’
45
Interactive execution of program scanf.c
Example: Program scanfc.c /* File: scanfc.c for input and output example */ #include <stdio.h> main() { int num; double d; printf("Please input an integer and one floating-point number\n”); scanf("%d %lf",&num, &d); printf("Your input values are %d and %f\n“, num, d); } Interactive execution of program scanf.c > scanfc.c Please input one integer and one floating-point number Your input number is 10 and >
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.