(O'SMART) ELE 276 Lecture Notes-Compressed

Download as pdf or txt
Download as pdf or txt
You are on page 1of 223

1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
2

1.1 Introduction
• We will learn
– The C programming language
– Structured programming and proper programming techniques
• This course is appropriate for
– Technically oriented people with little or no programming
experience
– Experienced programmers who want a deep and rigorous
treatment of the language
3

1.2 What is a Computer?


• Computer
– Device capable of performing computations and making
logical decisions
– Computers process data under the control of sets of
instructions called computer programs
• Hardware
– Various devices comprising a computer
– Keyboard, screen, mouse, disks, memory, CD-ROM, and
processing units
• Software
– Programs that run on a computer
4

1.3 Computer Organization


• Six logical units in every computer:
1. Input unit
• Obtains information from input devices (keyboard, mouse)
2. Output unit
• Outputs information (to screen, to printer, to control other
devices)
3. Memory unit
• Rapid access, low capacity, stores input information
4. Arithmetic and logic unit (ALU)
• Performs arithmetic calculations and logic decisions
5. Central processing unit (CPU)
• Supervises and coordinates the other sections of the computer
6. Secondary storage unit
• Cheap, long-term, high-capacity storage
• Stores inactive programs
5

1.4 Evolution of Operating Systems


• Batch processing
– Do only one job or task at a time
• Operating systems
– Manage transitions between jobs
– Increased throughput
• Amount of work computers process
• Multiprogramming
– Computer resources are shared by many jobs or tasks
• Timesharing
– Computer runs a small portion of one user’s job then moves
on to service the next user
6
1.5 Personal Computing, Distributed
Computing, and Client/Server Computing
• Personal computers
– Economical enough for individual
• Distributed computing
– Computing distributed over networks
• Client/server computing
– Sharing of information across computer networks between
file servers and clients (personal computers)
7
1.6 Machine Languages, Assembly
Languages, and High-level Languages
• Three types of programming languages
1. Machine languages
• Strings of numbers giving machine specific instructions
• Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
• English-like abbreviations representing elementary computer
operations (translated via assemblers)
• Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
8
1.6 Machine Languages, Assembly
Languages, and High-level Languages
3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via compilers)
• Example:
grossPay = basePay + overTimePay
9

1.7 History of C
• C
– Evolved by Ritchie from two previous programming
languages, BCPL and B
– Used to develop UNIX
– Used to write modern operating systems
– Hardware independent (portable)
– By late 1970's C had evolved to "Traditional C"
• Standardization
– Many slight variations of C existed, and were incompatible
– Committee formed to create a "unambiguous, machine-
independent" definition
– Standard created in 1989, updated in 1999
10

1.8 The C Standard Library


• C programs consist of pieces/modules called
functions
– A programmer can create his own functions
• Advantage: the programmer knows exactly how it works
• Disadvantage: time consuming
– Programmers will often use the C library functions
• Use these as building blocks
– Avoid re-inventing the wheel
• If a premade function exists, generally best to use it rather than
write your own
• Library functions carefully written, efficient, and portable
11
1.9 The Key Software Trend: Object
Technology
• Objects
– Reusable software components that model items in the real
world
– Meaningful software units
• Date objects, time objects, paycheck objects, invoice objects,
audio objects, video objects, file objects, record objects, etc.
• Any noun can be represented as an object
– Very reusable
– More understandable, better organized, and easier to
maintain than procedural programming
– Favor modularity
12

1.10 Structured Programming


• Structured programming
– Disciplined approach to writing programs
– Clear, easy to test and debug and easy to modify
• Multitasking
– Specifying that many activities run in parallel
13
1.11 Basics of a Typical C Program
Development Environment
Program is created in
• Phases of C Programs: Editor Disk
the editor and stored
on disk.
Preprocessor program
1. Edit Preprocessor Disk processes the code.
Compiler creates
2. Preprocess Compiler Disk object code and stores
it on disk.
3. Compile Linker Disk Linker links the object
code with the libraries
Primary Memory
4. Link Loader
Loader puts program
5. Load Disk ..
in memory.
..
..

6. Execute Primary Memory


CPUtakes each
CPU instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
14

1.12 Hardware Trends


• Every year or two the following approximately
double:
– Amount of memory in which to execute programs
– Amount of secondary storage (such as disk storage)
• Used to hold programs and data over the longer term
– Processor speeds
• The speeds at which computers execute their programs
15

1.13 History of the Internet


• The Internet enables
– Quick and easy communication via e-mail
– International networking of computers
• Packet switching
– The transfer of digital data via small packets
– Allows multiple users to send and receive data
simultaneously
• No centralized control
– If one part of the Internet fails, other parts can still operate
• Bandwidth
– Information carrying capacity of communications lines
16

1.14 History of the World Wide Web


• World Wide Web
– Locate and view multimedia-based documents on almost any
subject
– Makes information instantly and conveniently accessible
worldwide
– Possible for individuals and small businesses to get
worldwide exposure
– Changing the way business is done
17
1.15 General Notes About C
and This Book
• Program clarity
– Programs that are convoluted are difficult to read,
understand, and modify
• C is a portable language
– Programs can run on many different computers
– However, portability is an elusive goal
• We will do a careful walkthrough of C
– Some details and subtleties are not covered
– If you need additional technical details
• Read the C standard document
• Read the book by Kernigan and Ritchie
Downloaded from www.schoolnetwork.io 1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2

How to Learn C Effectively


• There is a close analogy between learning English
language and learning C language.
• The classical method of learning English is to first
learn the alphabets used in the language, then learn
to combine these alphabets to form words, which
in turn are combined to form sentences and
sentences are combined to form paragraphs.
Downloaded from www.schoolnetwork.io 3

How to Learn C Effectively


Downloaded from www.schoolnetwork.io 4

Basic Definitions
• Computer program is just a collection of the
instructions necessary to solve a specific problem.
• The basic operations of a computer system form
what is known as the computer’s instruction set.
• the approach or method that is used to solve the
problem is known as an algorithm.
• Programming language can be broadly divided
into two types: Low Level Languages and High
Level Languages.
Downloaded from www.schoolnetwork.io 5

Basic Definitions
• Low level languages can be subdivided into
machine level and assembly level language.
• In machine level language computer only
understand digital numbers i.e. in the form of 0
and 1 (binary digit). This type of program is not
portable, difficult to implement/maintain and also
error prone.
Downloaded from www.schoolnetwork.io 6

Basic Definitions
• The assembly language is modified version of
machine level language where instructions are
given in English like word as ADD, SUM, MOV
etc.
• It is easy to write and understand but not
understand by the machine.
• So the translator used here is assembler to
translate into machine level.
• Programmer has to know low level language
details. In the assembly level language the data are
stored in the computer register, which varies for
different computer. Hence it is not portable.
Downloaded from www.schoolnetwork.io 7

Basic Definitions
• High level language are machine independent,
means it is portable.
• The language in this category is MATLAB,
C/C++, Java, Pascal, Cobol, Fortran etc.
• High level languages are not understood by the
machine. So there is need to translate by the
translator into machine level.
• A translator is software which is used to translate
high level language as well as low level language
in to machine level language.
Downloaded from www.schoolnetwork.io 8

Basic Definitions
• There are three types of translator: Compiler,
Interpreter and Assembler.
• Compiler and interpreter are used to convert the
high level language into machine level language.
• The program written in high level language is
known as source program and the corresponding
machine level language program is called as object
program.
Downloaded from www.schoolnetwork.io 9

Basic Definitions
• Both compiler and interpreter perform the same
task but there working is different.
• Compiler read the program at-a-time and searches
the error and lists them. If the program is error
free then it is converted into object program.
• When program size is large then compiler is
preferred.
• Whereas interpreter read only one line of the
source code and convert it to object code. By
checking error, statement by statement, it takes
more time.
Downloaded from www.schoolnetwork.io 10

Basic Definitions
• Typical errors reported during the phase of
compilation might be due to an expression that has
unbalanced parentheses (syntax error), or due to
the use of a variable that is not “defined”
(semantic error).
• The process of compiling and linking a program is
often called building.
Downloaded from www.schoolnetwork.io 11

Basic Definitions
• Results that are displayed by the program, known
as output, appear in a window, sometimes called
the console.
• If the program does not produce the desired
results, it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging
phase, during which an attempt is made to remove
all the known problems or bugs from the program.
Downloaded from www.schoolnetwork.io 12

Basic Definitions
• The process of editing, compiling, running, and
debugging programs is often managed by a single
integrated application known as an Integrated
Development Environment, or IDE for short.
• An IDE is a windows-based program that allows
us to easily manage large software programs, edit
files in windows, and compile, link, run, and
debug programs.
Downloaded from www.schoolnetwork.io 13

Basic Definitions
• On Mac OS X, CodeWarrior and Xcode are two
IDEs that are used by many programmers.
• Under Windows, Microsoft Visual Studio is a
good example of a popular IDE.
• Kylix is a popular IDE for developing applications
under Linux.
• Most IDEs also support program development in
several different programming languages in
addition to C, such as C# and C++.
Downloaded from www.schoolnetwork.io 14

Structure of a C Program
• 1 ) Comment line
• 2) Preprocessor directive
• 3 ) Global variable declaration
• 4) main function( )
• {
• Local variables;
• Statements;
• }
• User defined function
• }
• }
Downloaded from www.schoolnetwork.io 15
Structure of a C Program
• Comment line:
• It indicates the purpose of the program. It is
represented as: /*……………………………..*/
• Comment line is used for increasing the
readability of the program.
• It is useful in explaining the program and
generally used for documentation.
• It is enclosed within the decimeters.
• Comment line can be single or multiple line but
should not be nested.
• It can be anywhere in the program except inside
string constant & character constant.
Downloaded from www.schoolnetwork.io 16
Structure of a C Program
• Preprocessor Directive:
• #include<stdio.h> tells the compiler to include
information about the standard input/output
library.
• It is also used in symbolic constant such as
#define PI 3.14(value).
• The stdio.h (standard input output header file)
contains definition & declaration of system
defined function such as printf( ), scanf( ), pow( )
etc.
• Generally printf() function used to display and
scanf() function used to read value.
Downloaded from www.schoolnetwork.io 17
Structure of a C Program
• Global Declaration:
• This is the section where variable are declared
globally so that it can be access by all the
functions used in the program.
• And it is generally declared outside the main
function.
Downloaded from www.schoolnetwork.io 18
Structure of a C Program
• main()
• It is the user defined function and every program has one
main() function from where actually program is started and
it is encloses within the pair of curly braces.
• The main( ) function can be anywhere in the program but
in general practice it is placed in the first position.
• Syntax :
• main()
• {
• ……..
• ……..
• ……..
• }
Downloaded from www.schoolnetwork.io 19
Structure of a C Program
• The main( ) function return value when it declared by data
type as
• int main( )
• {
• return 0
• }
• The main function does not return any value when void
(means null/empty) as
• void main(void ) or void main()
• {
• printf (“C language”);
• }
• Output: C language
Downloaded from www.schoolnetwork.io 20

Structure of a C Program
• The program execution start with opening braces
and end with closing brace.
• And in between the two braces declaration part as
well as executable part is mentioned.
• And at the end of each line, the semi-colon is
given which indicates statement termination.
Downloaded from www.schoolnetwork.io 21

Practice Exercise
One(1)
Downloaded from www.schoolnetwork.io 22
A Simple C Program:
Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n" );
8
9 return 0;
10 }
Welcome to C!

• Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor directive
• Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations
Downloaded from www.schoolnetwork.io 23
A Simple C Program:
Printing a Line of Text
• int main()
– C++ programs contain one or more functions, exactly one of
which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
• The bodies of all functions must be contained in braces
Downloaded from www.schoolnetwork.io 24
A Simple C Program:
Printing a Line of Text
• printf( "Welcome to C!\n" );
– Instructs computer to perform an action
• Specifically, prints the string of characters within quotes (“ ”)
– Entire line called a statement
• All statements must end with a semicolon (;)
– Escape character (\)
• Indicates that printf should do something out of the ordinary
• \n is the newline character
Downloaded from www.schoolnetwork.io 25
A Simple C Program:
Printing a Line of Text
• return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally
• Right brace }
– Indicates end of main has been reached
• Linker
– When a function is called, linker locates it in the library
– Inserts it into object program
– If function name is misspelled, the linker will produce an
error because it will not be able to find function in the
library
Downloaded from www.schoolnetwork.io 26

Practice Exercise
Two(2)
1 /* Fig. 2.5:
Downloaded fig02_05.c
from www.schoolnetwork.io 27
2 Addition program */ Outline
3 #include <stdio.h>
4 1. Initialize variables
5 int main()
6 { 2. Input
7 int integer1, integer2, sum; /* declaration */
8 2.1 Sum
9 printf( "Enter first integer\n" ); /* prompt */
10 scanf( "%d", &integer1 ); /* read an integer */
3. Print
11 printf( "Enter second integer\n" ); /* prompt */
12 scanf( "%d", &integer2 ); /* read an integer */
13 sum = integer1 + integer2; /* assignment of sum */
14 printf( "Sum is %d\n", sum ); /* print sum */
15
16 return 0; /* indicate that program ended successfully */
17 }

Enter first integer


45 Program Output
Enter second integer
72
Sum is 117
Downloaded from www.schoolnetwork.io 28
Another Simple C Program:
Adding Two Integers
• As before
– Comments, #include <stdio.h> and main
• int integer1, integer2, sum;
– Declaration of variables
• Variables: locations in memory where a value can be stored
– int means the variables can hold integers (-1, 3, 0, 47)
– Variable names (identifiers)
• integer1, integer2, sum
• Identifiers: consist of letters, digits (cannot begin with a digit)
and underscores( _ )
– Case sensitive
– Declarations appear before executable statements
• If an executable statement references and undeclared variable
it will produce a syntax (compiler) error
Downloaded from www.schoolnetwork.io 29
Another Simple C Program:
Adding Two Integers
• scanf( "%d", &integer1 );
– Obtains a value from the user
• scanf uses standard input (usually keyboard)
– This scanf statement has two arguments
• %d - indicates data should be a decimal integer
• &integer1 - location in memory to store variable
• & is confusing in beginning – for now, just remember to
include it with the variable name in scanf statements
– When executing the program the user responds to the
scanf statement by typing in a number, then pressing the
enter (return) key
Downloaded from www.schoolnetwork.io 30
Another Simple C Program:
Adding Two Integers
• = (assignment operator)
– Assigns a value to a variable
– Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
– Variable receiving value on left
• printf( "Sum is %d\n", sum );
– Similar to scanf
• %d means decimal integer will be printed
• sum specifies what integer will be printed
– Calculations can be performed inside printf statements
printf( "Sum is %d\n", integer1 + integer2 );
Downloaded from www.schoolnetwork.io 31

Memory Concepts
• Variables
– Variable names correspond to locations in the computer's
memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable (through
scanf, for example), it replaces (and destroys) the previous
value
– Reading variables from memory does not change them
• A visual representation

integer1 45
Downloaded from www.schoolnetwork.io 32

Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Downloaded from www.schoolnetwork.io 33

Arithmetic
• Arithmetic operators:
C op era tion Arithm etic Alg eb ra ic C exp ression
op era tor exp ression
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
• Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Downloaded from www.schoolnetwork.io 34
Decision Making: Equality and Relational
Operators
• Executable statements
– Perform actions (calculations, input/output of data)
– Perform decisions
• May want to print "pass" or "fail" given the value of a
test grade
• if control structure
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
• 0 is false, non-zero is true
– Control always resumes after the if structure
• Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names
Downloaded from www.schoolnetwork.io 35
Decision Making: Equality and Relational
Operators

Standard algebraic C equality or Example of C Meaning of C


equality operator or relational condition condition
relational operator operator
Equality Operators
= == x == y x is equal to y
not = != x != y x is not equal to y
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
Downloaded from www.schoolnetwork.io 36
Decision Making: Equality and Relational
Operators

Keyw ord s
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Downloaded from www.schoolnetwork.io 37

Practice Exercise
Three(3)
1 /* Fig. 2.13:
Downloaded fromfig02_13.c
www.schoolnetwork.io 38
2 Using if statements, relational Outline
3 operators, and equality operators */
4 #include <stdio.h>
1. Declare variables
5
6 int main()
7 { 2. Input
8 int num1, num2;
9
2.1 if statements
10 printf( "Enter two integers, and I will tell you\n" );
11 printf( "the relationships they satisfy: " );
12 scanf( "%d%d", &num1, &num2 ); /* read two integers */ 3. Print
13
14 if ( num1 == num2 )
15 printf( "%d is equal to %d\n", num1, num2 );
16
17 if ( num1 != num2 )
18 printf( "%d is not equal to %d\n", num1, num2 );
19
20 if ( num1 < num2 )
21 printf( "%d is less than %d\n", num1, num2 );
22
23 if ( num1 > num2 )
24 printf( "%d is greater than %d\n", num1, num2 );
25
26 if ( num1 <= num2 )
27 printf( "%d is less than or equal to %d\n",
28 num1, num2 );
29
Downloaded from www.schoolnetwork.io 39
30 if ( num1 >= num2 ) Outline
31 printf( "%d is greater than or equal to %d\n",
3.1 Exit main
32 num1, num2 );

33

34 return 0; /* indicate program ended successfully */

35 }

Enter two integers, and I will tell you


Program Output
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Downloaded from www.schoolnetwork.io 40

Practice Exercise
Four(4)
Downloaded from www.schoolnetwork.io 41

#include <stdio.h>
int main (void)
{
int v1, v2, sum; //v1,v2,sum are variables and int is data type declared
v1 = 150;
v2 = 25;
sum = v1 + v2;
printf ("The sum of %i and %i is= %i\n", v1, v2, sum);
return 0;
}
Output: The sum of 150 and 25 is=175
Downloaded from www.schoolnetwork.io 1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2

Introduction
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles
Downloaded from www.schoolnetwork.io 3

Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to executed
Downloaded from www.schoolnetwork.io 4

Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding C++ program
• Consists only of executable statements
Downloaded from www.schoolnetwork.io 5

Control Structures
• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in
sequence
– Overuse of goto statements led to many problems
• Bohm and Jacopini
– All programs written in terms of 3 control structures
• Sequence structures: Built into C. Programs executed
sequentially by default
• Selection structures: C has three types: if, if/else, and
switch
• Repetition structures: C has three types: while, do/while
and for
Downloaded from www.schoolnetwork.io 6

Control Structures
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols connected by
arrows called flowlines
– Rectangle symbol (action symbol):
• Indicates any type of action
– Oval symbol:
• Indicates the beginning or end of a program or a section of code
• Single-entry/single-exit control structures
– Connect exit point of one control structure to entry point of
the next (control-structure stacking)
– Makes programs easy to build
Downloaded from www.schoolnetwork.io 7

The if Selection Structure


• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
• If condition true
– Print statement executed and program goes on to next
statement
– If false, print statement is ignored and the program goes
onto the next statement
– Indenting makes programs easier to read
• C ignores whitespace characters
Downloaded from www.schoolnetwork.io 8

The if Selection Structure


• Pseudocode statement in C:
if ( grade >= 60 )
printf( "Passed\n" );
– C code corresponds closely to the pseudocode
• Diamond symbol (decision symbol)
– Indicates decision is to be made
– Contains an expression that can be true or false
– Test the condition, follow appropriate path
Downloaded from www.schoolnetwork.io 9

The if Selection Structure


• if structure is a single-entry/single-exit structure

A decision can be made on


any expression.

true zero - false


grade >= 60 print “Passed”
nonzero - true
Example:
false 3 - 4 is true
Downloaded from www.schoolnetwork.io 10

The if/else Selection Structure


• if
– Only performs an action if the condition is true
• if/else
– Specifies an action to be performed both when the condition
is true and when it is false
• Psuedocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
– Note spacing/indentation conventions
Downloaded from www.schoolnetwork.io 11

The if/else Selection Structure


• C code:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
• Ternary conditional operator (?:)
– Takes three arguments (condition, value if true, value if
false)
– Our pseudocode could be written:
printf( "%s\n", grade >= 60 ? "Passed" :
"Failed" );
– Or it could have been written:
grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );
Downloaded from www.schoolnetwork.io 12

The if/else Selection Structure


• Flow chart of the if/else selection structure

false true
grade >= 60

print “Failed” print “Passed”

• Nested if/else structures


– Test for multiple cases by placing if/else selection
structures inside if/else selection structures
– Once condition is met, rest of statements skipped
– Deep indentation usually not used in practice
Downloaded from www.schoolnetwork.io 13

The if/else Selection Structure


– Pseudocode for a nested if/else structure
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
Downloaded from www.schoolnetwork.io 14

The if/else Selection Structure


• Compound statement:
– Set of statements within a pair of braces
– Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else {
printf( "Failed.\n" );
printf( "You must take this course
again.\n" );
}
– Without the braces, the statement
printf( "You must take this course
again.\n" );
would be executed automatically
Downloaded from www.schoolnetwork.io 15

The if/else Selection Structure


• Block:
– Compound statements with declarations
• Syntax errors
– Caught by compiler
• Logic errors:
– Have their effect at execution time
– Non-fatal: program runs, but has incorrect output
– Fatal: program exits prematurely
Downloaded from www.schoolnetwork.io 16

The while Repetition Structure


• Repetition structure
– Programmer specifies an action to be repeated while some
condition remains true
– Psuedocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
Downloaded from www.schoolnetwork.io 17

The while Repetition Structure


• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;

true
product <= 1000 product = 2 * product

false
Downloaded from www.schoolnetwork.io 18
Formulating Algorithms
(Counter-Controlled Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value
– Definite repetition: number of repetitions is known
– Example: A class of ten students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are available to
you. Determine the class average on the quiz
– Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
Downloaded from www.schoolnetwork.io 19

Practice Exercise
One(1)
Downloaded
1 /* Fig. from
3.6: www.schoolnetwork.io
fig03_06.c 20
2 Class average program with Outline
3 counter-controlled repetition */
4 #include <stdio.h> 1. Initialize Variables
5
6 int main()
2. Execute Loop
7 {
8 int counter, grade, total, average;
9
3. Output results
10 /* initialization phase */
11 total = 0;
12 counter = 1;
13
14 /* processing phase */
15 while ( counter <= 10 ) {
16 printf( "Enter grade: " );
17 scanf( "%d", &grade );
18 total = total + grade;
19 counter = counter + 1;
20 }
21
22 /* termination phase */
23 average = total / 10;
24 printf( "Class average is %d\n", average );
25
26 return 0; /* indicate program ended successfully */
27 }
Downloaded from www.schoolnetwork.io 21
Enter grade: 98
Outline
Enter grade: 76
Enter grade: 71
Enter grade: 87
Program Output
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Downloaded from www.schoolnetwork.io 22
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run.
– Unknown number of students
– How will the program know to end?
• Use sentinel value
– Also called signal value, dummy value, or flag value
– Indicates “end of data entry.”
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)
Downloaded from www.schoolnetwork.io 23
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Top-down, stepwise refinement
– Begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
• Many programs have three phases:
– Initialization: initializes the program variables
– Processing: inputs data values and adjusts program variables
accordingly
– Termination: calculates and prints the final results
Downloaded from www.schoolnetwork.io 24
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine the initialization phase from Initialize
variables to:
Initialize total to zero
Initialize counter to zero
• Refine Input, sum and count the quiz grades to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
Downloaded from www.schoolnetwork.io 25
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine Calculate and print the class average to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Downloaded from www.schoolnetwork.io 26

Practice Exercise
Two(2)
Downloaded
1 /* Fig. from
3.8: www.schoolnetwork.io
fig03_08.c 27
2 Class average program with Outline
3 sentinel-controlled repetition */
4 #include <stdio.h> 1. Initialize Variables
5
6 int main() 2. Get user input
7 {
8 float average; /* new data type */ 2.1 Perform Loop
9 int counter, grade, total;
10
11 /* initialization phase */
12 total = 0;
13 counter = 0;
14
15 /* processing phase */
16 printf( "Enter grade, -1 to end: " );
17 scanf( "%d", &grade );
18
19 while ( grade != -1 ) {
20 total = total + grade;
21 counter = counter + 1;
22 printf( "Enter grade, -1 to end: " );
23 scanf( "%d", &grade );
24 }
Downloaded
25 from www.schoolnetwork.io 28
26 /* termination phase */ Outline
27 if ( counter != 0 ) {
28 average = ( float ) total / counter;
3. Calculate Average
29 printf( "Class average is %.2f", average );
30 }
31 else 3.1 Print Results
32 printf( "No grades were entered\n" );
33
34 return 0; /* indicate program ended successfully */
35 }

Enter grade, -1 to end: 75


Enter grade, -1 to end: 94 Program Output
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
Downloaded from www.schoolnetwork.io 29

Nested control structures


• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2
Downloaded from www.schoolnetwork.io 30

Nested control structures


• Top level outline
Analyze exam results and decide if tuition should be raised
• First Refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition should
be raised
• Refine Initialize variables to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
Downloaded from www.schoolnetwork.io 31

Nested control structures


• Refine Input the ten quiz grades and count passes
and failures to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
• Refine Print a summary of the exam results and
decide if tuition should be raised to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
Downloaded from www.schoolnetwork.io 32

Practice Exercise
Three(3)
Downloaded
1 /* Fig. from
3.10:www.schoolnetwork.io
fig03_10.c 33
2 Analysis of examination results */ Outline
3 #include <stdio.h>
4
5 int main() 1. Initialize variables
6 {
7 /* initializing variables in declarations */ 2. Input data and
8 int passes = 0, failures = 0, student = 1, result; count passes/failures
9
10 /* process 10 students; counter-controlled loop */
11 while ( student <= 10 ) { 3. Print results
12 printf( "Enter result ( 1=pass,2=fail ): " );
13 scanf( "%d", &result );
14
15 if ( result == 1 ) /* if/else nested in while */
16 passes = passes + 1;
17 else
18 failures = failures + 1;
19
20 student = student + 1;
21 }
22
23 printf( "Passed %d\n", passes );
24 printf( "Failed %d\n", failures );
25
26 if ( passes > 8 )
27 printf( "Raise tuition\n" );
28
29 return 0; /* successful termination */
30 }
Downloaded from www.schoolnetwork.io 34
Enter Result (1=pass,2=fail): 1
Outline
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Program Output
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Passed 6
Failed 4
Downloaded from www.schoolnetwork.io 35

Assignment Operators
• Assignment operators abbreviate assignment
expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Downloaded from www.schoolnetwork.io 36

Increment and Decrement Operators


• Increment operator (++)
– Can be used instead of c+=1
• Decrement operator (--)
– Can be used instead of c-=1
• Preincrement
– Operator is used before the variable (++c or --c)
– Variable is changed before the expression it is in is evaluated
• Postincrement
– Operator is used after the variable (c++ or c--)
– Expression executes before the variable is changed
Downloaded from www.schoolnetwork.io 37

Increment and Decrement Operators


• If c equals 5, then
printf( "%d", ++c );
– Prints 6
printf( "%d", c++ );
– Prints 5
– In either case, c now has the value of 6
• When variable not in an expression
– Preincrementing and postincrementing have the same effect
++c;
printf( “%d”, c );
– Has the same effect as
c++;
printf( “%d”, c );
Downloaded from www.schoolnetwork.io

COMPUTER
PROGRAMMING II
ELE 276
DEFINITIONS OF USEFUL
TERMS AND CONCEPTS
FOR LECTURE THREE (3)
This lecture material and
other distributed materials
for this ELE276 course are
not for sale.
Downloaded from www.schoolnetwork.io

Character set:
A character denotes any alphabet, digit or special symbol used to represent information. Valid
alphabets, numbers and special symbols allowed in C are as shown below:

The alphabets, numbers and special symbols when properly combined form constants, variables
and keywords.
Identifiers:
Identifiers are user defined word used to name of entities like variables, arrays, functions,
structures etc. Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and lower case), digits and underscore (_)
sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case considered differently, for example
code, Code, CODE etc. are different identifiers.
5) identifiers are generally given in some meaningful name such as value, net_salary, age, data
etc.
An identifier name may be long, some implementation recognizes only first eight characters,
most recognize 31 characters. ANSI standard compiler recognize 31 characters. Some invalid
identifiers are 5cb, int, res#, avg no etc.
Keyword:
There are certain words reserved for doing specific task, these words are known as reserved word
or keywords. These words are predefined and always written in lower case or small letter. These
Downloaded from www.schoolnetwork.io

keywords can’t be used as a variable name as it assigned with fixed meaning. Some examples are
int, short, signed, unsigned, default, volatile, float, long, double, break, continue, typedef, static,
do, for, union, return, while, do, extern, register, enum, case, goto, struct, char, auto, const etc.
Data types:
Data types refer to an extensive system used for declaring variables or functions of different
types before its use. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted. The value of a variable can be changed any time.
C has the following 4 types of data types:
Basic built-in data types: int, float, double, char
Enumeration data type: enum
Derived data type: pointer, array, structure, union
Void data type: void
A variable declared to be of type int can be used to contain integral values only—that is, values
that do not contain decimal places. A variable declared to be of type float can be used for storing
floating- point numbers (values containing decimal places). The double type is the same as type
float, only with roughly twice the precision. The char data type can be used to store a single
character, such as the letter a, the digit character 6, or a semicolon similarly A variable declared
char can only store character type value.
There are two types of type qualifier in c:
Size qualifier: short, long
Sign qualifier: signed, unsigned
When the qualifier unsigned is used the number is always positive, and when signed is used
number may be positive or negative. If the sign qualifier is not mentioned, then by default sign
qualifier is assumed. The range of values for signed data types is less than that of unsigned data
type. Because in signed type, the left most bit is used to represent sign, while in unsigned type
this bit is also used to represent the value. The size and range of the different data types on a 16
bit machine is given below:
Downloaded from www.schoolnetwork.io

Constants:
Constant is a any value that cannot be changed during program execution. In C, any number,
single character, or character string is known as a constant. A constant is an entity that doesn’t
change whereas a variable is an entity that may change.
For example, the number 50 represents a constant integer value. The character string
"Programming in C is fun.\n" is an example of a constant character string. C constants can be
divided into two major categories:
Primary Constants
Secondary Constants
These constants are further categorized as (Numeric, Character and String Constants) shown in
the figure below:
Downloaded from www.schoolnetwork.io

Numeric constant:
Numeric constant consists of digits. It required minimum size of 2 bytes and max 4 bytes. It may
be positive or negative but by default sign is always positive. No comma or space is allowed
within the numeric constant and it must have at least 1 digit. The allowable range for integer
constants is -32768 to 32767. Truly speaking the range of an Integer constant depends upon the
compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit
compiler the range would be even greater. Mean by a 16-bit or a 32-bit compiler, what range of
an Integer constant has to do with the type of compiler.
It is categorized a integer constant and real constant. An integer constants are whole number
which have no decimal point. Types of integer constants are:
Decimal constant: 0-------9(base 10)
Octal constant: 0-------7(base 8)
Hexa decimal constant: 0----9, A------F(base 16)
In decimal constant first digit should not be zero unlike octal constant first digit must be zero(as
076, 0127) and in hexadecimal constant first two digit should be 0x/ 0X (such as 0x24, 0x87A).
By default type of integer constant is integer but if the value of integer constant is exceeds range
then value represented by integer type is taken to be unsigned integer or long integer. It can also
be explicitly mention integer and unsigned integer type by suffix l/L and u/U.
Real constant:
Downloaded from www.schoolnetwork.io

It is also called floating point constant. To construct real constant we must follow these rules:
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within a real constant. Ex.: +325.34
426.0
-32.76
To express small/large real constant exponent(scientific) form is used where number is written in
mantissa and exponent form separated by e/E. Exponent can be positive or negative integer but
mantissa can be real/integer type, for example 3.6*105=3.6e+5. By default type of floating point
constant is double, it can also be explicitly defined it by suffix of f/F.
Character Constant:
Character constant represented as a single character enclosed within a single quote. These can be
single digit, single special symbol or white spaces such as ‘9’,’c’,’$’, ‘ ’ etc. Every character
constant has a unique integer like value in machine’s character code as if machine using ASCII
(American standard code for information interchange). Some numeric value associated with each
upper and lower case alphabets and decimal integers are as:
A------------ Z ASCII value (65-90)
a-------------z ASCII value (97-122)
0-------------9 ASCII value (48-59)
; ASCII value (59)
String constant:
Set of characters are called string and when sequence of characters are enclosed within a double
quote (it may be combination of all kind of symbols) is a string constant. String constant has
zero, one or more than one character and at the end of the string null character(\0) is
automatically placed by compiler. Some examples are “,sarathina” , “908”, “3”,” ”, “A” etc. In C
although same characters are enclosed within single and double quotes it represents different
meaning such as “A” and ‘A’ are different because first one is string attached with null character
at the end but second one is character constant with its corresponding ASCII value is 65.
Symbolic constant:
Symbolic constant is a name that substitute for a sequence of characters and, characters may be
numeric, character or string constant.
Downloaded from www.schoolnetwork.io

Variables:
Variable is a data name which is used to store some data value or symbolic names for storing
program computations and results. The value of the variable can be change during the execution.
The rule for naming the variables is same as the naming identifier. Before used in the program it
must be declared. Declaration of variables specify its name, data types and range of the value
that variables can store depends upon its data types.
Variable initialization:
When we assign any initial value to variable during the declaration, is called initialization of
variables. When variable is declared but contain undefined value then it is called garbage value.
Expressions:
An expression is a combination of variables, constants, operators and function call. Expressions
consisting entirely of constant values are called constant expressions.
Operator:
This is a symbol use to perform some operation on variables, operands or with the constant.
Some operator required 2 operand to perform operation or some required single operation.
Several operators are there those are, arithmetic operator, assignment, increment, decrement,
logical, conditional, comma, size of , bitwise and others.
Arithmetic Operator:
This operator used for numeric calculation. These are of either Unary arithmetic operator, Binary
arithmetic operator. Where Unary arithmetic operator required only one operand such as +,-, ++,
--,!, tiled. And these operators are addition, subtraction, multiplication, division. Binary
arithmetic operator on other hand required two operand and its operators are +(addition), -
(subtraction), *(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c. Unary (+) and Unary (-) is
different from addition and subtraction. When both the operand are integer then it is called
integer arithmetic and the result is always integer. When both the operand are floating point then
it is called floating arithmetic and when operand is of integer and floating point then it is called
mix type or mixed mode arithmetic . And the result is in float type.
Assignment Operator:
A value can be stored in a variable with the use of assignment operator. The assignment
operator(=) is used in assignment statement and assignment expression. Operand on the left hand
side should be variable and the operand on the right hand side should be variable or constant or
any expression. When variable on the left hand side is occur on the right hand side then we can
avoid by writing the compound statement.
Increment and Decrement:
Downloaded from www.schoolnetwork.io

The Unary operator ++, --, is used as increment and decrement which acts upon single operand.
Increment operator increases the value of variable by one. Similarly decrement operator decrease
the value of the variable by one. And these operator can only used with the variable, but cann't
use with expression and constant as ++6.
It again categories into prefix post fix . In the prefix the value of the variable is incremented 1st,
then the new value is used, where as in postfix the operator is written after the operand (such as
m++, m--). Similarly in the postfix increment and decrement operator is used in the operation.
And then increment and decrement is perform.
Relational Operator:
It is use to compared value of two expressions depending on their relation. Expression that
contain relational operator is called relational expression. Here the value is assign according to
true or false value.
Conditional Operator:
It sometimes called as ternary operator. Since it required three expressions as operand and it is
represented as (? , :).
SYNTAX
exp1 ? exp2 :exp3
Here exp1 is first evaluated. It is true then value return will be exp2 . If false then exp3.
Comma Operator:
Comma operator is use to permit different expression to be appear in a situation where only one
expression would be used. All the expression are separator by comma and are evaluated from left
to right.
Sizeof Operator:
Size of operator is a Unary operator, which gives size of operand in terms of byte that occupied
in the memory. An operand may be variable, constant or data type qualifier. Generally it is used
make portable program(program that can be run on different machine) . It determines the length
of entities, arrays and structures when their size are not known to the programmer. It is also use
to allocate size of memory dynamically during execution of the program.
Bitwise Operator:
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are:
one's complement (~)
bitwise AND (&)
Downloaded from www.schoolnetwork.io

bitwise OR (|)
bitwise XOR (^)
left shift (<<)
right shift (>>)
These operator can operate on integer and character value but not on float and double. In bitwise
operator the function showbits( ) function is used to display the binary representation of any
integer or character value.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its value would
obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise AND the
logical AND.
It operate on 2operands and operands are compared on bit by bit basic. And hence both the
operands are of same type.
Logical or Boolean Operator:
Operator used with one or more operand and return either value zero (for false) or one (for true).
The operand may be constant, variables or expressions. And the expression that combines two or
more expressions is termed as logical expression.
C has three logical operators:
Operator Meaning
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical AND gives
result true if both the conditions are true, otherwise result is false. And logial OR gives result
false if both the condition false, otherwise result is true.
Downloaded from www.schoolnetwork.io
Downloaded from www.schoolnetwork.io
Downloaded from www.schoolnetwork.io 1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io 2

Introduction
• This chapter introduces
– Additional repetition control structures
• for
• do/while
– switch multiple selection structure
– break statement
• Used for exiting immediately and rapidly from certain control
structures
– continue statement
• Used for skipping the remainder of the body of a repetition
structure and proceeding with the next iteration of the loop
Downloaded from www.schoolnetwork.io 3

The Essentials of Repetition


• Loop
– Group of instructions computer executes repeatedly while
some condition remains true
• Counter-controlled repetition
– Definite repetition: know how many times loop will execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
Downloaded from www.schoolnetwork.io 4

Essentials of Counter-Controlled Repetition


• Counter-controlled repetition requires
– The name of a control variable (or loop counter)
– The initial value of the control variable
– A condition that tests for the final value of the control variable (i.e.,
whether looping should continue)
– An increment (or decrement) by which the control variable is
modified each time through the loop
Downloaded from www.schoolnetwork.io 5

Essentials of Counter-Controlled Repetition


• Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition
printf( "%d\n", counter );
++counter; // increment
}
– The statement
int counter = 1;
• Names counter
• Declares it to be an integer
• Reserves space for it in memory
• Sets it to an initial value of 1
Downloaded from www.schoolnetwork.io 6

The for Repetition Structure


• Format when using for loops
for ( initialization; loopContinuationTest; increment )
statement
• Example:
for( int counter = 1; counter <= 10; counter++ )
printf( "%d\n", counter );
No
– Prints the integers from one to ten semicolon
(;) after last
expression
Downloaded from www.schoolnetwork.io 7

The for Repetition Structure


• For loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest ) {
statement;
increment;
}

• Initialization and increment


– Can be comma-separated lists
– Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );
Downloaded from www.schoolnetwork.io 8

The for Structure: Notes and Observations


• Arithmetic expressions
– Initialization, loop-continuation, and increment can contain
arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
• Notes about the for structure:
– "Increment" may be negative (decrement)
– If the loop continuation condition is initially false
• The body of the for structure is not performed
• Control proceeds with the next statement after the for structure
– Control variable
• Often printed or used inside for body, but not necessary
Downloaded from www.schoolnetwork.io 9

Practice Exercise
One(1)

Download the Example source codes from http://snet.io/t397 to copy and paste easily.
1 /* Fig. 4.5:
Downloaded fromfig04_05.c
www.schoolnetwork.io 10
2 Summation with for */ Outline
3 #include <stdio.h>
4 1. Initialize variables
5 int main()
2. for repetition
6 { structure
7 int sum = 0, number;
8
9 for ( number = 2; number <= 100; number += 2 )
10 sum += number;
11
12 printf( "Sum is %d\n", sum );
13
14 return 0;
15 }

Sum is 2550 Program Output


Downloaded from www.schoolnetwork.io 11

The switch Multiple-Selection Structure


• switch
– Useful when a variable or expression is tested for all the
values it can assume and different actions are taken
• Format
– Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
– break; exits from structure
Downloaded from www.schoolnetwork.io 12

The switch Multiple-Selection Structure


• Flowchart of the switch structure

true
case a case a action(s) break

false

true
case b case b action(s) break
false

.
.
.

true
case z case z action(s) break
false

default action(s)
Downloaded from www.schoolnetwork.io 13

Practice Exercise
Two(2)
1 /* Fig. 4.7:
Downloaded fromfig04_07.c
www.schoolnetwork.io 14
2 Counting letter grades */ Outline
3 #include <stdio.h>
4
5 int main() 1. Initialize variables
6 {
7 int grade;
2. Input data
8 int aCount = 0, bCount = 0, cCount = 0,
9 dCount = 0, fCount = 0;
10 2.1 Use switch loop to
11 printf( "Enter the letter grades.\n" ); update count
12 printf( "Enter the EOF character to end input.\n" );
13
14 while ( ( grade = getchar() ) != EOF ) {
15
16 switch ( grade ) { /* switch nested in while */
17
18 case 'A': case 'a': /* grade was uppercase A */
19 ++aCount; /* or lowercase a */
20 break;
21
22 case 'B': case 'b': /* grade was uppercase B */
23 ++bCount; /* or lowercase b */
24 break;
25
26 case 'C': case 'c': /* grade was uppercase C */
27 ++cCount; /* or lowercase c */
28 break;
29
30 case 'D': case 'd': /* grade was uppercase D */
31 ++dCount; /* or lowercase d */
32 break;
33
Downloaded from www.schoolnetwork.io 15
34 case 'F': case 'f': /* grade was uppercase F */ Outline
35 ++fCount; /* or lowercase f */
36 break; 2.1 Use switch loop to
37 update count
38 case '\n': case' ': /* ignore these in input */
39 break; 3. Print results
40
41 default: /* catch all other characters */
42 printf( "Incorrect letter grade entered." );
43 printf( " Enter a new grade.\n" );
44 break;
45 }
46 }
47
48 printf( "\nTotals for each letter grade are:\n" );
49 printf( "A: %d\n", aCount );
50 printf( "B: %d\n", bCount );
51 printf( "C: %d\n", cCount );
52 printf( "D: %d\n", dCount );
53 printf( "F: %d\n", fCount );
54
55 return 0;
56 }
Downloaded from www.schoolnetwork.io 16
Enter the letter grades.
Outline
Enter the EOF character to end input.
A
B
Program Output
C
C
A
D
F
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
B

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1
Downloaded from www.schoolnetwork.io 17

The do/while Repetition Structure


• The do/while repetition structure
– Similar to the while structure
– Condition for repetition tested after the body of the loop is
performed
• All actions are performed at least once
– Format:
do {
statement;
} while ( condition );
Downloaded from www.schoolnetwork.io 18

The do/while Repetition Structure


• Example (letting counter = 1):
do {
printf( "%d ", counter );
} while (++counter <= 10);
– Prints the integers from 1 to 10
Downloaded from www.schoolnetwork.io 19

The do/while Repetition Structure


• Flowchart of the do/while repetition structure

action(s)

true
condition

false
Downloaded from www.schoolnetwork.io 20

Practice Exercise
Three(3)
1 /* Fig. 4.9:
Downloaded fromfig04_09.c
www.schoolnetwork.io 21
2 Using the do/while repetition structure */
Outline
3 #include <stdio.h>
1. Initialize variable
4

5 int main() 2. Loop


6 {

7 int counter = 1; 3. Print


8

9 do {

10 printf( "%d ", counter );

11 } while ( ++counter <= 10 );

12

13 return 0;

14 }

1 2 3 4 5 6 7 8 9 10 Program Output
Downloaded from www.schoolnetwork.io 22

The break and continue Statements


• break
– Causes immediate exit from a while, for, do/while or
switch structure
– Program execution continues with the first statement after
the structure
– Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch structure
Downloaded from www.schoolnetwork.io 23

The break and continue Statements


• continue
– Skips the remaining statements in the body of a while,
for or do/while structure
• Proceeds with the next iteration of the loop
– while and do/while
• Loop-continuation test is evaluated immediately after the
continue statement is executed
– for
• Increment expression is executed, then the loop-continuation
test is evaluated
Downloaded from www.schoolnetwork.io 24

Practice Exercise
Four(4)
1 /* Fig. 4.12:
Downloaded fig04_12.c
from www.schoolnetwork.io 25
2 Using the continue statement in a for structure */ Outline
3 #include <stdio.h>
4 1. Initialize variable
5 int main()
6 {
2. Loop
7 int x;
8
9 for ( x = 1; x <= 10; x++ ) { 3. Print
10
11 if ( x == 5 )
12 continue; /* skip remaining code in loop only
13 if x == 5 */
14
15 printf( "%d ", x );
16 }
17
18 printf( "\nUsed continue to skip printing the value 5\n" );
19 return 0;
20 }

1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
Program Output
Downloaded from www.schoolnetwork.io 26

Logical Operators
• && ( logical AND )
– Returns true if both conditions are true
• || ( logical OR )
– Returns true if either of its conditions are true
• ! ( logical NOT, logical negation )
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
• Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
Downloaded from www.schoolnetwork.io 27
Confusing Equality (==) and Assignment (=)
Operators
• Dangerous error
– Does not ordinarily cause syntax errors
– Any expression that produces a value can be used in control
structures
– Nonzero values are true, zero values are false
– Example using ==:
if ( payCode == 4 )
printf( "You get a bonus!\n" );
• Checks paycode, if it is 4 then a bonus is awarded
Downloaded from www.schoolnetwork.io 28
Confusing Equality (==) and Assignment (=)
Operators
– Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
• This sets paycode to 4
• 4 is nonzero, so expression is true, and bonus awarded no
matter what the paycode was
– Logic error, not a syntax error
Downloaded from www.schoolnetwork.io 29
Confusing Equality (==) and Assignment (=)
Operators
• lvalues
– Expressions that can appear on the left side of an equation
– Their values can be changed, such as variable names
• x = 4;
• rvalues
– Expressions that can only appear on the right side of an
equation
– Constants, such as numbers
• Cannot write 4 = x;
• Must write x = 4;
– lvalues can be used as rvalues, but not vice versa
• y = x;
Downloaded from www.schoolnetwork.io 30

Structured-Programming Summary
• Structured programming
– Easier than unstructured programs to understand, test,
debug and, modify programs
• Rules for structured programming
– Rules developed by programming community
– Only single-entry/single-exit control structures are used
– Rules:
1. Begin with the “simplest flowchart”
2. Any rectangle (action) can be replaced by two rectangles
(actions) in sequence
3. Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while,
do/while or for)
4. Rules 2 and 3 can be applied in any order and multiple times
Downloaded from www.schoolnetwork.io 31

Structured-Programming Summary

Rule 2 - Any rectangle can be


Rule 1 - Begin with the
replaced by two rectangles in
simplest flowchart
sequence

Rule 2 Rule 2 Rule 2

.
.
.
Downloaded from www.schoolnetwork.io 32

Structured-Programming Summary
Rule 3 - Replace any rectangle with a control structure

Rule 3

Rule 3
Rule 3
Downloaded from www.schoolnetwork.io 33

Structured-Programming Summary
• All programs can be broken down into 3 controls
– Sequence – handled automatically by compiler
– Selection – if, if/else or switch
– Repetition – while, do/while or for
• Can only be combined in two ways
– Nesting (rule 3)
– Stacking (rule 2)
– Any selection can be rewritten as an if statement, and any
repetition can be rewritten as a while statement
1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded from www.schoolnetwork.io
Introduction
• Divide and conquer
– Construct a program from smaller pieces or components
• These smaller pieces are called modules
– Each piece more manageable than the original program

Downloaded from www.schoolnetwork.io


Program Modules in C
• Functions
– Modules in C
– Programs combine user-defined functions with library functions
• C standard library has a wide variety of functions
• Function calls
– Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
– Function call analogy:
• Boss asks worker to complete task
– Worker gets information, does task, returns result
– Information hiding: boss does not know details

Downloaded from www.schoolnetwork.io


Math Library Functions
• Math library functions
– perform common mathematical calculations
– #include <math.h>
• Format for calling functions
– FunctionName( argument );
• If multiple arguments, use comma-separated list
– printf( "%.2f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of its
argument
• All math functions return data type double
– Arguments may be constants, variables, or expressions

Downloaded from www.schoolnetwork.io


Functions
• Functions
– Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition

Downloaded from www.schoolnetwork.io


Function Definitions
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter unless, the
parameter is of type int

Downloaded from www.schoolnetwork.io


Function Definitions
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;

Downloaded from www.schoolnetwork.io


8

Practice Exercise
One(1)

Downloaded from www.schoolnetwork.io


1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */ Outline
3 #include <stdio.h>
4
5 int maximum( int, int, int ); /* function prototype */ 1. Function prototype
6 (3 parameters)
7 int main()
8 {
9 int a, b, c; 2. Input values
10
11 printf( "Enter three integers: " );
12 scanf( "%d%d%d", &a, &b, &c ); 2.1 Call function
13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
14
15 return 0; 3. Function definition
16 }
17
18 /* Function maximum definition */
19 int maximum( int x, int y, int z )
20 {
21 int max = x;
22
23 if ( y > max )
24 max = y;
25
26 if ( z > max )
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17
Maximum is: 85 Program Output
Downloaded from www.schoolnetwork.io
Function Prototypes
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after use
in program
– The function with the prototype
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors

Downloaded from www.schoolnetwork.io


Header Files
• Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions

Downloaded from www.schoolnetwork.io


Calling Functions: Call by Value and Call by
Reference
• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• For now, we focus on call by value

Downloaded from www.schoolnetwork.io


Random Number Generation
• rand function
– Load <stdlib.h>
– Returns "random" number between 0 and RAND_MAX (at
least 32767)
i = rand();
– Pseudorandom
• Preset sequence of "random" numbers
• Same sequence for every function call
• Scaling
– To get a random number between 1 and n
1 + ( rand() % n )
• rand() % n returns a number between 0 and n - 1
• Add 1 to make random number between 1 and n
1 + ( rand() % 6)
– number between 1 and 6
Downloaded from www.schoolnetwork.io
Random Number Generation
• srand function
– <stdlib.h>
– Takes an integer seed and jumps to that location in its
"random" sequence
srand( seed );
– srand( time( NULL ) ); //load <time.h>
• time( NULL )
– Returns the time at which the program was compiled in
seconds
– “Randomizes" the seed

Downloaded from www.schoolnetwork.io


15

Practice Exercise
Two(2)

Downloaded from www.schoolnetwork.io


1 /* Fig. 5.9: fig05_09.c
2 Randomizing die-rolling program */ Outline
3 #include <stdlib.h>
4 #include <stdio.h> 1. Initialize seed
5
6 int main() 2. Input value for seed
7 {
8 int i; 2.1 Use srand to
9 unsigned seed; change random
10
sequence
11 printf( "Enter seed: " );
12 scanf( "%u", &seed ); 2.2 Define Loop
13 srand( seed );
14 3. Generate and
15 for ( i = 1; i <= 10; i++ ) {
output random
numbers
16 printf( "%10d", 1 + ( rand() % 6 ) );
17
18 if ( i % 5 == 0 )
19 printf( "\n" );
20 }
21
22 return 0;
23 }

Downloaded from www.schoolnetwork.io


Enter seed: 67
6 1 4 6 2
Outline
1 6 1 6 4
Program Output
Enter seed: 867
2 4 6 1 6
1 1 3 6 2

Enter seed: 67
6 1 4 6 2
1 6 1 6 4

Downloaded from www.schoolnetwork.io


18

Practice Exercise
Three(3)

Downloaded from www.schoolnetwork.io


Example: A Game of Chance
• Craps simulator
• Rules
– Roll two dice
• 7 or 11 on first throw, player wins
• 2, 3, or 12 on first throw, player loses
• 4, 5, 6, 8, 9, 10 - value becomes player's "point"
– Player must roll his point before rolling 7 to win

Downloaded from www.schoolnetwork.io


1 /* Fig. 5.10: fig05_10.c
2 Craps */ Outline
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <time.h> 1. rollDice
6 prototype
7 int rollDice( void );
8
1.1 Initialize variables
9 int main()
10 {
11 int gameStatus, sum, myPoint; 1.2 Seed srand
12
13 srand( time( NULL ) );
14 sum = rollDice(); /* first roll of the dice */ 2. Define switch
15 statement for
16 switch ( sum ) { win/loss/continue
17 case 7: case 11: /* win on first roll */
18 gameStatus = 1;
19 break; 2.1 Loop
20 case 2: case 3: case 12: /* lose on first roll */
21 gameStatus = 2;
22 break;
23 default: /* remember point */
24 gameStatus = 0;
25 myPoint = sum;
26 printf( "Point is %d\n", myPoint );
27 break;
28 }
29
30 while ( gameStatus == 0 ) { /* keep rolling */
31 sum = rollDice();
Downloaded
32 from www.schoolnetwork.io
33 if ( sum == myPoint ) /* win by making point */
34 gameStatus = 1; Outline
35 else
36 if ( sum == 7 ) /* lose by rolling 7 */
2.2 Print win/loss
37 gameStatus = 2;
38 }
39
40 if ( gameStatus == 1 )
41 printf( "Player wins\n" );
42 else
43 printf( "Player loses\n" );
44
45 return 0;
46 }
47
48 int rollDice( void )
49 {
50 int die1, die2, workSum;
51
52 die1 = 1 + ( rand() % 6 );
53 die2 = 1 + ( rand() % 6 );
54 workSum = die1 + die2;
55 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum );
56 return workSum;
57 }
Player rolled 6 + 5 = 11
Player wins Program Output

Downloaded from www.schoolnetwork.io


Player rolled 6 + 6 = 12
Player loses
Outline
Player rolled 4 + 6 = 10
Point is 10 Program Output
Player rolled 2 + 4 = 6
Player rolled 6 + 5 = 11
Player rolled 3 + 3 = 6
Player rolled 6 + 4 = 10
Player wins

Player rolled 1 + 3 = 4
Point is 4
Player rolled 1 + 4 = 5
Player rolled 5 + 4 = 9
Player rolled 4 + 6 = 10
Player rolled 6 + 3 = 9
Player rolled 1 + 2 = 3
Player rolled 5 + 2 = 7
Player loses

Downloaded from www.schoolnetwork.io


Storage Classes
• Storage class specifiers
– Storage duration – how long an object exists in memory
– Scope – where object can be referenced in program
– Linkage – specifies the files in which an identifier is known
(more in Chapter 14)
• Automatic storage
– Object created and destroyed within its block
– auto: default for local variables
auto double x, y;
– register: tries to put variable into high-speed registers
• Can only be used for automatic variables
register int counter = 1;

Downloaded from www.schoolnetwork.io


Storage Classes
• Static storage
– Variables exist for entire program execution
– Default value of zero
– static: local variables defined in functions.
• Keep value after function ends
• Only known in their own function
– extern: default for global variables and functions
• Known in any function

Downloaded from www.schoolnetwork.io


Scope Rules
• File scope
– Identifier defined outside function, known in all functions
– Used for global variables, function definitions, function
prototypes
• Function scope
– Can only be referenced inside a function body
– Used only for labels (start:, case: , etc.)

Downloaded from www.schoolnetwork.io


Scope Rules
• Block scope
– Identifier declared inside a block
• Block scope begins at declaration, ends at right brace
– Used for variables, function parameters (local variables of
function)
– Outer blocks "hidden" from inner blocks if there is a variable
with the same name in the inner block
• Function prototype scope
– Used for identifiers in parameter list

Downloaded from www.schoolnetwork.io


27

Practice Exercise
Four(4)

Downloaded from www.schoolnetwork.io


1 /* Fig. 5.12: fig05_12.c
2 A scoping example */ Outline
3 #include <stdio.h>
4
5 void a( void ); /* function prototype */ 1. Function prototypes
6 void b( void ); /* function prototype */
7 void c( void ); /* function prototype */
1.1 Initialize global
8
variable
9 int x = 1; /* global variable */
10
11 int main() 1.2 Initialize local
12 { variable
13 int x = 5; /* local variable to main */
14
15 printf("local x in outer scope of main is %d\n", x ); 1.3 Initialize local
16 variable in block
17 { /* start new scope */
18 int x = 7;
19
2. Call functions
20 printf( "local x in inner scope of main is %d\n", x );
21 } /* end new scope */ 3. Output results
22
23 printf( "local x in outer scope of main is %d\n", x );
24
25 a(); /* a has automatic local x */
26 b(); /* b has static local x */
27 c(); /* c uses global x */
28 a(); /* a reinitializes automatic local x */
29 b(); /* static local x retains its previous value */
30 c(); /* global x also retains its value */
Downloaded from www.schoolnetwork.io
31
32 printf( "local x in main is %d\n", x ); Outline
33 return 0;
34 }
35
3.1 Function
36 void a( void ) definitions
37 {
38 int x = 25; /* initialized each time a is called */
39
40 printf( "\nlocal x in a is %d after entering a\n", x );
41 ++x;
42 printf( "local x in a is %d before exiting a\n", x );
43 }
44
45 void b( void )
46 {
47 static int x = 50; /* static initialization only */
48 /* first time b is called */
49 printf( "\nlocal static x is %d on entering b\n", x );
50 ++x;
51 printf( "local static x is %d on exiting b\n", x );
52 }
53
54 void c( void )
55 {
56 printf( "\nglobal x is %d on entering c\n", x );
57 x *= 10;
58 printf( "global x is %d on exiting c\n", x );
59 }
Downloaded from www.schoolnetwork.io
local x in outer scope of main is 5
Outline
local x in inner scope of main is 7
local x in outer scope of main is 5
Program Output
local x in a is 25 after entering a
local x in a is 26 before exiting a

local static x is 50 on entering b


local static x is 51 on exiting b

global x is 1 on entering c
global x is 10 on exiting c

local x in a is 25 after entering a


local x in a is 26 before exiting a

local static x is 51 on entering b


local static x is 52 on exiting b

global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5

Downloaded from www.schoolnetwork.io


Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step)
to solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem

Downloaded from www.schoolnetwork.io


Recursion
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;

Downloaded from www.schoolnetwork.io


Example Using Recursion: The Fibonacci
Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibaonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}

Downloaded from www.schoolnetwork.io


Example Using Recursion: The Fibonacci
Series
• Set of recursive calls to function fibonacci
f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

Downloaded from www.schoolnetwork.io


35

Practice Exercise
Five(5)

Downloaded from www.schoolnetwork.io


1 /* Fig. 5.15: fig05_15.c
2 Recursive fibonacci function */ Outline
3 #include <stdio.h>
4
5 long fibonacci( long ); 1. Function prototype
6
7 int main() 1.1 Initialize variables
8 {
9 long result, number;
10 2. Input an integer
11 printf( "Enter an integer: " );
12 scanf( "%ld", &number );
13 result = fibonacci( number );
2.1 Call function
14 printf( "Fibonacci( %ld ) = %ld\n", number, result );
fibonacci
15 return 0;
16 } 2.2 Output results.
17
18 /* Recursive definition of function fibonacci */
19 long fibonacci( long n ) 3. Define fibonacci
20 { recursively
21 if ( n == 0 || n == 1 )
22 return n;
23 else
24 return fibonacci( n - 1 ) + fibonacci( n - 2 );
25 }
Enter an integer: 0
Fibonacci(0) = 0 Program Output

Enter an integer: 1
Fibonacci(1) = 1

Downloaded from www.schoolnetwork.io


Enter an integer: 2
Fibonacci(2) = 1
Outline
Enter an integer: 3
Fibonacci(3) = 2
Program Output
Enter an integer: 4
Fibonacci(4) = 3

Enter an integer: 5
Fibonacci(5) = 5

Enter an integer: 6
Fibonacci(6) = 8

Enter an integer: 10
Fibonacci(10) = 55

Enter an integer: 20
Fibonacci(20) = 6765

Enter an integer: 30
Fibonacci(30) = 832040

Enter an integer: 35
Fibonacci(35) = 9227465

Downloaded from www.schoolnetwork.io


Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good software
engineering (recursion)

Downloaded from www.schoolnetwork.io


COMPUTER
PROGRAMMING II
ELE 276
DEFINITIONS OF USEFUL
TERMS AND CONCEPTS
FOR LECTURE FIVE (5)
This lecture material and
other distributed materials
for this ELE276 course are
not for sale.

Downloaded from www.schoolnetwork.io


Function:
A function is a self-contained block of codes or sub programs with a set of statements that
perform some specific task or coherent task when it is called. Any ‘C’ program contain at least
one function i.e., main().
There are basically two types of function these are:
1. Library function
2. User-defined function
The user-defined functions are defined by the user according to its requirement while system
defined function can’t be modified, it can only read and can be used.
These function are supplied with every C compiler.
Source of these library function are pre-complied and only object code get used by the user by
linking to the code by linker.
System defined function features:
Function definition: predefined, precompiled, stored in the library
Function declaration: In header file with or function prototype.
Function call: By the programmer
User defined function features:
Syntax:-
Return-type name-of-function (type 1 arg 1, type2 arg2, type3 arg3)
So when user gets his own function he has to know three things, these are:
Function declaration
Function definition
Function call
These three things are represented like:
int function(int, int, int); /*function declaration*/
main() /* calling function*/
{
function(arg1,arg2,arg3);
}

Downloaded from www.schoolnetwork.io


int function(type 1 arg 1,type2 arg2,type3, arg3) /*function definition/*
{
Local variable declaration;
Statement;
Return value;
}
Function declaration:-
Function declaration is also known as function prototype. It inform the compiler about three
thing, those are name of the function, number and type of argument received by the function and
the type of value returned by the function.
While declaring the name of the argument is optional and the function prototype always
terminated by the semicolon.
Function definition:-
Function definition consists of the whole description and code of the function. It tells about what
function is doing what are its inputs and what its output are. It consists of two parts function
header and function body.
Syntax:-
return type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
Return value
}
The return type denotes the type of the value that function will return and it is optional and if it is
omitted, it is assumed to be int by default. The body of the function is the compound statements
or block which consists of local variable declaration statement and optional return statement. The
local variable declared inside a function is local to that function only. It can’t be used anywhere
in the program and its existence is only within this function. The arguments of the function
definition are known as formal arguments.

Downloaded from www.schoolnetwork.io


Function Call:
When the function get called by the calling function then that is called, function call. The
compiler execute these functions when the semicolon is followed by the function name.
Example:-
function(arg1,arg2,arg3);
The argument that are used inside the function call are called actual argument
Ex:-
int S=sum(a, b); //actual arguments
Actual argument:
The arguments which are mentioned or used inside the function call is knows as actual argument
and these are the original values and copy of these are actually sent to the called function. It can
be written as constant, expression or any function call like:
Function (x);
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));
Formal Arguments:
The arguments which are mentioned in function definition are called formal arguments or
dummy arguments. These arguments are used to just hold the copied of the values that are sent
by the calling function through the function call. These arguments are like other local variables
which are created when the function call starts and destroyed when the function ends. The basic
difference between the formal argument and the actual argument are:
1) The formal argument are declared inside the parenthesis whereas the local variable declared at
the beginning of the function block.
2). The formal argument are automatically initialized when the copy of actual arguments are
passed while other local variable are assigned values through the statements.
Order number and type of actual arguments in the function call should be match with the order
number and type of the formal arguments.
Return type:
It is used to return value to the calling function. It can be used in two way as:
return
Or return(expression);

Downloaded from www.schoolnetwork.io


Ex:-
return (a);
return (a*b);
return (a*b+c);
Here the 1st return statement used to terminate the function without returning any value
Ex:- /*summation of two values*/
int sum (int a1, int a2);
main()
{
int a,b;
printf(“enter two no”);
scanf(“%d%d”,&a,&b);
int S=sum(a,b);
printf(“summation is = %d”,s);
}
int sum(intx1,int y1)
{
int z=x1+y1;
Return z;
}
Advantage of functions:
By using function large and difficult program can be divided in to subprograms and solved.
When we want to perform some task repeatedly or some code is to be used more than once at
different place in the program, then function avoids this repetition or rewritten over and over.
Due to reducing size, modular function it is easy to modify and test.
Summary:-
C program is a collection of one or more function.
A function is get called when function is followed by the semicolon.
A function is defined when a function name followed by a pair of curly braces

Downloaded from www.schoolnetwork.io


Any function can be called by another function even main() can be called by other function.
main()
{
function1()
}
function1()
{
Statement;
function2;
}
function 2()
{
}
So every function in a program must be called directly or indirectly by the main() function. A
function can be called any number of times.
A function can call itself again and again and this process is called recursion.
A function can be called from other function but a function can’t be defined in another function
Category of Function based on argument and return type:
i) Function with no argument & no return value
Function that have no argument and no return value is written as:-
void function(void);
main()
{
void function()
{
Statement;
}
Example:-
void me();

Downloaded from www.schoolnetwork.io


main()
{
me();
printf(“in main”);
}
void me()
{
printf(“come on”);
}
Output: come on
in main
ii) Function with no argument but return value
Syntax:-
int fun(void);
main()
{
int r;
r=fun();
}
int fun()
{
reurn(exp);
}
Example:-
int sum();
main()
{
int b=sum();

Downloaded from www.schoolnetwork.io


printf(“entered %d\n, b”);
}
int sum()
{
int a,b,s;
s=a+b;
return s;
}
Here called function is independent and are initialized. The values aren’t passed by the calling
function .Here the calling function and called function are communicated partly with each other.
iii ) function with argument but no return value
Here the function have argument so the calling function send data to the called function but
called function doesn’t return value.
Syntax:-
void fun (int,int);
main()
{
int (a,b);
}
void fun(int x, int y);
{
Statement;
}
Here the result obtained by the called function.
iv) function with argument and return value
Here the calling function has the argument to pass to the called function and the called function
returned value to the calling function.
Syntax:-
fun(int,int);

Downloaded from www.schoolnetwork.io


main()
{
int r=fun(a,b);
}
int fun(intx,inty)
{
return(exp);
}
Example:
main()
{
int fun(int);
int a,num;
printf(“enter value:\n”);
scanf(“%d”,&a)
int num=fun(a);
}
int fun(int x)
{
++x;
return x;
}
Call by value and call by reference:
There are two way through which we can pass the arguments to the function such as call by
value and call by reference.
1. Call by value
In the call by value copy of the actual argument is passed to the formal argument and the
operation is done on formal argument. When the function is called by ‘call by value’ method, it
doesn’t affect content of the actual argument. Changes made to formal argument are local to
block of called function so when the control back to calling function the changes made is vanish.

Downloaded from www.schoolnetwork.io


Example:-
main()
{
int x,y;
change(int,int);
printf(“enter two values:\n”);
scanf(“%d%d”,&x,&y);
change(x ,y);
printf(“value of x=%d and y=%d\n”,x ,y);
}
change(int a,int b);
{
int k;
k=a;
a=b;
b=k;
}
Output: enter two values: 12
23
Value of x=12 and y=23
2. Call by reference
Instead of passing the value of variable, address or reference is passed and the function operate
on address of the variable rather than value. Here formal argument is alter to the actual argument,
it means formal arguments calls the actual arguments.
Example:-
void main()
{
int a,b;
change(int *,int*);

Downloaded from www.schoolnetwork.io


printf(“enter two values:\n”);
scanf(“%d%d”,&a,&b);
change(&a,&b);
printf(“after changing two value of a=%d and b=%d\n:”a,b);
}
change(int *a, int *b)
{
int k;
k=*a;
*a=*b;
*b= k;
printf(“value in this function a=%d and b=%d\n”,*a,*b);
}
Output: enter two values: 12
32
Value in this function a=32 and b=12
After changing two value of a=32 and b=12
So here instead of passing value of the variable, directly passing address of the variables. Formal
argument directly access the value and swapping is possible even after calling a function.

Downloaded from www.schoolnetwork.io


1

ELE 276
• This lecture material and other distributed materials for this ELE276
course are not for sale.
• This lecture material is largely based on the programming text “C
How To Program” by Paul Deitel and Harvey Deitel.
• This lecture material is by no means a substitute for the
aforementioned programming text which students of this ELE276
course are advised to get a copy at the University Library, University
e-Library or University Resource Center.
• Students are also advised to get their system installed with C/C++
compiler for hands-on/practical programming exercises. You may
check (http://www.stroustrup.com/compilers.html) for suitable
compilers.
• For additional technical details, students are advised to consult the C
Standard Documentation or you may check
(http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html).
Downloaded for FREE at www.schoolnetwork.io
2

Introduction
• Arrays
– Structures of related data items
– Static entity – same size throughout program
– Dynamic data structures discussed in Chapter 12

Downloaded for FREE at www.schoolnetwork.io


3
Name of array
Arrays (Note that all
elements of this
• Array array have the
same name, c)
– Group of consecutive memory locations
– Same name and type c[0] -45
c[1] 6
• To refer to an element, specify c[2] 0
c[3] 72
– Array name c[4] 1543
– Position number c[5] -89
c[6] 0
• Format: c[7] 62

arrayname[ position number ] c[8] -3


c[9] 1
– First element at position 0 c[10] 6453
– n element array named c: c[11] 78

• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number
of the element
within array c
Downloaded for FREE at www.schoolnetwork.io
4

Arrays
• Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
– Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Downloaded for FREE at www.schoolnetwork.io


5

Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];

• Declaring multiple arrays of same type


– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];

Downloaded for FREE at www.schoolnetwork.io


6

Examples Using Arrays


• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced syntax error
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array

Downloaded for FREE at www.schoolnetwork.io


7

Practice Exercise
One(1)

Downloaded for FREE at www.schoolnetwork.io


1 /* Fig. 6.8: fig06_08.c 8
2 Histogram printing program */ Outline
3 #include <stdio.h>
4 #define SIZE 10
5
1. Initialize array
6 int main()
7 { 2. Loop
8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
9 int i, j;
10 3. Print
11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
12
13 for ( i = 0; i <= SIZE - 1; i++ ) {
14 printf( "%7d%13d ", i, n[ i ]) ;
15
16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */
17 printf( "%c", '*' );
18
19 printf( "\n" );
20 }
21
22 return 0;
23 }

Downloaded for FREE at www.schoolnetwork.io


9
Element Value Histogram
Outline
0 19 *******************
1 3 ***
2 15 ***************
Program Output
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *

Downloaded for FREE at www.schoolnetwork.io


10

Examples Using Arrays


• Character arrays
– String “first” is really a static array of characters
– Character arrays can be initialized using string literals
char string1[] = "first";
• Null character '\0' terminates strings
• string1 actually has 6 elements
– It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
– Can access individual characters
string1[ 3 ] is character ‘s’
– Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );
• Reads characters until whitespace encountered
• Can write beyond end of array, be careful

Downloaded for FREE at www.schoolnetwork.io


11

Practice Exercise
Two(2)

Downloaded for FREE at www.schoolnetwork.io


1 /* Fig. 6.10: fig06_10.c 12
2 Treating character arrays as strings */ Outline
3 #include <stdio.h>
4 1. Initialize strings
5 int main()
6 {
2. Print strings
7 char string1[ 20 ], string2[] = "string literal";
8 int i;
2.1 Define loop
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 ); 2.2 Print characters
12 printf( "string1 is: %s\nstring2: is %s\n" individually
13 "string1 with spaces between characters is:\n",
14 string1, string2 ); 2.3 Input string
15
16 for ( i = 0; string1[ i ] != '\0'; i++ ) 3. Print string
17 printf( "%c ", string1[ i ] );
18
19 printf( "\n" );
20 return 0;
21 }
Enter a string: Hello there
string1 is: Hello Program Output
string2 is: string literal
string1 with spaces between characters is:
H e l l o

Downloaded for FREE at www.schoolnetwork.io


13

Passing Arrays to Functions


• Passing arrays
– To pass an array argument to a function, specify the name of
the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
• Array size usually passed to function
– Arrays passed call-by-reference
– Name of array is address of first element
– Function knows where the array is stored
• Modifies original memory locations
• Passing array elements
– Passed by call-by-value
– Pass subscripted name (i.e., myArray[ 3 ]) to function

Downloaded for FREE at www.schoolnetwork.io


14

Passing Arrays to Functions


• Function prototype
void modifyArray( int b[], int arraySize );
– Parameter names optional in prototype
• int b[] could be written int []
• int arraySize could be simply int

Downloaded for FREE at www.schoolnetwork.io


15

Practice Exercise
Three(3)

Downloaded for FREE at www.schoolnetwork.io


1 /* Fig. 6.13: fig06_13.c 16
2 Passing arrays and individual array elements to functions */ Outline
3 #include <stdio.h>
4 #define SIZE 5
5 1. Function definitions
6 void modifyArray( int [], int ); /* appears strange */
7 void modifyElement( int );
8
2. Pass array to a
9 int main() function
10 {
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;
2.1 Pass array element
12
13 printf( "Effects of passing entire array call "
to a function
14 "by reference:\n\nThe values of the "
15 "original array are:\n" ); 3. Print
16
17 for ( i = 0; i <= SIZE - 1; i++ )
Entire arrays passed call-by-
18 printf( "%3d", a[ i ] ); reference, and can be modified
19
20 printf( "\n" );
21 modifyArray( a, SIZE ); /* passed call by reference */
22 printf( "The values of the modified array are:\n" );
23
24 for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-by-
25 printf( "%3d", a[ i ] ); value, and cannot be modified
26
27 printf( "\n\n\nEffects of passing array element call "
28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );
29 modifyElement( a[ 3 ] );
30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
31 return 0;
Downloaded
32 } for FREE at www.schoolnetwork.io
33 17
34 void modifyArray( int b[], int size ) Outline
35 {
36 int j; 3.1 Function
37
definitions
38 for ( j = 0; j <= size - 1; j++ )
39 b[ j ] *= 2;
40 }
41
42 void modifyElement( int e )
43 {
44 printf( "Value in modifyElement is %d\n", e *= 2 );
45 }

Effects of passing entire array call by reference:

The values of the original array are:


0 1 2 3 4 Program Output
The values of the modified array are:
0 2 4 6 8

Effects of passing array element call by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[3] is 6

Downloaded for FREE at www.schoolnetwork.io


18

Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical ), no change
• If decreasing order, elements exchanged
– Repeat
• Example:
– original: 3 4 2 6 7
– pass 1: 3 2 4 6 7
– pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Downloaded for FREE at www.schoolnetwork.io
19
Case Study: Computing Mean, Median and
Mode Using Arrays
• Mean – average
• Median – number in middle of sorted list
– 1, 2, 3, 4, 5
– 3 is the median
• Mode – number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5
– 1 is the mode

Downloaded for FREE at www.schoolnetwork.io


20

Practice Exercise
Four(4)

Downloaded for FREE at www.schoolnetwork.io


1 /* Fig. 6.16: fig06_16.c 21
2 This program introduces the topic of survey data analysis. Outline
3 It computes the mean, median, and mode of the data */
4 #include <stdio.h>
5 #define SIZE 99 1. Function prototypes
6
7 void mean( const int [] );
8 void median( int [] );
1.1 Initialize array
9 void mode( int [], const int [] ) ;
10 void bubbleSort( int [] ); 2. Call functions mean,
11 void printArray( const int [] );
median, and mode
12
13 int main()
14 {
15 int frequency[ 10 ] = { 0 };
16 int response[ SIZE ] =
17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
26 4, 5, 6, 1, 6, 5, 7, 8, 7 };
27
28 mean( response );
29 median( response );
30 mode( frequency, response );
31 return 0;
Downloaded
32 } for FREE at www.schoolnetwork.io
33 22
34 void mean( const int answer[] ) Outline
35 {
36 int j, total = 0;
37 3. Define function
38 printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); mean
39
40 for ( j = 0; j <= SIZE - 1; j++ )
41 total += answer[ j ]; 3.1 Define function
42 median
43 printf( "The mean is the average value of the data\n"
44 "items. The mean is equal to the total of\n"
45 "all the data items divided by the number\n"
3.1.1 Sort Array
46 "of data items ( %d ). The mean value for\n"
47 "this run is: %d / %d = %.4f\n\n", 3.1.2 Print middle
48 SIZE, total, SIZE, ( double ) total / SIZE );
element
49 }
50
51 void median( int answer[] )
52 {
53 printf( "\n%s\n%s\n%s\n%s",
54 "********", " Median", "********",
55 "The unsorted array of responses is" );
56
57 printArray( answer );
58 bubbleSort( answer );
59 printf( "\n\nThe sorted array is" );
60 printArray( answer );
61 printf( "\n\nThe median is element %d of\n"
62 "the sorted %d element array.\n"
63 "For this run the median is %d\n\n",
Downloaded
64 for FREE
SIZE at
/ www.schoolnetwork.io
2, SIZE, answer[ SIZE / 2 ] );
65 } 23
66 Outline
67 void mode( int freq[], const int answer[] )
68 {
69 int rating, j, h, largest = 0, modeValue = 0;
3.2 Define function
70
mode
71 printf( "\n%s\n%s\n%s\n", 3.2.1 Increase
72 "********", " Mode", "********" ); frequency[]
73
depending on
74 for ( rating = 1; rating <= 9; rating++ )
response[]
75 freq[ rating ] = 0;
76 Notice how the subscript in
77 for ( j = 0; j <= SIZE - 1; j++ ) frequency[] is the value of an
78 ++freq[ answer[ j ] ]; element in response[]
79 (answer[])
80 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
81 "Response", "Frequency", "Histogram",
82 "1 1 2 2", "5 0 5 0 5" );
83
84 for ( rating = 1; rating <= 9; rating++ ) {
85 printf( "%8d%11d ", rating, freq[ rating ] );
86
87 if ( freq[ rating ] > largest ) {
88 largest = freq[ rating ];
89 modeValue = rating;
90 }
91 Print stars depending on value of
92 for ( h = 1; h <= freq[ rating ]; h++ ) frequency[]
93 printf( "*" );
94
Downloaded for FREE at www.schoolnetwork.io
95 printf( "\n" ); 24
96 } Outline
97
98 printf( "The mode is the most frequent value.\n"
99 "For this run the mode is %d which occurred" 3.3 Define bubbleSort
100 " %d times.\n", modeValue, largest );
101 } 3.3 Define printArray
102
103 void bubbleSort( int a[] )
104 {
105 int pass, j, hold;
106
107 for ( pass = 1; pass <= SIZE - 1; pass++ )
108
109 for ( j = 0; j <= SIZE - 2; j++ )
110
111 if ( a[ j ] > a[ j + 1 ] ) {
112 hold = a[ j ];
113 a[ j ] = a[ j + 1 ]; Bubble sort: if elements out of order,
114 a[ j + 1 ] = hold; swap them.
115 }
116 }
117
118 void printArray( const int a[] )
119 {
120 int j;
121
122 for ( j = 0; j <= SIZE - 1; j++ ) {
123
124 if ( j % 20 == 0 )
125
Downloaded forprintf(
FREE at"\n" );
www.schoolnetwork.io
126 25
127 printf( "%2d", a[ j ] ); Outline
128 }
129 }
Program Output
********
Mean
********
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788

********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

The sorted array is


1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

The median is element 49 of


the sorted 99 element array.
For this run the median is 7

Downloaded for FREE at www.schoolnetwork.io


26
********
Mode
Outline
********
Response Frequency Histogram
Program Output
1 1 2 2
5 0 5 0 5

1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.

Downloaded for FREE at www.schoolnetwork.io


27
Searching Arrays: Linear Search and Binary
Search
• Search an array for a key value
• Linear search
– Simple
– Compare each element of array with key value
– Useful for small and unsorted arrays

Downloaded for FREE at www.schoolnetwork.io


28
Searching Arrays: Linear Search and Binary
Search
• Binary search
– For sorted arrays
– Compares middle element with key
• If equal, match found
• If key < middle, looks in first half of array
• If key > middle, looks in last half
• Repeat
– Very fast; at most n steps, where 2n > number of elements
• 30 element
5 array takes at most 5 steps
– 25 > 30 so at most 5 steps

Downloaded for FREE at www.schoolnetwork.io


29

Multiple-Subscripted Arrays
• Multiple subscripted arrays
– Tables with rows and columns (m by n array)
– Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3


Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript

Downloaded for FREE at www.schoolnetwork.io


30

Multiple-Subscripted Arrays
• Initialization
1 2
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0

• Referencing elements 3 4

– Specify row, then column


printf( "%d", b[ 0 ][ 1 ] );

Downloaded for FREE at www.schoolnetwork.io


31

Practice Exercise
Five(5)

Downloaded for FREE at www.schoolnetwork.io


1 /* Fig. 6.22: fig06_22.c 32
2 Double-subscripted array example */ Outline
3 #include <stdio.h>
4 #define STUDENTS 3
5 #define EXAMS 4 1. Initialize variables
6
7 int minimum( const int [][ EXAMS ], int, int );
8 int maximum( const int [][ EXAMS ], int, int );
1.1 Define functions to
9 double average( const int [], int ); take double scripted
10 void printArray( const int [][ EXAMS ], int, int ); arrays
11
Each row is a particular student,
12 int main() each column is the grades on the
13 { exam. 1.2 Initialize
14 int student;
studentgrades[][]
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
16 { { 77, 68, 86, 73 },
2. Call functions
17 { 96, 87, 89, 78 },
18 { 70, 90, 86, 81 } };
minimum, maximum,
19 and average
20 printf( "The array is:\n" );
21 printArray( studentGrades, STUDENTS, EXAMS );
22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
23 minimum( studentGrades, STUDENTS, EXAMS ),
24 maximum( studentGrades, STUDENTS, EXAMS ) );
25
26 for ( student = 0; student <= STUDENTS - 1; student++ )
27 printf( "The average grade for student %d is %.2f\n",
28 student,
29 average( studentGrades[ student ], EXAMS ) );
30
31 return 0;
Downloaded
32 } for FREE at www.schoolnetwork.io
33 33
34 /* Find the minimum grade */ Outline
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 { 3. Define functions
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 double average( const int setOfGrades[], int tests )
Downloaded
64 { for FREE at www.schoolnetwork.io
65 int i, total = 0; 34
66 Outline
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69 3. Define functions
70 return ( double ) total / tests;
71 }
72
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
77 int i, j;
78
79 printf( " [0] [1] [2] [3]" );
80
81 for ( i = 0; i <= pupils - 1; i++ ) {
82 printf( "\nstudentGrades[%d] ", i );
83
84 for ( j = 0; j <= tests - 1; j++ )
85 printf( "%-5d", grades[ i ][ j ] );
86 }
87 }

Downloaded for FREE at www.schoolnetwork.io


35
The array is:
Outline
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
Program Output
studentGrades[2] 70 90 86 81

Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75

Downloaded for FREE at www.schoolnetwork.io

You might also like