SlideShare a Scribd company logo
1 of 257
1© 2018 The Knowledge Academy Ltd
C Programming
2© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
About The Knowledge Academy
• World Class Training Solutions
• Subject Matter Experts
• Highest Quality Training Material
• Accelerated Learning Techniques
• Project, Programme, and Change
Management, ITIL® Consultancy
• Bespoke Tailor Made Training Solutions
• PRINCE2®, MSP®, ITIL®, Soft Skills, and More
3© 2018 The Knowledge Academy Ltd
• Trainer
• Fire Procedures
• Facilities
• Days/Times
• Breaks
• Special Needs
• Delegate ID Check
• Phones and Mobile Devices
Administration
4© 2018 The Knowledge Academy Ltd
• What is a program?
• (De)constructing a simple program
• Variables and Constants
• Operators and Terminologies
• Constructs
• Arrays
• Strings
Outline day 1
5© 2018 The Knowledge Academy Ltd
• A bit of C programming history…
• Functions
• Pointers
• Structures
• Operating Bigger Programs
Outline day 2
6© 2018 The Knowledge Academy Ltd
What is a program?
7© 2018 The Knowledge Academy Ltd
A program is
a recipe!
8© 2018 The Knowledge Academy Ltd
Analyse this:
9© 2018 The Knowledge Academy Ltd
Main Kitchen
(RETURNS hot sauce) Sous-chef sauce kitchen (can take in and )
Grind meat (using meat grinder)
Read recipe book no.1
Boil pasta and veggies. Use blender for veggies.
Cook meat in butter. Add salt and a touch of wine.
Ask Sous-chef sauce kitchen to make hot sauce! (send sous-chef some and some )
Hot sauce received.
Meal ready and sent to customer!
Read recipe book no.2
Heat up butter in milk.
Use blender to chop up chillies.
Add salt and red wine.
Send hot sauce to main kitchen!
10© 2018 The Knowledge Academy Ltd
Notion 1: GLOBAL vs LOCAL
GLOBAL ingredients
(that can be used from any kitchen)
LOCAL ingredients
(that can only be used one specific kitchen)
11© 2018 The Knowledge Academy Ltd
(in programming terms…)
GLOBAL variables = variables that can be read from any
function
LOCAL variables = variables that can only be read from
the function where they are declared
(as we can see: some local variables can be sent from one function to another. We will have a
closer look at this on Day 2)
12© 2018 The Knowledge Academy Ltd
Notion 2: main structure of a C program
Headers, pre-processor directives, global/constant variables, function prototypes…
Main function
Function A
Function B
13© 2018 The Knowledge Academy Ltd
Analyse this…
14© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
15© 2018 The Knowledge Academy Ltd
in fact…
Headers, pre-processor directives, global/constant variables, function prototypes…
Documentation
Main function
Function A
Function B
16© 2018 The Knowledge Academy Ltd
Analyse this…
17© 2018 The Knowledge Academy Ltd
/*
Documentation section
C programming basics & structure of C programmes
Author: theknowledgecacademy.com
Date: 06/11/2018
*/
#include <stdio.h> /* Link section */
int total = 0; /* Global declaration, definition section */
int sum = (int, int); /* Function declaration section */
int main () /* Main function */
{
printf (“This is a C basic programme n”);
total = sum (1, 1);
printf (“Sum of two numbers : %d n”, total)l
return 0;
}
int sum (int a, int b) /* User defined function */
{
return a + b; /* definition section */
}
18© 2018 The Knowledge Academy Ltd
RECAP
In general, most C programs use the following structure:
• Documentation section (if necessary)
• Pre-processors directives and/or header files and/or global variable
declarations and/or function prototypes…
• Main() function  absolutely mandatory!!!
• Other functions (if necessary)
19© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
(De)constructing a simple program
20© 2018 The Knowledge Academy Ltd
(De)constructing a simple program
Let’s start by typing this code in:
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
21© 2018 The Knowledge Academy Ltd
(De)constructing a simple program
• We are going to start by writing the
basic program "Hello World”, which
will print (or output) the message
"Hello, World!" on screen
• This is a very simple program
designed to help you understand the
syntax of C
• We will break down each component
line by line and explain its function
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
22© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
line 1
• The first line is the #include command,
followed by <stdio.h>
• stdio.h is a header file containing
standard input and output functions for
the program (such as printf)
• Without this file, input and output
functions will not work and the program
will not compile
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
23© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
more on line 1
• the #include command is in fact called a pre-processor directive
• Pre-processor directives tell the compiler how to modify the code before it is
compiled
• This is the section where header files (here: <stdio.h>) are placed in the system
library to access predefined functions
• We include files using #include followed by the name of the file in < >
• All header files end in .h
• Pre-processors are specified using the # directive
24© 2018 The Knowledge Academy Ltd
(De)constructing a simple rogram:
more on line 1
• Examples include:
#include
<stdio.h>
#define pi=3.14 #undefine pi #ifdef
25© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
line 2
• The next line is the start of the int main()
function (notice the curly brackets {…})
• This int main() may or may not have
other elements (called arguments) inside
its (…) (but we won’t talk about this)
• As with any other function, int placed
before main() means that the main()
function returns a value once all of the
contents inside its {…} has been
processed  we can see this on the last
line, where it is said: return 0
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
26© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
more on line 2
• The main() function defines where the C
program starts.
• Regardless of where it is placed, it is
always the first function executed when
the program starts.
• This main() function is mandatory for
any C program, as all other functions are
called from it.
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
27© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
line 3
• The printf() function displays the text
inside quotation marks (“Hello, World!”)
• It is a library function that sends the
output to the screen
• Printf() will not work without stdio.h
• /n is an escape sequence, which
essentially represents a newline
character for the “Hello, World!” string
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
28© 2018 The Knowledge Academy Ltd
(De)constructing a simple program:
line 4
The program ends when the
return statement is encountered
within the main() function (but it
in this very rare case, it is not
mandatory)
‘0’ provides an exit status,
showing that the program
executed successfully with no
errors
#include <stdio.h>
int main()
{
printf(“Hello, World!n”);
return 0;
}
29© 2018 The Knowledge Academy Ltd
How it all runs
The following steps are used in every C program – whether small or large – to generate an
output:
Create Compile Execute or run Get the output
30© 2018 The Knowledge Academy Ltd
Note on the notion of compiling
• Compiling means converting C code into machine language that can be
read and understood by the computer
• Popular C compilers include GCC (Linux), Visual C++ (Windows), Turbo C,
and Borland C
• Once the .C program has been compiled, a new file with the same name
but the extension .EXE is generated
• It is this .EXE file that is executed
31© 2018 The Knowledge Academy Ltd
Exercise!
Write a short C program where five statements of your
choice are printed out.
Watch out! Each statement must start on a new line!
32© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
33© 2018 The Knowledge Academy Ltd
The fascinating world of variables
34© 2018 The Knowledge Academy Ltd
What is a variable?
First and foremost, a variable is a memory location, the
name of which (“cat”, “var1”, “loopiloo”…) is decided
by the programmer.
This memory location contains a specific type of data
(confirmed through its declaration), the size and layout
of which is precisely determined by the type.
A variable can have its contents changed at any time
(as long as it is of the same type)
(NOTE: we will talk more about memory when we talk
about pointers)
RAM
8
Memory location
a is reserved
35© 2018 The Knowledge Academy Ltd
Two sorts of memory locations
There are two types of memory locations:
- Variables: memory locations whose contents can change during the
execution of a program
- Constants: memory locations whose contents cannot be changed while the
program is executing (the use of const determines when a variable is a
constant)
See example:
36© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
37© 2018 The Knowledge Academy Ltd
Try and change the value of a const variable!!
38© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
39© 2018 The Knowledge Academy Ltd
4 main Data Types
Before we can use a variable in C we must declare it. When we declare it, we
tell the computer what data type it is.
There are 4 basic data types:
• int – an integer, or a whole number
• char – a single character
• float – decimals, numbers with a ‘floating point’ value up to 7 digits
• double – a more precise version of float up to 15 digits
40© 2018 The Knowledge Academy Ltd
Real purpose of declaring a variable
When we declare a variable, we in fact inform the computer how much
memory space we require for this variable!
This memory space is generally in bytes (remember: 1 byte = 8 bits)
Try the following to know the amount of memory required for each type of
variable…
41© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
42© 2018 The Knowledge Academy Ltd
Various rules for naming variables
• A variable’s name can only start with a letter or underscore; it will not accept
integers
• Able to contain letters, integers, and underscores though!
• Reserved word/keyword (e.g. char, float) cannot be used for variable’s name
• No whitespace is permitted
43© 2018 The Knowledge Academy Ltd
2 ways of declaring variables
(manually)
Technique 1:
Technique 2: int age, yearOfBirth, population;
int age;
int yearOfBirth;
int population;
44© 2018 The Knowledge Academy Ltd
Initialising variables: how it is done
Now that we have seen how to declare a variable (ie: to inform the computer
of the amount of memory space required for the variables we wish to use),
the time now comes to place values inside these variables!
This is called: initialisation, and it is done through the symbol =
WARNING: as we shall see, the = symbol does not mean ‘equal’!
45© 2018 The Knowledge Academy Ltd
2 ways of initialising variables
(manually)
Technique 1:
Technique 2: FirstNumber = SecondNumber = ThirdNumber = 24;
FirstNumber = 24;
SecondNumber = 24;
ThirdNumber = 24;
46© 2018 The Knowledge Academy Ltd
Declaring + initialising variables all in one go
(manually)
int FirstNumber = 24, SecondNumber = 45, ThirdNumber = 9001;
47© 2018 The Knowledge Academy Ltd
Rules for declaring variables
• Declared variables cannot be changed, as shown below
• int cannot be changed to floating point 5.5, nor can it be changed to a double
number
• Error generated as a result of this
int number = 5; // integer variable
number – 5.5; // error
double number; // error
48© 2018 The Knowledge Academy Ltd
Example of
LOCAL variable
declaration &
initialisation
49© 2018 The Knowledge Academy Ltd
Example of
GLOBAL
variable
declaration &
initialisation
50© 2018 The Knowledge Academy Ltd
Initialising variables
(user)
To enable users to test your program by entering whatever value they want, the scanf() function
must be used.
The syntax is as follows:
51© 2018 The Knowledge Academy Ltd
Format identifiers(1)
Notice the “…%” expression, when we use scanf()?
This is to enable the real-time input of values through
scanf().
This expression is called a format identifier.
52© 2018 The Knowledge Academy Ltd
Format identifiers(2)
53© 2018 The Knowledge Academy Ltd
Format identifiers - examples
#include <stdio.h>
int main()
{
char ch = 'A';
printf("%cn", ch);
return 0;
}
#include <stdio.h>
int main()
{
float a = 12.67;
printf("%fn", a);
printf("%en", a);
return 0;
}
54© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Operators and Terminologies
55© 2018 The Knowledge Academy Ltd
Operators
An operator in C is a symbol that tells
the compiler to perform a specific
mathematical or logical function.
The C language has many built-in
operators, such as:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Misc Operators
56© 2018 The Knowledge Academy Ltd
Operators
The various Arithmetic Operators in C are:
Operator Description Example
+ Adds two numbers A+B= 20
- Subtracts second
number from the
first
A-B=10
* Multiplies both
numbers
A*B=200
/ Divides two numbers A/B=10
% Finds the remainder
after division
B%A=0
57© 2018 The Knowledge Academy Ltd
Operators
Relational Operators
Operator Description Example
== Checks if the values of two numbers
are equal or not. If yes, then the
condition becomes true
A==B is not true
!= Checks if the values of two numbers
are equal or not.
If the values are not equal, then the
condition becomes true
(A != B) is true
> Checks if the value of left number is
greater than the value of right
number. If yes, then the condition
becomes true
(A > B) is not true
These are used to check the relationship between two numbers.
58© 2018 The Knowledge Academy Ltd
Operators
Arithmetic Unary Operators
Operator Description Example
++ Increment operator
– increases a
number by 1
A++
--
Decrement operator
– decreases a
number by 1
A--
59© 2018 The Knowledge Academy Ltd
Operators
Relational Operators
Operator Description Example
< Checks if the value of left number
is less than the value of right
number. If yes, the condition
becomes true
(A < B) is true
>= Checks if the value of left number
is greater than or equal to the
value of right number. If yes, the
condition becomes true
(A >= B) is not true
<= Checks if the value of left number is
less than or equal to the value of
right number. If yes, the condition
becomes true
(A <= B) is true
60© 2018 The Knowledge Academy Ltd
Operators
Logical Operators
Operator Description Example
&& Logical AND Operator – if both numbers are
true, then the condition becomes true
(A && B) is false
|| Logical OR Operator – if any of the two
numbers is true, then the condition
becomes true
(A || B) is true
! Logical NOT Operator – if the numbers are
true, the condition is false. If the numbers
are false, the condition becomes true.
!(A && B) is true
These are used to check if multiple conditions are true.
61© 2018 The Knowledge Academy Ltd
Operators and Terminologies
Assignment Operators
Operator Description Example
= Basic Assignment – assigns one
value so it is equal to another
C = A + B will assign the
value of A + B to C
+= Addition Assignment – adds the
right number to the left number and
assigns the result to the left number
C += A is equivalent to C
= C + A
-= Subtraction Assignment –
subtracts the right number from the
left number and assigns the result to
the left number
C -= A is equivalent to C
= C - A
These are used to assign one value to another.
62© 2018 The Knowledge Academy Ltd
Assignment Operators
Operator Description Example
*= Multiplication Assignment –
multiplies the left number by the right number
and assigns the result to the left number
C *= A is equivalent to C = C * A
/= Division Assignment – divides the left number
with the right number and assigns the result to
the left number
C /= A is equivalent to C = C / A
%= Remainder Assignment – finds the remainder of
a division and assigns the result to the left
number
C %= A is equivalent to C = C %
A
Operators and Terminologies
63© 2018 The Knowledge Academy Ltd
Bitwise Operators
Operator Description Example
& Bitwise AND Operator – if both bits
are true, then the condition becomes
true
(A & B) = 12, i.e., 0000
1100
| Bitwise OR Operator – if either bit is
true, the condition becomes true
(A | B) = 61, i.e., 0011
1101
^ Bitwise XOR Operator – returns true if
either bit is true (but not both)
(A ^ B) = 49, i.e., 0011
0001
These operate on numbers at the bit level, allowing users to manipulate individual bits. A bit with
value 1 is equivalent to true, a bit with value 0 is equivalent to false.
Operators and Terminologies
64© 2018 The Knowledge Academy Ltd
Bitwise Operators
Operator Description Example
~ Bitwise Complement Operator – changes
true to false and false to true
(~A ) = -61, i.e., 1100 0011
in 2's complement form
>> Right Shift Operator – shifts all bits to the
right by a specified number
(A | B) = 61, i.e., 0011
1101
<< Left Shift Operator – shifts all bits to the
right by a specified number
A << 2 = 240 i.e., 1111
0000
Operators and Terminologies
65© 2018 The Knowledge Academy Ltd
Operators and Terminologies
Bitwise Operators
P Q P&Q P|Q P^Q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
66© 2018 The Knowledge Academy Ltd
Terms used in C
Terminologies
The Terminology of C
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while
67© 2018 The Knowledge Academy Ltd
Terminologies
• auto: the variables declared with auto are declared every time the program starts
• break: used to exit out of a conditional or iterative structure
• case: used for selecting an option from a given set of options. Preferred in place
of multiple ifs
• char: represents a data-type to store a single character
• const: declare a constant value
68© 2018 The Knowledge Academy Ltd
Terminologies
• continue: skip the current iteration and start with the next
• default: the option to be selected if none of the others are selected
• do: starts the do loop that executes at least once even if the given condition is
false
• double: data-type to store a value with decimal points in case the value is
beyond the range of float
• else: the part that executes in case the if part evaluates to false
69© 2018 The Knowledge Academy Ltd
Terminologies
• enum: used for declaring enumerated types
• extern: used to declare variables or functions having external links
• float: data-type to store decimal point values
• for: used for creating a loop to repeat some process
• goto: used for transferring control to another part of the program
70© 2018 The Knowledge Academy Ltd
Terminologies
• int: used for storing integer values
• long: used for storing values greater than the range of int
• register: create register variables
• return: return a value to the calling function. Used in functions only
• short: limit the range of int data-type between -32768 to 32767
71© 2018 The Knowledge Academy Ltd
Terminologies
• signed: same as short
• sizeof: the operator is used to calculate the size of a data-type
• static: static variables are used to store their previous values
• struct: used to define structures containing a number of variables of
different types
• switch: construct used along with case instead of if
72© 2018 The Knowledge Academy Ltd
Terminologies
• typedef: used for defining user-defined types
• union: used for grouping different variables under a single name
• unsigned: allow storage of unsigned data only
• void: used when a function returns nothing
• volatile: used for creating volatile objects that can be modified by the hardware
• while: loop executes only when a condition is true
73© 2018 The Knowledge Academy Ltd
Constants
Backslash and character constants
• Backslash preceding symbol indicates a special function
Backslash character Meaning
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
” Double quote
74© 2018 The Knowledge Academy Ltd
Constants
Backslash and character constants
Backslash character Meaning
’ Single quote
 Backslash
v Vertical tab
a Alert or bell
? Question mark
N Octal constant
XN Hexadecimal constant
75© 2018 The Knowledge Academy Ltd
Escape Sequences
Escape sequences are functions within a string literal or character that are not a
character themselves. They always begin with a backslash.
Operator Description
? Question mark
n New line
r Reset cursor to beginning of the current line
t Horizontal tab
v Vertical tab
 Insert a backslash
’ Insert a single quote
” Insert a double quote
a Alert noise
76© 2018 The Knowledge Academy Ltd
Variables: RECAP
Local variable
• Declared inside the function
• Usable only inside the function inside which it is declared
Global variable
• Declared outside the function
• Can be used throughout a C programme
77© 2018 The Knowledge Academy Ltd
Variables: RECAP
Static variable
• Retains value between multiple calling of functions
• Declared via static keyboard
External variable
• May be shared across multiple C source files
• Declared via extern keyboard
Automatic variable
• Declared inside the block
78© 2018 The Knowledge Academy Ltd
Key Terms
• Keywords – These are predefined terms that have specialised meanings in C
• Identifiers – These are the unique names assigned to variables, functions, macros,
arrays etc.
• Variable – A name used to refer to a location in the memory; a placeholder for a
changeable value
• Constants – The opposite of variables: data that will not change during program
execution
• Operator – A symbol that performs an action on a variable
79© 2018 The Knowledge Academy Ltd
Let’s code!
80© 2018 The Knowledge Academy Ltd
1) Write a C program that asks the user to enter 3
integers, then:
- Adds these three INT variables up
- Multiplies the result with a CONST INT variable
- Multiplies the result with a GLOBAL INT variable
- Verifies if the final result is even or odd
Print a statement for each result.
81© 2018 The Knowledge Academy Ltd
82© 2018 The Knowledge Academy Ltd
2) Write a C program that prompts the user to enter a
double value for Celsius degrees, then convert this
Celsius temperature to Fahrenheit
83© 2018 The Knowledge Academy Ltd
84© 2018 The Knowledge Academy Ltd
3) Write a C program that calculates the total average and
percentage of five school subjects
85© 2018 The Knowledge Academy Ltd
86© 2018 The Knowledge Academy Ltd
4) Write a C program that does the following:
- If variable var1 is greater than 5 and var2 smaller than 17, print:
“Exercise 1: passed”
else:
“Exercise 1: failed”
- If variable m1 is greater than 13 or if m2 is equal to 509, print:
“Exercise 2: passed”
else:
“Exercise 2: failed”
87© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Constructs
88© 2018 The Knowledge Academy Ltd
Constructs
What are constructs?
• Comparable to the syntax of programming language
• Able to be read and understood by a compiler, and
free of ambiguity
• Comprised of curly braces, semicolons, etc.
• Loops, statements, invocations, and conditions are
types of constructs
89© 2018 The Knowledge Academy Ltd
Constructs
• The language C uses various constructs to
accomplish specific tasks
• These include conditional constructs as well as
iterative constructs
• Conditional constructs include if, if else, if else
if else, and switch case constructs
• The iterative constructs include do...while,
while, and for loops
90© 2018 The Knowledge Academy Ltd
Constructs
Sequence constructs
• Set of instructions that denote the
order of execution
• Often runs ‘top to bottom’ (i.e. line
1, line 2, line 3, and so on)
• Sequences sometimes illustrated by
flow charts, which make use of
different shapes (e.g. circles,
squares, rhombuses)
91© 2018 The Knowledge Academy Ltd
Constructs
Selection constructs
• Selective execution, which is
dependent on conditions being met
• Compiler ‘asks’ questions in the form
of an if statement
• Sometimes known as ‘branching’
92© 2018 The Knowledge Academy Ltd
Constructs
Iteration constructs
• Repetitive execution of statements using loop
statements
• Loop statements consist of three types:
o For loops
o While loops
o Repeat until loops
• Saves programmers re-writing same lines of
codes
93© 2018 The Knowledge Academy Ltd
Constructs
Constructs
Conditional
If
If else
If else if else
switch case
Iterative
do while
while
for
94© 2018 The Knowledge Academy Ltd
Conditional Constructs
However, the program does not output anything as the condition specified is false
95© 2018 The Knowledge Academy Ltd
Conditional Constructs
This program outputs j is greater as the condition i > j is false
96© 2018 The Knowledge Academy Ltd
Conditional Constructs
This program first evaluates if (which returns false), then evaluates else if (which also returns false)
and finally executes the else part and prints both are equal
97© 2018 The Knowledge Academy Ltd
Conditional Constructs
This program assigns a value to I, and based on that value it prints a word wherever that condition
is met. A break statement is required after every case except default. This program prints Two
98© 2018 The Knowledge Academy Ltd
Conditional Constructs
This program prompts the user to enter a value between 1 and 3. Depending on
the value entered, the switch case construct returns a result.
99© 2018 The Knowledge Academy Ltd
Iterative Constructs
• The do while loop executes a minimum of once
• This is because the condition is checked after the first execution
• Thereafter it depends upon the value of the control variable
100© 2018 The Knowledge Academy Ltd
Iterative Constructs
• The while loop is contrary to the do while loop as it executes only if a condition is true
• The condition is checked first, after which the body of the loop is executed only if the
loop condition evaluates to true
101© 2018 The Knowledge Academy Ltd
Iterative Constructs
• The for loop is more or less like a while loop
• Within a for loop, the initial value, the terminating condition, and the increment/decrement
value are all specified in a single statement
102© 2018 The Knowledge Academy Ltd
Iterative Constructs
• If a loop needs to be executed in reverse order, this can be done by specifying the bigger
value as the initial value and the smaller value as the terminating value
• The loop should then decrement the value instead of incrementing it
103© 2018 The Knowledge Academy Ltd
Iterative Constructs
• C also allows the use of infinite loops (though not recommended)
• These can be specified as follows:
int i=1;
do
{
printf(“%d”,i);
} while (i<=1);
int i=1;
while (i=1)
{
printf(“%d”,i);
};
for(;;;)
104© 2018 The Knowledge Academy Ltd
Let’s code!
105© 2018 The Knowledge Academy Ltd
1) Write a C program to find the largest of
two numbers using IF…ELSE
106© 2018 The Knowledge Academy Ltd
107© 2018 The Knowledge Academy Ltd
2) Write a C program to find the largest value between
three numbers.
108© 2018 The Knowledge Academy Ltd
109© 2018 The Knowledge Academy Ltd
3) Write a C program to print all natural numbers from 1
to n using WHILE loop, then FOR loop
110© 2018 The Knowledge Academy Ltd
111© 2018 The Knowledge Academy Ltd
4) Write a C program to find the sum of all even numbers
between 1 to n
112© 2018 The Knowledge Academy Ltd
113© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Arrays
114© 2018 The Knowledge Academy Ltd
Arrays
Introduction
• An array is simply an ordered collection of elements, all of which are the
same data type
• Each of the elements are numbered, allowing individual access
• Arrays can be one-dimensional (like a list) or two-dimensional (like a table)
“A group of elements belonging to a homogenous type
and accessed by an index can be called an array”
115© 2018 The Knowledge Academy Ltd
Declaring & initialising arrays
(manually)
There are various way of declaring & initialising an array:
1) Either by entering every value, separated by commas (with the array size):
double str[5] = {3.455, 21.609, 4.44, 31000.9, 8.504};
2) Either by entering every value, separated by commas (without the array size):
int str[] = {12, 34, 5, 1777, 56, 2358, 380};
116© 2018 The Knowledge Academy Ltd
Declaring & initialising arrays
(user)
117© 2018 The Knowledge Academy Ltd
Accessing Elements in an Array
• An Array element in C can be accessed using its index number
• The index number is a numeric value that starts with 0 and the last value can be 1 less
than the size of the array
• In an array with 10 elements, the first index number would be 0 and the last would be 9
• So, to access element 5, we would simply access the element with the index as 4,
shown below:
int x = list[4];
118© 2018 The Knowledge Academy Ltd
Accessing Elements in an Array
• The following program initialises the array at runtime and then
displays the contents of that array:
119© 2018 The Knowledge Academy Ltd
Two-Dimensional Arrays
• In a two-dimensional array we can declare rows and columns
• To access individual elements, we use two numbers instead of one
• For example, to access 2 in this list we would use the reference [0] [1]
1 2 3 4
5 6 7 8
list[0] [0] list[0] [3]list[0] [2]list[0] [1]
list[1] [3]list[1] [2]list[1] [1]list [1] [0]
int list[2][4]=
{
{1,2,3,4},
{5,6,7,8}
};
120© 2018 The Knowledge Academy Ltd
Two-Dimensional Arrays
121© 2018 The Knowledge Academy Ltd
Exercise time!
122© 2018 The Knowledge Academy Ltd
1) Write a C program where you declare & initialise an
array of any type (your choice) and of size 20, then print
the 9th and 15th values of that array.
123© 2018 The Knowledge Academy Ltd
2) Write a C program to find the sum of an array’s
elements.
124© 2018 The Knowledge Academy Ltd
3) Write a C program to count all even and odd elements
in a given array
125© 2018 The Knowledge Academy Ltd
4) Write a C program to copy all elements of first array
into a second array in reverse order.
126© 2018 The Knowledge Academy Ltd
Sorting Arrays
• Arrays can be initialised with random values and displayed in a particular
order
• This is possible due to various sorting algorithms that can be applied
• The simplest of these is the Bubble Sort
• The program here accepts a few numbers from the user and stores them
in an array, in the order in which they have been entered
• Thereafter, the array is sorted in the next step using Bubble Sort
• Finally, the sorted array is displayed to the user
127© 2018 The Knowledge Academy Ltd
128© 2018 The Knowledge Academy Ltd
Let’s have a look at an example
Say we have the following array of 10 integers, stored in random order:
129© 2018 The Knowledge Academy Ltd
In the first pass of the outer loop (ie: when i == 0), we
have:
130© 2018 The Knowledge Academy Ltd
And so: we have essentially pushed the highest value in
the array to the rightmost box of the array.
The second pass (ie: i == 1) will therefore push the second
largest value of the array to the right, and so on until
i == 9 and the array is finally sorted in ascending order.
131© 2018 The Knowledge Academy Ltd
QUESTION
Look at both terminating values for the outer and inner
loops.
What do you notice?
Why are they different?
132© 2018 The Knowledge Academy Ltd
The efficiency of sorting algorithms
By clicking here, we can see that Bubble Sort isn’t great:
133© 2018 The Knowledge Academy Ltd
Question: what should we change in the previous to
order the array in decreasing order?
134© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Strings
135© 2018 The Knowledge Academy Ltd
Introduction to strings
So far, we have seen how to declare, initialise and manipulate arrays of
various data types.
Among these, we haven’t mentioned the possibility of implementing arrays
of type char, as so:
char myCharArray[];
Since char arrays hold, in effect, characters that can make up a word, several
words, or even sentences with meaning, could we then say that arrays of
type char constitute strings – ie: text?
 WRONG!
136© 2018 The Knowledge Academy Ltd
Introduction to strings
There lies in fact a difference between any sort of array (including char arrays) and strings:
Strings are arrays of type char that end with a compulsory ‘0’ (null) character!!!
Following is the memory presentation of the above defined string in C:
137© 2018 The Knowledge Academy Ltd
NOTE:
The null character shows the computer where the string
ends.
But we do not need to place the null character at the end
of a string!
The C compiler automatically does that for us: it places
the '0' at the end of the string when it initializes the
array.
138© 2018 The Knowledge Academy Ltd
Declaring & initialising a string in C
(manually)
There are several ways to declare and initialise a string:
1) Either by entering every character in single quotes (with or without the array size):
- char str[] = {'H','e','l','l','o',' ','w','o','r','l','d','0’};
- char str[14] = {'H','e','l','l','o',' ','w','o','r','l','d','0’};
2) Either by entering full words and spaces in text style and in double quotes (with or without
the array size):
- char str[] = "Hello world!";
- char str[50] = "Hello world!";
139© 2018 The Knowledge Academy Ltd
Declaring & initialising a string in C
(user)
There are several ways to have a string initialised by users.
One of the safest and enduring ways is as follows:
#include <stdio.h>
int main()
{
char str[20];
printf(“Please enter your string:nn”);
scanf("%[^n]%*c", str);
printf(“nnYour string:nn%s", str);
return 0;
}
140© 2018 The Knowledge Academy Ltd
String Methods
• If we want to do anything with our strings, such as compare, concatenate
or copy them, we need access string methods
• We do this using the header file string.h
• Here are some of the most popular string handling methods:
o strlen()
o strcpy()
o strncpy()
o strcat()
o strncat()
o strcmp()
141© 2018 The Knowledge Academy Ltd
String Methods
strlen
• This calculates the length of the string, minus the null character
• Format: strlen (string variable)
142© 2018 The Knowledge Academy Ltd
String Methods
strcpy
• This copies the content of one string to another
• Format: strcpy(destination_string, source_string);
143© 2018 The Knowledge Academy Ltd
String Methods
strncpy
• This allows us to copy a selected number characters from one string to another
• Format: strncpy (destination_string, source_string, number of characters to copy);
144© 2018 The Knowledge Academy Ltd
String Methods
strcat
• This allows us to concatenate (or join) two strings together
• Format: strcat(destination_string, source_string);
strcat (str2,str1);
145© 2018 The Knowledge Academy Ltd
String Methods
strncat
• Like strcat, this lets us join strings together, but unlike strncat, it lets us specify how
many characters
• Format: strncat (destination_string, source_string, number of characters);
146© 2018 The Knowledge Academy Ltd
String Methods
strcmp
• This compares strings
• If the strings are equal, it returns 0.
If the 1st is greater than the 2nd, it
returns a value greater than 0. If the
1st is less than the 2nd, it returns a
value less than 0
• Format: strcmp (string_1,string_2);
147© 2018 The Knowledge Academy Ltd
String Methods
strcmp
148© 2018 The Knowledge Academy Ltd
Library of most string functions
Function Description
strlen Finds the length of a string
strlwr Makes string characters lowercase
strupr Makes string characters uppercase
strcat Appends one string at the end of another
strncat Appends first n character of string at the end of another
strcpy Copies one string into another
strncopy Copies first n characters of one string into another
strcmp Compares two strings
149© 2018 The Knowledge Academy Ltd
Library of most string functions
Function Description
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case
stricmp Compares two strings without regard to case
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates string
strchr Seeks first occurrence of given character within string
strrchr Seeks last occurrence of given character within string
150© 2018 The Knowledge Academy Ltd
Library of most string functions
Function Description
strstr Find first occurrence of given string in another string
strset Sets all characters of a string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses a string
151© 2018 The Knowledge Academy Ltd
1) Write a C program to concatenate two strings
152© 2018 The Knowledge Academy Ltd
153© 2018 The Knowledge Academy Ltd
2) Write a C program to compare two strings.
154© 2018 The Knowledge Academy Ltd
155© 2018 The Knowledge Academy Ltd
What is C
Programming?
• A general purpose programming
language closely related to the UNIX
operating system
• Developed specifically for UNIX,
given that most systems and
programmes running in UNIX are
written in C language
• Standardised by American National
Standards Institute (ANSI) in 1989
156© 2018 The Knowledge Academy Ltd
UNIX – what’s that again…?
Unix distinguishes itself from its predecessors as the first portable operating system: almost the entire
operating system is written in the C programming language, thus allowing Unix to reach numerous
platforms.
Development started in the 1970s at the Bell Labs research centre. by Ken Thompson, Dennis Ritchie,
and others.
Both Unix and the C programming language were developed by AT&T and distributed to government
and academic institutions, which led to both being ported to a wider variety of machine families than
any other operating system
The Unix system had significant impact on other operating systems. It achieved its reputation by its
interactivity, by providing the software at a nominal fee for educational use, by running on inexpensive
hardware, and by being easy to adapt and move to different machines.
157© 2018 The Knowledge Academy Ltd
History of C
• It was developed by Dennis Ritchie of Bell
Labs between 1969 and 1973 as a
successor to the B language
• In 1978, the publication of "The C
Programming Language" by Bryan
Kerninghan and Ritchie caused a
revolution in the computing world
• In 1983, the American National Standards
Institute (ANSI) established a committee
to provide a modern definition of C and
this definition was completed in late 1988
158© 2018 The Knowledge Academy Ltd
History of C
Year Language Developed by Remarks
1960 ALGOL International committee Too general and too
abstract
1963 CPL Cambridge University Hard to learn,
difficult to
implement
1967 BCPL Martin Richards at
Cambridge University
Could deal only with
specific problems
1970 B Ken Thompson at AT & T Could deal only with
specific problems
1972 C Dennis Ritchie at AT & T Lost generality of
BCPL and B restored
159© 2018 The Knowledge Academy Ltd
C Facts
• Today, C is one of the most widely
used programming languages in the
world
• C has been used for everything
imaginable, from operating systems to
databases to network drivers
• Linux OS, PHP, and MYSQL are all
written in C
• Modern programming concepts are
based on C
160© 2018 The Knowledge Academy Ltd
According to
• According to TIOBE Index:
• https://www.tiobe.com/tiobe-index/
161© 2018 The Knowledge Academy Ltd
C and Other Languages
• C is considered the mother tongue for programming because its features strongly
influenced subsequent languages
• Many popular languages like Java, C++, Perl, Ruby, PHP, Bash, Python, and Objective
C have borrowed syntaxes and functions from the C language
• They have the same operators, expressions, statements, and control structures of C
• High level programming languages like JAVA and Python can merge with C
• The C compiler combines the capabilities of an assembly language, along with the
features of a high level language, making it suitable for developing system software
and packages
162© 2018 The Knowledge Academy Ltd
Assembly language – what’s that again…?
163© 2018 The Knowledge Academy Ltd
High-level language – ok…
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that enables a programmer to
write programs that are more or less independent of a particular type of computer. Such languages are considered
high-level because they are closer to human languages and further from machine languages.
In contrast, assembly languages are considered low-level because they are very close to machine languages.
Advantages of High-Level Languages
The main advantage of high-level languages over low-level languages is that they are easier to read, write, and
maintain. Ultimately,
programs written in a high-level language must be translated into machine language by a compiler or interpreter.
The first high-level programming languages were designed in the 1950s. Now there are dozens of different
languages, including Ada,
Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal, and Prolog.
164© 2018 The Knowledge Academy Ltd
Reasons to Use C
C has now become a widely used programming language, and is favoured for
the following reasons among others:
• Easy to learn
• Structured programming language
• Runs programmes efficiently
• Compiles code quickly
• Handles low-level activities
• Can be used on a variety of operating systems (e.g. Windows, Android, Mac)
165© 2018 The Knowledge Academy Ltd
What is a structured programming language?
Structure programming is a "computing philosophy" which states that there three main ways of combining programs:
- sequencing
- selection
- iteration (+ recursion)
These are deemed sufficient to express any computable function.
"Sequence"; ordered statements or subroutines executed in sequence.
"Selection"; one or a number of statements is executed depending on the state of the program. This is usually expressed with
keywords such as if..then..else..endif.
"Iteration"; a statement or block is executed until the program reaches a certain state, or operations have been applied to every
element of a collection. This is usually expressed with keywords such as while, repeat, for or do..until. Often it is recommended that
each loop should only have one entry point (and in the original structural programming, also only one exit point, and a few
languages enforce this).
"Recursion"; a statement is executed by repeatedly calling itself until termination conditions are met. While similar in practice to
iterative loops, recursive loops may be more computationally efficient, and are implemented differently as a cascading stack.
166© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Foundation of modern information
technology sector, including a great
deal of IT principles such as:
o Operating systems
o Databases
o Graphic user interfaces
o Image processing
o Real-time systems
o Algorithms
167© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Used by over 90% of desktop programmes
(e.g. email clients in web browsers) use C
• Used extensively in robotics
• Standardised by ANSI and International
Organisation for Standardisation (ISO)
• Foundation skill for more advanced
programming techniques like multithread
programming, embedded programming, real-
time programming, and cloud computing
168© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Highly flexible and adaptable, due to
the presence of different data types
• Possesses capabilities of assembly
language, along with high-level
language for developing system
software and packages
• Uses 32 keywords and several
functions
169© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Able to extend itself
• Language has a collection of functions
• C library is able to continuously
accommodate new functions
• Procedural in nature
170© 2018 The Knowledge Academy Ltd
What is procedural programming?
Historically, procedural programming arose out of the concept of structured programming.
The idea is that programs can be written with only three things:
- Sequence (execution moves forward one statement at a time)
- Selection (if statements)
- Iteration (loops)
But all in all, procedural programming (PP) is a programming paradigm that takes a top-down approach.
It is about writing a list of instructions to tell the computer what to do step by step.
It relies on procedures or routines.
Procedural programs can be faster than most alternatives. This is especially true historically.
We can easily get the maximum performance out of procedures because we become “empathetic” to what the
machine’s most efficient way to perform a task is.
171© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Can be said to use object oriented
programming (OOP)
• Absence of ‘garbage collection’ and
‘dynamic typing’ allows C to function
faster than its language counterparts
• Portable, and therefore easy to
compile from disparate systems
172© 2018 The Knowledge Academy Ltd
Portability
• C’s portability means that, when
written well, it can be compiled
once and then moved to another
system without modification
• However, C does not guarantee
portability. Programs must be
optimised in certain ways in order
to run elsewhere without issue
C programs are portable
173© 2018 The Knowledge Academy Ltd
Reasons to Use C
• Sections of C can be stored for future
use (i.e. modularity), thanks to its
libraries
• Statistically typed as opposed to
dynamically typed
• Seamlessly merges with high-level
programming languages like Java and
Python
174© 2018 The Knowledge Academy Ltd
Statically-typed vs dynamically-typed
Statically typed languages
A language is statically typed if the type of a variable is known at compile time. For some languages this means that
you as the programmer must specify what type each variable is (e.g.: Java, C, C++); other languages offer some form
of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala,
Kotlin). The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of
trivial bugs are caught at a very early stage.
Examples: C, C++, Java, Rust, Go, Scala
Dynamically typed languages
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc.
This means that you as a programmer can write a little quicker because you do not have to specify types every time
(unless using a statically-typed language with type inference).
Examples: Perl, Ruby, Python, PHP, JavaScript
175© 2018 The Knowledge Academy Ltd
Reasons to Use C
C is middle level and structured
• Middle level means it fills the gap
between machine language (what the
computer reads) and high-level
languages (languages like Ruby that are
closer to natural human language)
• Structured means that C follows a
logical structure which divides
problems into individual modules
176© 2018 The Knowledge Academy Ltd
Features of C
• This means instructions are executed step-by-step to carry out tasks
• A program may contain one or more procedures for performing these tasks
• This makes C quite intuitive as it works how you may expect a program to
work – by following instructions
C is a procedural language
177© 2018 The Knowledge Academy Ltd
Features of C
C programs are fast
• As C is a compiled language, it only needs to be run through a compiler
once for it to be translated into machine code that a computer can
understand
• Interpreted languages, in comparison, must be interpreted every time
they are run, which slows down performance and takes a lot longer
178© 2018 The Knowledge Academy Ltd
Features of C
C is a statically typed language
• This means types of variable are checked while the language is being
compiled, rather than when it is run
• This again makes it faster than other (dynamically typed) languages
• It also ensures errors are caught earlier in the development process
179© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Functions
180© 2018 The Knowledge Academy Ltd
Main Kitchen
(RETURNS hot sauce) Sous-chef sauce kitchen (can take in and )
Grind meat (using meat grinder)
Read recipe book no.1
Boil pasta and veggies. Use blender for veggies.
Cook meat in butter. Add salt and a touch of wine.
Ask Sous-chef sauce kitchen to make hot sauce! (send sous-chef some and some )
Hot sauce received.
Meal ready and sent to customer!
Read recipe book no.2
Heat up butter in milk.
Use blender to chop up chillies.
Add salt and red wine.
Send hot sauce to main kitchen!
181© 2018 The Knowledge Academy Ltd
Describing Functions
• Sometimes while programming, the need arises to repeat a set of statements again and
again
• The programmer could choose to write the code again provided it is small and not being
constantly replicated
• To avoid this, C makes use of functions
• One function we have already seen is the main() function
• Main is an in-built function that can be used for calling other functions, as we saw in the
case of Strings
• This section will describe how functions can be created in C
182© 2018 The Knowledge Academy Ltd
User Defined Functions
There are two categories of functions:
- In-built functions are those that have been defined by the C development team for
performing basic jobs . These functions reside in the header files (e.g. stdio.h, string.h,
math.h etc.). Each of these header files contain functions as per their names.
- User-defined functions are sets of statements that can be defined and subsequently
called across multiple program files
183© 2018 The Knowledge Academy Ltd
Parts of a Function
Function name
Actual name of the function
Parameter list
Comparable to a placeholder, as value is passed to the parameter
when a function commences. Not all functions have parameters
Function body
A collection of statements that defines the operations of the functions
Return type
Function may return a value, but not always the case (even when
desired operation has taken place)
184© 2018 The Knowledge Academy Ltd
Parts of a Function
185© 2018 The Knowledge Academy Ltd
Declaring Functions
• Tells compiler how many parameters the function will be taking, as well as data types
and the return type
• Below is a function taking two integers as parameters, and then returning an integer
int max(int, in);
• Following is a function taking a char and int as parameters, which return an integer
int fun(char, int);
186© 2018 The Knowledge Academy Ltd
Functions
printf() functions
• In-built library functions available by default
• Declared stdio.h header file
• Used to print characters, strings, floats, integers, octals, and hexadecimal
values on output screen
• New line generated by n
187© 2018 The Knowledge Academy Ltd
Functions
C programme with printf() functions
#include <stdio.h>
int main()
{
char ch = ‘A’;
char str[30] = “theknowledgeacademy.com”;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(“Character is %c n”, ch);
printf(“String is %s n” , str);
printf(“Float value is %f n”, flt);
printf(“Integer value is %dn” , no);
printf(“Double value is %lf n” , dbl);
printf(“Octal value is %o n” , no);
printf(“Hexadecimal value is %x n” , no);
return 0;
}
OUTPUT
Character is A
String is theknowledgeacademy.com
Float value is 10.234999
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
188© 2018 The Knowledge Academy Ltd
Functions
scanf() functions
• Format specifier %d is used in scanf() statement, so that value entered
is received as an integer and in %s for string
• Ampersand (&) is used before name of variable ch in scanf() statement
as &ch
• Comparable to a pointer, as it ‘points’ to the variable
189© 2018 The Knowledge Academy Ltd
User Defined Functions
• Every user defined function in C has a structure like this:
• Any user-defined function must be declared immediately after the pre-
processors, to enable the compiler to locate them
<return type> function name ([<list of
arguments>])
{
body of function
…
[optional return statement];
}
190© 2018 The Knowledge Academy Ltd
User Defined Functions
• Return type – the return type is the type of the data that will be returned by the
function to the calling function. If no data is returned then return type is void and the
function will have no return statement, as in main()
• Function name – this is the name of the function that another function will call in the set
of statements
• Argument list – if any extra information needs to be passed to the function to complete
its processing, it is passed as an argument. The function can have no arguments, or
many. Arguments are of two types – actual and formal
• Body – this is the part of the function which is actually doing the processing
• Return statement – this is used for returning data of the return type. It is optional
191© 2018 The Knowledge Academy Ltd
User Defined Functions
• Example:
192© 2018 The Knowledge Academy Ltd
User Defined Functions
• The program shown here defines two functions that do not return any value or
accept any arguments
• Both functions are first declared immediately after the #include statement, so
that the compiler knows that these functions have been defined by the user in
this program and does not come up with any error when they are called
• The welcome() statement invokes a function by the same name and so does the
terminate() statement
• void specifies that no value is returned and as such no return keyword in either of
the functions
193© 2018 The Knowledge Academy Ltd
User Defined Functions
• Example demonstrating the use of return keyword and argument list
194© 2018 The Knowledge Academy Ltd
User Defined Functions
• This program accepts two numbers, First and Second (of integer type)
• The numbers are passed to the user-defined function add() where they are
received in the formal parameters a and b
• Inside the function, a local variable c is declared to hold the sum of a and b
• The return statement is used to return this value to the main program
• Inside main(), the variable Result holds the returned value, which is then printed
on the user’s screen
195© 2018 The Knowledge Academy Ltd
Nesting Function Calls
• Functions in C can be called
from another function the
same as they are called from
main()
• When the main() function
calls FunctionOne(),
FunctionOne() calls
FunctionTwo(), FunctionTwo()
calls FunctionThree(), and so
on, this is known as nesting
196© 2018 The Knowledge Academy Ltd
Recursive Functions
• Sometimes programmers come across situations where a function needs to be
called repeatedly
• This can be hazardous: an infinite loop may result in an “Out of Memory” error
and the system may as well crash
• To avoid this, programmers often include an if condition that helps them to
terminate the loop at a specified point
• These are known as recursive functions
• The terminating condition is known as the base condition
• The best example of a recursive function is the factorial of a number
197© 2018 The Knowledge Academy Ltd
Recursive Functions
198© 2018 The Knowledge Academy Ltd
Setting a
number to
the power n –
technique 1
199© 2018 The Knowledge Academy Ltd
Setting a
number to
the power n –
technique 2
200© 2018 The Knowledge Academy Ltd
Setting a
number to
the power n –
technique 3
201© 2018 The Knowledge Academy Ltd
Exercise time!
202© 2018 The Knowledge Academy Ltd
1) Write a C program to input a number from user and
check whether given number is even or odd using
functions.
203© 2018 The Knowledge Academy Ltd
2) Write a C program to input a number from user and
check whether given number is even or odd using
functions.
204© 2018 The Knowledge Academy Ltd
3) Write a recursive function in C programming to find
the sum of all natural numbers between 1 to n.
205© 2018 The Knowledge Academy Ltd
206© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Pointers
207© 2018 The Knowledge Academy Ltd
Using Pointers
• Pointers are an advanced way of dealing with data in C
• A Pointer is a special type of variable that can store
the address of another variable. They are unique to C
and C++
• A pointer can point to a variable of the same type as
that of the pointer
• Pointers use two special symbols to operate
• These are & to store the address of a variable and * to
access the value of a variable. &var generates an
address for var within the programme’s memory
• * is also used while declaring a pointer variable
#include <stdio.h>
int main()
{
int var = 10;
printf(“Value: %dn”, var);
printf(“Address: %u”, &var);
return 0;
}
208© 2018 The Knowledge Academy Ltd
Using Pointers
209© 2018 The Knowledge Academy Ltd
Using Pointers
• If the value of the pointer is incremented or decremented using the ++ or – operators, the
address stored in the pointer will change
• This may (though not always) lead to erroneous output
210© 2018 The Knowledge Academy Ltd
Using Pointers
• The program shown on the last slide initialises the pointer to the address
of i
• It also increments the value of ptr twice, which changes the address stored
in it and consequently the value
• As such, it is imperative that pointers are handled very carefully
211© 2018 The Knowledge Academy Ltd
String Pointers
• Pointers can be used with almost any data type
• With Strings, pointers can be used to manipulate each and every character
• This example counts the number of characters in a string using pointers
212© 2018 The Knowledge Academy Ltd
String Pointers
• The ‘&’ character was not used in the above
program
• This is because a string is already a character array
and the ptr = str statement assigns the address of
the 0th element of str to the pointer variable ptr
• When we increment ptr, it increments the address
to the next index number
• Thus, calling *ptr displays one character at a time
instead of the entire string
• We use i as a counter variable to keep track of the
length of the string
213© 2018 The Knowledge Academy Ltd
Pointers to Pointers
214© 2018 The Knowledge Academy Ltd
Pointers to Pointers
• The previous example illustrates how a user can define a Pointer to a Pointer
• Initially, we define a pointer ptr that points to an integer point i
• Next, another pointer variable ptr2ptr (also of integer type) points to ptr
• Using either of these variables we can get the value 340 as depicted in the output
• Remember a Pointer to a Pointer must be declared with a ** instead of a *
215© 2018 The Knowledge Academy Ltd
Array of Pointers
• C allows users to declare an array of pointers
• An array of pointers can be declared like any other array but the contents are only pointers
216© 2018 The Knowledge Academy Ltd
Array of Pointers
• This program declares an array of
integers and then an array of integer
pointers
• The first for loop assigns the address of
the integer array cells to the array of
pointers
• Once this is done, the pointer’s address
and its values are printed on to the user
screen
217© 2018 The Knowledge Academy Ltd
NULL Pointers
• You can declare a pointer as NULL in value if the address of pointer
variable is not known
• NULL pointers are constant
• Not to be confused with an uninitialised/dangling pointer, which is not
guaranteed to be compared as unequal to an initialised pointer
• Two NULL pointers will compare as equal
218© 2018 The Knowledge Academy Ltd
RECAP
219© 2018 The Knowledge Academy Ltd
Exercises!
220© 2018 The Knowledge Academy Ltd
1) Write a C program to create, initialize and demonstrate
the use of pointers.
221© 2018 The Knowledge Academy Ltd
2) Write a C program to prompts the user to enter two
float values, assigns their addresses to two float pointers
and adds these two float values using both pointers.
222© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Structures
223© 2018 The Knowledge Academy Ltd
Structures
• In C, structures are used for storing different types of data that is grouped together
• A user may want to store employee details such as Employee Code, Employee
Name and Salary or Customer Details such as Customer Number, Customer Name,
Product Purchased, Qty Purchased, or Amount Paid
• All these details could be stored in a single structure, such as Employee or
Customer
• An object of the structure could then be created to store or access its values
• A structure is by default public in nature
224© 2018 The Knowledge Academy Ltd
Structures
Example of a structure
#include <stdio.h>
struct EmployeeData{
char *employee_name;
char *employee_title;
char *employee_dept;
};
char main()
{
struct EmployeeData employee;
employee.employee_name = "John Bonham";
employee.employee_title = "Marketing Executive";
employee.employee_dept = "Marketing";
printf("Employee Name is: %s", employee.employee_name);
printf("nEmployee Title is: %s", employee.employee_title);
printf("nEmployee Department is: %s", employee.employee_dept);
return 0;
}
OUTPUT
Employee Name is: John Bonham
Employee Title is: Marketing Executive
Employee Department is: Marketing
225© 2018 The Knowledge Academy Ltd
Structures
typedefs
• Define types using a different name
when working with structs and
pointers, which appear as asterisks
• Essentially saves coder from constantly
typing struct throughout the code
• Code is shorter and more visually
accessible
typedef struct work_address{
int house_number;
char *street_name;
char *town;
char *city;
char *county;
int *postcode;
}addr;
..
..
addr var1;
var.town = “London”;
226© 2018 The Knowledge Academy Ltd
Structures
Designated initialisation
• Members of the structure (i.e.
variables) can be initialised in
any given order
• Added to C99 standard
• Unavailable in C++
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialisation using designated initialisation
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z);
printf ("x = %d", p2.x);
return 0;
}
227© 2018 The Knowledge Academy Ltd
Array of Structures
• It is possible to create a
structure and use it in an array
• This would be useful in a
situation where there are
more than one employees for
whom the same details need
to be entered or retrieved
• In such cases, we could make
use of an array of structures,
as in this example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
struct employee
{
int empcode;
int salary;
float allow;
float deduct;
float netsal;
};
228© 2018 The Knowledge Academy Ltd
Array of Structures
• Structure Example (contd.)
struct employee emp[3];
int i;
clrscr();
for(i=0;i<3;i++)
{
printf("Enter Code Number:");scanf("%d", &emp[i].empcode);
printf("Enter Employee Salary:");scanf("%d", &emp[i].salary);
emp[i].allow=0.05 * emp[i].salary;
emp[i].deduct=0.02 * emp[i].salary;
emp[i].netsal=emp[i].salary+ emp[i].allow-emp[i].deduct;
printf("n================================n");
}
229© 2018 The Knowledge Academy Ltd
Array of Structures
• Structure Example (contd.)
clrscr();
for(i=0;i<3;i++)
{
printf("nCode:%d", emp[i].empcode);
printf("nBasic Salary:%d", emp[i].salary);
printf("nAllowance:%.2f",emp[i].allow);
printf("nDeduction:%.2f",emp[i].deduct);
printf("nNet Salary:%.2f",emp[i].netsal);
printf("n================================");
}
getch();
}
230© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• A very common concept in C is that of the linked list
• A linked list is a list of nodes where each node is a structure
• A Single Linked List has nodes that are added at the end of the list
• The first node added is known as the start node, the final node is called the last
node, and the node being traversed currently is called the current node
• Whenever a node is added, the program checks whether the list contains any
nodes
• If the list is empty, the new node becomes the first as well as the last node
231© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• As the nodes are added, the start node
remains fixed but the last node moves
ahead
• Every new node contains a NULL value
in its next pointer
• The last pointer replaces this with the
address of the next node
• The result is as follows:
232© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• Example Program
#include <stdio.h>
void showlist();
struct node* getnode();
struct node *start;
struct node *last;
struct node
{
int empcode;
int salary;
struct node* next;
};
233© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• Example Program
void main()
{
struct node *ptr;
char ans='y';
clrscr();
start=NULL;
while (ans=='y')
{
if(start==NULL)
{
ptr=getnode();
start=ptr;
last=start;
}
234© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• Example Program
else
{
ptr= getnode();
last->next=ptr;
last=ptr;
}
printf("n Continue(y/n)?");
ans=getch();
}
showlist();
getch();
}
235© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• Example Program
void showlist()
{
struct node *temp; int i=1;
clrscr();
temp=start;
while(temp!=NULL)
{
printf("nRecord No:%d",i++);
printf("nCode:%d", temp->empcode);
printf("nSalary:%d", temp->salary);
printf("n=====================");
temp=temp->next;
getch();
}
}
236© 2018 The Knowledge Academy Ltd
Using Structures with Pointers
• Example Program
struct node* getnode()
{
struct node *temp;
temp = (struct node*) malloc (sizeof (struct node));
printf("nEnter Code:");
scanf("%d", &temp->empcode);
printf("nEnter Salary:");
scanf("%d",&temp->salary);
temp->next=NULL;
return temp;
}
237© 2018 The Knowledge Academy Ltd
Project Management,
Management
& Leadership
Operating Bigger Programs
238© 2018 The Knowledge Academy Ltd
Dividing Programs
• Sometimes programmers are asked to write very large programs
• Navigating huge programs is an extremely difficult process
• As a best practice, it is always advisable to divide a single huge program into
multiple modules as well as a library of functions containing a suite of
subroutines within one or more modules
• However, only one of these files will contain the main() function
• By writing a group of functions in different module files, these module files can
be shared with many other programs as well
239© 2018 The Knowledge Academy Ltd
Dividing Programs
Why write modules instead of a single programme?
• Modules will naturally divide into common
groups of functions
• It is much easier to compile each module
separately, rather than link them in compiled
modules
• UNIX utilities can help maintain large systems
240© 2018 The Knowledge Academy Ltd
Header Files
• If we are dealing with modular files, we will have to store the definition
of the variables and functions somewhere
• As per convention, the best place would be a header file
• C allows its users to create their own header files
• These header files can be included into our C program using the keyword
#include in the following manner:
#include “userdefined.h”
241© 2018 The Knowledge Academy Ltd
Header Files
Example of modules
#define .....
void .....
int .....
#include< >
#include “header.h”
main()
{
.....
}
#include “header.h”
void
WriteMyString()
{
.....
}
header.h
main.c WriteMyString.c
#include .....
fns .....
#include .....
fns .....
#include .....
fns .....
Other modules
mod1.c
mod2.c
mod3.c
242© 2018 The Knowledge Academy Ltd
Header Files
Full listings
main.c:
/* * main.c */
#include "header.h"
#include <stdio.h>
char *AnotherString = "Hello Everyone";
main()
{
printf("Running...n");
/* * Call WriteMyString() - defined in another file */
WriteMyString(MY_STRING);
printf("Finished.n");
}
243© 2018 The Knowledge Academy Ltd
Header Files
Full listings
WriteMyString.c:
/*
* WriteMyString.c
*/
extern char *AnotherString;
void WriteMyString(ThisString)
char *ThisString;
{
printf("%sn", ThisString);
printf("Global Variable = %sn", AnotherString);
}
244© 2018 The Knowledge Academy Ltd
Header Files
Full listings
header.h:
/*
* header.h
*/
#define MY_STRING "Hello World"
void WriteMyString();
245© 2018 The Knowledge Academy Ltd
Header Files
Full listings
• Some modules have a #include “header.h” that share common definitions
• Some (like main.c) also include standard header files
• main calls the function WriteMyString(), which is in the WriteMyString.c module
• The function prototype void for WriteMyString is defined in header.h
246© 2018 The Knowledge Academy Ltd
Header Files
Sharing variables
• If global variables are declared in a module, the knowledge of said variables must be
passed on to other modules
• This can be achieved by passing values as parameters to functions; however:
o This can be a convoluted process if the same parameters are passed to many
functions, and/or if there is a long argument list involved
o Large arrays and structures are difficult to store locally, and there are often memory
problems associated with the stack function
247© 2018 The Knowledge Academy Ltd
Header Files
External variables and functions
• “Internal” implies that arguments and functions are defined inside the functions (i.e.
locally)
• Therefore, “external” variables are defined outside of functions
• In other words, they are potentially available to the entire programme
• External variables are always permanent
248© 2018 The Knowledge Academy Ltd
Header Files
Scope of externals
• External variables/functions are not always completely global
• With that in mind, C programming language will apply the following rule:
“The scope of an external variable (or function) begins at its point of declaration and
lasts to the end of the file (module) it is declared in.”
A. D. Marshall (1998)
Hands On: C Programming and Unix Application Design: UNIX System Calls and Subroutines Using C
249© 2018 The Knowledge Academy Ltd
Using Several Files
• In a team of programmers, each programmer could work on different files and
yet access the same modules
• An object oriented style can be used, with each file defining a particular type of
object as a data type and various operations that can be carried on that object
• To make it more structured, the object can be implemented privately
• Files can contain all functions from a related group, which can be accessed like a
function library
• Well implemented objects or function definitions can be re-used in other
programs
250© 2018 The Knowledge Academy Ltd
Using Several Files
• In very large programs, each major function can occupy a file to itself
• Any lower-level functions used to implement them can be kept in the
same file – this reduces distraction for developers
• When changes are made to a file, only that file needs to be recompiled
to rebuild the program
• The UNIX make facility is very useful for rebuilding multi-file programs in
this way
251© 2018 The Knowledge Academy Ltd
The Modular Approach
Advantages
• Teams of programmers can work on individual
programmes, and focus on their area of expertise
• An object-oriented style can be used; each file defines
a particular type of object as a data type, and
operations on that object as functions
• Implementation of the object can be kept private from
the rest of the programme
252© 2018 The Knowledge Academy Ltd
The Modular Approach
Advantages
• Guarantees well-structured programmes that are
easy to maintain
• Files can contain all functions from a related group
o e.g. All matrix operations can be accessed like a
function library
253© 2018 The Knowledge Academy Ltd
The Modular Approach
Advantages
• Well-implemented object/function definitions can be
re-used in other programmes, therefore reducing
development time
• Each major function within a large programme can
occupy a file to itself; any lower level functions used to
implement these can be kept in the same files
• Changes made to a file can easily be recompiled when
re-building the programme
254© 2018 The Knowledge Academy Ltd
The Modular Approach
Dividing a programme between several files
• Where objects are implemented as data structures, it is sensible to keep all functions
(which access that object) in the same file
• The advantages are:
o The object can easily be re-used in other programmes
o All related functions are stored together
o Future changes to the object require only one file to modified
255© 2018 The Knowledge Academy Ltd
The Modular Approach
Organisation of data
• Any and every file must have its data organised in a certain order, which will typically be:
o A preamble consisting of #defined constraints, #included header files, and typedefs
of important datatypes
o A declaration of global and external variables, the former of which may be initialised
o One or more functions
256© 2018 The Knowledge Academy Ltd
The Modular Approach
Organisation of data
• Ordering must not be overlooked, since every object must be defined before it can be used
• Functions that return values must be defined before they are called
• One of two definitions may be applicable:
o Where the function is defined and called in the same file, a full declaration of the
function can be placed ahead of any call to the function
o If the function is called from a file where it is not defined, a prototype should appear
before the call to the function
257© 2018 The Knowledge Academy Ltd
Congratulations
Congratulations on completing this course!
Keep in touch
info@theknowledgeacademy.com
Thank you

More Related Content

What's hot

9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTBatra Centre
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12Terry Yoast
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programingAhammed Alamin
 
Constructive Cost Model - II (COCOMO-II)
Constructive Cost Model - II (COCOMO-II)Constructive Cost Model - II (COCOMO-II)
Constructive Cost Model - II (COCOMO-II)AmanSharma1172
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06Terry Yoast
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 

What's hot (20)

9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
Gireesh G.G Resume
Gireesh G.G ResumeGireesh G.G Resume
Gireesh G.G Resume
 
Lesson 1 introduction to programming
Lesson 1 introduction to programmingLesson 1 introduction to programming
Lesson 1 introduction to programming
 
Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
Book ppt
Book pptBook ppt
Book ppt
 
Chapter 02 - Problem Solving
Chapter 02 - Problem SolvingChapter 02 - Problem Solving
Chapter 02 - Problem Solving
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
Problem solving methodology
Problem solving methodologyProblem solving methodology
Problem solving methodology
 
C aptitude book
C aptitude bookC aptitude book
C aptitude book
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
 
Abc c program
Abc c programAbc c program
Abc c program
 
Constructive Cost Model - II (COCOMO-II)
Constructive Cost Model - II (COCOMO-II)Constructive Cost Model - II (COCOMO-II)
Constructive Cost Model - II (COCOMO-II)
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06
 
Lesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving processLesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving process
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
JavaScript functions
JavaScript functionsJavaScript functions
JavaScript functions
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Lesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th stepLesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th step
 

Similar to Lesson slides for C programming course

Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in PythonHaim Michael
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"GlobalLogic Ukraine
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeksAashutoshChhedavi
 
Chapter 1-INTRO TO PF.pptx
Chapter 1-INTRO TO PF.pptxChapter 1-INTRO TO PF.pptx
Chapter 1-INTRO TO PF.pptxSitiZaharahSidek
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEMMansi Tyagi
 
Chapter 1 (Solid Mechanics).ppt
Chapter 1 (Solid Mechanics).pptChapter 1 (Solid Mechanics).ppt
Chapter 1 (Solid Mechanics).ppt2022449652
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkAbdullahNadeem78
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++DSCIGDTUW
 
C++ language basic
C++ language basicC++ language basic
C++ language basicWaqar Younis
 
Computer programming all chapters
Computer programming all chaptersComputer programming all chapters
Computer programming all chaptersIbrahim Elewah
 
Refinery Blending Problems by Engr. Adefami Olusegun
Refinery Blending Problems by Engr. Adefami OlusegunRefinery Blending Problems by Engr. Adefami Olusegun
Refinery Blending Problems by Engr. Adefami OlusegunEngr. Adefami Segun, MNSE
 
Learn C Programming Full Course Free
Learn C Programming Full Course FreeLearn C Programming Full Course Free
Learn C Programming Full Course FreeDheeraj Patidar
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfMMRF2
 
Book management system
Book management systemBook management system
Book management systemSHARDA SHARAN
 
No liftoff, touchdown, or heartbeat shall miss because of a software failure
No liftoff, touchdown, or heartbeat shall miss because of a software failureNo liftoff, touchdown, or heartbeat shall miss because of a software failure
No liftoff, touchdown, or heartbeat shall miss because of a software failureRogue Wave Software
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit orderMalikireddy Bramhananda Reddy
 

Similar to Lesson slides for C programming course (20)

Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
 
Chapter 1-INTRO TO PF.pptx
Chapter 1-INTRO TO PF.pptxChapter 1-INTRO TO PF.pptx
Chapter 1-INTRO TO PF.pptx
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
 
Chapter 1 (Solid Mechanics).ppt
Chapter 1 (Solid Mechanics).pptChapter 1 (Solid Mechanics).ppt
Chapter 1 (Solid Mechanics).ppt
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net framework
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Computer programming all chapters
Computer programming all chaptersComputer programming all chapters
Computer programming all chapters
 
Refinery Blending Problems by Engr. Adefami Olusegun
Refinery Blending Problems by Engr. Adefami OlusegunRefinery Blending Problems by Engr. Adefami Olusegun
Refinery Blending Problems by Engr. Adefami Olusegun
 
Learn C Programming Full Course Free
Learn C Programming Full Course FreeLearn C Programming Full Course Free
Learn C Programming Full Course Free
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Yogesh_job_resume
Yogesh_job_resumeYogesh_job_resume
Yogesh_job_resume
 
C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
 
Book management system
Book management systemBook management system
Book management system
 
No liftoff, touchdown, or heartbeat shall miss because of a software failure
No liftoff, touchdown, or heartbeat shall miss because of a software failureNo liftoff, touchdown, or heartbeat shall miss because of a software failure
No liftoff, touchdown, or heartbeat shall miss because of a software failure
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Lesson slides for C programming course

  • 1. 1© 2018 The Knowledge Academy Ltd C Programming
  • 2. 2© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership About The Knowledge Academy • World Class Training Solutions • Subject Matter Experts • Highest Quality Training Material • Accelerated Learning Techniques • Project, Programme, and Change Management, ITIL® Consultancy • Bespoke Tailor Made Training Solutions • PRINCE2®, MSP®, ITIL®, Soft Skills, and More
  • 3. 3© 2018 The Knowledge Academy Ltd • Trainer • Fire Procedures • Facilities • Days/Times • Breaks • Special Needs • Delegate ID Check • Phones and Mobile Devices Administration
  • 4. 4© 2018 The Knowledge Academy Ltd • What is a program? • (De)constructing a simple program • Variables and Constants • Operators and Terminologies • Constructs • Arrays • Strings Outline day 1
  • 5. 5© 2018 The Knowledge Academy Ltd • A bit of C programming history… • Functions • Pointers • Structures • Operating Bigger Programs Outline day 2
  • 6. 6© 2018 The Knowledge Academy Ltd What is a program?
  • 7. 7© 2018 The Knowledge Academy Ltd A program is a recipe!
  • 8. 8© 2018 The Knowledge Academy Ltd Analyse this:
  • 9. 9© 2018 The Knowledge Academy Ltd Main Kitchen (RETURNS hot sauce) Sous-chef sauce kitchen (can take in and ) Grind meat (using meat grinder) Read recipe book no.1 Boil pasta and veggies. Use blender for veggies. Cook meat in butter. Add salt and a touch of wine. Ask Sous-chef sauce kitchen to make hot sauce! (send sous-chef some and some ) Hot sauce received. Meal ready and sent to customer! Read recipe book no.2 Heat up butter in milk. Use blender to chop up chillies. Add salt and red wine. Send hot sauce to main kitchen!
  • 10. 10© 2018 The Knowledge Academy Ltd Notion 1: GLOBAL vs LOCAL GLOBAL ingredients (that can be used from any kitchen) LOCAL ingredients (that can only be used one specific kitchen)
  • 11. 11© 2018 The Knowledge Academy Ltd (in programming terms…) GLOBAL variables = variables that can be read from any function LOCAL variables = variables that can only be read from the function where they are declared (as we can see: some local variables can be sent from one function to another. We will have a closer look at this on Day 2)
  • 12. 12© 2018 The Knowledge Academy Ltd Notion 2: main structure of a C program Headers, pre-processor directives, global/constant variables, function prototypes… Main function Function A Function B
  • 13. 13© 2018 The Knowledge Academy Ltd Analyse this…
  • 14. 14© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership
  • 15. 15© 2018 The Knowledge Academy Ltd in fact… Headers, pre-processor directives, global/constant variables, function prototypes… Documentation Main function Function A Function B
  • 16. 16© 2018 The Knowledge Academy Ltd Analyse this…
  • 17. 17© 2018 The Knowledge Academy Ltd /* Documentation section C programming basics & structure of C programmes Author: theknowledgecacademy.com Date: 06/11/2018 */ #include <stdio.h> /* Link section */ int total = 0; /* Global declaration, definition section */ int sum = (int, int); /* Function declaration section */ int main () /* Main function */ { printf (“This is a C basic programme n”); total = sum (1, 1); printf (“Sum of two numbers : %d n”, total)l return 0; } int sum (int a, int b) /* User defined function */ { return a + b; /* definition section */ }
  • 18. 18© 2018 The Knowledge Academy Ltd RECAP In general, most C programs use the following structure: • Documentation section (if necessary) • Pre-processors directives and/or header files and/or global variable declarations and/or function prototypes… • Main() function  absolutely mandatory!!! • Other functions (if necessary)
  • 19. 19© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership (De)constructing a simple program
  • 20. 20© 2018 The Knowledge Academy Ltd (De)constructing a simple program Let’s start by typing this code in: #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 21. 21© 2018 The Knowledge Academy Ltd (De)constructing a simple program • We are going to start by writing the basic program "Hello World”, which will print (or output) the message "Hello, World!" on screen • This is a very simple program designed to help you understand the syntax of C • We will break down each component line by line and explain its function #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 22. 22© 2018 The Knowledge Academy Ltd (De)constructing a simple program: line 1 • The first line is the #include command, followed by <stdio.h> • stdio.h is a header file containing standard input and output functions for the program (such as printf) • Without this file, input and output functions will not work and the program will not compile #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 23. 23© 2018 The Knowledge Academy Ltd (De)constructing a simple program: more on line 1 • the #include command is in fact called a pre-processor directive • Pre-processor directives tell the compiler how to modify the code before it is compiled • This is the section where header files (here: <stdio.h>) are placed in the system library to access predefined functions • We include files using #include followed by the name of the file in < > • All header files end in .h • Pre-processors are specified using the # directive
  • 24. 24© 2018 The Knowledge Academy Ltd (De)constructing a simple rogram: more on line 1 • Examples include: #include <stdio.h> #define pi=3.14 #undefine pi #ifdef
  • 25. 25© 2018 The Knowledge Academy Ltd (De)constructing a simple program: line 2 • The next line is the start of the int main() function (notice the curly brackets {…}) • This int main() may or may not have other elements (called arguments) inside its (…) (but we won’t talk about this) • As with any other function, int placed before main() means that the main() function returns a value once all of the contents inside its {…} has been processed  we can see this on the last line, where it is said: return 0 #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 26. 26© 2018 The Knowledge Academy Ltd (De)constructing a simple program: more on line 2 • The main() function defines where the C program starts. • Regardless of where it is placed, it is always the first function executed when the program starts. • This main() function is mandatory for any C program, as all other functions are called from it. #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 27. 27© 2018 The Knowledge Academy Ltd (De)constructing a simple program: line 3 • The printf() function displays the text inside quotation marks (“Hello, World!”) • It is a library function that sends the output to the screen • Printf() will not work without stdio.h • /n is an escape sequence, which essentially represents a newline character for the “Hello, World!” string #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 28. 28© 2018 The Knowledge Academy Ltd (De)constructing a simple program: line 4 The program ends when the return statement is encountered within the main() function (but it in this very rare case, it is not mandatory) ‘0’ provides an exit status, showing that the program executed successfully with no errors #include <stdio.h> int main() { printf(“Hello, World!n”); return 0; }
  • 29. 29© 2018 The Knowledge Academy Ltd How it all runs The following steps are used in every C program – whether small or large – to generate an output: Create Compile Execute or run Get the output
  • 30. 30© 2018 The Knowledge Academy Ltd Note on the notion of compiling • Compiling means converting C code into machine language that can be read and understood by the computer • Popular C compilers include GCC (Linux), Visual C++ (Windows), Turbo C, and Borland C • Once the .C program has been compiled, a new file with the same name but the extension .EXE is generated • It is this .EXE file that is executed
  • 31. 31© 2018 The Knowledge Academy Ltd Exercise! Write a short C program where five statements of your choice are printed out. Watch out! Each statement must start on a new line!
  • 32. 32© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership
  • 33. 33© 2018 The Knowledge Academy Ltd The fascinating world of variables
  • 34. 34© 2018 The Knowledge Academy Ltd What is a variable? First and foremost, a variable is a memory location, the name of which (“cat”, “var1”, “loopiloo”…) is decided by the programmer. This memory location contains a specific type of data (confirmed through its declaration), the size and layout of which is precisely determined by the type. A variable can have its contents changed at any time (as long as it is of the same type) (NOTE: we will talk more about memory when we talk about pointers) RAM 8 Memory location a is reserved
  • 35. 35© 2018 The Knowledge Academy Ltd Two sorts of memory locations There are two types of memory locations: - Variables: memory locations whose contents can change during the execution of a program - Constants: memory locations whose contents cannot be changed while the program is executing (the use of const determines when a variable is a constant) See example:
  • 36. 36© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership
  • 37. 37© 2018 The Knowledge Academy Ltd Try and change the value of a const variable!!
  • 38. 38© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership
  • 39. 39© 2018 The Knowledge Academy Ltd 4 main Data Types Before we can use a variable in C we must declare it. When we declare it, we tell the computer what data type it is. There are 4 basic data types: • int – an integer, or a whole number • char – a single character • float – decimals, numbers with a ‘floating point’ value up to 7 digits • double – a more precise version of float up to 15 digits
  • 40. 40© 2018 The Knowledge Academy Ltd Real purpose of declaring a variable When we declare a variable, we in fact inform the computer how much memory space we require for this variable! This memory space is generally in bytes (remember: 1 byte = 8 bits) Try the following to know the amount of memory required for each type of variable…
  • 41. 41© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership
  • 42. 42© 2018 The Knowledge Academy Ltd Various rules for naming variables • A variable’s name can only start with a letter or underscore; it will not accept integers • Able to contain letters, integers, and underscores though! • Reserved word/keyword (e.g. char, float) cannot be used for variable’s name • No whitespace is permitted
  • 43. 43© 2018 The Knowledge Academy Ltd 2 ways of declaring variables (manually) Technique 1: Technique 2: int age, yearOfBirth, population; int age; int yearOfBirth; int population;
  • 44. 44© 2018 The Knowledge Academy Ltd Initialising variables: how it is done Now that we have seen how to declare a variable (ie: to inform the computer of the amount of memory space required for the variables we wish to use), the time now comes to place values inside these variables! This is called: initialisation, and it is done through the symbol = WARNING: as we shall see, the = symbol does not mean ‘equal’!
  • 45. 45© 2018 The Knowledge Academy Ltd 2 ways of initialising variables (manually) Technique 1: Technique 2: FirstNumber = SecondNumber = ThirdNumber = 24; FirstNumber = 24; SecondNumber = 24; ThirdNumber = 24;
  • 46. 46© 2018 The Knowledge Academy Ltd Declaring + initialising variables all in one go (manually) int FirstNumber = 24, SecondNumber = 45, ThirdNumber = 9001;
  • 47. 47© 2018 The Knowledge Academy Ltd Rules for declaring variables • Declared variables cannot be changed, as shown below • int cannot be changed to floating point 5.5, nor can it be changed to a double number • Error generated as a result of this int number = 5; // integer variable number – 5.5; // error double number; // error
  • 48. 48© 2018 The Knowledge Academy Ltd Example of LOCAL variable declaration & initialisation
  • 49. 49© 2018 The Knowledge Academy Ltd Example of GLOBAL variable declaration & initialisation
  • 50. 50© 2018 The Knowledge Academy Ltd Initialising variables (user) To enable users to test your program by entering whatever value they want, the scanf() function must be used. The syntax is as follows:
  • 51. 51© 2018 The Knowledge Academy Ltd Format identifiers(1) Notice the “…%” expression, when we use scanf()? This is to enable the real-time input of values through scanf(). This expression is called a format identifier.
  • 52. 52© 2018 The Knowledge Academy Ltd Format identifiers(2)
  • 53. 53© 2018 The Knowledge Academy Ltd Format identifiers - examples #include <stdio.h> int main() { char ch = 'A'; printf("%cn", ch); return 0; } #include <stdio.h> int main() { float a = 12.67; printf("%fn", a); printf("%en", a); return 0; }
  • 54. 54© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Operators and Terminologies
  • 55. 55© 2018 The Knowledge Academy Ltd Operators An operator in C is a symbol that tells the compiler to perform a specific mathematical or logical function. The C language has many built-in operators, such as: • Arithmetic Operators • Relational Operators • Logical Operators • Assignment Operators • Bitwise Operators • Misc Operators
  • 56. 56© 2018 The Knowledge Academy Ltd Operators The various Arithmetic Operators in C are: Operator Description Example + Adds two numbers A+B= 20 - Subtracts second number from the first A-B=10 * Multiplies both numbers A*B=200 / Divides two numbers A/B=10 % Finds the remainder after division B%A=0
  • 57. 57© 2018 The Knowledge Academy Ltd Operators Relational Operators Operator Description Example == Checks if the values of two numbers are equal or not. If yes, then the condition becomes true A==B is not true != Checks if the values of two numbers are equal or not. If the values are not equal, then the condition becomes true (A != B) is true > Checks if the value of left number is greater than the value of right number. If yes, then the condition becomes true (A > B) is not true These are used to check the relationship between two numbers.
  • 58. 58© 2018 The Knowledge Academy Ltd Operators Arithmetic Unary Operators Operator Description Example ++ Increment operator – increases a number by 1 A++ -- Decrement operator – decreases a number by 1 A--
  • 59. 59© 2018 The Knowledge Academy Ltd Operators Relational Operators Operator Description Example < Checks if the value of left number is less than the value of right number. If yes, the condition becomes true (A < B) is true >= Checks if the value of left number is greater than or equal to the value of right number. If yes, the condition becomes true (A >= B) is not true <= Checks if the value of left number is less than or equal to the value of right number. If yes, the condition becomes true (A <= B) is true
  • 60. 60© 2018 The Knowledge Academy Ltd Operators Logical Operators Operator Description Example && Logical AND Operator – if both numbers are true, then the condition becomes true (A && B) is false || Logical OR Operator – if any of the two numbers is true, then the condition becomes true (A || B) is true ! Logical NOT Operator – if the numbers are true, the condition is false. If the numbers are false, the condition becomes true. !(A && B) is true These are used to check if multiple conditions are true.
  • 61. 61© 2018 The Knowledge Academy Ltd Operators and Terminologies Assignment Operators Operator Description Example = Basic Assignment – assigns one value so it is equal to another C = A + B will assign the value of A + B to C += Addition Assignment – adds the right number to the left number and assigns the result to the left number C += A is equivalent to C = C + A -= Subtraction Assignment – subtracts the right number from the left number and assigns the result to the left number C -= A is equivalent to C = C - A These are used to assign one value to another.
  • 62. 62© 2018 The Knowledge Academy Ltd Assignment Operators Operator Description Example *= Multiplication Assignment – multiplies the left number by the right number and assigns the result to the left number C *= A is equivalent to C = C * A /= Division Assignment – divides the left number with the right number and assigns the result to the left number C /= A is equivalent to C = C / A %= Remainder Assignment – finds the remainder of a division and assigns the result to the left number C %= A is equivalent to C = C % A Operators and Terminologies
  • 63. 63© 2018 The Knowledge Academy Ltd Bitwise Operators Operator Description Example & Bitwise AND Operator – if both bits are true, then the condition becomes true (A & B) = 12, i.e., 0000 1100 | Bitwise OR Operator – if either bit is true, the condition becomes true (A | B) = 61, i.e., 0011 1101 ^ Bitwise XOR Operator – returns true if either bit is true (but not both) (A ^ B) = 49, i.e., 0011 0001 These operate on numbers at the bit level, allowing users to manipulate individual bits. A bit with value 1 is equivalent to true, a bit with value 0 is equivalent to false. Operators and Terminologies
  • 64. 64© 2018 The Knowledge Academy Ltd Bitwise Operators Operator Description Example ~ Bitwise Complement Operator – changes true to false and false to true (~A ) = -61, i.e., 1100 0011 in 2's complement form >> Right Shift Operator – shifts all bits to the right by a specified number (A | B) = 61, i.e., 0011 1101 << Left Shift Operator – shifts all bits to the right by a specified number A << 2 = 240 i.e., 1111 0000 Operators and Terminologies
  • 65. 65© 2018 The Knowledge Academy Ltd Operators and Terminologies Bitwise Operators P Q P&Q P|Q P^Q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
  • 66. 66© 2018 The Knowledge Academy Ltd Terms used in C Terminologies The Terminology of C auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
  • 67. 67© 2018 The Knowledge Academy Ltd Terminologies • auto: the variables declared with auto are declared every time the program starts • break: used to exit out of a conditional or iterative structure • case: used for selecting an option from a given set of options. Preferred in place of multiple ifs • char: represents a data-type to store a single character • const: declare a constant value
  • 68. 68© 2018 The Knowledge Academy Ltd Terminologies • continue: skip the current iteration and start with the next • default: the option to be selected if none of the others are selected • do: starts the do loop that executes at least once even if the given condition is false • double: data-type to store a value with decimal points in case the value is beyond the range of float • else: the part that executes in case the if part evaluates to false
  • 69. 69© 2018 The Knowledge Academy Ltd Terminologies • enum: used for declaring enumerated types • extern: used to declare variables or functions having external links • float: data-type to store decimal point values • for: used for creating a loop to repeat some process • goto: used for transferring control to another part of the program
  • 70. 70© 2018 The Knowledge Academy Ltd Terminologies • int: used for storing integer values • long: used for storing values greater than the range of int • register: create register variables • return: return a value to the calling function. Used in functions only • short: limit the range of int data-type between -32768 to 32767
  • 71. 71© 2018 The Knowledge Academy Ltd Terminologies • signed: same as short • sizeof: the operator is used to calculate the size of a data-type • static: static variables are used to store their previous values • struct: used to define structures containing a number of variables of different types • switch: construct used along with case instead of if
  • 72. 72© 2018 The Knowledge Academy Ltd Terminologies • typedef: used for defining user-defined types • union: used for grouping different variables under a single name • unsigned: allow storage of unsigned data only • void: used when a function returns nothing • volatile: used for creating volatile objects that can be modified by the hardware • while: loop executes only when a condition is true
  • 73. 73© 2018 The Knowledge Academy Ltd Constants Backslash and character constants • Backslash preceding symbol indicates a special function Backslash character Meaning b Backspace f Form feed n New line r Carriage return t Horizontal tab ” Double quote
  • 74. 74© 2018 The Knowledge Academy Ltd Constants Backslash and character constants Backslash character Meaning ’ Single quote Backslash v Vertical tab a Alert or bell ? Question mark N Octal constant XN Hexadecimal constant
  • 75. 75© 2018 The Knowledge Academy Ltd Escape Sequences Escape sequences are functions within a string literal or character that are not a character themselves. They always begin with a backslash. Operator Description ? Question mark n New line r Reset cursor to beginning of the current line t Horizontal tab v Vertical tab Insert a backslash ’ Insert a single quote ” Insert a double quote a Alert noise
  • 76. 76© 2018 The Knowledge Academy Ltd Variables: RECAP Local variable • Declared inside the function • Usable only inside the function inside which it is declared Global variable • Declared outside the function • Can be used throughout a C programme
  • 77. 77© 2018 The Knowledge Academy Ltd Variables: RECAP Static variable • Retains value between multiple calling of functions • Declared via static keyboard External variable • May be shared across multiple C source files • Declared via extern keyboard Automatic variable • Declared inside the block
  • 78. 78© 2018 The Knowledge Academy Ltd Key Terms • Keywords – These are predefined terms that have specialised meanings in C • Identifiers – These are the unique names assigned to variables, functions, macros, arrays etc. • Variable – A name used to refer to a location in the memory; a placeholder for a changeable value • Constants – The opposite of variables: data that will not change during program execution • Operator – A symbol that performs an action on a variable
  • 79. 79© 2018 The Knowledge Academy Ltd Let’s code!
  • 80. 80© 2018 The Knowledge Academy Ltd 1) Write a C program that asks the user to enter 3 integers, then: - Adds these three INT variables up - Multiplies the result with a CONST INT variable - Multiplies the result with a GLOBAL INT variable - Verifies if the final result is even or odd Print a statement for each result.
  • 81. 81© 2018 The Knowledge Academy Ltd
  • 82. 82© 2018 The Knowledge Academy Ltd 2) Write a C program that prompts the user to enter a double value for Celsius degrees, then convert this Celsius temperature to Fahrenheit
  • 83. 83© 2018 The Knowledge Academy Ltd
  • 84. 84© 2018 The Knowledge Academy Ltd 3) Write a C program that calculates the total average and percentage of five school subjects
  • 85. 85© 2018 The Knowledge Academy Ltd
  • 86. 86© 2018 The Knowledge Academy Ltd 4) Write a C program that does the following: - If variable var1 is greater than 5 and var2 smaller than 17, print: “Exercise 1: passed” else: “Exercise 1: failed” - If variable m1 is greater than 13 or if m2 is equal to 509, print: “Exercise 2: passed” else: “Exercise 2: failed”
  • 87. 87© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Constructs
  • 88. 88© 2018 The Knowledge Academy Ltd Constructs What are constructs? • Comparable to the syntax of programming language • Able to be read and understood by a compiler, and free of ambiguity • Comprised of curly braces, semicolons, etc. • Loops, statements, invocations, and conditions are types of constructs
  • 89. 89© 2018 The Knowledge Academy Ltd Constructs • The language C uses various constructs to accomplish specific tasks • These include conditional constructs as well as iterative constructs • Conditional constructs include if, if else, if else if else, and switch case constructs • The iterative constructs include do...while, while, and for loops
  • 90. 90© 2018 The Knowledge Academy Ltd Constructs Sequence constructs • Set of instructions that denote the order of execution • Often runs ‘top to bottom’ (i.e. line 1, line 2, line 3, and so on) • Sequences sometimes illustrated by flow charts, which make use of different shapes (e.g. circles, squares, rhombuses)
  • 91. 91© 2018 The Knowledge Academy Ltd Constructs Selection constructs • Selective execution, which is dependent on conditions being met • Compiler ‘asks’ questions in the form of an if statement • Sometimes known as ‘branching’
  • 92. 92© 2018 The Knowledge Academy Ltd Constructs Iteration constructs • Repetitive execution of statements using loop statements • Loop statements consist of three types: o For loops o While loops o Repeat until loops • Saves programmers re-writing same lines of codes
  • 93. 93© 2018 The Knowledge Academy Ltd Constructs Constructs Conditional If If else If else if else switch case Iterative do while while for
  • 94. 94© 2018 The Knowledge Academy Ltd Conditional Constructs However, the program does not output anything as the condition specified is false
  • 95. 95© 2018 The Knowledge Academy Ltd Conditional Constructs This program outputs j is greater as the condition i > j is false
  • 96. 96© 2018 The Knowledge Academy Ltd Conditional Constructs This program first evaluates if (which returns false), then evaluates else if (which also returns false) and finally executes the else part and prints both are equal
  • 97. 97© 2018 The Knowledge Academy Ltd Conditional Constructs This program assigns a value to I, and based on that value it prints a word wherever that condition is met. A break statement is required after every case except default. This program prints Two
  • 98. 98© 2018 The Knowledge Academy Ltd Conditional Constructs This program prompts the user to enter a value between 1 and 3. Depending on the value entered, the switch case construct returns a result.
  • 99. 99© 2018 The Knowledge Academy Ltd Iterative Constructs • The do while loop executes a minimum of once • This is because the condition is checked after the first execution • Thereafter it depends upon the value of the control variable
  • 100. 100© 2018 The Knowledge Academy Ltd Iterative Constructs • The while loop is contrary to the do while loop as it executes only if a condition is true • The condition is checked first, after which the body of the loop is executed only if the loop condition evaluates to true
  • 101. 101© 2018 The Knowledge Academy Ltd Iterative Constructs • The for loop is more or less like a while loop • Within a for loop, the initial value, the terminating condition, and the increment/decrement value are all specified in a single statement
  • 102. 102© 2018 The Knowledge Academy Ltd Iterative Constructs • If a loop needs to be executed in reverse order, this can be done by specifying the bigger value as the initial value and the smaller value as the terminating value • The loop should then decrement the value instead of incrementing it
  • 103. 103© 2018 The Knowledge Academy Ltd Iterative Constructs • C also allows the use of infinite loops (though not recommended) • These can be specified as follows: int i=1; do { printf(“%d”,i); } while (i<=1); int i=1; while (i=1) { printf(“%d”,i); }; for(;;;)
  • 104. 104© 2018 The Knowledge Academy Ltd Let’s code!
  • 105. 105© 2018 The Knowledge Academy Ltd 1) Write a C program to find the largest of two numbers using IF…ELSE
  • 106. 106© 2018 The Knowledge Academy Ltd
  • 107. 107© 2018 The Knowledge Academy Ltd 2) Write a C program to find the largest value between three numbers.
  • 108. 108© 2018 The Knowledge Academy Ltd
  • 109. 109© 2018 The Knowledge Academy Ltd 3) Write a C program to print all natural numbers from 1 to n using WHILE loop, then FOR loop
  • 110. 110© 2018 The Knowledge Academy Ltd
  • 111. 111© 2018 The Knowledge Academy Ltd 4) Write a C program to find the sum of all even numbers between 1 to n
  • 112. 112© 2018 The Knowledge Academy Ltd
  • 113. 113© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Arrays
  • 114. 114© 2018 The Knowledge Academy Ltd Arrays Introduction • An array is simply an ordered collection of elements, all of which are the same data type • Each of the elements are numbered, allowing individual access • Arrays can be one-dimensional (like a list) or two-dimensional (like a table) “A group of elements belonging to a homogenous type and accessed by an index can be called an array”
  • 115. 115© 2018 The Knowledge Academy Ltd Declaring & initialising arrays (manually) There are various way of declaring & initialising an array: 1) Either by entering every value, separated by commas (with the array size): double str[5] = {3.455, 21.609, 4.44, 31000.9, 8.504}; 2) Either by entering every value, separated by commas (without the array size): int str[] = {12, 34, 5, 1777, 56, 2358, 380};
  • 116. 116© 2018 The Knowledge Academy Ltd Declaring & initialising arrays (user)
  • 117. 117© 2018 The Knowledge Academy Ltd Accessing Elements in an Array • An Array element in C can be accessed using its index number • The index number is a numeric value that starts with 0 and the last value can be 1 less than the size of the array • In an array with 10 elements, the first index number would be 0 and the last would be 9 • So, to access element 5, we would simply access the element with the index as 4, shown below: int x = list[4];
  • 118. 118© 2018 The Knowledge Academy Ltd Accessing Elements in an Array • The following program initialises the array at runtime and then displays the contents of that array:
  • 119. 119© 2018 The Knowledge Academy Ltd Two-Dimensional Arrays • In a two-dimensional array we can declare rows and columns • To access individual elements, we use two numbers instead of one • For example, to access 2 in this list we would use the reference [0] [1] 1 2 3 4 5 6 7 8 list[0] [0] list[0] [3]list[0] [2]list[0] [1] list[1] [3]list[1] [2]list[1] [1]list [1] [0] int list[2][4]= { {1,2,3,4}, {5,6,7,8} };
  • 120. 120© 2018 The Knowledge Academy Ltd Two-Dimensional Arrays
  • 121. 121© 2018 The Knowledge Academy Ltd Exercise time!
  • 122. 122© 2018 The Knowledge Academy Ltd 1) Write a C program where you declare & initialise an array of any type (your choice) and of size 20, then print the 9th and 15th values of that array.
  • 123. 123© 2018 The Knowledge Academy Ltd 2) Write a C program to find the sum of an array’s elements.
  • 124. 124© 2018 The Knowledge Academy Ltd 3) Write a C program to count all even and odd elements in a given array
  • 125. 125© 2018 The Knowledge Academy Ltd 4) Write a C program to copy all elements of first array into a second array in reverse order.
  • 126. 126© 2018 The Knowledge Academy Ltd Sorting Arrays • Arrays can be initialised with random values and displayed in a particular order • This is possible due to various sorting algorithms that can be applied • The simplest of these is the Bubble Sort • The program here accepts a few numbers from the user and stores them in an array, in the order in which they have been entered • Thereafter, the array is sorted in the next step using Bubble Sort • Finally, the sorted array is displayed to the user
  • 127. 127© 2018 The Knowledge Academy Ltd
  • 128. 128© 2018 The Knowledge Academy Ltd Let’s have a look at an example Say we have the following array of 10 integers, stored in random order:
  • 129. 129© 2018 The Knowledge Academy Ltd In the first pass of the outer loop (ie: when i == 0), we have:
  • 130. 130© 2018 The Knowledge Academy Ltd And so: we have essentially pushed the highest value in the array to the rightmost box of the array. The second pass (ie: i == 1) will therefore push the second largest value of the array to the right, and so on until i == 9 and the array is finally sorted in ascending order.
  • 131. 131© 2018 The Knowledge Academy Ltd QUESTION Look at both terminating values for the outer and inner loops. What do you notice? Why are they different?
  • 132. 132© 2018 The Knowledge Academy Ltd The efficiency of sorting algorithms By clicking here, we can see that Bubble Sort isn’t great:
  • 133. 133© 2018 The Knowledge Academy Ltd Question: what should we change in the previous to order the array in decreasing order?
  • 134. 134© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Strings
  • 135. 135© 2018 The Knowledge Academy Ltd Introduction to strings So far, we have seen how to declare, initialise and manipulate arrays of various data types. Among these, we haven’t mentioned the possibility of implementing arrays of type char, as so: char myCharArray[]; Since char arrays hold, in effect, characters that can make up a word, several words, or even sentences with meaning, could we then say that arrays of type char constitute strings – ie: text?  WRONG!
  • 136. 136© 2018 The Knowledge Academy Ltd Introduction to strings There lies in fact a difference between any sort of array (including char arrays) and strings: Strings are arrays of type char that end with a compulsory ‘0’ (null) character!!! Following is the memory presentation of the above defined string in C:
  • 137. 137© 2018 The Knowledge Academy Ltd NOTE: The null character shows the computer where the string ends. But we do not need to place the null character at the end of a string! The C compiler automatically does that for us: it places the '0' at the end of the string when it initializes the array.
  • 138. 138© 2018 The Knowledge Academy Ltd Declaring & initialising a string in C (manually) There are several ways to declare and initialise a string: 1) Either by entering every character in single quotes (with or without the array size): - char str[] = {'H','e','l','l','o',' ','w','o','r','l','d','0’}; - char str[14] = {'H','e','l','l','o',' ','w','o','r','l','d','0’}; 2) Either by entering full words and spaces in text style and in double quotes (with or without the array size): - char str[] = "Hello world!"; - char str[50] = "Hello world!";
  • 139. 139© 2018 The Knowledge Academy Ltd Declaring & initialising a string in C (user) There are several ways to have a string initialised by users. One of the safest and enduring ways is as follows: #include <stdio.h> int main() { char str[20]; printf(“Please enter your string:nn”); scanf("%[^n]%*c", str); printf(“nnYour string:nn%s", str); return 0; }
  • 140. 140© 2018 The Knowledge Academy Ltd String Methods • If we want to do anything with our strings, such as compare, concatenate or copy them, we need access string methods • We do this using the header file string.h • Here are some of the most popular string handling methods: o strlen() o strcpy() o strncpy() o strcat() o strncat() o strcmp()
  • 141. 141© 2018 The Knowledge Academy Ltd String Methods strlen • This calculates the length of the string, minus the null character • Format: strlen (string variable)
  • 142. 142© 2018 The Knowledge Academy Ltd String Methods strcpy • This copies the content of one string to another • Format: strcpy(destination_string, source_string);
  • 143. 143© 2018 The Knowledge Academy Ltd String Methods strncpy • This allows us to copy a selected number characters from one string to another • Format: strncpy (destination_string, source_string, number of characters to copy);
  • 144. 144© 2018 The Knowledge Academy Ltd String Methods strcat • This allows us to concatenate (or join) two strings together • Format: strcat(destination_string, source_string); strcat (str2,str1);
  • 145. 145© 2018 The Knowledge Academy Ltd String Methods strncat • Like strcat, this lets us join strings together, but unlike strncat, it lets us specify how many characters • Format: strncat (destination_string, source_string, number of characters);
  • 146. 146© 2018 The Knowledge Academy Ltd String Methods strcmp • This compares strings • If the strings are equal, it returns 0. If the 1st is greater than the 2nd, it returns a value greater than 0. If the 1st is less than the 2nd, it returns a value less than 0 • Format: strcmp (string_1,string_2);
  • 147. 147© 2018 The Knowledge Academy Ltd String Methods strcmp
  • 148. 148© 2018 The Knowledge Academy Ltd Library of most string functions Function Description strlen Finds the length of a string strlwr Makes string characters lowercase strupr Makes string characters uppercase strcat Appends one string at the end of another strncat Appends first n character of string at the end of another strcpy Copies one string into another strncopy Copies first n characters of one string into another strcmp Compares two strings
  • 149. 149© 2018 The Knowledge Academy Ltd Library of most string functions Function Description strncmp Compares first n characters of two strings strcmpi Compares two strings without regard to case stricmp Compares two strings without regard to case strnicmp Compares first n characters of two strings without regard to case strdup Duplicates string strchr Seeks first occurrence of given character within string strrchr Seeks last occurrence of given character within string
  • 150. 150© 2018 The Knowledge Academy Ltd Library of most string functions Function Description strstr Find first occurrence of given string in another string strset Sets all characters of a string to a given character strnset Sets first n characters of a string to a given character strrev Reverses a string
  • 151. 151© 2018 The Knowledge Academy Ltd 1) Write a C program to concatenate two strings
  • 152. 152© 2018 The Knowledge Academy Ltd
  • 153. 153© 2018 The Knowledge Academy Ltd 2) Write a C program to compare two strings.
  • 154. 154© 2018 The Knowledge Academy Ltd
  • 155. 155© 2018 The Knowledge Academy Ltd What is C Programming? • A general purpose programming language closely related to the UNIX operating system • Developed specifically for UNIX, given that most systems and programmes running in UNIX are written in C language • Standardised by American National Standards Institute (ANSI) in 1989
  • 156. 156© 2018 The Knowledge Academy Ltd UNIX – what’s that again…? Unix distinguishes itself from its predecessors as the first portable operating system: almost the entire operating system is written in the C programming language, thus allowing Unix to reach numerous platforms. Development started in the 1970s at the Bell Labs research centre. by Ken Thompson, Dennis Ritchie, and others. Both Unix and the C programming language were developed by AT&T and distributed to government and academic institutions, which led to both being ported to a wider variety of machine families than any other operating system The Unix system had significant impact on other operating systems. It achieved its reputation by its interactivity, by providing the software at a nominal fee for educational use, by running on inexpensive hardware, and by being easy to adapt and move to different machines.
  • 157. 157© 2018 The Knowledge Academy Ltd History of C • It was developed by Dennis Ritchie of Bell Labs between 1969 and 1973 as a successor to the B language • In 1978, the publication of "The C Programming Language" by Bryan Kerninghan and Ritchie caused a revolution in the computing world • In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern definition of C and this definition was completed in late 1988
  • 158. 158© 2018 The Knowledge Academy Ltd History of C Year Language Developed by Remarks 1960 ALGOL International committee Too general and too abstract 1963 CPL Cambridge University Hard to learn, difficult to implement 1967 BCPL Martin Richards at Cambridge University Could deal only with specific problems 1970 B Ken Thompson at AT & T Could deal only with specific problems 1972 C Dennis Ritchie at AT & T Lost generality of BCPL and B restored
  • 159. 159© 2018 The Knowledge Academy Ltd C Facts • Today, C is one of the most widely used programming languages in the world • C has been used for everything imaginable, from operating systems to databases to network drivers • Linux OS, PHP, and MYSQL are all written in C • Modern programming concepts are based on C
  • 160. 160© 2018 The Knowledge Academy Ltd According to • According to TIOBE Index: • https://www.tiobe.com/tiobe-index/
  • 161. 161© 2018 The Knowledge Academy Ltd C and Other Languages • C is considered the mother tongue for programming because its features strongly influenced subsequent languages • Many popular languages like Java, C++, Perl, Ruby, PHP, Bash, Python, and Objective C have borrowed syntaxes and functions from the C language • They have the same operators, expressions, statements, and control structures of C • High level programming languages like JAVA and Python can merge with C • The C compiler combines the capabilities of an assembly language, along with the features of a high level language, making it suitable for developing system software and packages
  • 162. 162© 2018 The Knowledge Academy Ltd Assembly language – what’s that again…?
  • 163. 163© 2018 The Knowledge Academy Ltd High-level language – ok… A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that enables a programmer to write programs that are more or less independent of a particular type of computer. Such languages are considered high-level because they are closer to human languages and further from machine languages. In contrast, assembly languages are considered low-level because they are very close to machine languages. Advantages of High-Level Languages The main advantage of high-level languages over low-level languages is that they are easier to read, write, and maintain. Ultimately, programs written in a high-level language must be translated into machine language by a compiler or interpreter. The first high-level programming languages were designed in the 1950s. Now there are dozens of different languages, including Ada, Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal, and Prolog.
  • 164. 164© 2018 The Knowledge Academy Ltd Reasons to Use C C has now become a widely used programming language, and is favoured for the following reasons among others: • Easy to learn • Structured programming language • Runs programmes efficiently • Compiles code quickly • Handles low-level activities • Can be used on a variety of operating systems (e.g. Windows, Android, Mac)
  • 165. 165© 2018 The Knowledge Academy Ltd What is a structured programming language? Structure programming is a "computing philosophy" which states that there three main ways of combining programs: - sequencing - selection - iteration (+ recursion) These are deemed sufficient to express any computable function. "Sequence"; ordered statements or subroutines executed in sequence. "Selection"; one or a number of statements is executed depending on the state of the program. This is usually expressed with keywords such as if..then..else..endif. "Iteration"; a statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as while, repeat, for or do..until. Often it is recommended that each loop should only have one entry point (and in the original structural programming, also only one exit point, and a few languages enforce this). "Recursion"; a statement is executed by repeatedly calling itself until termination conditions are met. While similar in practice to iterative loops, recursive loops may be more computationally efficient, and are implemented differently as a cascading stack.
  • 166. 166© 2018 The Knowledge Academy Ltd Reasons to Use C • Foundation of modern information technology sector, including a great deal of IT principles such as: o Operating systems o Databases o Graphic user interfaces o Image processing o Real-time systems o Algorithms
  • 167. 167© 2018 The Knowledge Academy Ltd Reasons to Use C • Used by over 90% of desktop programmes (e.g. email clients in web browsers) use C • Used extensively in robotics • Standardised by ANSI and International Organisation for Standardisation (ISO) • Foundation skill for more advanced programming techniques like multithread programming, embedded programming, real- time programming, and cloud computing
  • 168. 168© 2018 The Knowledge Academy Ltd Reasons to Use C • Highly flexible and adaptable, due to the presence of different data types • Possesses capabilities of assembly language, along with high-level language for developing system software and packages • Uses 32 keywords and several functions
  • 169. 169© 2018 The Knowledge Academy Ltd Reasons to Use C • Able to extend itself • Language has a collection of functions • C library is able to continuously accommodate new functions • Procedural in nature
  • 170. 170© 2018 The Knowledge Academy Ltd What is procedural programming? Historically, procedural programming arose out of the concept of structured programming. The idea is that programs can be written with only three things: - Sequence (execution moves forward one statement at a time) - Selection (if statements) - Iteration (loops) But all in all, procedural programming (PP) is a programming paradigm that takes a top-down approach. It is about writing a list of instructions to tell the computer what to do step by step. It relies on procedures or routines. Procedural programs can be faster than most alternatives. This is especially true historically. We can easily get the maximum performance out of procedures because we become “empathetic” to what the machine’s most efficient way to perform a task is.
  • 171. 171© 2018 The Knowledge Academy Ltd Reasons to Use C • Can be said to use object oriented programming (OOP) • Absence of ‘garbage collection’ and ‘dynamic typing’ allows C to function faster than its language counterparts • Portable, and therefore easy to compile from disparate systems
  • 172. 172© 2018 The Knowledge Academy Ltd Portability • C’s portability means that, when written well, it can be compiled once and then moved to another system without modification • However, C does not guarantee portability. Programs must be optimised in certain ways in order to run elsewhere without issue C programs are portable
  • 173. 173© 2018 The Knowledge Academy Ltd Reasons to Use C • Sections of C can be stored for future use (i.e. modularity), thanks to its libraries • Statistically typed as opposed to dynamically typed • Seamlessly merges with high-level programming languages like Java and Python
  • 174. 174© 2018 The Knowledge Academy Ltd Statically-typed vs dynamically-typed Statically typed languages A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: Java, C, C++); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin). The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage. Examples: C, C++, Java, Rust, Go, Scala Dynamically typed languages A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference). Examples: Perl, Ruby, Python, PHP, JavaScript
  • 175. 175© 2018 The Knowledge Academy Ltd Reasons to Use C C is middle level and structured • Middle level means it fills the gap between machine language (what the computer reads) and high-level languages (languages like Ruby that are closer to natural human language) • Structured means that C follows a logical structure which divides problems into individual modules
  • 176. 176© 2018 The Knowledge Academy Ltd Features of C • This means instructions are executed step-by-step to carry out tasks • A program may contain one or more procedures for performing these tasks • This makes C quite intuitive as it works how you may expect a program to work – by following instructions C is a procedural language
  • 177. 177© 2018 The Knowledge Academy Ltd Features of C C programs are fast • As C is a compiled language, it only needs to be run through a compiler once for it to be translated into machine code that a computer can understand • Interpreted languages, in comparison, must be interpreted every time they are run, which slows down performance and takes a lot longer
  • 178. 178© 2018 The Knowledge Academy Ltd Features of C C is a statically typed language • This means types of variable are checked while the language is being compiled, rather than when it is run • This again makes it faster than other (dynamically typed) languages • It also ensures errors are caught earlier in the development process
  • 179. 179© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Functions
  • 180. 180© 2018 The Knowledge Academy Ltd Main Kitchen (RETURNS hot sauce) Sous-chef sauce kitchen (can take in and ) Grind meat (using meat grinder) Read recipe book no.1 Boil pasta and veggies. Use blender for veggies. Cook meat in butter. Add salt and a touch of wine. Ask Sous-chef sauce kitchen to make hot sauce! (send sous-chef some and some ) Hot sauce received. Meal ready and sent to customer! Read recipe book no.2 Heat up butter in milk. Use blender to chop up chillies. Add salt and red wine. Send hot sauce to main kitchen!
  • 181. 181© 2018 The Knowledge Academy Ltd Describing Functions • Sometimes while programming, the need arises to repeat a set of statements again and again • The programmer could choose to write the code again provided it is small and not being constantly replicated • To avoid this, C makes use of functions • One function we have already seen is the main() function • Main is an in-built function that can be used for calling other functions, as we saw in the case of Strings • This section will describe how functions can be created in C
  • 182. 182© 2018 The Knowledge Academy Ltd User Defined Functions There are two categories of functions: - In-built functions are those that have been defined by the C development team for performing basic jobs . These functions reside in the header files (e.g. stdio.h, string.h, math.h etc.). Each of these header files contain functions as per their names. - User-defined functions are sets of statements that can be defined and subsequently called across multiple program files
  • 183. 183© 2018 The Knowledge Academy Ltd Parts of a Function Function name Actual name of the function Parameter list Comparable to a placeholder, as value is passed to the parameter when a function commences. Not all functions have parameters Function body A collection of statements that defines the operations of the functions Return type Function may return a value, but not always the case (even when desired operation has taken place)
  • 184. 184© 2018 The Knowledge Academy Ltd Parts of a Function
  • 185. 185© 2018 The Knowledge Academy Ltd Declaring Functions • Tells compiler how many parameters the function will be taking, as well as data types and the return type • Below is a function taking two integers as parameters, and then returning an integer int max(int, in); • Following is a function taking a char and int as parameters, which return an integer int fun(char, int);
  • 186. 186© 2018 The Knowledge Academy Ltd Functions printf() functions • In-built library functions available by default • Declared stdio.h header file • Used to print characters, strings, floats, integers, octals, and hexadecimal values on output screen • New line generated by n
  • 187. 187© 2018 The Knowledge Academy Ltd Functions C programme with printf() functions #include <stdio.h> int main() { char ch = ‘A’; char str[30] = “theknowledgeacademy.com”; float flt = 10.234; int no = 150; double dbl = 20.123456; printf(“Character is %c n”, ch); printf(“String is %s n” , str); printf(“Float value is %f n”, flt); printf(“Integer value is %dn” , no); printf(“Double value is %lf n” , dbl); printf(“Octal value is %o n” , no); printf(“Hexadecimal value is %x n” , no); return 0; } OUTPUT Character is A String is theknowledgeacademy.com Float value is 10.234999 Integer value is 150 Double value is 20.123456 Octal value is 226 Hexadecimal value is 96
  • 188. 188© 2018 The Knowledge Academy Ltd Functions scanf() functions • Format specifier %d is used in scanf() statement, so that value entered is received as an integer and in %s for string • Ampersand (&) is used before name of variable ch in scanf() statement as &ch • Comparable to a pointer, as it ‘points’ to the variable
  • 189. 189© 2018 The Knowledge Academy Ltd User Defined Functions • Every user defined function in C has a structure like this: • Any user-defined function must be declared immediately after the pre- processors, to enable the compiler to locate them <return type> function name ([<list of arguments>]) { body of function … [optional return statement]; }
  • 190. 190© 2018 The Knowledge Academy Ltd User Defined Functions • Return type – the return type is the type of the data that will be returned by the function to the calling function. If no data is returned then return type is void and the function will have no return statement, as in main() • Function name – this is the name of the function that another function will call in the set of statements • Argument list – if any extra information needs to be passed to the function to complete its processing, it is passed as an argument. The function can have no arguments, or many. Arguments are of two types – actual and formal • Body – this is the part of the function which is actually doing the processing • Return statement – this is used for returning data of the return type. It is optional
  • 191. 191© 2018 The Knowledge Academy Ltd User Defined Functions • Example:
  • 192. 192© 2018 The Knowledge Academy Ltd User Defined Functions • The program shown here defines two functions that do not return any value or accept any arguments • Both functions are first declared immediately after the #include statement, so that the compiler knows that these functions have been defined by the user in this program and does not come up with any error when they are called • The welcome() statement invokes a function by the same name and so does the terminate() statement • void specifies that no value is returned and as such no return keyword in either of the functions
  • 193. 193© 2018 The Knowledge Academy Ltd User Defined Functions • Example demonstrating the use of return keyword and argument list
  • 194. 194© 2018 The Knowledge Academy Ltd User Defined Functions • This program accepts two numbers, First and Second (of integer type) • The numbers are passed to the user-defined function add() where they are received in the formal parameters a and b • Inside the function, a local variable c is declared to hold the sum of a and b • The return statement is used to return this value to the main program • Inside main(), the variable Result holds the returned value, which is then printed on the user’s screen
  • 195. 195© 2018 The Knowledge Academy Ltd Nesting Function Calls • Functions in C can be called from another function the same as they are called from main() • When the main() function calls FunctionOne(), FunctionOne() calls FunctionTwo(), FunctionTwo() calls FunctionThree(), and so on, this is known as nesting
  • 196. 196© 2018 The Knowledge Academy Ltd Recursive Functions • Sometimes programmers come across situations where a function needs to be called repeatedly • This can be hazardous: an infinite loop may result in an “Out of Memory” error and the system may as well crash • To avoid this, programmers often include an if condition that helps them to terminate the loop at a specified point • These are known as recursive functions • The terminating condition is known as the base condition • The best example of a recursive function is the factorial of a number
  • 197. 197© 2018 The Knowledge Academy Ltd Recursive Functions
  • 198. 198© 2018 The Knowledge Academy Ltd Setting a number to the power n – technique 1
  • 199. 199© 2018 The Knowledge Academy Ltd Setting a number to the power n – technique 2
  • 200. 200© 2018 The Knowledge Academy Ltd Setting a number to the power n – technique 3
  • 201. 201© 2018 The Knowledge Academy Ltd Exercise time!
  • 202. 202© 2018 The Knowledge Academy Ltd 1) Write a C program to input a number from user and check whether given number is even or odd using functions.
  • 203. 203© 2018 The Knowledge Academy Ltd 2) Write a C program to input a number from user and check whether given number is even or odd using functions.
  • 204. 204© 2018 The Knowledge Academy Ltd 3) Write a recursive function in C programming to find the sum of all natural numbers between 1 to n.
  • 205. 205© 2018 The Knowledge Academy Ltd
  • 206. 206© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Pointers
  • 207. 207© 2018 The Knowledge Academy Ltd Using Pointers • Pointers are an advanced way of dealing with data in C • A Pointer is a special type of variable that can store the address of another variable. They are unique to C and C++ • A pointer can point to a variable of the same type as that of the pointer • Pointers use two special symbols to operate • These are & to store the address of a variable and * to access the value of a variable. &var generates an address for var within the programme’s memory • * is also used while declaring a pointer variable #include <stdio.h> int main() { int var = 10; printf(“Value: %dn”, var); printf(“Address: %u”, &var); return 0; }
  • 208. 208© 2018 The Knowledge Academy Ltd Using Pointers
  • 209. 209© 2018 The Knowledge Academy Ltd Using Pointers • If the value of the pointer is incremented or decremented using the ++ or – operators, the address stored in the pointer will change • This may (though not always) lead to erroneous output
  • 210. 210© 2018 The Knowledge Academy Ltd Using Pointers • The program shown on the last slide initialises the pointer to the address of i • It also increments the value of ptr twice, which changes the address stored in it and consequently the value • As such, it is imperative that pointers are handled very carefully
  • 211. 211© 2018 The Knowledge Academy Ltd String Pointers • Pointers can be used with almost any data type • With Strings, pointers can be used to manipulate each and every character • This example counts the number of characters in a string using pointers
  • 212. 212© 2018 The Knowledge Academy Ltd String Pointers • The ‘&’ character was not used in the above program • This is because a string is already a character array and the ptr = str statement assigns the address of the 0th element of str to the pointer variable ptr • When we increment ptr, it increments the address to the next index number • Thus, calling *ptr displays one character at a time instead of the entire string • We use i as a counter variable to keep track of the length of the string
  • 213. 213© 2018 The Knowledge Academy Ltd Pointers to Pointers
  • 214. 214© 2018 The Knowledge Academy Ltd Pointers to Pointers • The previous example illustrates how a user can define a Pointer to a Pointer • Initially, we define a pointer ptr that points to an integer point i • Next, another pointer variable ptr2ptr (also of integer type) points to ptr • Using either of these variables we can get the value 340 as depicted in the output • Remember a Pointer to a Pointer must be declared with a ** instead of a *
  • 215. 215© 2018 The Knowledge Academy Ltd Array of Pointers • C allows users to declare an array of pointers • An array of pointers can be declared like any other array but the contents are only pointers
  • 216. 216© 2018 The Knowledge Academy Ltd Array of Pointers • This program declares an array of integers and then an array of integer pointers • The first for loop assigns the address of the integer array cells to the array of pointers • Once this is done, the pointer’s address and its values are printed on to the user screen
  • 217. 217© 2018 The Knowledge Academy Ltd NULL Pointers • You can declare a pointer as NULL in value if the address of pointer variable is not known • NULL pointers are constant • Not to be confused with an uninitialised/dangling pointer, which is not guaranteed to be compared as unequal to an initialised pointer • Two NULL pointers will compare as equal
  • 218. 218© 2018 The Knowledge Academy Ltd RECAP
  • 219. 219© 2018 The Knowledge Academy Ltd Exercises!
  • 220. 220© 2018 The Knowledge Academy Ltd 1) Write a C program to create, initialize and demonstrate the use of pointers.
  • 221. 221© 2018 The Knowledge Academy Ltd 2) Write a C program to prompts the user to enter two float values, assigns their addresses to two float pointers and adds these two float values using both pointers.
  • 222. 222© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Structures
  • 223. 223© 2018 The Knowledge Academy Ltd Structures • In C, structures are used for storing different types of data that is grouped together • A user may want to store employee details such as Employee Code, Employee Name and Salary or Customer Details such as Customer Number, Customer Name, Product Purchased, Qty Purchased, or Amount Paid • All these details could be stored in a single structure, such as Employee or Customer • An object of the structure could then be created to store or access its values • A structure is by default public in nature
  • 224. 224© 2018 The Knowledge Academy Ltd Structures Example of a structure #include <stdio.h> struct EmployeeData{ char *employee_name; char *employee_title; char *employee_dept; }; char main() { struct EmployeeData employee; employee.employee_name = "John Bonham"; employee.employee_title = "Marketing Executive"; employee.employee_dept = "Marketing"; printf("Employee Name is: %s", employee.employee_name); printf("nEmployee Title is: %s", employee.employee_title); printf("nEmployee Department is: %s", employee.employee_dept); return 0; } OUTPUT Employee Name is: John Bonham Employee Title is: Marketing Executive Employee Department is: Marketing
  • 225. 225© 2018 The Knowledge Academy Ltd Structures typedefs • Define types using a different name when working with structs and pointers, which appear as asterisks • Essentially saves coder from constantly typing struct throughout the code • Code is shorter and more visually accessible typedef struct work_address{ int house_number; char *street_name; char *town; char *city; char *county; int *postcode; }addr; .. .. addr var1; var.town = “London”;
  • 226. 226© 2018 The Knowledge Academy Ltd Structures Designated initialisation • Members of the structure (i.e. variables) can be initialised in any given order • Added to C99 standard • Unavailable in C++ struct Point { int x, y, z; }; int main() { // Examples of initialisation using designated initialisation struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z); printf ("x = %d", p2.x); return 0; }
  • 227. 227© 2018 The Knowledge Academy Ltd Array of Structures • It is possible to create a structure and use it in an array • This would be useful in a situation where there are more than one employees for whom the same details need to be entered or retrieved • In such cases, we could make use of an array of structures, as in this example #include <stdio.h> #include <stdlib.h> #include <string.h> void main() { struct employee { int empcode; int salary; float allow; float deduct; float netsal; };
  • 228. 228© 2018 The Knowledge Academy Ltd Array of Structures • Structure Example (contd.) struct employee emp[3]; int i; clrscr(); for(i=0;i<3;i++) { printf("Enter Code Number:");scanf("%d", &emp[i].empcode); printf("Enter Employee Salary:");scanf("%d", &emp[i].salary); emp[i].allow=0.05 * emp[i].salary; emp[i].deduct=0.02 * emp[i].salary; emp[i].netsal=emp[i].salary+ emp[i].allow-emp[i].deduct; printf("n================================n"); }
  • 229. 229© 2018 The Knowledge Academy Ltd Array of Structures • Structure Example (contd.) clrscr(); for(i=0;i<3;i++) { printf("nCode:%d", emp[i].empcode); printf("nBasic Salary:%d", emp[i].salary); printf("nAllowance:%.2f",emp[i].allow); printf("nDeduction:%.2f",emp[i].deduct); printf("nNet Salary:%.2f",emp[i].netsal); printf("n================================"); } getch(); }
  • 230. 230© 2018 The Knowledge Academy Ltd Using Structures with Pointers • A very common concept in C is that of the linked list • A linked list is a list of nodes where each node is a structure • A Single Linked List has nodes that are added at the end of the list • The first node added is known as the start node, the final node is called the last node, and the node being traversed currently is called the current node • Whenever a node is added, the program checks whether the list contains any nodes • If the list is empty, the new node becomes the first as well as the last node
  • 231. 231© 2018 The Knowledge Academy Ltd Using Structures with Pointers • As the nodes are added, the start node remains fixed but the last node moves ahead • Every new node contains a NULL value in its next pointer • The last pointer replaces this with the address of the next node • The result is as follows:
  • 232. 232© 2018 The Knowledge Academy Ltd Using Structures with Pointers • Example Program #include <stdio.h> void showlist(); struct node* getnode(); struct node *start; struct node *last; struct node { int empcode; int salary; struct node* next; };
  • 233. 233© 2018 The Knowledge Academy Ltd Using Structures with Pointers • Example Program void main() { struct node *ptr; char ans='y'; clrscr(); start=NULL; while (ans=='y') { if(start==NULL) { ptr=getnode(); start=ptr; last=start; }
  • 234. 234© 2018 The Knowledge Academy Ltd Using Structures with Pointers • Example Program else { ptr= getnode(); last->next=ptr; last=ptr; } printf("n Continue(y/n)?"); ans=getch(); } showlist(); getch(); }
  • 235. 235© 2018 The Knowledge Academy Ltd Using Structures with Pointers • Example Program void showlist() { struct node *temp; int i=1; clrscr(); temp=start; while(temp!=NULL) { printf("nRecord No:%d",i++); printf("nCode:%d", temp->empcode); printf("nSalary:%d", temp->salary); printf("n====================="); temp=temp->next; getch(); } }
  • 236. 236© 2018 The Knowledge Academy Ltd Using Structures with Pointers • Example Program struct node* getnode() { struct node *temp; temp = (struct node*) malloc (sizeof (struct node)); printf("nEnter Code:"); scanf("%d", &temp->empcode); printf("nEnter Salary:"); scanf("%d",&temp->salary); temp->next=NULL; return temp; }
  • 237. 237© 2018 The Knowledge Academy Ltd Project Management, Management & Leadership Operating Bigger Programs
  • 238. 238© 2018 The Knowledge Academy Ltd Dividing Programs • Sometimes programmers are asked to write very large programs • Navigating huge programs is an extremely difficult process • As a best practice, it is always advisable to divide a single huge program into multiple modules as well as a library of functions containing a suite of subroutines within one or more modules • However, only one of these files will contain the main() function • By writing a group of functions in different module files, these module files can be shared with many other programs as well
  • 239. 239© 2018 The Knowledge Academy Ltd Dividing Programs Why write modules instead of a single programme? • Modules will naturally divide into common groups of functions • It is much easier to compile each module separately, rather than link them in compiled modules • UNIX utilities can help maintain large systems
  • 240. 240© 2018 The Knowledge Academy Ltd Header Files • If we are dealing with modular files, we will have to store the definition of the variables and functions somewhere • As per convention, the best place would be a header file • C allows its users to create their own header files • These header files can be included into our C program using the keyword #include in the following manner: #include “userdefined.h”
  • 241. 241© 2018 The Knowledge Academy Ltd Header Files Example of modules #define ..... void ..... int ..... #include< > #include “header.h” main() { ..... } #include “header.h” void WriteMyString() { ..... } header.h main.c WriteMyString.c #include ..... fns ..... #include ..... fns ..... #include ..... fns ..... Other modules mod1.c mod2.c mod3.c
  • 242. 242© 2018 The Knowledge Academy Ltd Header Files Full listings main.c: /* * main.c */ #include "header.h" #include <stdio.h> char *AnotherString = "Hello Everyone"; main() { printf("Running...n"); /* * Call WriteMyString() - defined in another file */ WriteMyString(MY_STRING); printf("Finished.n"); }
  • 243. 243© 2018 The Knowledge Academy Ltd Header Files Full listings WriteMyString.c: /* * WriteMyString.c */ extern char *AnotherString; void WriteMyString(ThisString) char *ThisString; { printf("%sn", ThisString); printf("Global Variable = %sn", AnotherString); }
  • 244. 244© 2018 The Knowledge Academy Ltd Header Files Full listings header.h: /* * header.h */ #define MY_STRING "Hello World" void WriteMyString();
  • 245. 245© 2018 The Knowledge Academy Ltd Header Files Full listings • Some modules have a #include “header.h” that share common definitions • Some (like main.c) also include standard header files • main calls the function WriteMyString(), which is in the WriteMyString.c module • The function prototype void for WriteMyString is defined in header.h
  • 246. 246© 2018 The Knowledge Academy Ltd Header Files Sharing variables • If global variables are declared in a module, the knowledge of said variables must be passed on to other modules • This can be achieved by passing values as parameters to functions; however: o This can be a convoluted process if the same parameters are passed to many functions, and/or if there is a long argument list involved o Large arrays and structures are difficult to store locally, and there are often memory problems associated with the stack function
  • 247. 247© 2018 The Knowledge Academy Ltd Header Files External variables and functions • “Internal” implies that arguments and functions are defined inside the functions (i.e. locally) • Therefore, “external” variables are defined outside of functions • In other words, they are potentially available to the entire programme • External variables are always permanent
  • 248. 248© 2018 The Knowledge Academy Ltd Header Files Scope of externals • External variables/functions are not always completely global • With that in mind, C programming language will apply the following rule: “The scope of an external variable (or function) begins at its point of declaration and lasts to the end of the file (module) it is declared in.” A. D. Marshall (1998) Hands On: C Programming and Unix Application Design: UNIX System Calls and Subroutines Using C
  • 249. 249© 2018 The Knowledge Academy Ltd Using Several Files • In a team of programmers, each programmer could work on different files and yet access the same modules • An object oriented style can be used, with each file defining a particular type of object as a data type and various operations that can be carried on that object • To make it more structured, the object can be implemented privately • Files can contain all functions from a related group, which can be accessed like a function library • Well implemented objects or function definitions can be re-used in other programs
  • 250. 250© 2018 The Knowledge Academy Ltd Using Several Files • In very large programs, each major function can occupy a file to itself • Any lower-level functions used to implement them can be kept in the same file – this reduces distraction for developers • When changes are made to a file, only that file needs to be recompiled to rebuild the program • The UNIX make facility is very useful for rebuilding multi-file programs in this way
  • 251. 251© 2018 The Knowledge Academy Ltd The Modular Approach Advantages • Teams of programmers can work on individual programmes, and focus on their area of expertise • An object-oriented style can be used; each file defines a particular type of object as a data type, and operations on that object as functions • Implementation of the object can be kept private from the rest of the programme
  • 252. 252© 2018 The Knowledge Academy Ltd The Modular Approach Advantages • Guarantees well-structured programmes that are easy to maintain • Files can contain all functions from a related group o e.g. All matrix operations can be accessed like a function library
  • 253. 253© 2018 The Knowledge Academy Ltd The Modular Approach Advantages • Well-implemented object/function definitions can be re-used in other programmes, therefore reducing development time • Each major function within a large programme can occupy a file to itself; any lower level functions used to implement these can be kept in the same files • Changes made to a file can easily be recompiled when re-building the programme
  • 254. 254© 2018 The Knowledge Academy Ltd The Modular Approach Dividing a programme between several files • Where objects are implemented as data structures, it is sensible to keep all functions (which access that object) in the same file • The advantages are: o The object can easily be re-used in other programmes o All related functions are stored together o Future changes to the object require only one file to modified
  • 255. 255© 2018 The Knowledge Academy Ltd The Modular Approach Organisation of data • Any and every file must have its data organised in a certain order, which will typically be: o A preamble consisting of #defined constraints, #included header files, and typedefs of important datatypes o A declaration of global and external variables, the former of which may be initialised o One or more functions
  • 256. 256© 2018 The Knowledge Academy Ltd The Modular Approach Organisation of data • Ordering must not be overlooked, since every object must be defined before it can be used • Functions that return values must be defined before they are called • One of two definitions may be applicable: o Where the function is defined and called in the same file, a full declaration of the function can be placed ahead of any call to the function o If the function is called from a file where it is not defined, a prototype should appear before the call to the function
  • 257. 257© 2018 The Knowledge Academy Ltd Congratulations Congratulations on completing this course! Keep in touch info@theknowledgeacademy.com Thank you

Editor's Notes

  1. NOTE: SUCH LOOPS ARE NOT RECOMMENDED
  2. ALGOL – Algorithmic language CPL- Combined programming language BCPL- Basic combined programming language