unit 3 programming calculations using numeric data introduction to c programming
TRANSCRIPT
Unit 3
Programming Calculations Using Numeric Data
Introduction toC Programming
Review of Unit 2
Unit 3: Review
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);}
Performing Calculations
Unit 3: Arithmetic Operators and Assignment Statements
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>
Assignment Statement Examples
days = 8;
dist_in_kms = 1.609 * dist_in_miles;
value = value * 2;
result = value - 10;
average = sum / 3;
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))
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.
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.
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
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
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;
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
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 */
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
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 */
Example from Electronics
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
Example - Area of a Circle
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);
}
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 */
Advanced Use of printf( )
Unit 3: More on the printf( ) Function
Formatting Output of Type int
Table 2.11
Displaying 234 and -234 Using Different Placeholders
Formatting Output of Type double
Table 2.13
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);
C Standard Libraries
Unit 3: Library Functions
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 */
Table 3.1 pg 121
For more information on the math library, Google "math.h C library"
The enum Data Type
Unit 3: Enumerated Data Types
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" */
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);}
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)
Making Programs Appear Professional
Unit 3: Coding Standards
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
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;
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.
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 # */
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
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); }