Basic C Programming

Download Report

Transcript Basic C Programming

Basic C Programming
Data Types and Arithmetic Operations
01/30/15
Objectives







Know the basic data types in C.
Use arithmetic operators in C.
Tell what data type an expression has.
Use output formats to display values.
Declare and use variables.
Use assignment statements to give variables
values.
Input values using scanf
Data Types

Integer



int
char
Floating Point


float
double
Integer
• Binary number with sign
• In memory:
Sign bit
• e.g. 100, 15, 0, -19, -100000
• Precise
Integer

int



Stores +/- counting numbers
Stored as integer
char – stores characters.



Also stored as Integer
Stores numeric codes for characters
'A', 'z', '1', '\n'


More escape sequences on page 62.
ASCII codes on pg. 61

How would “Cat” be stored?
Floating Point
In Memory:
mantissa
exponent
Number = mantissa x 2exponent
Floating Point
• float
• e.g. 45.7, 8.97e-4, -15.4
– e-format ^
8.97 x 10 -4
• Not exact
• double is similar
– Uses twice as much storage
– Use when number needs to be more accurate or
greater magnitude
Arithmetic Operators
Math
C
+, - (Unary)
+ - (Unary)
*, /, %
+, - (Binary)
No exponent op
X,•, /, ÷
+, - (Binary)
xn
Expression

Combination of operators and operands
85
22+6
7.5 / 2.5 + 3.0
Order of Operations
1.
2.
3.
4.
Parenthesis
Unary +, *, /, %
Binary +, -
e.g.
4 + 2 * 5
5 * ( 14 + -7)
Expression Type

Type of results is same as operands
5 + 4 --> int 9
1.3 * 2.0 --> double 3.5

Result of mixed operation is double type
5 + 1.2 --> double 6.2
What is the result of each?
6 + 18 / 2
1.2 * 3.0
5.0 * 9
3.0 * 0.1 + 1.5 * 2.0
4 * (9 + 1)
Integer Division





11/4 --> 2
11%4 --> 3
drops remainder
% gives remainder
Want to find the area of a triangle with height
4 and base 3.
1/2bh
How would I write that in C?
Displaying Numeric Values

Control string tells printf what form to display
the result in.




%d – int displayed as decimal
%c – Display char
%f – Display floating point number as decimal
number
ch2/formats.c
What is the output of these two
lines?
printf("Half off is $%d", 11/2);
printf("Tax is $%f\n", 11/2*.06);
Next

Variables and Assignment Statements.