0% found this document useful (0 votes)
26 views

Chapter 1 Introduction to Programming-1

Uploaded by

Dacity Kipkorir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Chapter 1 Introduction to Programming-1

Uploaded by

Dacity Kipkorir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

School of Computing and Informatics

BCS 111 – Introduction to Programming

R
Chapter 1 – Introduction

1 Introduction

U
Programming is the art of writing computer instructions in a language that the computer can interpret
and/or understand. In this topic, we shall look at some basic definitions and introduce some basic concepts
in programming.

UL
Definition 1. A computer is an electronic machine that accepts data as its input, process these data based
on some instructions to produce information as it output. These instructions that guide a computer on
how to process the data is what we refer to as a program.

Definition 2. Data – These are raw facts and figures found in a user environment
G
Definition 3. Information – This is meaningful processed data

Definition 4. Program – A program is a set of unambiguous instructions, written in a high level language,
that guide a computer on how to perform some specific task.
AN

Definition 5. Algorithm – This is a step-by-step procedure of accomplishing a task using a computer.


Algorithms are normally written in human readable language, though not natural language.

Definition 6. High level languages are computer programming languages that use English-like and mathe-
matical notation to express computer instruction. Examples of these languages are Java, C++, C, Python,
PHP etc. We will use C for this unit. If you need to add two numbers a and b in high level language you
will have an instruction like a + b, which uses a mathematical notation. A program written in high level
language is often referred to as a source code.
.
DR

However, computers (read computer hardware) does not understand these languages. Therefore, these
languages have to be converted to low level languages or machine level languages for the computer (hardware)
to execute the instructions.

Definition 7. Low level language are computer programming languages that use mnemonics (read com-
mands) to express computer instruction. An example of this language is Assembly language. If you need to
add two numbers 6 and 4 in low level language you will have an instruction like ADD(4,6).

Definition 8. Machine language express computer instructions as a stream/collection of zeros (0) and
ones (1). Assume add operation is expressed as 11001001 and the number 1 is expressed as 00000001 and
number 2 is expressed as 00000010, the operation 1+2 will be expressed (something like) 00000001 00000010
11001001 in machine language. A program written in machine language is often referred to as a object
code.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 1


Now, how do we convert from source code to object code (machine language)?
The programming Integrated Development Environment (IDE) (often referred to as compilers), like Dev-
C++ come with some basic tools that help us with programming tasks. These tools are Editor, debugger,
interpreter and compiler.

Definition 9. Editor - An editor allows the programmer to enter the program source code and save it to
files. Most programming editors increase programmer productivity by using colors to highlight language
features.

Definition 10. Compiler - A compiler translates the source code to target code. The target code may be
the machine language for a particular platform or embedded device. The target code could be another source
language; for example, the earliest C++ compiler translated C++ into C, another higher-level language.

R
The resulting C code was then processed by a C compiler to produce an executable program.

Definition 11. Interpreter - An interpreter is like a compiler, in that it translates higher-level source code
into target code (usually machine language). It works differently, however. While a compiler produces
an executable program that may run many times with no additional translation needed, an interpreter
translates source code statements into machine language each time a user runs the program. A compiled

U
program does not need to be recompiled to run, but an interpreted program must be reinterpreted each
time it executes.

UL
Definition 12. Debugger - A debugger allows a programmer to more easily trace a programs execution
in order to locate and correct errors in the programs implementation. With a debugger, a developer can
simultaneously run a program and see which line in the source code is responsible for the programs current
actions. The programmer can watch the values of variables and other program elements to see if their values
change as expected. Debuggers are valuable for locating errors (also called bugs) and repairing programs
that contain errors.
G
Now we have said that we have several programming languages like C, C++, Java, PHP, Python etc. But,
what is a language? Consider the following sentences and state if its English or Kiswahili
AN

English or Kiswahili

1. huyu ni mtoto mdogo.


2. This is a small kid
3. Huyu ni mukidy mu young.
4. Sanibonani bafoethu?

You must have noticed that non of the four sentences above is English or Kiswahili. Why?
.
DR

1. First sentence, as much as all its word have a distinct meaning in Kiswahili, it breaks the rule of
Kiswahili language that requires a sentence to start with a capital letter.

2. Second sentence, all words have a meaning in English, but sentence does not terminate with a full
stop as required by English rules.

3. Third sentence is either Kiswahili nor English. Although it observes all the rules of both languages,
some words have no meaning in English while others have no meaning in Kiswahili.

4. Fourth sentence looks like isiZulu.

So, what is a language?

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 2


Definition 13. A language is a set of rules and semantics (words with distinct meaning) that aid in
communication between two entities.
Programming languages also have rules (syntax) and a set of words with distinct meaning (keywords or
reserved words) that aid in communication between programmers and computers.

We will use C programming language for this unit.

1.1 Why C?
• Compact, fast, and powerful

• Standard for program development as it is widely acceptable

R
• It is portable – Can run on different platforms like Windows, Linux, Mac

• Supports modular programming

• C is the native language of UNIX and many windows apps are done in C

U
• Easy to interface with system devices/assembly routines

1.2 Rules of C programming language

UL
• Every executable statement must end with a semi-colon

• Variables must be declared before being used

• For a C program to execute, it must have a main function

• Function return type must match the type returned by the function
G
• C is case sensitive. All C instructions must be in lower case

Definition 14. A statement is an executable line of code


AN

Definition 15. Expression is a collection of variables, constants and operators that evaluate to some value.
For example
y = 4x + c (1)
Definition 16. A variable is a named memory location whose content may vary/change.

There are some rules that must be observed when naming variables:-
1. Variable name should not start with a digit, may start with alphabet or an underscore
.
DR

2. Variable name should not contain space in-between

3. Variable name should not contain an operator

4. Variable name should not be a reserved word/keyword


C programming language has a number of keywords or reserved words. These are words with special meaning
in C programming language. Most of these words are listed in Table 1 Computer program processes different
types of data ranging from textual to numerical. These data are grouped into 8 primitive data types
Definition 17. Data type is classification of data based on its possible values, possible operations and
memory requirements

These data types are shown in Table 2. Fill in the blanks in the Table.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 3


Table 1: C Keywords

if for else switch int float double char long short


return void bool goto const break continue enum do while
auto default register extern typedef union struct usigned signed sizeof

Table 2: Data types in C

Data type Memory (bits) Possible values Possible Operations


bool 1 bit
char 8 bits)
short 16 bits

R
int 16 or 32 or 64 bits
long 32 bits
float 32 bits
double 64 bits

U
1.3 Declaring a variable
A variable is a named memory location in which data of a certain type can be stored. The contents of a

UL
variable can change, thus the name. User defined variables must be declared before they can be used in a
program. It is during the declaration phase that the actual memory for the variable is reserved. All variables
in C must be declared before use.

Get into the habit of declaring variables using lowercase characters. Remember that C is case sensitive.

The basic format for declaring variables is


G
DATATYPE var1, var2, var3 ... varN;
AN

where DATATYPE is one of the 8 primitive data types. It could be int, float, char, bool, double etc.

For example, the code in Listing 1 shows 2 variables (length and width) declared as integers and one
variable (area) declared as a float.
1 int length, width;
2 float area;
.

Listing 1: Variable Declaration


DR

You can use assignment operator (=) to give/assign a value to a variable during variable declaration as
1 int length = 10;
2 int width = 20;
3 float area = length ∗ width;

Listing 2: Variable Declaration

Note that, the value assigned to variable can be a result of an expression as shown on Line 3 of Listing 2.

1.4 Constants
Definition 18. A constant is a value that appears in a program and does not change during the entire
execution of the program.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 4


There are two type of constants in C
1. Literal constant – These are values that are typed directly into a program and it does not change
during entire execution of the program.
2. Symbolic constant – This is a constant that has been given a name using the #define preprocessor
command.

Remember, preprocessor commands start with # symbol and are NOT terminated by a semicolon.

Declaring a symbolic or named constant follows the general structure shown in Listing 3.
1 #define NAME value

R
Listing 3: How to define symbolic/named constant

Listing 4 shows how to use constants in a C program


1 #include<stdio.h>

U
2 int main()
3 {
4 #define PI 3.142 //PI is a named constant
5 int radius = 7;
6 float area = PI ∗ radius ∗ radius ;
7
8
9
10
11 }
return 0;
UL
float perimeter = 2 ∗ PI ∗ radius; // 2 is a Literal constant
printf (”Area = %f Perimeter = %f”, area, perimeter);

Listing 4: Constants in C
G
Note that, whenever a defined symbol, like PI in this case, appears in a program, it is replaced by its actual
value, for this case 3.142 is inserted at the position the symbol PI appears in Line 6 and 7 of Listing 4.

The output of the code in Listing 4 is shown in Figure 1.


AN

Figure 1: Output of the code in Listing 4

1.5 Comments
.

Definition 19. A comment in a non-executable line of code meant for in-line documentation of the program.
DR

Comments are commonly used to explain complex algorithms being implemented in the program.
There are two types of comments in C
1. Single line comments - These comments start with double forward slashes (//) and only occupy a
single line. For example line 1 in Listing 5 shows a single line comment.
1 //This is a single line comment

Listing 5: Single line comment

2. Multi-line comment - These comments start with a forward slash and an asterisk and may occupy
several lines and must be terminated by an asterisk and a forward slash. For example line 1. . . 3 in
Listing 6 shows a multi-line comment.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 5


1 /∗ This is a
2 multiline comment
3 that occupies several lines ∗/

Listing 6: Multi-line comment

Comments are used for:-

• Documentation of variables and functions and their usage

• Explaining difficult sections of code or complex algorithm

• Describes the program, author, date, modification changes, revisions

R
1.6 Errors/bugs
Definition 20. An error (bug) is a mistake or an omission in a program that causes the program to stop
executing of the program may continue to execute but give wrong results. There are three types of errors

U
that can be commited in programming

(i) Syntax error – This is an error that occurs when a programmer fails to observe rules of a particular
programming language. Example of syntax errors are:-

UL
• Not terminating a statement with a semi-colon
• Mistyping a keyword/reserved word
• Omitting some necessary punctuation like a comma
• Using an opening brace (bracket) without a corresponding closing brace
G
It is easy to detect these errors because the compiler tells you where they are and what caused them.

(ii) Logical error – This error occurs when a programmer uses a wrong algorithm to solve a problem.
The error does not stop the program from executing, the program will continue executing but give
AN

wrong results. For example using the formula a = 3.142 + rad + rad to calculate area of a circle where
rad is the magnitude of the radius.

(iii) Runtime error – This error occurs when the program is executing and it encounters an illegal
statement (like division by zero) or a statement that cannot be executed (like trying to open a file
that does not exist).

1.7 A simple C program


.

Listing 7 shows a simple program written in C


DR

1 //A simple program in C


2 #include<stdio.h>
3 /∗The function main is the entry point
4 of every C program. All C programs must have this function ∗/
5 int main()
6 {
7 // calling a function found in stdio .h library
8 printf (”Welcome to C Programming\n”); //display a string on the screen and move cursor to the next line
9
10 return 0;
11 }//end of main function

Listing 7: Simple Program in C

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 6


Line 1 is a single line comment.
Line 2 is a #include preprocessor directive that is processed by the preprocessor before the program is
compiled. This preprocessor directive is used to instruct the preprocessor to include a file, library or any
other resource into the program before the program is compiled.

For this case, Line 2 instructs the preprocessor to include a library called stdio.h. The angle brack-
ets around the library name instructs the preprocessor to search for the library from th root directory where
that particular compiler is installed.

If the resource to be include in enclosed in double quotation marks, that instructs the preprocessor to
search for that particular resource in the current directory where the source file is saved.

R
Line 3 and 4 is a multi-line comment.

Line 5 is the header of a main function. Every C program must have a main function for it to exe-
cute.

U
Line 6 to 11 is a block of code that makes the body of the main function.

Line 8 we are calling a printf() function defined in the stdio.h library and we give it a string to dis-
play on the console (screen).
UL
Definition 21. String – This is a collection of characters enclosed in double quotation marks.

Line 10 is fulfilling the promise the main function made that it will return an integer (int) to signify that
it has finished executing.
G
Figure 2 shows the output of the code in Listing 7.
AN

Figure 2: Output of the code in Listing 7

Definition 22. Library – A library is a collection of precompiled functions.

Definition 23. Function – A function is a named block of code


.

Definition 24. Block of code – A block of code is a collection of lines of code enclosed in curl brackets
({}) and the compiler treats them as a single statement
DR

1.8 Escape sequences


Consider the code in Listing 7 and its corresponding output in Figure 2. You will notice that the characters
\n are not printed. This backslash (\) as used here is called escape character.

The escape character indicates that printf() is supposed to do something out of the ordinary.

When the compiler encounters a backslash in a string, it looks ahead at the next character and com-
bines it with the backslash to form an escape sequence.

The escape sequence \n means newline. This tells the compiler to display the string and move the

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 7


cursor on the next line of the console. So if there is another string (output) to be displayed, it will be on
the next line and not on the same line as the line with the newline escape sequence.

Some common escape sequences are listed in Table 3

Table 3: Common Escape Sequences

Escape Sequence Description


\n Newline. Position the cursor at the beginning of the next
line
\t Horizontal tab. Move the cursor to the next tab stop
\a Alert. Produces a sound or visible alert without changing

R
the current cursor position
\ Backslash. Insert a backslash character in a string
\” Double quote. Insert double quotes character in a string

U
1.9 Operators
These are symbols that denote type of operation to be performed on the data. There are three main
categories of operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
UL
G
1.9.1 Arithmetic operators
Table 4 shows arithmetic operators Note use of various symbols not used in algebra. Like asterisk (*)

Table 4: Arithmetic operators


AN

Operation Arithmetic operator Algebraic expression C expression


Addition + f +7 f+7
Subtraction - p−c p-c
Multiplication * bm or b × m b*m
Division / x/y or xy or x ÷ y x/y
Modulus/Remainder % r mod s r%s
.

indicates mmultiplication and the percentage sign (%) denotes the remainder operation.
DR

Integer division and remainder operator: – When you divide an integer with another integer you get
an integers. For example 7/2 = 3 and NOT 3.5. The remainder operator yields the modulus/remainder
after integer division. For example 7 % 2 = 1 and 5 % 6 = 5.

Parentheses for grouping sub-expression: – Parentheses (brackets) are used in the same manner it is
used in algebra to denote that some sub-expression should be performed first before others. For example,
to multiply b by the sum of c and d is written as b ∗ (c + d).

Precedence rules of operators


C applies the operators in an arithmetic expression in a precise sequence determined by the following rules
of operator precedence, which are generally same as those in algebra

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 8


1. Sub-expressions in parentheses are evaluated first. In the case of nested operator like d + (a × (b + c)),
the operator in the innermost brackets are evaluated first. If there are several brackets but not nested,
they are evaluated left-to-right.

2. Multiplication, division and modulus/remainder are evaluated second. If all or two appear in the same
expression, they are evaluated left-to-right.

3. Addition and subtraction are evaluated third. If both appear in the same expression, they are evaluated
left-to-right.

4. Assignment operator is evaluated last

Increment and decrement operators

R
These are special types of arithmetic operator that adds or subtracts one from the previous value held in a
variable.
1. Increment operator (Its symbol is ++) - It adds one to the previous value. There are two types

U
of increment operators

(i) Pre-increment – Adds one to the previous value before using the new value with another expres-
sion.
1
2
3
int x = 10;
int y = ++x;
UL
printf (”x = %d y = %d\n”, x, y);

Listing 8: Pre-increment
G
Figure 3: Output of the code in Listing 8
AN

The output in Figure 3 shows that the value stored in x that is 10 is incremented (increased by
1) before being assigned to the variable y.

Consider the code in Listing 9.


1 int a = 10;
2 int b = ++a + 10;
3 printf (”a = %d b = %d”, a, b);
.

Listing 9: Pre-increment
DR

Figure 4: Output of the code in Listing 9

The output in Figure 4 shows that the value held in variable a is first incremented before being
used for addition to value 10 (see line 2 of code in Listing 9) that is why b has the value 21
which is 11 + 10.
(ii) Post-increment – Adds one to the previous value after using the new value with another expres-
sion.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 9


1 int x = 10;
2 int y = x++;
3 printf (”x = %d y = %d\n”, x, y);

Listing 10: Post-increment

Figure 5: Output of the code in Listing 10

R
The output in Figure 5 shows that the value stored in x that is 10 is incremented (increased by
1) after being assigned to the variable y.

Consider the code in Listing 11.

U
1 int a = 10;
2 int b = a++ + 10;
3 printf (”a = %d b = %d”, a, b);

Listing 11: Post-increment

UL
Figure 6: Output of the code in Listing 11
G
The output in Figure 6 shows that the value held in variable a is incremented after being used
for addition to value 10 (see line 2 of code in Listing 11) that is why b has the value 20 which
AN

is 10 + 10.

2. Decrement operator (Its symbol is −−) – It subtracts one from the previous value. There are
two types of decrement operators

(i) Pre-decrement – Subtracts one from the previous value before using the new value with another
operator.
1 int x = 10;
2 int y = −−x;
3 printf (”x = %d y = %d\n”, x, y);
.

Listing 12: Pre-decrement


DR

Figure 7: Output of the code in Listing 12

The output in Figure 7 shows that the value stored in x that is 10 is decremented (reduced by
1) before being assigned to the variable y.

Consider the code in Listing 13.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 10


1 int a = 10;
2 int b = −−a + 10;
3 printf (”a = %d b = %d”, a, b);

Listing 13: Pre-decrement

Figure 8: Output of the code in Listing 13

R
The output in Figure 8 shows that the value held in variable a is first decremented before being
used for addition to value 10 (see line 2 of code in Listing 13) that is why b has the value 19
which is 9 + 10.
(ii) Post-decrement – Subtracts one from the previous value after using the new value with another
operator (expression).

U
1 int x = 10;
2 int y = x−−;
3 printf (”x = %d y = %d\n”, x, y);

Listing 14: Post-decrement


UL
G
Figure 9: Output of the code in Listing 14

The output in Figure 9 shows that the value stored in x that is 10 is decremented (reduced by
AN

1) after being assigned to the variable y.

Consider the code in Listing 15.


1 int a = 10;
2 int b = a−− + 10;
3 printf (”a = %d b = %d\n”, a, b);

Listing 15: Post-decrement


.
DR

Figure 10: Output of the code in Listing 15

The output in Figure 10 shows that the value held in variable a is decremented after being used
for addition to value 10 (see line 2 of code in Listing 15) that is why b has the value 20 which
is 10 + 10 and a has the value 9.

1.9.2 Assignment operator - Symbol =


It is used to assign (give) a value to a variable. For instance, consider Line 1 in Listing 15 where assignment
operator is used to assign (give/initialize) variable a with the value 10.

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 11


The general syntax of writing expressions is

variable = variable op expression

where op denotes an arithmetic operator which can be either of (+, -, *, /, %) We can combine assignment
operator and arithmetic operators as

variable op= expression

For example, the expression


x = x + b ∗ 10

R
Can be written as
x += b ∗ 10
Table 5 shows how arithmetic operators can be combined with assignment operator

Table 5: Combining Arithmetic and assignment operators

U
Arithmetic operator Combined Example Equivalent
+ += a += b a=a+b

%
-
*
/
UL -=
*=
/=
%=
a -= b
a *= b
a /= b
a %= b
a=a-b
a=a*b
a=a/b
a=a%b
G
1.9.3 Relational and equality operators
These operators check two quantities and return true (1) or false (0). They are used for comparison of two
quantities. Table 6 shows these operators and what they mean.
AN

Table 6: Relational and Equality operators

Algebraic operator C equivalent Example in C Meaning


Relational operators
> > x>y x is greater than y
< < x<y x is less than y
≥ >= x >= y x is greater than or equal to y
≤ <= x <= y x is less than or equal to y
.

Equality operators
DR

= == x == y x is equal to y
6 = != x != y x is not equal to y

1.9.4 Logical operators


These operators are used to combine two or more logical conditions. A logical condition is a condition whose
output is either true (1) or false (0). There are THREE logical operators:-

1. AND–Symbol is && – It checks two logical conditions and return true (1) if both conditions are
true (1) or return false (0) if either (any) of the conditions is false (0). Summary of AND can be

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 12


seen as
1×1=1
1×0=0
0×1=0
0×0=0
where × denote the AND operation. Consider the code in Listing 16.
1 int x = 10;
2 int y = 23;
3 if (y > 5 && x % 2 == 0)
4 {
printf (”%d is Even and %d is greater than %d\n”, x, y, x);

R
5
6 }

Listing 16: Using logical AND

At Line 3 of this code, we are using logical AND to check two conditions:-

U
• If the value in y is greater than 5
• If the value in x is an even number (If we divide by 2 and the remainder is zero)

both conditions tested are true.


UL
Note that, Line 5 will only execute if Line 3 returns true. For this case it will return true because

2. OR – Symbol is || – It checks two logical conditions and return true (1) if any of the conditions is
true (1) or return false (0) if both conditions are false (0). Summary of OR can be seen as
1+1=1
G
1+0=1
0+1=1
0+0=0
AN

where + denote the OR operation. Consider the code in Listing 17.


1 int a = 3;
2 int b = 7;
3 if ((a ∗ 3) < b || (b / 2.0) > a)
4 {
5 printf (”%d is greater than twice %d”, b, a);
6 }

Listing 17: Using logical OR


.

At Line 3 of this code, we are using logical OR to check two conditions:-


DR

• If 3 times the value in a is less than the value b


• If the value in b divided by 2 is greater than the value in a
Note that, Line 5 will only execute if Line 3 returns true. For this case it will return true because
second condition tested is true, even though first condition is false.
3. NOT – Symbol is ! – It used for negation. Changes true (1) to false (0) and vice versa.

We will use these logical operators mostly in our second topic – SELECTION

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 13


1.10 Formatting input and output
C requires that you format your inputs and outputs.

1.10.1 Formatting output


The printf() function is used for output, to display information on the console (screen). Now, lets look
closely at line 5 of code in Listing 15 which is reproduced below
1 printf (”a = %d b = %d\n”, a, b);

Listing 18: Formatting output

The first argument of the printf() function ”a = %d b = %d” is referred to as control string.

R
When the printf() is executed, it starts printing the text in the control string until it encounters a %
character.

The % sign is a special character in C and marks the beginning of a format specifier. A format specifier

U
controls how the value of a variable will be displayed on the screen.

When a format specifier is found,printf() looks up the next argument (in this case a), displays its value
and continues on.

UL
The d character that follows the % indicates that a (d)ecimal integer will be displayed.

The general form of printf() statement is

printf (”control string”, arguements list);


G
where the control string consists of

• Literal text to be displayed in this example we have a = and b =


AN

• Format specifiers. For this case we have two %d meaning two integers are gona be displayed

• Escape sequence for this case we have \n meaning after displaying, go to next line

The arguments list can be made up of variables,constants, expressions, or function calls – anything that
produces a value which can be displayed.

Note that, the number and order of format specifiers must match the number and order
.

of arguments in the argument list. Table 7 shows what format specifiers should be used with what
data types
DR

Table 7: Format Specifier Table

Format specifier Data type


%c char
%d int
%f float
%lf double
%s string

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 14


1.10.2 Formatting input
The scanf() function is used for reading input from the keyboard. Consider the following code in Listing 19.
1 int x;
2 float a;
3 char c;
4 scanf(”%d”, &x);
5 scanf(”%f %c”, &a, &c);

Listing 19: Formatting input

Line 1 . . . 3 declares three variables.

R
Line 4 reads an integer (specified by the %d format specifier) into the variable x.

The scanf() function, which accepts input from the keyboard, has a control string and an address list.
In the control string, the format specifier %d shows what data type is expected. The &x argument specifies
the memory location (address of x) of the variable the input will be placed in.

U
The & character has a very special meaning in C. It is the address operator. (Much more with & when we
get to pointers).

UL
Line 5 just shows that you can read several values (of different data types) using a single scanf() state-
ment. Though I do not like that, use a single scanf() for a single input. It also good to precede
every input with a prompt message (using printf()) to make your program interactive. Consider the program
in Listing 20 which reads radius of a circle from the keyboard and calculates area and perimeter of the circle.
1 #include<stdio.h>
2 int main()
G
3 {
4 #define PI 3.142
5 int rad;
6 double area;
AN

7 float perimeter;
8 printf (”Enter radius of the circle : ”);
9 scanf(”%d”, &rad);
10 area = PI ∗ rad ∗ rad;
11 perimeter = 2 ∗ PI ∗ rad;
12 printf (”Radius = %d\n”, rad);
13 printf (”Area = %lf\tPerimeter = %f”, area, perimeter);
14
15 return 0;
16 }
.

Listing 20: Read radius from keyboard and calculate area and perimeter of the circle
DR

Output of this code is shown in Figure 11.

Figure 11: Output of the code in Listing 20

Dr. Raphael Angulu, BCS111 SCI, MMUST, 2020: Introduction Notes 15

You might also like