Chapter 2 C Basics

1 / 32
About This Presentation
Title:

Chapter 2 C Basics

Description:

To examine the use of arithmetic expressions. To define flow of control via ... symbol, and all the remaining symbols must be alphanumeric or underscores. ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0

less

Transcript and Presenter's Notes

Title: Chapter 2 C Basics


1
Chapter 2C Basics
Goals
  • To introduce the concept of a variable and its
    assignment
  • To explore primitive input and output operations
  • To survey the primitive data types in C
  • To examine the use of arithmetic expressions
  • To define flow of control via conditionals and
    loops

2
Variables
Variables are memory locations within RAM.
When a program variable is declared, adequate
space in RAM is reserved for it. The variable is
named with an identifier and can be given a
value. That value is stored at its memory
address, which is known as a pointer.
RAM
Binary Address 00000000
RAM is divided into 8-bit segments called
bytes. Each byte is numbered with a binary
address.
Variable of type char
Variable of type int
Binary Address 11111111
Variable of type double
3
Identifiers
Variables names, or identifiers, must start with
an underscore or an alphabetic symbol, and all
the remaining symbols must be alphanumeric or
underscores.
theValueThatIsUsedWhenIAmInAGoodMood
x27
Cost_of_living
_b4Value
8AMtemperature
Largest Value
amt_in_
vice-president
4
Reserved C Keywords -Cant Be Used As
Identifiers!
asm auto bad_cast bad_typeid bool break case
catch char class const const_cast continue def
ault delete do double dynamic_cast else enum e
xcept explicit extern false finally float for
friend goto if inline int long mutable nam
espace new operator private protected public re
gister reinterpret_cast return short signed siz
eof static static_cast struct switch template t
his throw true try type_info typedef typeid t
ypename union unsigned using virtual void volat
ile while
5
Variable Declarations
Variables must be declared before being used in a
program.
int count
float salaryPerWeek
char middleInitial
int nbr_of_rings, nbr_of_knocks
float MonPay, TuePay, WedPay, ThuPay,
FriPay
double measurement1, measurement2
6
Assignment Statements
Variables may be assigned values via the
assignment operator () in assignment statements.
count 0
salaryPerWeek 40 salaryPerHour
middleInitial W
nbr_of_rings 2 nbr_of_knocks - 1
MonPay TuePay WedPay 47.25F ThuPay
FriPay (float)62.75
measurement2 measurement1 / count
7
Initializing Variables
Variables may be initialized in their
declarations to possess specific values.
int value 0
float Radius 16.00F
bool flag false
double errorMargin 0.00000003
char firstltr A, lastltr Z
int loserCount(0), winnerCount(0)
float GPA(4.00F)
8
Output to the Monitor via cout
Values may be output to the monitor by means of
output statements that use the output operator
(ltlt) to stream to the output file cout.
cout ltlt 1492
int val 97 cout ltlt val
cout ltlt 1997 ltlt was great! cout ltlt I made a
fortune!
cout ltlt 1997 ltlt was great!\n cout ltlt I made
a fortune!
cout ltlt val ltlt million\n\ndollars!
9
include ltiostream.hgt void main() cout ltlt
"1Aa\azzz\aZZZ" ltlt endl cout ltlt
"2Bb\bzzz\bZZZ" ltlt endl cout ltlt
"3Cc\nzzz\nZZZ" ltlt endl cout ltlt
"4Dd\rzzz\rZZZ" ltlt endl cout ltlt
"5Ee\tzzz\tZZZ" ltlt endl cout ltlt
"6Ff\'zzz\'ZZZ" ltlt endl cout ltlt
"7Gg\"zzz\"ZZZ" ltlt endl cout ltlt
"8Hh\\zzz\\ZZZ" ltlt endl return
Escape Sequences
When a character value contains a character
preceded by a backslash (\), then it represents a
single symbol known as an escape sequence.
\a Bell (alert)
\b Backspace
\n New line
\r Carriage return
\t Horizontal tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
10
Formatting Real Number Output
To ensure that real numbers are output with
decimal points, an integer part, and a specific
number of decimal places, the following lines
should be included before outputting
Avoids Scientific Notation.
cout.setf(iosfixed) cout.setf(iosshowpoint)
cout.precision(4)
Shows Decimal Point Trailing Zeros.
Shows 4 Digits After Decimal Point.
11
include ltiostream.hgt include ltiomanip.hgt void
main() cout.setf(iosfixed)
cout.setf(iosshowpoint) cout.precision(8)
cout ltlt 9876.543210 ltlt endl cout ltlt
0.246813579 ltlt endl cout ltlt 37.00000000 ltlt
endl ltlt endl cout.precision(4) cout ltlt
9876.543210 ltlt endl cout ltlt 0.246813579 ltlt
endl cout ltlt 37.00000000 ltlt endl ltlt endl
cout.precision(2) cout ltlt 9876.543210 ltlt
endl cout ltlt 0.246813579 ltlt endl cout ltlt
37.00000000 ltlt endl ltlt endl return
Sample Program
12
Input from the Keyboard via cin
Values may be input from the keyboard by means of
input statements that use the input operator (gtgt)
to stream from the input file cin.
include ltiostream.hgt void main() int nbr
cin gtgt nbr char init1, init2, init3
cin gtgt init1 gtgt init2 gtgt init3 float temp
cout ltlt "Enter the temperature " cin gtgt
temp return
13
Data Types - Integers
include ltiostream.hgt include ltlimits.hgt void
main() int NTjurA 5, NTjurB INT_MAX,
NTjurC INT_MIN cout ltlt "REGULAR INTEGERS"
ltlt endl ltlt NTjurA ltlt endl ltlt NTjurB ltlt
endl ltlt NTjurC ltlt endl ltlt endl long
NNNNNTjurD 5, NNNNNTjurE LONG_MAX, NNNNNTjurF
LONG_MIN cout ltlt "LONG INTEGERS" ltlt endl
ltlt NNNNNTjurD ltlt endl ltlt NNNNNTjurE ltlt endl
ltlt NNNNNTjurF ltlt endl ltlt endl short nTjurG
5, nTjurH SHRT_MAX, nTjurI SHRT_MIN cout
ltlt "SHORT INTEGERS" ltlt endl ltlt nTjurG ltlt
endl ltlt nTjurH ltlt endl ltlt nTjurI ltlt endl ltlt
endl unsigned int UnNTjurJ 5, UnNTjurK
UINT_MAX cout ltlt "UNSIGNED INTEGERS" ltlt
endl ltlt UnNTjurJ ltlt endl ltlt UnNTjurK ltlt
endl ltlt endl ltlt endl return
14
Data Types - Floating-Point
include ltiostream.hgt include ltfloat.hgt void
main() float floA 9.87654321F, floB
FLT_EPSILON, floC FLT_MAX, floD FLT_MIN
cout ltlt "REGULAR FLOATS" ltlt endl ltlt floA
ltlt endl ltlt floB ltlt endl ltlt floC ltlt endl ltlt floD
ltlt endl ltlt endl double dubE 9.87654321,
dubF DBL_EPSILON, dubG DBL_MAX, dubH
DBL_MIN cout ltlt "DOUBLE FLOATS" ltlt endl
ltlt dubE ltlt endl ltlt dubF ltlt endl ltlt dubG ltlt
endl ltlt dubH ltlt endl ltlt endl long double ldI
9.87654321, ldJ LDBL_EPSILON, ldK LDBL_MAX,
ldL LDBL_MIN cout ltlt "LONG DOUBLE FLOATS"
ltlt endl ltlt ldI ltlt endl ltlt ldJ ltlt endl ltlt
ldK ltlt endl ltlt ldL ltlt endl ltlt endl ltlt endl
return
15
Data Types - Characters and Booleans
include ltiostream.hgt void main() char chA
'T' char chB '\t' char chC '\\'
cout ltlt chA ltlt chB ltlt chC ltlt endl ltlt chB
ltlt chC ltlt chA ltlt endl ltlt chC ltlt chA ltlt
chB ltlt endl ltlt endl return
include ltiostream.hgt void main() bool booX
true bool booY false bool booZ (532
gt 738) cout ltlt booX ltlt endl ltlt booY
ltlt endl ltlt booZ ltlt endl ltlt endl
return
16
Type Incompatibilities
include ltiostream.hgt void main() int
NTjurA 9.635F, NTjurB 9.635, NTjurC ',
NTjurD true cout ltlt NTjurA ltlt '\t' ltlt
NTjurB ltlt '\t' ltlt NTjurC ltlt '\t' ltlt NTjurD ltlt
"\n\n" float floE 65, floF 65.34, floG
'Q, floH false cout ltlt floE ltlt '\t' ltlt
floF ltlt '\t' ltlt floG ltlt '\t' ltlt floH ltlt "\n\n"
double dubI 14, dubJ 14.92F, dubK '?,
dubL true cout ltlt dubI ltlt '\t' ltlt dubJ ltlt
'\t' ltlt dubK ltlt '\t' ltlt dubL ltlt "\n\n" char
chM 3, chN 3.1416F, chO 3.1416, chP
true cout ltlt chM ltlt '\t' ltlt chN ltlt '\t' ltlt
chO ltlt '\t' ltlt chP ltlt "\n\n" bool booQ
467, booR 467.927F, booS 467.927, booT
'w' cout ltlt booQ ltlt '\t' ltlt booR ltlt '\t' ltlt
booS ltlt '\t' ltlt booT ltlt "\n\n" return
include ltiostream.hgt void main() int
NTjurA 9.635F, NTjurB 9.635, NTjurC ',
NTjurD true cout ltlt NTjurA ltlt '\t' ltlt
NTjurB ltlt '\t' ltlt NTjurC ltlt '\t' ltlt NTjurD ltlt
"\n\n" float floE 65, floF 65.34, floG
'Q, floH false cout ltlt floE ltlt '\t' ltlt
floF ltlt '\t' ltlt floG ltlt '\t' ltlt floH ltlt "\n\n"
double dubI 14, dubJ 14.92F, dubK '?,
dubL true cout ltlt dubI ltlt '\t' ltlt dubJ ltlt
'\t' ltlt dubK ltlt '\t' ltlt dubL ltlt "\n\n" char
chM 3, chN 3.1416F, chO 3.1416, chP
true cout ltlt chM ltlt '\t' ltlt chN ltlt '\t' ltlt
chO ltlt '\t' ltlt chP ltlt "\n\n" bool booQ
467, booR 467.927F, booS 467.927, booT
'w' cout ltlt booQ ltlt '\t' ltlt booR ltlt '\t' ltlt
booS ltlt '\t' ltlt booT ltlt "\n\n" return
The compiler gives warning messages for each
underlined statement, but allows the program to
run nevertheless.
17
include ltiostream.hgt void main() double
interestRate 0.075 double balance
278.93 double depositAmount 309.14
double withdrawalAmount 416.72 int
daysUntilPayday 19 double interestEarned
double dailyAllowance balance balance
depositAmount - withdrawalAmount
interestEarned interestRate balance
balance balance interestEarned
dailyAllowance balance / daysUntilPayday
cout.setf(iosfixed) cout.setf(iosshowpoint
) cout.precision(2) cout ltlt "Until
payday, you\'ll have to get by on " ltlt
dailyAllowance ltlt " per day!" ltlt endl ltlt endl
return
Floating-PointArithmetic
There are four arithmetic operators for
floating-point numbers.
Addition
- Subtraction
Multiplication
/ Division
18
include ltiostream.hgt void main() int
nbrOfLargePizzas int nbrOfSmallPizzas int
piecesPerLargePizza 8 int
piecesPerSmallPizza 4 int nbrOfConsumers
int nbrOfPieces int piecesPerConsumer
int nbrOfSparePieces cout ltlt "How many large
pizzas? " cin gtgt nbrOfLargePizzas cout ltlt
"How many small pizzas? " cin gtgt
nbrOfSmallPizzas cout ltlt "How many consumers?
" cin gtgt nbrOfConsumers nbrOfPieces
nbrOfLargePizzas piecesPerLargePizza
nbrOfSmallPizzas piecesPerSmallPizza
piecesPerConsumer nbrOfPieces /
nbrOfConsumers nbrOfSparePieces nbrOfPieces
nbrOfConsumers cout ltlt "\nOn the average,
" ltlt piecesPerConsumer ltlt " pieces
each.\n" ltlt "(with " ltlt nbrOfSparePieces
ltlt " pieces left over!)" ltlt endl ltlt endl
return
IntegerArithmetic
There are five arithmetic operators for integers.
Addition
- Subtraction
Multiplication
/ Integer Division
Modulus
19
Arithmetic Precedence Rules
When evaluating arithmetic expressions, C uses
specific precedence rules to determine which
operators should be executed in which order.
  • Parentheses take the highest precedence
  • Multiplication, division, and modulus come
    second.
  • Addition and subtraction take the lowest
    precedence.
  • Precedence ties are handled in left-to-right
    fashion.

100 - 5 4 75
80 75
155
100 - 20 75
(100 - 5) 4 75
95 4 75
380 75
455
100 - 5 (4 75)
100 - 5 79
-295
100 - 395
20
Additional Assignment Operators
Certain shorthand operators can be used when a
variables value is being altered by performing a
simple operation on it.
value value otherValue
x x - y z
value otherValue
x - y z
probability probability / 100
probability / 100
dayOfYear dayOfYear 365
salary salary 3.5
dayOfYear 365
salary 3.5
21
Increment and Decrement Operators
Incrementing or decrementing a numerical value by
one can be done with an even simpler mechanism.
number number 1
number
number
ctdown ctdown - 1
ctdown--
--ctdown
include ltiostream.hgt void main() int nbr
57 cout ltlt nbr ltlt endl cout ltlt nbr ltlt
endl cout ltlt nbr ltlt endl cout ltlt nbr ltlt
endl cout ltlt nbr ltlt endl ltlt endl
return
The order in which the increment or decrement
operator is applied will determine whether the
operation is applied before or after a value is
returned.
22
Branching
There may be circumstances in a program when the
next step to perform depends on a particular
condition.
Did the employee work over 40 hours?
Is the chosen letter anywhere in the puzzle?
No
No
Yes
Yes
Pay total hours worked at regular rate
Pay 40 hours at regular rate extra hours at
time-and-a-half
Proceed to the next player
Increment the players winnings by the dollar
amount times the number of occurrences of the
letter
23
Branchingvia ifand else
include ltiostream.hgt void main() double
orderAmt double orderWeight double
discount double shipping char yOrN bool
inState double tax double totalAmt cout
ltlt "Enter the total amount of the order "
cin gtgt orderAmt if (orderAmt gt 100.00)
discount 0.20 else discount 0.00
cout ltlt "Enter the weight of the order (in
pounds) " cin gtgt orderWeight if
(orderWeight lt 1.0) shipping 0.00 else
shipping 2.00 orderWeight
In C, simple branching is done with if-else
statements.
Branch is determined by a boolean greater-than
operator
Branch is determined by a boolean
less-than-or-equal-to operator
24
cout ltlt "Is this an in-state order? Enter Y or
N " cin gtgt yOrN if ((yOrN 'y') (yOrN
'Y')) inState true else inState
false if (inState) tax 0.0675
(orderAmt - discount orderAmt) else tax
0.00 if ((discount gt 0.0) (!inState))
discount / 2 totalAmt (orderAmt -
discount orderAmt) tax shipping
cout.setf(iosfixed) cout.setf(iosshowpoint)
cout.precision(2) cout ltlt endl ltlt endl
ltlt "Order " ltlt orderAmt ltlt
endl ltlt "Discount -" ltlt discount
orderAmt ltlt endl ltlt "Shipping " ltlt
shipping ltlt endl ltlt "Tax
" ltlt tax ltlt endl ltlt endl
ltlt "Total " ltlt totalAmt ltlt endl
ltlt endl return
Equality and OR operators
Boolean variable examined
AND and NOT operators
25
include ltiostream.hgt void main() int
favNbr, leastFavNbr cout ltlt "Enter your
favorite number " cin gtgt favNbr if
(favNbr 7) cout ltlt "LUCKY NUMBER
SEVEN!\n" cout ltlt "The odds are in your
favor!\n\n" else cout ltlt "What a
risk-taker!\n\n" cout ltlt "Enter your least
favorite number " cin gtgt leastFavNbr if
(leastFavNbr 13) cout ltlt "SILLY
SUPERSTITION!\n" cout ltlt "Grow up,
already!\n\n\n" else cout ltlt
"Too bad!\n" cout ltlt "I was just about to
give you " ltlt leastFavNbr ltlt "
dollars!\n" cout ltlt "Oh, well. Maybe next
time...\n\n\n" return
Anotherif-elseExample
By using compound statements (enclosed in braces)
if-else statements can have more complex branches.
Because the assignment operator was used instead
of the equality operator!
Why did this happen?
26
if (month 2) if (year 4 0)
payday2 29 else payday2
28 else if ((month 4)
(month 6) (month 9)
(month 11)) payday2 30 else
payday2 31 cout ltlt "This
month's paydays are on " ltlt month ltlt '/'
ltlt payday1 ltlt '/' ltlt (year 100) ltlt "
and " ltlt month ltlt '/' ltlt payday2 ltlt '/'
ltlt (year 100) ltlt ".\n\n" return
One Moreif-else Example
include ltiostream.hgt void main() int
month, year, payday1, payday2 cout ltlt "Enter
an integer representing ltlt " the month
" cin gtgt month cout ltlt "Enter the
four-digit year " cin gtgt year if
((month 2) (year 4 ! 0)) payday1
14 else payday1 15
27
Looping
There may be circumstances in a program when a
certain step should be repeated until a
particular condition is true.
Has the user entered the letter Y or N yet?
Proceed with rest of program
Yes
No
Request another letter from the user
28
if ((isItPerishable 'Y')
(isItPerishable 'y')) cout ltlt
"Enter the number of " ltlt "days until
the product expires " cin gtgt
nbrDaysUntilExpire while
(nbrDaysUntilExpire lt 0) cout
ltlt "Invalid response. " ltlt "Enter a
positive number " cin gtgt
nbrDaysUntilExpire cout ltlt endl
ltlt "The product expires in " ltlt
nbrDaysUntilExpire ltlt " days." ltlt endl
ltlt endl return
Branchingvia while
In C, simple looping may be done with while
statements.
include ltiostream.hgt void main() char
isItPerishable int nbrDaysUntilExpire 90
cout ltlt "Is the product perishable? "
ltlt "(Enter Y or N) " cin gtgt isItPerishable
while ((isItPerishable ! 'Y')
(isItPerishable ! 'y')
(isItPerishable ! 'N')
(isItPerishable ! 'n')) cout ltlt
"Invalid response. " ltlt "Enter Y or N
" cin gtgt isItPerishable
29
include ltiostream.hgt void main() int
receiptCount 0 double receiptTotal 0.00
double receiptAmount double receiptMean
cout ltlt "Enter the amount of each receipt." ltlt
endl cout ltlt "When finished, enter -1." ltlt
endl ltlt endl cout ltlt '' cin gtgt
receiptAmount while (receiptAmount gt 0.00)
receiptCount receiptTotal
receiptAmount cout ltlt '' cin gtgt
receiptAmount receiptMean
receiptTotal / receiptCount
cout.setf(iosfixed) cout.setf(iosshowpoint
) cout.precision(2) cout ltlt endl ltlt endl
ltlt "Average receipt amount " ltlt
receiptMean ltlt endl ltlt endl return
Counting and Totaling with Loops
30
Branching via do-while
With a while statement, the loop condition is
checked before executing the loop contents,
making it possible to never execute those
contents. If the algorithm calls for executing
the contents at least once, then it might be
better to use a do-while statement, which checks
the loop condition after executing the loop
contents.
while loop
do-while loop
31
A Simple do-while Example
include ltiostream.hgt void main() int
favoriteNumber do cout ltlt
"Enter your favorite number " cin gtgt
favoriteNumber while (favoriteNumber
! 13) cout ltlt endl ltlt "13! Why, that\'s my
favorite number, too!\n\n" return
32
Infinite Loops
One danger with looping is the prospect of
generating an infinite loop, whose exit condition
is never met.
include ltiostream.hgt void main() int
value int guessedValue cout ltlt "Enter a
value " cin gtgt value guessedValue 0
while (value ! guessedValue) cout ltlt
guessedValue ltlt endl cout ltlt "\nTIME!!!
The computer FINALLY guessed your value!\n\n"
return
This condition may never be true!
Write a Comment
User Comments (0)