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
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