0% found this document useful (0 votes)
0 views63 pages

6-LM Programing

This document serves as facilitating and learning material for C Programming under the National Certificate II program, covering essential learning outcomes such as demonstrating skills in C programming, operators, statements, loops, and functions. It includes an introduction to C programming, guidance on using an Integrated Development Environment (IDE), and detailed explanations of variables, data types, and operators in C. The material is designed to promote learner autonomy and includes practical exercises and assessments to reinforce understanding.

Uploaded by

mahamoodhilim0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views63 pages

6-LM Programing

This document serves as facilitating and learning material for C Programming under the National Certificate II program, covering essential learning outcomes such as demonstrating skills in C programming, operators, statements, loops, and functions. It includes an introduction to C programming, guidance on using an Integrated Development Environment (IDE), and detailed explanations of variables, data types, and operators in C. The material is designed to promote learner autonomy and includes practical exercises and assessments to reinforce understanding.

Uploaded by

mahamoodhilim0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FACILITATING AND LEARNING MATERIAL FOR C

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.

ICONS AND THEIR MEANINGS


# Meaning

Icon

2
1 Learning Outcome

4.
Self- Assessment

Table 1. You should know what each icon represents. Carefully observe the icons and their
meanings.

Congratulations on going through the icons and their


meanings! We will next look at the activities under LO 1.

LO 1 Demonstrate knowledge of c programming


This LO is developed to help you acquire knowledge of C Programming
In this learning session, you will be learning the rudiments of C programming, before you

proceed you have to define the term ‘Program”

3
A computer program is the collection of detailed expressions that you give to the computer to

perform a specific task.

To achieve this, we will go through PCs (a) – (f).

PC (a) Define C Programming

C programming is a high-level and general-purpose procedural computer programming language


that allows software used to efficiently communicate with a computer.
The basic structure of the C language is listed below.

 Preprocessor Commands

 Functions

 Variables

 Statements & Expressions

 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 */

printf (“Hello, World! \n”);

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

Figure 1: download code blocks


An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. An IDE normally
consists of at least a source code editor, build automation tools, and a debugger.

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.

PC(b) Install interacted development environment (IDE) software

Step 1: Double-click on the [Link] in your download folder


Step 2: Click Next as shown below
Step 3: Click on I agree.

6
Step 4: Click on Next (you need to have at least 600 MB free storage on your drive for the
installation).

Step 5: Select your Destination and Click on Install

7
8
step 6: Once Installation gets completed, click on Next and then
Click on Finish

The below checklist will be used to assess your learning

Checklist

Table 1.1 Observation checklist


No Achieve Not -Achieved
1 Open setup file

9
2 Click Next
3 Click I agree
4 Click on Next
5 Click install
6 Click finish

PC (c) Explain variables in C programming

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.

Variable Declaration in C Program:


A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceeds for further compilation without needing
complete detail about the variable. A variable declaration has its meaning at the time of
compilation only, the compiler needs actual variable declaration at the time of linking of the
program.
A variable declaration is useful when you are using multiple files and you define your variable in
one of the files, which will be available at the time of linking of the program. You will use extern
keyword to declare a variable at any place. Though you can declare a variable multiple times in
your C program it can be defined only once in a file, a function, or a block of code.

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

printf("value of z : %d \n", z);

f = 70.0/3.0;

printf("value of f : %f \n", f);

return 0;

Result after compilation and execution:


value of z: 15
value of f: 23.333334

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.

Table 1.3: show the classifications of data types in the C Program

SN Types and Description


1 Basic Types: The basic types are used for arithmetic such as
i. Integer types
ii. Floating-point types
2 Enumerated types: They are also arithmetic types used to define variables that can
only be assigned certain discrete integer values throughout the program
3 The type void: The type specifier void indicates that no value is available.
4 Derived types: They include; i. Pointer types ii. Array types iii. Structure types iv.

12
Union types and v. Function types.

Integer Types
Table 2: provide details of standard integer types with storage sizes and value ranges

Types Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to
2.147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32.767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

Floating-Point Types
Table 3: gives you details about standard floating-point types with storage sizes and value ranges
and their precision

Type Storage Size Value range Precision


float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places
double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places
long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places

Table 4: The void Type

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.

PC (d) Explain Math operators in C programming


An operator in a programming language is a symbol that tells the program to perform the specific
mathematical, relational or logical operation and produce results. Computer programs
extensively perform mathematical calculations using mathematical operators. Two important
math operators are arithmetic and relational operators.

14
LO 2 Demonstrate skills in operators used in c programming

In this learning session, you will be learning about arithmetic operators, logical operators,

relational operators, and bitwise operators.

To achieve this, we will go through PCs (a) – (f).

PC (a)Explain Arithmetic operators


Arithmetic operators are maths operators used for calculation involving only numeric data types
such as addition, subtraction, multiplication, division etc. on numerical values (constants and

15
variables). Table 7 shows all the arithmetic operators supported by C language. Assume variable
A holds 5 and B holds 10, then:

Table 5: Key arithmetic operators

Operator Description Operation


Arithmetic
Addition Sums up A+B will give 15
+
operands
Minus Subtracts A-B will give -5
-
operands
Multiplication Multiplies A*B will give 50
*
operands
Division Divides B/A will give 2
/
operands
Modulus Operator and remainder of after Reminder B%A will give 0
%
an integer division operands
Increments operator increases integer Increase A++ will give 6
++
value by one operands
Decrements operator decreases integer Decrease A-- will give 5
--
value by one operands

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;

printf("Line 1 - Value of c is %d\n", c );


c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );

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

PC (b) Explain Relational operators

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.

Operator Description Operation Example


== Equal to Checks if operands are equal (A==B) is not true
!= Unequal to Checks if operands are unequal (A != B) is true.
Greater than Checks if left operand is greater than (A>B) is not true
>
right operand
Less than Checks if left operand is less than (A < B) is true.
<
right operand
Greater than or Checks if left operand is greater than (A >= B) is not true
>=
Equal to or equal to right operand
Less than or Equal Checks if left operand is less than or (A <= B) is true
<=
to equal to right operand

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" );
}

/* Lets change value of a and b */


a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}

Results after compile and execute


Line 1 -a is not equal to b

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

PC (c) Explain Logical operators


Logical operators are very important in any programming language as they help users to make
decisions based on certain conditions.
Table 8 lists a few examples of important logical operators available in the C programming
language.

Table 2.2: Key arithmetic and relational Maths operators

Operator Description Operation


&& AND Checks if operands are non-zero
|| OR Checks if any of the operands are non-zero.
! NOT Reverses the logical state of the operand.

#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" );
}

/* lets change the value of a and b */


a = 0;
b = 10;
if ( a && b ) {
printf("Row 3 - Condition is true\n" ); }
else
{
printf("Row 3 - Condition is not true\n" );
}
if ( !(a && b) )

19
{
printf("Row 4 - Condition is true\n" );
}
}

Results after compile and execute

Row 1 - Condition is true


Row 2 - Condition is true
Row 3 - Condition is not true
Row 4 - Condition is true

PC (d)Explain Bitwise operators

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.

The truth tables for &, |, and ^ are as follows:

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

A&B = 0000 1100

A|B = 0011 1101

20
A^B = 0011 0001

~A = 1100 0011

Table2.4: shows the Bitwise operators supported by the C language

Operator Description
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
~ one’s complement operator
(unary)
<< Left shift operator
>> Right shift operator

PC (e) Perform programming exercises

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;

printf("After performing AND operation, the output is:%d",a&b);

return 0;
}
The result after compilation:
After performing AND operation, the output is: 5

The below checklist will be used to assess your learning

Checklist table 2.5


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

………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………

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

The below checklist will be used to assess your learning

Table 2.6 Observation Checklist


No Yes No
1 Correct tools selected
2 Correct tools used
3 Marking out correct
4 Straight cuts
5 Tight fit of joint
6 Timber left clean
7 Apply safe working practices

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:

Perform programming exercises

1. Explain arithmetic operators

2. Explain Relational operators

25
3. Explain Logical operators

4. Explain Bitwise 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,

switch-case statements, Nested Switch statements, and some exercises.

To achieve this, we will go through PCs (a) – (f).

PC (a) Explain if the statement


Computer programs use if conditional statements to check whether a given condition is true, and
then the conditional body acts to execute the given statements. Various forms of if statements
and switch statements are available in the C programming language. For if statement, the
condition is followed by a conditional statement, which executes when the condition is true.
Decision-making is critical to computer programming. Different programming languages provide
different types of decision-making statements, but the basic concept remains the same. There
will always be situations when you will have to select an option among two or more options
based on given conditions. Almost all programming languages provide conditional statements
that work based on the flow diagram in Fig. 3.
Here, the computer evaluates the given conditions and then the conditional statement will be
executed, otherwise, no statement will be executed.

28
Figure 3.1 Flow diagram for decision-making in conditional statements execution

PC (b) Explain if…else statement


The if...else is a branching statement. It is used to take any action based on some condition. For
example - if the user inputs valid account number and pin code, then allow money withdrawal.
The if...else statement is an advanced form of the if statement. An if statement can be followed
by an optional else statement, which executes when the condition is false. And if...else statement
is useful when you have to make a decision out of two options. The syntax of an if...else
statement in the C programming language can be represented in the form of a flow diagram as
shown in Fig. 3.2

29
Figure 2.2 Flow diagram for if…else statement execution

PC (c) Explain Nested if Statement


In nested if statements, initially, the test expression of outer if the loop is evaluated. When the
condition of outer if becomes true, the if part statement is executed and the output displayed.
Then, the flow of control jumps to the inner– if loop and evaluates test expression of inner if the
loop is evaluated. when the condition of inner if becomes true, the statements of it is executed.
When the condition is false, else part is executed then the else statement is displayed. Then
nested if loop may be an exit or terminated.
A nested if statement is the if...else if...else statement. An if statement can be followed by an
optional elseif...else statement, which is very useful to test various conditions.
While using if, else if, else statements, there are a few points to keep in mind:

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

PC (d) Explain Switch Case Statement


A switch case statement is a branching statement used to perform an action based on available
choices, instead of making decisions based on conditions. Using a switch case, you can write
more clean and optimal code than if-else statements. Switch case only works with integer,
character, and enumeration constants.
A switch case statement is an alternative to if statements which allows a variable to be tested for
equality against a list of values. Each value is called a case, and the variable being switched is
checked for each switch case. The expression used in a switch statement must give an integer
value, which will be compared for equality with different given cases. Wherever an expression
value matches with a cash value, the body of that case will be executed and finally, the switch
will be terminated using a break statement. If no break statements are provided, then the
computer continues executing other following statements available to the matched case. If none
of the cases matches, then the default case body is executed.

31
Figure 3.3: Flow diagram for executing switch statements

32
Syntax of Switch Case Statement

#include <stdio.h>
#include <stdio.h>

switch (variable or an integer expression)


{
case constant:
//C Statements
;
case constant:
//C Statements
;
default:
//C Statements
;
}

PC (e) Explain Nested Switch statement


Nested if statement in C is the nesting of if statement within another if statement and nesting of if
statement with an else statement. Once an else statement gets failed there are times when the
next execution of the statement wants to return a true statement, there we need nesting of if
statement to make the entire flow of code in a semantic order. Nested if statement in C plays a
very pivotal role in making a check on the inner nested statement of if statement with an else
very carefully.
The flowchart below shows how nested statement works

Figure3.4: Nested Switch statement

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

The below checklist will be used to assess your learning

Table 3.1 Observation check list


No Achieved Not- Achieve
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
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………

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;

/* Input week number from user */


printf("Enter week number(1-7): ");
scanf("%d", &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;
}

Result after compilation:


Enter week number (1-7): 1
Monday

The below checklist will be used to assess your learning

Table 3.2 Observation checklist


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

………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………

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

if(age<35){ //elseif statement


printf("you are a younger!\n");
}

else{ //else statement


printf("you are a older!\n");
}
getch();
return 0;
}

Result after compilation:


Enter your age

35

older

Table 3.3 Observation Checklist


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

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

The below checklist will be used to assess your learning

Checklist

Table 3.4 Observation check list


No Achieve Not -Achieve
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

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

6. Explain nested switch statement

7. Explain if else statement

44
8. Explain if statement

LO. 4 Demonstrate knowledge of loops used in C programming

PC (a) Explain While loop

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

PC (b) Explain For loop

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:

The syntax of a for loop in C programming language is:


for (initialization; condition; increment/decrement)
{
statement-block;
}

Example:

Using Code:Blocks write a C program to print the first 10 natural numbers

#include<stdio.h>

void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
print("%d\t", x);
}
}

PC (c) Do while loop


A computer program makes use of a while loop to execute a set of programming statements. A
while loop starts with a keyword while followed by a condition. Further to the while statement,
you will have the body of the loop. A while loop body can have one or more lines of source code
to be executed repeatedly. If the body of a while loop has just one line, then it is optional to use
curly braces {...}. A while loop keeps executing its body till a given condition holds true. As

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.

Figure4.4: Flow diagram for break statement

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

diagram as shown in Fig. 9.

51
Figure 4.5: Flow diagram for executing continue statement

PC (e) Explain Infinite loop


A loop is said to be an infinite loop if the control enters but never leaves the body of the loop.
This happens when the test condition of the loop never evaluates too false. The example below
shows how, the variable i, the iterator, is initialized to 0. The test condition is initially true.
However, i have not modified anywhere in the body and the update expression is empty. Hence, i
will remain 0, and the test condition will never evaluate to false, leading to an infinite loop.

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

3. Explain Nested If Statement

54
4. Explain Switch Case Statement

5. Explain Infinite loop

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.

The reason why functions are important are;

i. To improve the readability of code


ii. Improves the reusability of the code, the same function can be used in any program rather
than writing the same code from scratch.
iii. Debugging of the code would be easier if you use functions, as errors are easy to be
traced.
iv. Reduces the size of the code, duplicate sets of statements are replaced by function calls.

PC (b) Explain types of functions


There are two types of functions and these types are;
i. Predefined standard library functions
ii. User-defined functions

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.

PC (c) Explain structured programming

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.

PC (d) Explain recursion

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

PC (e)Perform Programming Exercises

Write a function that takes two parameters n1 and n2 and returns the maximum value between
the two.

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 program

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

if (n1 > n2)


result = n1;

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:

Perform Programming Exercises

1. Explain functions in C Programming

2. Explain types of functions

61
3. Explain structured programming

62
4. Explain recursion

63

You might also like