1 / 77

CPS125

Learn about arithmetic operators, operator precedence, and math functions in C programming. Explore examples and shortcuts for performing calculations.

sandford
Télécharger la présentation

CPS125

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPS125 Week 4

  2. Example:HOMEWORK

  3. Addition (+): 3+4 or 55.1+43.58 Subtraction (-): 50-20 or 45.3-0.78 Multiplication (*): 5*10 or 0.6*3.4 Division (/): 50.0/2.0 or 45/2 Remainder (%): Also called modulus Ex: 30%7 is 2, 45%3 is 0, 23%77 is 23. % works only with integers! Arithmetic operators

  4. Precedence of Arithmetic Operations Priority of arithmetic operations over each other Operations are performed from left to right based on the precedence Order Of Arithmetic Operations • Example: • 1 + 8 / 2  5 • ( 1 + 8 ) / 2  4 • 1 + 8 / 9 * 2 - 10  -9 • Note: • Integer divided by another integer results in an integer result

  5. Integer expressions Expressions containing only integers are called integer expressions. The result of an integer expression is always an integer. This is particularly important for the division operator. For example, 5/2 is an integer division and will give 2,not 2.5. There is never a rounding up of values. 99/100 will give 0 not 1. Now that we know about integer division, we find that a%b is the same as a - (a / b) * b. Double expressions Expressions containing only doubles are called double expressions. The result of an double expression is always a double. For example 5.0/2.0 is a double division and will give 2.5. 99.0/100.0 will give 0.99. Mixed expressions Expressions containing doubles and integers are called mixed expressions. The result of a mixed expression is always a double. For example 5/2.0 or 5.0/2 is a mixed division and will give 2.5. 35*2.0 will give 70.0. Expressions

  6. Rule #1: Parentheses rule: All parentheses must be evaluated first from the inside out. Rule #2: Operator precedence rule: 2.1 Evaluate unary operators first. 2.2 Evaluate *, / and % next. 2.3 Evaluate + and – next. Rule #3: Associativity rule: All binary operators must be evaluated left to right, unary operators right to left. Evaluating expressions

  7. Square roots in C are computed with a special function taken from a special library: the math library. To use that library, we need to include the proper header file: #include <math.h> The square root function is called sqrt and is used by calling it this way: sqrt (x) where x is the number we wish to know the square root of. We can put that answer in another variable y=sqrt(x); x sqrt y Math functions Math functions can be integrated in other C statements and expressions. All math functions use doubles. z = a + sqrt (b-c); printf (“The square root of %lf is %lf”, x, sqrt(x)); Square root

  8. y=floor (x): the largest whole number <= x. If x is 3.7, y will be 3.0. If x is -14.2, y will be -15.0. y=ceil (x): the smallest number >= x. If x is 3.7, y will be 4.0. If x is -14.2, y will be -14.0. y=log(x): finds the natural log of x (ln). y=log10(x): finds the decimal log of x (log). y=fabs(x): finds the absolute value of x. sin(x), cos(x), tan(x) and arctan(x) are trig functions giving the sine, cosine, tangent and arctangent of an angle expressed in radians (not degrees). radians = degrees * PI / 180 y = exp (x): gives e to the power of x. z = pow (x,y): gives x to the power of y. atan(x): calculate the arc tangent of a real number giving an angle expressed in radians. Other math functions

  9. Other functions can be found in the standard library (also need to #include <stdlib.h>). Be careful! b=abs(a): gives the absolute value of an integer. n = rand(): will give a random integer number between 0 and RAND_MAX, a predefined constant macro. To find the value of RAND_MAX on your computer just try this: printf (“%d”, RAND_MAX); Other functions

  10. x=x*5; may be shortened to x*=5; a=a/2; may be shortened to a/=2; i=i+1; may be shortened to i+=1; Since adding and subtracting 1 is very common, there is a shorter version still. i=i+1; may be shortened to ++i; i=i-1; may be shortened to - -i; Increment and decrement ++i is called an increment, --i a decrement. i++ and i-- can also be used. There is no difference between the prefix ++i and postfix i++ forms as far as the value of i is concerned. But is an assignment is used, there is a difference. In b=++i; i is incremented and the answer is then placed into b. In b=i++, the value of i is placed in b and then i is incremented. Shortcut operators: HOMEWORK

  11. #include <stdio.h> void main(void) { inti=1, j=1, k1=10, k2=20, k3=30, k4=40, k5=50, k, h, m, n; float a=7, b=6, c=5, d=4, e, p, q, x, y, z; printf("Before increment, i=%2d, j=%2d\n",i,j); k=i++; h=++j; printf("After increment, i=%2d, j=%2d\n“ k=%2d, h=%2d \n\n",i,j,k,h); m=6/4; p=6/4; n=6/4.0; q=printf("m=%2d, p=%3.1f\nn=%2d, q=%3.1f\n\n",m, p, n, q); printf("Original k1=%2d, k2=%2d, k3=%2d, k4=%2d, k5=%2d\n“, k1,k2,k3,k4,k5); k1 += 2; k2 -= i; k3 *= (8/4); k4 /= 2.0; k5 %= 2; printf("New k1=%2d, k2=%2d, k3=%2d, k4=%2d, k5=%2d\n\n", k1,k2,k3,k4,k5); e= 3; x= a + b -c /d *e; y= a +(b -c) /d *e;z=((a + b)-c /d)*e; printf("a=%3.0f, b=%3.0f, c=%3.0f\nd=%3.1f, e=%3.1f\n\n“, a,b,c,d,e); printf("x= a + b -c /d *e = %10.3f \n“ "y= a +(b -c) /d *e = %10.3f \n" "z=((a + b)-c /d)*e = %10.3f\n", x,y,z); } Practice! Mixed Type Arithmetic

  12. How to Access a Memory Location? • Either use the corresponding address Or • Declare a variable and use the variable name • Variable • Specific memory location • Set aside for specific kind of data • Has a name for reference • Has an address for reference 12

  13. scanf( ) function Q) How to get the address of a variable? A) By using the address operator (&), we can get the address. e.g. main( ){ intVar=5; … } • Var in this example represents the value of variable which is 5. (from memory point of view, Var represents the content of the memory set aside for Var and that content again is 5) • &Var in this example represents the address of the variable which is 1002.

  14. Address Of Var In Memory

  15. Pointers

  16. POINTERS IN C • Memory is a collection of storage locations. • Locations are numbered sequentially. • Each location has a unique address.

  17. /* PROGRAM # 45 */ • /* DEMONSTRATES USE OF MEMORY STORAGE */ • #include <stdio.h> • main( ){ • int number; • intvar; • int sum; • number = 55; • var = 25; • /* Add two integer numbers */ • sum=number + var; • printf("sum is %d", sum); • } • Q) What does “int number;” do? • A) Compiler looks at the memory and tries to set aside enough storage (2 bytes for an integer for example) for a new variable that is called number. This location can be anywhere in the memory that is actually available for usage (i.e., is free).

  18. Memory Map Memory Address of Variables In this example:address 1000 and 1001 are set aside for number.(We may note that knowing the address 1000 is enough since number is INTEGER and we know int needs 2 bytes so knowing the address of first byte would be sufficient.) address 2000 and 2001 are set aside for var. address 3000 and 3001 are set aside for sum.

  19. Memory Location • So, there are 2 methods of accessing the memory locations that holding the value of the variable number: • We can use the name that we have picked up for that location, i.e., number • We can use the address of the location, i.e., 1000 • We already know how to use number as the variable name in a C program. • Pointers are needed if we want to use the address instead.

  20. Address Operator • Q) How do we get hold of the address of a variable? • A) We can use the address operator. • & is the address operator. • EXAMPLE: • number name of the variable • &number address of the variable

  21. /* PROGRAM # 46 */ • /* DEMONSTRATES USE OF ADDRESS OPERATOR*/ • #include<stdio.h> • main( ){ • int number = 55; • /* Display address of the variable in memory */ • printf(" The address of the variable is: %d\n",&number); • /* Display value of the variable */ • printf(" The value of the variable is: %d\n", number); • } • The address of the variable is: 1002 • The value of the variable is: 55

  22. Pointer Declaration in C • Q) What does a pointer variable hold? • A)Pointers are holding addresses. • Q) Anything else we need to know? • A) Declare the pointer. • Immediately afterward, get the pointer to point to a variable. • Q) How to declare a pointer? • A) 3 steps: • Pick up a name for the pointer variable • Put a * before the pointer name to indicate that this is a pointer variable not a regular variable • Indicate what type of data we find in that address • Q) How to get the pointer to point to a variable? • A)Assign the address of a variable to the pointer. • Make sure the data types are matching. • Q) Any regular variable has address associate with it. Would it be true for pointer • variable as well? • A) Yes. Any pointer variable has also an address.

  23. /* PROGRAM # 47 */ • /* BASIC POINTER USE*/ • #include <stdio.h> • main( ){ • int number; /* declare a regular variable*/ • int *ptr; /* declare a pointer variable*/ • /* note: the pointer’s name is ptr, NOT *ptr */ • number = 55; /* assign a value to the regular variable */ • ptr = &number; /* assign an address to pointer variable */ • /* by putting the address of the regular variable in a pointer variable, we get the pointer to point to the variable */ • }

  24. Storage Space of Different types of variables 55 1002

  25. Using the Pointer • Two new operators: • * indirection operator • & address operator • Passing Variables with Pointers : One possible use of the pointer is to Change the value of variable pointed to by the pointer. For this we need to know what does *ptr means? • One Good Application of Pointers: Pointers can be used to pass more than one variable back from a function.

  26. /* PROGRAM # 48 */ • /* PROPER USE OF POINTER*/ • #include <stdio.h> • main( ){ int number; • /* Declare pointer */ • int *ptr; number = 55; • /* Initialize ptr to point to number */ • ptr = &number; • printf("Address stored in pointer is %d\n", ptr); • printf("Address of pointer is %d\n", &ptr); • printf("Value pointed to by the pointer is %d\n", *ptr); • printf("Value stored in the regular variable is %d\n", number);} • NOTE: • Things to remember when dealing with pointers: • ptr: contains the address stored in the pointer variable. • &ptr: gives the address of the pointer variable. • *ptr: gives the value stored at the memory location whose address is stored in the pointer variable.

  27. /* PROGRAM # 49 */ • /* PASSING VARIABLES USING POINTERS*/ • #include <stdio.h> • main( ){ • /* Declare pointer ptr */ • int *ptr; • int variable; • variable = 55; • /* Initialize ptr to point to variable */ • ptr = &variable; /* remember we should get the pointer to point to a variable as soon as we can */ • printf("The value stored in variable right now is %d\n", variable); • *ptr = 77; /* change the content of the location pointed • to by the pointer variable, ptr */ • printf("Notice that we changed the value stored in variable using the • pointer%d\n", variable); }

  28. Passing Variables using Pointers (Change of Value of the Variable ) 55 77 1002 1002

  29. similar to printf( ) but just to use to print text (no variable) don’t need to use \n since puts( ) automatically produce one must include <stdio.h> in the program puts( ) function

  30. Q) What is the difference between the following 2 statements? (num1 + num2)/2 AND (num1 + num2)/2.0 Question

  31. A) This operation is division and num1 and num2 are integer numbers. Therefore, in (num1 + num2)/2, we are dividing an integer by a second integer and as such the result would be another integer. The average produced this way is incorrect. (num1 + num2)/2.0, however, represents a case where 2.0 is a float constant and the result of the division would produce the correct float average. Answer

  32. /* TO CALCULATE AVERAGE OF TWO INTEGER NUMBERS */ Practice more Q

  33. #include<stdio.h> /* TO CALCULATE AVERAGE OF TWO INTEGER NUMBERS */ int main(void ){ int num1, num2; float average; /* Input two numbers */ puts(“Pls enter two integer numbers & we’ll average them for you”); scanf(“%d %d”, &num1, &num2); /* Calculate the average */ average=(num1 + num2)/2.0; /* Display the average of two numbers and message Thanks you! */ printf(“The average is %f.\n”, average); puts(“Thank You!”); } Practice! /* PROGRAM # 3 */

  34. Practice! /* PROGRAM # 3 */

  35. Good programming practice: DO NOT MIX DATA TYPES USE TYPE CASTING INSTEAD Type casting: Converting a variable to a particular type. Done by using a unary cast operator ( ) General Synatx: ( type ) variable e.g., int value (float)value Type Casting

  36. /* TO CONVERT VARIABLE’S TYPE */ #include<stdio.h> int main(void ){ intvar; /* Get a number */ printf(“Pls enter an integer number: “); scanf(“%d”, &var); /* Print the number as an integer */ printf(“The integer number that you entered is: %d.\n”, var); /* Print the number as a float */ printf(“The integer number printed as a float is: %f.\n”, (float)var); } Practice! /* PROGRAM # 5* /

  37. Practice! /* PROGRAM # 5* /

  38. Did you finish your practice from the previous slides????

  39. RELATIONAL/EQUALITY OPERATORS THE IF STATEMENT LOGICAL OPERATIONS – AND, OR, NOT PRECEDENCE FOR C OPERATORS, MATHEMATICAL, RELATIONAL, LOGICAL TYPE CASTING C SWITCH CONDITIONAL OPERATOR CONDITIONAL STATEMENTS

  40. Control structures combine individual instructions into a single logical unit with one entry point at the top and one exit point at the bottom. 3 kinds of control structures: Sequence (default control structure) Selection (branches) Repetition (loops) Control Structures

  41. A condition is an expression that is either true or false. Ex: CPS125_Grade=98; CPS125_Grade < 0 will be false CPS125_Grade >90 will be true Comparison (relational) operators are: < > <= >= == != Conditions

  42. Relational Operations • Relationship between 2 variables, expressions • Returns a numerical value depending on the result • The value returned for TRUE is 1, 0 otherwise Relational Operators in C

  43. Equality Operations • Equality between 2 variables, expressions • The value returned for TURE is 1, 0 otherwise Equity Operators in C

  44. Missing #include… Missing variable declaration Wrong variable declaration Missing semicolon Incorrect assignment Using the name of the variable instead of its address Incorrect nested if Wrong looping condition Misusing pointers Missing Braces Using incorrect format specifier Common Mistakes When Writing a C Program

  45. = denotes assignment result of operation in right hand side is assigned to the variable mentioned in left hand side. x = 5; /* returns 5 to x*/ ==denoted equal to is relational operators returns either 1 or 0. x == 6; /* returns 0 */ Note on = and == 

  46. A logical expression contains one or more comparison and/or logical operators. The logical operators are: &&: the and operator, true only when all operands are true. ||: the or operator, false only when all operands are false. !: the not operator, false when the operand is true, true when the operand is false. Logical Operators

  47. Logical AND (&&) ( expression1 ) && ( expression2 ) This operation is TRUE only if expression1 is TRUE and expression2 is TRUE. Works based on the AND truth table as follows: Logical AND Truth Table Logical Operations – AND, OR, NOT

  48. Logical OR (||) (expression1) || (expression2) This operation is FALSE only if expression1 is FALSE and expression2 is FALSE. Works based on the OR truth table as follows: Logical OR Truth Table Logical OR Operation

  49. Logical NOT (!) ! (expression1) This operation will negate the logical value of the expression. Works based on the NOT truth table as follows: Logical NOT Truth Table Logical NOT Operation

More Related