6-LM Programing
6-LM Programing
PROGRAMMING
National Certificate II
This facilitating and learning material covers all the Learning Outcomes for Programming for the
National Certificate II programme
LEARNING OUTCOMES
1 Demonstrate skills in C Programming
2 Demonstrate skills in operators used in C programming
3 Demonstrate skills in statements used in C programming
4 Demonstrate knowledge of the use of Loops of C programming
5 Demonstrate skills in Functions used in C programming
1
1.0 Introduction and Preliminary Notes
In this unit, you will be C programming and how to write codes to accomplish a given job. After
the learning, you will be able to use
operators used in C programming, have knowledge of statement of C programming, and use of
functions in C programming,
The knowledge gained about the use of C programming will lead you to apply the skills to solve
problems.
This learning material should be used with the unit specification given as the unit specification
will guide you on the standards stated with all the range statements. You should also be guided
by the evidence requirements so that your learning is relevant to the required standards.
The way the learning material is written is to encourage learner autonomy and initiative (i.e.,
activities that require the learner to work independently of the facilitator and to make decisions
concerning how he/she might approach a task) so that you as a learner can take ownership of
your own learning. Follow the instructions and the steps indicated in the learning material and
work as independently as possible.
Icon
2
1 Learning Outcome
4.
Self- Assessment
Table 1. You should know what each icon represents. Carefully observe the icons and their
meanings.
3
A computer program is the collection of detailed expressions that you give to the computer to
Preprocessor Commands
Functions
Variables
Comments
Take a look at how a simple “Hello, World” program below shows how all the parts mentioned
above play a role in the structure of the C programming language.
#include <studio’s>
int main () {
/* my first program in C */
return 0;
Explanation of the code above
4
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So, such lines are called comments in the program.
4. The next line print(...) is another function available in C that causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates main () function and returns the value 0.
Before you can write and execute a C program on your computer, you need a C compiler. The C
compiler takes the C program you write and builds or compiles it to enable you to run the
compiled program when you’re ready to look at the results. Luckily, many excellent free
software packages are available in which you can edit and compile your C programs. There are
so many compilers available on the internet that you can search, download and use but
throughout this unit, you will learn how to download, install and use the Code::Blocks IDE
because it has versions for Windows, Macs, and Linux
5
You can use a code editor to write and edit code when the program is lightweight but as the
program gets larger, you will need to test and debug your code, that is where the use of IDE
becomes very important.
Follow the following procedure to download and install
Step 1: Enter the link in your web address [Link].
Step 2: Click Download from the menu, scroll down
Step 3: Click on download the binary release
Step 4: Select your preferred operating system
Step 5: Click on [Link] to download as shown in figure 1 or enter this link
[Link]
[Link]
Step 6: Wait for the download to complete.
6
Step 4: Click on Next (you need to have at least 600 MB free storage on your drive for the
installation).
7
8
step 6: Once Installation gets completed, click on Next and then
Click on Finish
Checklist
9
2 Click Next
3 Click I agree
4 Click on Next
5 Click install
6 Click finish
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive
Table 1.2 Variables data types in C programming
Type Description
Char Typically, a single octet (one byte). This is an integer type.
int The most natural size of integer for the machine.
Float A single-precision floating point value.
Double A double-precision floating point value.
Void Represents the absence of type.
Variable Definition in C:
A variable definition means to tell the compiler where and how much to create the storage for the
variable. A variable definition specifies a data type and contains a list of one or more variables of
that type as follows:
type variable list;
The type must be a valid C data type including char, w_char, int, float, double, bool or any user-
defined object, etc., and variable list may consist of one or more identifier names separated by
commas. int i, j, k; char c, ch; float f, salary; doubled; The line int i, j, k; both declares and
defines the variables i, j and k; which instructs the compiler to create variables named i, j and k
of type int.
10
A variable can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:
type variable name = value;
extern int a = 2; b = 7; // declaration of a and b.
int a = 3, b = 5; //definition and initializing a and b
byte y = 13; //definition and initializes y
char z = ‘z’; // the variable z has the value ‘z’
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables is
undefined.
#include <stdio.h>
// Variable definition:
extern int x, y;
extern int z;
extern float f;
int main ()
{
// Variable definition:
int x, y;
int z;
float f;
11
// actual initialization
x =5;
y =10;
z = x + y;
f = 70.0/3.0;
return 0;
In the C programming language, data types refer to an extensive system used for declaring
variables or functions of different types. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted.
12
Union types and v. Function types.
Integer Types
Table 2: provide details of standard integer types with storage sizes and value ranges
Floating-Point Types
Table 3: gives you details about standard floating-point types with storage sizes and value ranges
and their precision
13
SN Types and Description
1 Function returns as void: There are various functions in C which do not return value
2 Function arguments as void: There are various functions in C which do not accept
any parameter. A function with no parameter can accept as a void. For example, int
rand(void);
3 Pointers to void: A pointer of type void * represents the address of an object, but not
its type. For example, a memory allocation function void *malloc( size_t size );
returns a pointer to void which can be casted to any data type
As its name indicates, a data type represents a type of data that can be processed by a computer
program. There are different types of data such as numeric (numbers: whole numbers (integers),
decimal numbers (floating point numbers)), strings (characters), alphanumeric, etc. You may
develop computer programs to process these different types of data, so you need to specify the
data type clearly. This helps the computer to perform the required operations of given data. A
data type that is a mix of whole numbers and a string of two characters is called alphanumeric.
These data types are called primitive data types because you can use these data types to build
more complex data types, which are called user-defined data types. Different programming
languages use different keywords to specify the different data types. For example, C
programming languages use int to specify integer data and char specifies a character data type.
These different data types are used in different situations.
14
LO 2 Demonstrate skills in operators used in c programming
In this learning session, you will be learning about arithmetic operators, logical operators,
15
variables). Table 7 shows all the arithmetic operators supported by C language. Assume variable
A holds 5 and B holds 10, then:
Using code::Blocks, try the following example to understand all the arithmetic operators
available in C programming language:
#include <stdio.h>
main() {
int a = 10;
int b = 2;
int c ;
c = a + b;
16
}
Results after compiling and executing the above C program:
Line 1 - Value of c is 12
Line 2 - Value of c is -8
Line 3 - Value of c is 20
Line 4 - Value of c is 5
Line 5 - Value of c is 0
Line 6 - Value of c is 11
Line 7 - Value of c is 9
Relational operators are important for making decisions. They allow you to compare numeric
values to determine if one is greater than, less than, equal to, or not equal to another.
Assume variable A holds 5 and variable B holds 10.
Table 2.1 lists all relational operators available in the C programming language.
Open your Code:Blocks software and try the following example to understand all the
relational operators available in C programming language:
#include <stdio.h>
int main() {
17
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1- a is equal to b\n" );
}
else
{
printf("Line 1- a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
18
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
#include <stdio.h>
int main()
{
int a = 2;
int b = 10;
int c;
if ( a && b ) {
printf("Row 1 - Condition is true\n" ); }
if ( a || b )
{
printf("Row 2 - Condition is true\n" );
}
19
{
printf("Row 4 - Condition is true\n" );
}
}
A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary
numerals that involve the manipulation of individual bits. When you perform the bitwise
operations, which is also known as bit-level programming. It consists of two digits, either 0 or 1.
It is mainly used in numerical computations to make calculations faster. Bitwise operator works
on bits and performs a bit-by-bit operation.
Table 2.3
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
20
A^B = 0011 0001
~A = 1100 0011
Operator Description
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
~ one’s complement operator
(unary)
<< Left shift operator
>> Right shift operator
Exercise 1:
Write a C program to perform bitwise AND operation of two integers
Follow the following steps to complete these exercises using Code: Blocks
Open code: blocks
Create a project
Select console application
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include <stdio.h>
#include <stdlib.h>
21
void main()
{
int a=5, b=15;
return 0;
}
The result after compilation:
After performing AND operation, the output is: 5
Assessor
Date
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
22
Exercise 2
Write a C program to perform bitwise right shift operation.
Follow the following steps to complete these exercises using Code: Blocks
Open code: blocks
Create a project
Select console application
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include<stdio.h>
void main()
{
int no,s;
printf("Enter the number\n");
scanf("%d",&no);
printf("Enter how many bits you won’t to right shift\n");
scanf("%d",&s);
printf("Output after performing right-shift operation is:%d",no>>s);
}
Result after compilation:
Enter the number
15
Enter how many bits you won’t to right shift
2
23
Output after performing right-shift operation is: 3
Assessor
Date
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
24
Self-Assessment
This learning outcome (LO) has a little quiz at the end. I recommend you take this whole
quiz without looking back for any of the answers. This is meant to help you determine how
well you have understood this learning outcome. Now assess yourself with the questions
below:
25
3. Explain Logical operators
26
27
LO 3 Demonstrates skills in statement used c programming
In this unit, you will be learning about if statements, if…else statements, nested if statements,
28
Figure 3.1 Flow diagram for decision-making in conditional statements execution
29
Figure 2.2 Flow diagram for if…else statement execution
i. An if can have zero or one else and it must come after an elseif.
ii. An if can have zero or many else…if and they must come before else.
iii. Once an elseif succeeds, none of the remaining elseif or else will be tested
Syntax for nested if statement
#include <stdio.h>
#include <stdio.h>
int main ()
{
if(condition1) //outer if
30
{//executes when condition1 is true
if(condition1)// inner if
{ //executes when condition2 is true
}}
31
Figure 3.3: Flow diagram for executing switch statements
32
Syntax of Switch Case Statement
#include <stdio.h>
#include <stdio.h>
33
The flow of execution goes in a way that condition 1 will get tested if it becomes false then,
statement 3 will get executed. If condition 1 gets satisfied i.e., if it gets true then it will go for the
next execution of test condition 2. In case the statement with condition 2 gets false or unsatisfied
then it will execute else with statement 2 in consideration.
34
PC (f)Preform Programming Exercises
Exercise 1:
Program to find which number is greater among the considered number and then how the
execution happens with the help of nested if statement if the flow gets successful then it is
counted as normal flow.
Follow the following steps to complete this exercises using Code:Blocks
Open code:blocks
Create a project
Select console application
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int x = 65, y = 35, z = 2;
if (x > y)
{
if (x > z)
{
printf("x is larger than y and z ");
}
}
printf("\n flow for the program is proper ");
return 0;
35
}
Result after compilation:
x is larger than y and z flow for the program is proper
Assessor
Date
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
Exercise 2:
Write a C program to print day of the week number (1-7) and print day of week name
using switch case.
Follow the following steps to complete this exercises using Code:Blocks
Open code:blocks
Create a project
Select console application
36
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int week;
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
37
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}
Assessor
Date
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
38
Exercise 3:
Write a C program that asks the user to enter the age and determine if the person is a
child, younger or older.
Follow the following steps to complete these exercises using Code: Blocks
Open code: blocks
Create a project
Select console application
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("Enter your age Here\n");
scanf("%d",&age); //get input
if(age<13){ // if statement
39
printf("you are a child!\n");
} else
35
older
Assessor
Date
Feedback to learner
40
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
Exercise 4
Write a C program to check leap year using if else.
Follow the following steps to complete this exercises using Code:Blocks
Open code: blocks
Create a project
Select console application
Select the language you want to use
Give the project a name
Click finish
Expand the sources
Double-click on main.c
Enter the codes below
Press F9
Save your work
C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int year;
/* Input year from user */
printf("Enter year : ");
scanf("%d", &year);
/*
* If year is exactly divisible by 4 and year is not divisible by 100
* or year is exactly divisible by 400 then
* the year is leap year.
41
* Else year is normal year
*/
if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400==0))
{
printf("LEAP YEAR");
}
else
{
printf("COMMON YEAR");
}
return 0;
}
The result after compilation:
Enter year: 2004
LEAP YEAR
Checklist
Assessor
Date
42
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
Self-Assessment 3
This learning outcome (LO) has a little quiz at the end. I recommend you take this whole
quiz without looking back for any of the answers. This is meant to help you determine how
well you have understood this learning outcome. Now assess yourself with the questions
below:
43
5. Explain nested if statement
44
8. Explain if statement
Consider another situation when you want to repeat a statement a thousand times. You can
certainly not write the statement a thousand times. Almost all high-level programming languages
45
provide a concept called loop, which can be used to execute one or more statements repeatedly.
There are various forms of loops. To conclude, a loop statement allows you to execute a
statement or group of statements multiple times. A general form of a loop statement in most of
the programming languages is shown in Fig. 4.
Figure 4.1: Flow diagram for the general form of a loop statement
For loop is used to execute a set of statements repeatedly until a particular condition is satisfied.
In for loop, there are two semicolons, one after initialization and the second after the condition.
In this loop, you can have more than one initialization or increment/decrement, separated using a
comma operator.
Flow of control in a for loop:
a. The init (initialization) step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put a statement
here, as long as a semicolon appears.
b. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the for a loop.
46
c. After the body of the for loop executes, the flow of control jumps back up to the
increment/decrement statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
d. The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of the loop, then increment step, and then again condition). After the
condition becomes false, the for loop terminates.
Syntax:
Example:
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
print("%d\t", x);
}
}
47
soon as the condition becomes false, the while loop comes out and continues executing from the
immediate next statement after the while loop body.
A condition is usually a relational statement, which is evaluated to be either true or false. A value
equal to zero is treated as false and any non-zero value works like true. A while loop checks a
given condition before it executes any statements given in the body part. C programming
provides another form of a loop, called do...while loop that allows executing a loop body before
checking a given condition.
48
Figure4.2: Flow diagram for executing while loop Figure4.3: Flow diagram
for executing do…while loop
49
50
PC (d) Explain the Break statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop. A break statement can be
represented in the form of a flow diagram as shown in Fig. 7.
The continue statement in C programming language works somewhat like the break statement.
Instead of forcing termination, continue forces the next iteration of the loop to take place,
skipping any code in between. A continue statement can be represented in the form of a flow
51
Figure 4.5: Flow diagram for executing continue statement
For example:
#include <stdio.h>
void main()
{
for (int i = 0; i >= 0;)
{
/* body of the loop where i is not changed*/
}
52
Self-Assessment 4
This learning outcome (LO) has a little quiz at the end. I recommend you take this whole
quiz without looking back for any of the answers. This is meant to help you determine how
well you have understood this learning outcome. Now assess yourself with the questions
below:
1. Explain If statement
53
2. Explain else if statement
54
4. Explain Switch Case Statement
55
LO. 5 Demonstrate knowledge of function in C programming.
In this units, you will be learning about functions in C programming, types of functions,
structured programming, and recursion.
PC (a) Explain Functions
A function is a block of statements that performs a specific task. A function is used when you
want to avoid a repetitive task. So instead of repeating the statement every time you want to
perform the task, you rather create a function to perform that task, just call it when you need it.
A function definition in C programming consists of a function header and a function body. Here
are the parts of a function
Return Type − A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as an actual parameter or argument. The
56
parameter list refers to the type, order, and a number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what
the function does.
Predefined Standard Library Functions: Standard library functions are also known as built-in
functions. Functions such as puts(), gets(),printf(), scanf(), etc. are examples of standard
library functions. These functions are already defined in header files (files with .h extensions are
called header files such as (stdio.h). For example, printf() function is defined in <stdio.h>
header file so in order to use the printf() function, you need to include the <stdio.h> header file
in our program using #include<stdio.h
User-Defined Functions: The functions that you create in a program are called user-defined
functions.
57
A structure is a user-defined data type in C language which allows us to combine data of
different types together. Structure helps to construct a complex data type that is more
meaningful.
The process of repeating the items in a similar way as it was before is known as recursion. A
function is said to be recursive if it is called within itself. A recursive function is called with an
argument passed into it say x, memory in the stack is allocated to the local variables as well as
the functions. All the operations present in the function are performed using that memory. The
condition for exit is checked if it is fulfilled. When the compiler detects a call to another function
it immediately allocates new memory on the top of the stack where a different copy of the same
local variables and the function get created. Enter the same process continues.
When the base condition returns true, the particular value is passed to the calling function. The
memory allocated to that function gets cleared. similarly, the new value gets calculated in the
calling function and IT returns to the super calling function. This way recursive calls are made to
the function delete reaches the first function and the whole stack memory gets cleared and output
is returned. In case base condition or exit, the condition is not specified in the function then
recursive calls to the function can lead to an infinite loop.
The two conditions that are critical for implementing recursion in C:
An exit condition: This condition helps the function to identify when to exit that function.
In case we do not specify the exit condition then the code will enter into an infinite loop.
Changing the counter: Changing the counter in every call to that function.
Example of Recursive Function in C. Try typing the code below in your IDE to see the
output.
#include <stdio.h>
int fun(int n)
{
if(n==1) return 1; //exit or base condition which gives an idea when to exit this loop.
58
return n*fun(n-1); //function is called with n-1 as it’s argument.
//The value returned is multiplied with the argument passed in calling function.
}
int main(){
int test=4;
int result =0;
result =fun(test);
printf("%d",result); //prints the output result.
}
Write a function that takes two parameters n1 and n2 and returns the maximum value between
the two.
#include <stdio.h>
#include <stdlib.h>
void main() {
/* function returning the maximum between two numbers */
Int max(int n1, int n2){
/* local variable declaration */
int result;
59
else
result = n2;
return result;
}
The below checklist will be used to assess your learning
Checklist
Table 5.1
No Yes No
1 Open code:blocks
2 Create a project
3 Select console application
4 Select the language you want to use
5 Give the project a name
6 Click finish
7 Expand the sources
8 Double-click on main.c
9 Enter the codes below
10 Press F9
11 Save your work
Assessor
Date
Feedback to learner
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………
60
Self-Assessment 5
This learning outcome (LO) has a little quiz at the end. I recommend you take this
whole quiz without looking back for any of the answers. This is meant to help you determine
how well you have understood this learning outcome. Now assess yourself with the questions
below:
61
3. Explain structured programming
62
4. Explain recursion
63