SlideShare uma empresa Scribd logo
1 de 35
Modelling 2A
Lecture 3
Chapter 5 and 6
Philip Robinson
2015
Scanf()
• Scanf() is used to read input from the keyboard entered by the
user.
• The scanf() function is related to the printf() function and shares
the same form of parameters.
• Eg. Scanf(“%d %d %f”,&aInt,&bInt,&cFloat);
• The first parameter is the control string. In this string you define
the kinds of values you want to read in and in what order. Only
the specifiers are considered and any other characters are
ignored.
• The parameters that follow specify the variables where you want
the read value to be stored.
• When entering the values scanf will look for white space or new-
line characters as delimiters that show when a specific value is
finished being entered. 2
Scanf() Function
3
• The general form of the input function is:
scanf(control string,variable,variable,...)
• The control string specifies how strings of characters, usually
typed on the keyboard, should be converted into values and stored
in the listed variables.
• The scanf() function reads data from the keyboard and delivers
that data to the program.
• The scanf() function can convert string input into various forms:
integers, floating point numbers, characters and C strings.
• scanf has to change the values stored in the parts of computers
memory that is associated with parameters (variables).
• There are two rules to remember:
• If you need to read a variable for a non-string type, precede the
variable name with &.
• If you read in a value for a string variable, do not use &.
• The & operator provides the address where the variable is stored.
Scanf() Function
• The rule is that scanf processes the control string from left to right
and each time it reaches a specifier it tries to interpret what has been
typed as a value.
• If you input multiple values then these are assumed to be separated
by white space - i.e. spaces, newline or tabs. This means you can
type:
3 4 5
• or
3
4
5
• and it doesn't matter how many spaces are included between items.
• For example:
scanf("%d %d",&i,&j);
• will read in two integer values into i and j.
• The integer values can be typed on the same line or on different lines
as long as there is at least one white space character between them.
4
Scanf() Function
• The only exception to this rule is the %c specifier which always
reads in the next character typed no matter what it is.
• You can also use a width modifier in scanf. In this case its effect
is to limit the number of characters accepted to the width.
• For example:
scanf("%lOd",&i)
• would use at most the first ten digits typed as the new value for i.
• There is one main problem with scanf function which can make it
unreliable in certain cases.
• The reason being is that scanf tends to ignore white spaces, i.e.
the space character.
• If you require your input to contain spaces this can cause a
problem.
• Therefore for string data input the function getstr() may well be
more reliable as it records spaces in the input text and treats
them as an ordinary characters.
5
Scanf() Function
• When the program reaches the scanf statement it pauses to
give the user time to type something on the keyboard and
continues only when users press <Enter>, or <Return>, to
signal that he, or she, has finished entering the value.
• Then the program continues with the new value stored in iAge,
fBal and caPet.
• In this way, each time the program is run the user gets a
chance to type in a different value to the variable and the
program also gets the chance to produce a different result!
• Note: the scanf function does not prompt for an input. You
should get in the habit of always using a printf function,
informing the user of the program what they should type,
before a scanf function.
• The %d, %f, %c, %s simply lets the compiler know that the
type of the variable value being read in.
6
ANSI C Conversion Specifications for
scanf() and printf()
7
Converstion specification Output
%c Single character
%d, i Signed decimal integer
%e Floating point number e-notation
%E Floating point number E-notation
%f, g Floating point number, decimal
notation
%s Character string
%x Hexidecimal number
Formatting your output
• The type conversion specifier only does what you ask of it - it convert
a given bit pattern into a sequence of characters that a human can
read.
• If you want to format the characters then you need to know a little
more about the printf function's control string.
• Each specifier can be preceded by a modifier which determines how
the value will be printed.
• The most general modifier is of the form:
flag width.precision
• The flag can be any of:
8
flag meaning
- left justify
+ always display sign
Space display space if there is no sign
0 pad with leading zeros
Formatting your output
• The width specifies the number of characters used in total to
display the value and precision indicates the number of
characters used after the decimal point.
For example, %10.3f will display the float using ten characters
with three digits after the decimal point.
• Notice that the ten characters includes the decimal point, and a
- sign if there is one.
• If the value needs more space than the width specifies then
the additional space is used - width specifies the smallest
space that will be used to display the value.
• The specifier %-1Od will display an int left justified in a ten
character space. The specifier %+5d will display an int using
the next five character locations and will add a + or - sign to
the value.
• Example: Lect3_formatting.c
9
Printf() and Scanf()
• Far more detail on these two functions can be found at:
• http://www.cplusplus.com/reference/cstdio/printf/
and
• http://www.cplusplus.com/reference/cstdio/scanf/
10
getchar()
• There are a number of other ways to read inputted text. Generally
Printf and Scanf are flexible enough that they will suit most
purposes but there is one other function that will come in handy
• The getchar() function will capture the next inputted character.
• The function is blocking. This means that when it is called the
function will stop the execution of the program until a character is
inputted and enter is pressed.
• This function returns the character that was inputted
• Eg. char c = getchar(); 11
The Loop Statements
• Loop statements allow you to execute one or more lines of
code repetitively.
• Many tasks consist of trivial operations that must be
repeated, so looping structures are an important part of any
programming language.
• C supports the following loop statements:
For
While
Do while
12
Triangle Numbers
• If you arrange a series of dots to form a triangle so that the first
row has 1 dot and each subsequent row has 1 extra dot.
• T6 = 1 + 2 + 3 + 4 + 5 + 6 = 21
13
Triangle Numbers
• How do you calculate the value of the first 200 triangle numbers?
• How would you write this process using a mathematical notation?
• 𝑇200 = 𝑘=1
200
𝑘 = 1 + 2 + … + 199 + 200
• 𝑇𝑛 = 𝑘=1
𝑛
𝑘 = 1 + 2 + … + (n-1) + n
14
The FOR statement
• The general form of the for statement is :
For (initialize; test; update)
{
Body Statements
}
• The loop is repeated until test becomes false or zero
15
The FOR statement
• The for statement uses three control expressions, to control a
looping process.
• The initialize expression is executed once, before any of the
loop statements are executed.
• If the test expression is true (or non-zero), the loop is cycled
through once.
• Then the update expression is evaluated, and the test
expression is checked again.
• The for statement is an entry-condition loop, which means
that the decision to go through one more pass of the loop is
made before the loop is traversed.
• Thus it is possible that the loop is never traversed. The
statement part of the form can be a simple (single) statement
or a compound (multiple) statement. 16
The FOR statement
17
Start For Loop
Initialize expression
E.g. i = 0
Check Test
Expression
Exit For Loop
Execute For Loop Body
Execute Update
Statement
False
True
Triangle Numbers with For Loop:
Calculate the 6th Triangle Number
18
Start
Initialize:
n =1
Test:
Is n<=6?
triNum =
triNum + n
Update:
n++
False
True
Declare
variabes:
Int n, triNum
triNum = 0
Display
result
End
For Loop
Nested FOR Loop
19
Relational Operators
Operator Meaning Example
== Equal to count == 10
!= Not equal to flag != DONE
< Less than a < b
<= Less than or equal to low <= high
> Greater than Pointer > end_of_list
>= Greater than or equal to j >= 0
20
The WHILE statement
• The while statement creates a loop that repeats until the
test expression becomes false, or zero.
• It is an entry-condition loop, which means that the
decision to go through one more pass of the loop is
made before the loop is traversed.
• Thus, it is possible that the loop is never traversed.
• The statement part of the form can be a simple (single)
statement or a compound (multiple) statement.
• The general form of the while statement is :
while (expression)
{
program statement/s
} 21
The WHILE statement
22
Start While Loop
Check Test
Expression
Exit While Loop
Execute While Loop
Body
False
True
The While loop as a For Loop
• The following For loop:
For (initialize; test; update)
{
Statement
}
• Could be implemented as follows:
initialize
while(test)
{
Statement
update
}
23
The DO WHILE statement
• The do while statement creates a loop that repeats until the test
expression becomes false or zero.
• The do while statement is an exit-condition loop which means that
the decision to through one more pass of the loop is made after the
loop is traversed.
• Thus, the loop is executed at least once.
• The statement part of the form can be a simple (single) statement or
a compound (multiple) statement.
• The general form of the do while statement is :
• do
• {
• statement
• } while (expression);
• The statement portion is repeated until the expression becomes
false, or zero. 24
The Do-While statement
25
Factorial with While Loop:
Display all factorials that are less than 1
Million
26
Branching: The if, else statement
• In each of the following forms, the statement can be either a simple
statement or a compound statement.
• Form 1
• if (expression)
• {
• Statement
• }
• The statement is executed if the expression is true.
• Form 2
• if (expression)
• {
• statement1
• }
• else
• {
• statement2
• }
• If the expression is true, statement 1 is executed, otherwise statement2
is executed.
27
Branching: The if, else statement
• Form 3
• if (expression1)
• {
• statement1
• }
• else if (expression2)
• {
• statement2
}
• else
• {
• statement3
}
• If the expression1 is true, statement 1 is executed. If expression1 is
false but expression2 is true, statement2 is executed. Otherwise, if
both expressions are false, statement3 is executed.
• NB: the == operator must be used for comparisons not the = operator
which is for assignments!!! 28
Multiple choices: switch and break
• The if else statement make it easy to write programs to
choose between two alternatives. Sometimes a program
needs to choose between several alternatives.
• To accomplish this task we can use if else if else …, but in
many cases it is more convenient to use the C switch
statement
• The value of the Expression is compared downwards to the
values of each Label. Once a matching Label is found the
statements that follow are executed.
• Program flow then proceeds through the remaining
statements unless redirected again using the Break
statement. The remaining labels are now ignored.
• Both the expression and the labels must have integer values
(type char is included), and the labels must be constants or
expressions formed solely from constants.
• If no label matches the expression value, control passes to the
statement default, if present. Otherwise control passes to the
next statement following the switch statement.
29
Multiple choices: switch and break
• Form
• switch (expression)
• {
• case label1:
• statement1;
• break;
• case label2:
• statement2;
• break;
• .
• .
• .
• default:
• statement;
• break;
• }
30
Multiple choices: switch and break
• The break statement is used to immediately exit any loop or
switch block bounded by {….} .
• When the Break statement is executed program flow jumps to
immediately after the set of brackets that the statement is
inside.
• This is useful for jumping out of loops.
• In the case of a Switch statement a break must follow each
set of statements for a specific case or the statements of the
cases that follow will be executed as well.
31
Random Numbers in C
• To produce a Pseudo-Random integral number in C one can use
the rand() function in the stdio.h library.
• This function will return a “random” integer between 0 and 32767.
• The algorithm will produce very different numbers but always in
the same sequence unless the algorithm is given a different Seed
everytime it is executed.
• This is done by using the srand() function and passing a unique
number.
• In the time.h library there is a function time(NULL) which will
return the number of seconds that have passed since January 1,
1970.
32
Random Numbers in C
• To produce a random number in a specific range we use
modulus.
• Rand()%N will produce a number between 0 and N (not including
N).
• Rand()%N + c will produce a random number between c and
c+(N).
33
Fibonacci Sequence!
• The Fibonacci series is a sequence of numbers that is produced
by starting with 0 and 1 and repeating a simple process where the
next number is the sum of the previous two numbers in the
sequence.
• 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144……….
• Mathematically this sequence is described thus:
– Fn = Fn-1 + Fn-2 where F0 = 0 and F1 = 1 are seed values.
• This integer sequence is found in many places in nature and
mathematics!
– Found the way plants grow
– Found in Pascal’s triangle
– Produces the Golden Ratio 𝜑
• This ratio is found in the proportions of your face and many other animal
bodies and speaks to a naturally efficient structural element in nature.
• Many great painters have used the Golden Ratio to layout their paintings34
Fibonacci Sequence
• The Golden Spiral
• Vi Hart videos about the Fibonacci sequence:
– http://youtu.be/ahXIMUkSXX0
– http://youtu.be/lOIP_Z_-0Hs
– http://youtu.be/14-NdQwKz9w
35

Mais conteúdo relacionado

Mais procurados (18)

Ch03
Ch03Ch03
Ch03
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
Ch05
Ch05Ch05
Ch05
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Ch08
Ch08Ch08
Ch08
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
C language basics
C language basicsC language basics
C language basics
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Input And Output
 Input And Output Input And Output
Input And Output
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 

Semelhante a Lecture 3

Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
Discussing Fundamentals of C
Discussing Fundamentals of CDiscussing Fundamentals of C
Discussing Fundamentals of Ceducationfront
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdfsantosh147365
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing TutorialMahira Banu
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageDr.Florence Dayana
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 

Semelhante a Lecture 3 (20)

Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
C programming language
C programming languageC programming language
C programming language
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
Discussing Fundamentals of C
Discussing Fundamentals of CDiscussing Fundamentals of C
Discussing Fundamentals of C
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
Session 3
Session 3Session 3
Session 3
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 
C language
C languageC language
C language
 
FUNDAMENTAL OF C
FUNDAMENTAL OF CFUNDAMENTAL OF C
FUNDAMENTAL OF C
 
Loops c++
Loops c++Loops c++
Loops c++
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Introduction
IntroductionIntroduction
Introduction
 
Cpu
CpuCpu
Cpu
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 

Último

Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectssuserb6619e
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 

Último (20)

Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 

Lecture 3

  • 1. Modelling 2A Lecture 3 Chapter 5 and 6 Philip Robinson 2015
  • 2. Scanf() • Scanf() is used to read input from the keyboard entered by the user. • The scanf() function is related to the printf() function and shares the same form of parameters. • Eg. Scanf(“%d %d %f”,&aInt,&bInt,&cFloat); • The first parameter is the control string. In this string you define the kinds of values you want to read in and in what order. Only the specifiers are considered and any other characters are ignored. • The parameters that follow specify the variables where you want the read value to be stored. • When entering the values scanf will look for white space or new- line characters as delimiters that show when a specific value is finished being entered. 2
  • 3. Scanf() Function 3 • The general form of the input function is: scanf(control string,variable,variable,...) • The control string specifies how strings of characters, usually typed on the keyboard, should be converted into values and stored in the listed variables. • The scanf() function reads data from the keyboard and delivers that data to the program. • The scanf() function can convert string input into various forms: integers, floating point numbers, characters and C strings. • scanf has to change the values stored in the parts of computers memory that is associated with parameters (variables). • There are two rules to remember: • If you need to read a variable for a non-string type, precede the variable name with &. • If you read in a value for a string variable, do not use &. • The & operator provides the address where the variable is stored.
  • 4. Scanf() Function • The rule is that scanf processes the control string from left to right and each time it reaches a specifier it tries to interpret what has been typed as a value. • If you input multiple values then these are assumed to be separated by white space - i.e. spaces, newline or tabs. This means you can type: 3 4 5 • or 3 4 5 • and it doesn't matter how many spaces are included between items. • For example: scanf("%d %d",&i,&j); • will read in two integer values into i and j. • The integer values can be typed on the same line or on different lines as long as there is at least one white space character between them. 4
  • 5. Scanf() Function • The only exception to this rule is the %c specifier which always reads in the next character typed no matter what it is. • You can also use a width modifier in scanf. In this case its effect is to limit the number of characters accepted to the width. • For example: scanf("%lOd",&i) • would use at most the first ten digits typed as the new value for i. • There is one main problem with scanf function which can make it unreliable in certain cases. • The reason being is that scanf tends to ignore white spaces, i.e. the space character. • If you require your input to contain spaces this can cause a problem. • Therefore for string data input the function getstr() may well be more reliable as it records spaces in the input text and treats them as an ordinary characters. 5
  • 6. Scanf() Function • When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press <Enter>, or <Return>, to signal that he, or she, has finished entering the value. • Then the program continues with the new value stored in iAge, fBal and caPet. • In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! • Note: the scanf function does not prompt for an input. You should get in the habit of always using a printf function, informing the user of the program what they should type, before a scanf function. • The %d, %f, %c, %s simply lets the compiler know that the type of the variable value being read in. 6
  • 7. ANSI C Conversion Specifications for scanf() and printf() 7 Converstion specification Output %c Single character %d, i Signed decimal integer %e Floating point number e-notation %E Floating point number E-notation %f, g Floating point number, decimal notation %s Character string %x Hexidecimal number
  • 8. Formatting your output • The type conversion specifier only does what you ask of it - it convert a given bit pattern into a sequence of characters that a human can read. • If you want to format the characters then you need to know a little more about the printf function's control string. • Each specifier can be preceded by a modifier which determines how the value will be printed. • The most general modifier is of the form: flag width.precision • The flag can be any of: 8 flag meaning - left justify + always display sign Space display space if there is no sign 0 pad with leading zeros
  • 9. Formatting your output • The width specifies the number of characters used in total to display the value and precision indicates the number of characters used after the decimal point. For example, %10.3f will display the float using ten characters with three digits after the decimal point. • Notice that the ten characters includes the decimal point, and a - sign if there is one. • If the value needs more space than the width specifies then the additional space is used - width specifies the smallest space that will be used to display the value. • The specifier %-1Od will display an int left justified in a ten character space. The specifier %+5d will display an int using the next five character locations and will add a + or - sign to the value. • Example: Lect3_formatting.c 9
  • 10. Printf() and Scanf() • Far more detail on these two functions can be found at: • http://www.cplusplus.com/reference/cstdio/printf/ and • http://www.cplusplus.com/reference/cstdio/scanf/ 10
  • 11. getchar() • There are a number of other ways to read inputted text. Generally Printf and Scanf are flexible enough that they will suit most purposes but there is one other function that will come in handy • The getchar() function will capture the next inputted character. • The function is blocking. This means that when it is called the function will stop the execution of the program until a character is inputted and enter is pressed. • This function returns the character that was inputted • Eg. char c = getchar(); 11
  • 12. The Loop Statements • Loop statements allow you to execute one or more lines of code repetitively. • Many tasks consist of trivial operations that must be repeated, so looping structures are an important part of any programming language. • C supports the following loop statements: For While Do while 12
  • 13. Triangle Numbers • If you arrange a series of dots to form a triangle so that the first row has 1 dot and each subsequent row has 1 extra dot. • T6 = 1 + 2 + 3 + 4 + 5 + 6 = 21 13
  • 14. Triangle Numbers • How do you calculate the value of the first 200 triangle numbers? • How would you write this process using a mathematical notation? • 𝑇200 = 𝑘=1 200 𝑘 = 1 + 2 + … + 199 + 200 • 𝑇𝑛 = 𝑘=1 𝑛 𝑘 = 1 + 2 + … + (n-1) + n 14
  • 15. The FOR statement • The general form of the for statement is : For (initialize; test; update) { Body Statements } • The loop is repeated until test becomes false or zero 15
  • 16. The FOR statement • The for statement uses three control expressions, to control a looping process. • The initialize expression is executed once, before any of the loop statements are executed. • If the test expression is true (or non-zero), the loop is cycled through once. • Then the update expression is evaluated, and the test expression is checked again. • The for statement is an entry-condition loop, which means that the decision to go through one more pass of the loop is made before the loop is traversed. • Thus it is possible that the loop is never traversed. The statement part of the form can be a simple (single) statement or a compound (multiple) statement. 16
  • 17. The FOR statement 17 Start For Loop Initialize expression E.g. i = 0 Check Test Expression Exit For Loop Execute For Loop Body Execute Update Statement False True
  • 18. Triangle Numbers with For Loop: Calculate the 6th Triangle Number 18 Start Initialize: n =1 Test: Is n<=6? triNum = triNum + n Update: n++ False True Declare variabes: Int n, triNum triNum = 0 Display result End For Loop
  • 20. Relational Operators Operator Meaning Example == Equal to count == 10 != Not equal to flag != DONE < Less than a < b <= Less than or equal to low <= high > Greater than Pointer > end_of_list >= Greater than or equal to j >= 0 20
  • 21. The WHILE statement • The while statement creates a loop that repeats until the test expression becomes false, or zero. • It is an entry-condition loop, which means that the decision to go through one more pass of the loop is made before the loop is traversed. • Thus, it is possible that the loop is never traversed. • The statement part of the form can be a simple (single) statement or a compound (multiple) statement. • The general form of the while statement is : while (expression) { program statement/s } 21
  • 22. The WHILE statement 22 Start While Loop Check Test Expression Exit While Loop Execute While Loop Body False True
  • 23. The While loop as a For Loop • The following For loop: For (initialize; test; update) { Statement } • Could be implemented as follows: initialize while(test) { Statement update } 23
  • 24. The DO WHILE statement • The do while statement creates a loop that repeats until the test expression becomes false or zero. • The do while statement is an exit-condition loop which means that the decision to through one more pass of the loop is made after the loop is traversed. • Thus, the loop is executed at least once. • The statement part of the form can be a simple (single) statement or a compound (multiple) statement. • The general form of the do while statement is : • do • { • statement • } while (expression); • The statement portion is repeated until the expression becomes false, or zero. 24
  • 26. Factorial with While Loop: Display all factorials that are less than 1 Million 26
  • 27. Branching: The if, else statement • In each of the following forms, the statement can be either a simple statement or a compound statement. • Form 1 • if (expression) • { • Statement • } • The statement is executed if the expression is true. • Form 2 • if (expression) • { • statement1 • } • else • { • statement2 • } • If the expression is true, statement 1 is executed, otherwise statement2 is executed. 27
  • 28. Branching: The if, else statement • Form 3 • if (expression1) • { • statement1 • } • else if (expression2) • { • statement2 } • else • { • statement3 } • If the expression1 is true, statement 1 is executed. If expression1 is false but expression2 is true, statement2 is executed. Otherwise, if both expressions are false, statement3 is executed. • NB: the == operator must be used for comparisons not the = operator which is for assignments!!! 28
  • 29. Multiple choices: switch and break • The if else statement make it easy to write programs to choose between two alternatives. Sometimes a program needs to choose between several alternatives. • To accomplish this task we can use if else if else …, but in many cases it is more convenient to use the C switch statement • The value of the Expression is compared downwards to the values of each Label. Once a matching Label is found the statements that follow are executed. • Program flow then proceeds through the remaining statements unless redirected again using the Break statement. The remaining labels are now ignored. • Both the expression and the labels must have integer values (type char is included), and the labels must be constants or expressions formed solely from constants. • If no label matches the expression value, control passes to the statement default, if present. Otherwise control passes to the next statement following the switch statement. 29
  • 30. Multiple choices: switch and break • Form • switch (expression) • { • case label1: • statement1; • break; • case label2: • statement2; • break; • . • . • . • default: • statement; • break; • } 30
  • 31. Multiple choices: switch and break • The break statement is used to immediately exit any loop or switch block bounded by {….} . • When the Break statement is executed program flow jumps to immediately after the set of brackets that the statement is inside. • This is useful for jumping out of loops. • In the case of a Switch statement a break must follow each set of statements for a specific case or the statements of the cases that follow will be executed as well. 31
  • 32. Random Numbers in C • To produce a Pseudo-Random integral number in C one can use the rand() function in the stdio.h library. • This function will return a “random” integer between 0 and 32767. • The algorithm will produce very different numbers but always in the same sequence unless the algorithm is given a different Seed everytime it is executed. • This is done by using the srand() function and passing a unique number. • In the time.h library there is a function time(NULL) which will return the number of seconds that have passed since January 1, 1970. 32
  • 33. Random Numbers in C • To produce a random number in a specific range we use modulus. • Rand()%N will produce a number between 0 and N (not including N). • Rand()%N + c will produce a random number between c and c+(N). 33
  • 34. Fibonacci Sequence! • The Fibonacci series is a sequence of numbers that is produced by starting with 0 and 1 and repeating a simple process where the next number is the sum of the previous two numbers in the sequence. • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144………. • Mathematically this sequence is described thus: – Fn = Fn-1 + Fn-2 where F0 = 0 and F1 = 1 are seed values. • This integer sequence is found in many places in nature and mathematics! – Found the way plants grow – Found in Pascal’s triangle – Produces the Golden Ratio 𝜑 • This ratio is found in the proportions of your face and many other animal bodies and speaks to a naturally efficient structural element in nature. • Many great painters have used the Golden Ratio to layout their paintings34
  • 35. Fibonacci Sequence • The Golden Spiral • Vi Hart videos about the Fibonacci sequence: – http://youtu.be/ahXIMUkSXX0 – http://youtu.be/lOIP_Z_-0Hs – http://youtu.be/14-NdQwKz9w 35