Introduction to C Programming

Presentation on theme: "Introduction to C Programming"— Presentation transcript:

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

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 = * 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 Left side of assignment must be a variable (called lvalue) Right side of assignment is expression <Variable> = <Expression> ; Meaning: "Put value of <Expression> into <Variable>" Previous contents of <Variable> are lost Data type of <Expression> should match data type of <Variable>

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

Expressions Could be a constant Could be a variable
52.6 Could be a variable numberOfTurns Could be a simple or complex calculation using operators setting + 1 ((tempF ) * (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 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.

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) x n 4.5 4

Casting an expression's type
This calculation produces the "wrong" answer: int totalScores, numStudents; double average; totalScores = 569; numStudents = 6; average = totalScores / numStudents; If the totalScores is 569, and numStudents is 6, the result in C is 94, but the desired answer is 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 Negation (-) Positive (+) Examples: x = -y; y = -3.1; p = +x; Two operands a <op> b Add (+) Subtract (-) Multiply (*) Divide (/) 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 * ) Specifies order of operations in complex expressions Parentheses Precedence Rules Operator Precedence Rules Associativity Rules

Parentheses Precedence Rules
What is inside parentheses is evaluated first. Used to overrule the natural operator precedence order Example: (2 + 10) * 3 /* result is 36 */ Nested parentheses - innermost set is evaluated first. (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: * 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: /* result is 5, not 3 */

Example from Electronics

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

Example - Area of a Circle

Example Program - Compute Area
#include <stdio.h> #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); }

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

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

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 Corporate policies or guidelines Includes
Make code easier to read and understand Make maintenance easier Corporate policies or guidelines Includes Variable naming Code formatting Comments Human factors

Variable Naming Be consistent in naming styles Pick meaningful names
Camel Case: dayOfWeek 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.