Download presentation

Presentation is loading. Please wait.

Published byMatthew Arnold Modified over 2 years ago

1
Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

2
Review of Unit 2 Unit 3: Review

3
Review: Conversion Program #include int main(void) { double dist_in_miles, dist_in_kms; printf("Convert miles to kilometers\n"); printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles); dist_in_kms = * dist_in_miles; printf("The distance in kilometers is: "); printf("%f", dist_in_kms); return (0); }

4
Performing Calculations Unit 3: Arithmetic Operators and Assignment Statements

5
Assignment Statement Used to change a variable Stores a value, or computational result, in a variable Looks like equation, but is NOT o Left side of assignment must be a variable (called lvalue) o Right side of assignment is expression = ; Meaning: "Put value of into " o Previous contents of are lost o Data type of should match data type of

6
Assignment Statement Examples days = 8; dist_in_kms = * dist_in_miles; value = value * 2; result = value - 10; average = sum / 3;

7
Expressions Could be a constant 52.6 Could be a variable numberOfTurns Could be a simple or complex calculation using operators setting + 1 ((tempF ) * (5.0/9.0))

8
Arithmetic Operators Table 2.6 Remember: A number with a decimal point has the 'double' data type. A number without a decimal point has the 'int' data type.

9
Mixed-type assignments int m, n; double p, x, y; m = 3; n = 2; p = 2.0; x = m / p; /* result is 1.5 */ y = m / n; /* result is 1.0! */ If both operands are int, the division is an int. The type of the target does not matter to the division.

10
Assigning to an int vs. a double double x; int n; x = 9 * 0.5; n = 9 * 0.5; Assigning to an int variable truncates (the fraction part is discarded) 4.54 xn

11
Casting an expression's type This calculation produces the "wrong" answer: int totalScores, numStudents; double average; totalScores = 569; numStudents = 6; average = totalScores / numStudents; o If the totalScores is 569, and numStudents is 6, the result in C is 94, but the desired answer is o Why ? Because the division is done with two ints. By using a cast, we can promote the calculation to be a double: average = (double)totalScores / numStudents; Now, average is assigned 94.83

12
Classification of Operators Unary OperatorsBinary Operators One operand a o Negation (-) o Positive (+) Examples: x = -y; y = -3.1; p = +x; Two operands a b o Add (+) o Subtract (-) o Multiply (*) o Divide (/) o Remainder (%) or 'modulo' Examples: x = t + 4; z = 5 * x; y = (2 - y) / z; i = g % 2;

13
Rules of Precedence Which operation is done first? (3 + x) * y / (height * ) Specifies order of operations in complex expressions o Parentheses Precedence Rules o Operator Precedence Rules o Associativity Rules

14
Parentheses Precedence Rules What is inside parentheses is evaluated first. o Used to overrule the natural operator precedence order o Example: (2 + 10) * 3/* result is 36 */ Nested parentheses - innermost set is evaluated first. o Example: (2 + (10 - 1)) * 3/* result is 33 */

15
Operator Precedence Rules Unary operations are performed first. Multiplication and Division operations are second. Addition and subtraction are last. Example: * 2/* result is 11 */ The unary negation is first:(-3) + 7 * 2 The multiplication is next:(-3) + 14 The addition is last:11

16
Associativity Rules Multiple multiplication / division are done left-to-right: 8/2*4/* result is 16, not 1 */ Multiple addition / subtraction are done left-to-right: 8-4+1/* result is 5, not 3 */

17
Example from Electronics

18
Creating a Named Constant To use a constant in a C program, create a named constant. o Created with #define, which defines a macro o Names are traditionally written in all caps. o The definition goes at the top of the file, with #include. #define PI

19
Example - Area of a Circle

20
Example Program - Compute Area #include #define PI int main(void) { double radius, area; printf("Enter radius of a circle: "); scanf("%lf", &radius); area = PI * radius * radius; printf("Area is %f\n", area); return (0); }

21
Use of const Keyword Another means of specifying a constant: o Standardized with ANSI C The const keyword specifies a read-only variable: o The variable cannot be changed by the program const double PI = ; No assignment statement is allowed: PI = 0;/* Compiler prevents this */

22
Advanced Use of printf( ) Unit 3: More on the printf( ) Function

23
Formatting Output of Type int Table 2.11 Displaying 234 and -234 Using Different Placeholders

24
Formatting Output of Type double Table 2.13

25
Formatting Currency Amounts Assume you have a dollar-and-cents amount to print: double coinsInDollars; What printf statement would you use to print a dollar sign, followed by a number with two decimal digits? The answer is: printf("$%.2f", coinsInDollars);

26
C Standard Libraries Unit 3: Library Functions

27
C Standard Libraries We have already seen the use of for I/O functions: o printf o scanf The library is a collection of prewritten calculations. Examples: double x, y; x = pow(10, y); /* Calculates 10 ^ y */ x = sqrt(y); /* Calculates square root */

28
Table 3.1 pg 121 For more information on the math library, Google "math.h C library"

29
The enum Data Type Unit 3: Enumerated Data Types

30
The enum Data Type With typedef keyword, creates a new data type List of identifiers Compiler associates these with constants First in list is 0, next is 1, and so on typedef enum { SUN, MON, TUE, WED, THU, FRI, SAT } days_t; days_t today; today = SUN;/* 'today' is set to 0 */ printf("%d", today);/* prints '0', not "SUN" */

31
Example: Color Bands enum Consider the Example below - what does this do? #include typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t; int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res; res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0); }

32
Enum Data Type - Starting Value An enum data type typically starts the first enum at 0: typedef enum {ZERO, ONE} binary_t; However, C provides a way to start the first enum at a different value: typedef enum {A=1, B, C, D} alphabet_t; (A is 1, B is 2, C is 3, D is 4)

33
Making Programs Appear Professional Unit 3: Coding Standards

34
Coding Standards Purposes o Make code easier to read and understand o Make maintenance easier Corporate policies or guidelines Includes o Variable naming o Code formatting o Comments o Human factors

35
Variable Naming Be consistent in naming styles o Camel Case: dayOfWeek o Underscores: day_of_week Pick meaningful names Avoid excessively long names Examples: double inputCurrent, outputVoltage; int partCount, loopCount; Don't use such obscure or confusing names as: double x, yy, my_football_team_rocks;

36
Code Formatting A program that looks good is easier to read. Indent the body of a function Insert spaces and blank lines for readability Place only one statement on a line These techniques are demonstrated in class materials and text.

37
Comments Use comments (not too few, not too many) Comment code that is not obvious Consider it a courtesy to yourself and those who come after For the class lab assignments: - Put the following information every time /* Your name */ /* ET Instructor's name */ /* Unit # Lab # and Task # */

38
Human Factors Make programs user-friendly o Use spacing appropriately for separation as needed o Use newline characters in printf to create blank lines as needed Spell correctly, especially in program output Provide self-explanatory output text Design a simple, easy-to-understand interface Keep input and output neatly formatted

39
Coding Standards Example #include #define PI /* Your name */ /* This program accepts the radius of a circle, calculates the area, and outputs the radius and the area. */ int main(void) { double radius; /* Stores radius entered by the user */ double area; /* Stores area after the calculation */ printf("Enter the radius of the circle: "); scanf("%lf", &radius); /* Calculate area as PI times r-squared */ area = PI * radius * radius; /* Output the area */ printf("The area of a circle with radius %f is %f\n", radius, area); return(0); }

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google