unit 3 programming calculations using numeric data introduction to c programming

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

Upload: matthew-arnold

Post on 27-Mar-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

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

Unit 3

Programming Calculations Using Numeric Data

Introduction toC Programming

Page 2: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Review of Unit 2

Unit 3: Review

Page 3: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Review: Conversion Program

#include <stdio.h>

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 = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);

return (0);}

Page 4: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Performing Calculations

Unit 3: Arithmetic Operators and Assignment Statements

Page 5: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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

<Variable> = <Expression> ;

Meaning: "Put value of <Expression> into <Variable>"o Previous contents of <Variable> are losto Data type of <Expression> should match data type of

<Variable>

Page 6: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Assignment Statement Examples

days = 8;

dist_in_kms = 1.609 * dist_in_miles;

value = value * 2;

result = value - 10;

average = sum / 3;

Page 7: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Expressions Could be a constant52.6

Could be a variablenumberOfTurns

Could be a simple or complex calculation using operators

setting + 1

((tempF - 32.0) * (5.0/9.0))

Page 8: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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.

Page 9: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Mixed-type assignmentsint 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.

Page 10: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Assigning to an int vs. a doubledouble x;int n;x = 9 * 0.5;n = 9 * 0.5;

Assigning to an int variable truncates(the fraction part is discarded)

4.5 4

x n

Page 11: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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 94.83.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

Page 12: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Classification of Operators

Unary Operators Binary Operators

One operand<op> a

oNegation (-)oPositive (+)

Examples:x = -y;y = -3.1;p = +x;

Two operandsa <op> 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;

Page 13: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Rules of Precedence Which operation is done first?

(3 + x) * y / (height * 1.1 - 17)

Specifies order of operations in complex expressionsoParentheses Precedence RulesoOperator Precedence RulesoAssociativity Rules

Page 14: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Parentheses Precedence Rules What is inside parentheses is evaluated

first.o Used to overrule the natural operator

precedence ordero Example:

(2 + 10) * 3 /* result is 36 */

Nested parentheses - innermost set is evaluated first.o Example:(2 + (10 - 1)) * 3 /* result is 33 */

Page 15: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Operator Precedence Rules Unary operations are performed first. Multiplication and Division operations are

second. Addition and subtraction are last.

Example:-3 + 7 * 2 /* result is 11 */

The unary negation is first: (-3) + 7 * 2 The multiplication is next: (-3) + 14 The addition is last: 11

Page 16: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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 */

Page 17: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Example from Electronics

Page 18: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Creating a Named Constant To use a constant in a C program, create a

named constant.o Created with #define, which defines a macroo Names are traditionally written in all caps.o The definition goes at the top of the file, with #include.

#define PI 3.14159

Page 19: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Example - Area of a Circle

Page 20: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Example Program - Compute Area

#include <stdio.h>#define PI 3.14159

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);

}

Page 21: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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 = 3.14159;

No assignment statement is allowed:PI = 0; /* Compiler prevents this */

Page 22: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Advanced Use of printf( )

Unit 3: More on the printf( ) Function

Page 23: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Formatting Output of Type int

Table 2.11

Displaying 234 and -234 Using Different Placeholders

Page 24: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Formatting Output of Type double

Table 2.13

Page 25: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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);

Page 26: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

C Standard Libraries

Unit 3: Library Functions

Page 27: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

C Standard Libraries We have already seen the use of <stdio.h> for

I/O functions:o printfo scanf

The <math.h> library is a collection of prewritten calculations.

Examples: double x, y; x = pow(10, y); /* Calculates 10 ^ y */ x = sqrt(y); /* Calculates square root */

Page 28: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Table 3.1 pg 121

For more information on the math library, Google "math.h C library"

Page 29: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

The enum Data Type

Unit 3: Enumerated Data Types

Page 30: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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" */

Page 31: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Example: Color Bands enum Consider the Example below - what does this

do?

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

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);}

Page 32: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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)

Page 33: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Making Programs Appear Professional

Unit 3: Coding Standards

Page 34: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Coding Standards Purposes

o Make code easier to read and understando Make maintenance easier

Corporate policies or guidelines

Includeso Variable namingo Code formattingo Commentso Human factors

Page 35: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Variable Naming Be consistent in naming styles

o Camel Case: dayOfWeeko 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;

Page 36: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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.

Page 37: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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 *//* ET2560 - Instructor's name *//* Unit # Lab # and Task # */

Page 38: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

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

Page 39: Unit 3 Programming Calculations Using Numeric Data Introduction to C Programming

Coding Standards Example

#include <stdio.h>#define PI 3.14159

/* 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); }