CMP201 Lecture Material
CMP201 Lecture Material
Course Description
Introduction to problem solving, problem solving methods: algorithm development and flowcharting,
programming language concepts. Designing, coding, debugging and documenting programs using
techniques of a good programming language style, Programming examples and solutions.
Note: The programming language to be used in teaching the course is C Programming Language.
Learning Objectives
At the completion of this e-note, it s expected that learners will achieve the following:
introducing first and then establish relationship between them and subsequent topics/terms. Now, let’s
start with Problem Solving as a topic.
Problem solving is an integral part of Computer Science. Computer is used as a problem solving
tool in both public and private organizations. This statement is a testimony to the rate at which computer
and ICT solutions are used for driving services and operations of government and private establishments
in Nigeria and beyond. From different sectors of the economy, computers are being put to use. They are
used for manufacturing, educating, researching, distributing, and increasing productivity.
While we want to develop a software application, set up a network, troubleshoot a computer problem
(hardware or software) we engage n problem solving. The problem solver is expected to make use of
1
some skills and techniques while solving problems.
Note: In the context of this course, only Algorithm and Flowchart will be covered at this introductory
level
While developing a program (software), there are stages that the software product (program) must
pass through. The stages are generally called Software Development Life Cycle (SDLC). Depending on
the software development methodology being used, a programmer may need to iterate some of these
stages. For instance, if a programmer is able to conceptualize a solution to a given problem, he may need
to revisit the different stages of the SDLC after testing the solution. If the solution fails to meet the
expected expectations of the client/user, the first set of processes may need to be carried out once more.
While providing solutions to a wide range of IT problems, problem solving tools can be used. Algorithm
and Flowchart are being introduced herein as problem solving tools that can help drive varying solutions.
Algorithm
2
An algorithm can be defined as the step-by-step procedure for solving a given problem. It clearly spells
out how a solution to a particular problem is achieved. It is equally regarded as sequence of steps that
have to be followed for solving a given problem or performing a given task.
Irrespective of a programming problem to be solved in computing, it is expected that the programmer is
able to identify the best algorithmic approach to be used.
Step I:Start
Step II:Initialise Pi=3.142
Step III:Enter radius of the circle
Step IV: Compute Area=Pie * square of radius
If you look closely at the above algorithm, you will discover that the various steps that are required for
finding the area of a circle are listed in chronological order. This is made possible
because the formula for finding area of a circle is understood and the various components are well
utilized.
Supposing we have another problem that requires that we draw an algorithm that can accept and display
the personal details of a lecturer in Al-Hikmah University, we may provide the following solution:
//This is an algorithm to accept and display details of a lecturer Step I:
Start
Step II: Accept StaffNo
3
Step III:Accept Surname
Step IV: Accept Firstname
Step V: Accept MiddleName
Step VI: Accept Faculty
Step VII: Accept Department
Step VIII: Accept Gender
Step IX: Print all the accepted values in step II to VIII Step
X; Stop
Flowchart
A flowchart is the pictorial representation of an algorithm. That is a flowchart refers to as the diagrammatic
representation of steps followed in solving a given problem.
The flowchart symbols include:
Terminal Symbol-This is the symbol that is used to indicate the beginning and ending of a flowchart
Start
Processing Symbol-This is the symbol that is used to denote processing and computational activities.
Calculate Total
Flow Arrow-This is the symbol that is used to indicate the direction in which a particular operations is
going.
Decision Symbol-This is the flowchart symbol that is used while making decision.
Input and Output Symbol-This is the kind of symbol that is used for feeding the computers with the set
of needed inputs. The symbol is equally used for generating outputs.
4
Connector-This is used to join a flowchart diagram from one page to another. It should be properly
labeled so as to avoid confusing the user of the diagram.
Note: It has to be pointed out that these symbols are used together to draw flowchart depending on the
problem at hand.
In order to give you a solid foundation in flowcharting, I will like to also provide an example. Lets refer
to the first example on algorithm. Each time you are to draw a flowchart; you must be able to either
sketch the algorithm on paper or having the steps involved in arriving at the algorithm in your head. What
is then left is to use the suitable flowchart symbol to represent the different stages of the algorithm.
The flowchart symbol on the problem mentioned is as shown below. I want to advise that you take time
to peruse the instructions herein and master the various examples so that you can understand better.
Examples on Flowchart Design
(i) Design a flowchart that can accept the matric number, name and score of a student in two courses
and then display the details.
Solution
Start
Accept Matric No
Accept Name
Stop
(ii) Design and a flowchart that can be used to compute the area of a circle
Solution
Start
5
Initialize Pi=3.14
Stop
Program
Syntax
Syntax Error
Logical Error
Loop
Data Types
Looping
Identifier-this can be a variable name, a function name and so on.
Programming/Computer Programming
Data Descriptor (%d,%f,%c e.t.c)
Constant
Control Structures
Program logic
Function (In-built function, user-defined function) and many others.
Let me use this opportunity to remind you that there is a need to have a good understanding of these concepts
before you can write meaning program in C.
The section below is used to briefly explain some of the concepts before we go into programming, proper.
6
will be focusing on introducing you to the syntaxes of C as a programming language.
a. Simple data type (e.g. integer, character, float, double, long integer e.t.c)
and
b. Composite/Complex Data Type (e.g Array, Structures, String, Enumerated, Union e.t.c).
Note: It is expected that a programmer determines and use the most appropriate data type in a particular
program before proceeding to writing the codes.
This course being an introductory course considers only simple data types in some of the examples and
exercises..
In C language, for each of the data that is to be handled, a data descriptor should be used. The data
descriptor, as it name implies-gives the description of the data that the user can supply from an input
device into the c program.
(iii) Computer Programming or Programming is the act of coding instructions for computer to
carry out. Providing solution to a problem is achieved with the use of suitable programming
language. The choice of a programming language for a given problem depends on a number of
factors. These factors include:
7
Object Oriented programming languages and so on. Object Oriented Programming is a programming
method that combines data and instructions for processing that data into a self- sufficient ‘object’ that can
be used within a program or in other programs. In OOP, Objects are modeled on real world entities. This
enables modeling complex systems of real world into manageable software solutions.
These languages are written using human language and have their well defined syntaxes. A
programmer in whatever level has to obey the syntax of the chosen language he/she wants to use to
develop the targeted applications/softwares. High Level Languages use language translator to be executed
on a computer/machine. These translators are either interpreter or compiler.
Programming in C Language
Brief History
C Programming Language is a Structured programming language that can be used for developing varying
mathematical and scientific applications. C was developed by Dennis Ritchie at AT&T Bell Labs, the
USA in early 1970s. As a High level programming language, C has support for various mathematical and
scientific functions. The language makes use of compiler. These compilers are from various vendors and
of different versions. Examples of such C compilers include: Tiney C, Netbeans C, GNU C, Open64,
Smaller C, Borland C and so on.
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to
develop the UNIX operating system at Bell Labs. C has now become a widely used professional language
for various reasons:
C is Easy to learn
It is a Structured Programming language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
While programming in C, there are a lot of compiler types that are available. They are: Turbo C, Open64,
Tiny C, Small C, Borland C, Netbeans C, Code Blocks and many others.
Note: While writing programs in C language, efforts should be made to have a good understanding of the
syntaxes of the language. Syntax simply means the set of rules that have to be followed while writing
valid program statement in the language. When the syntax of the language is violated, we have what is
called syntax error.
The choice programming language is C and the compiler being used to run the codes in this course for
demonstration purposes is Netbeans C.
It has to be mentioned that Netbeans is an IDE that support various programming languages (Java, C, C+
+, PhP) depending on the one that is installed on the machine being used for the programming activities.
8
For you to write valid program using C langu, you are expected to master the syntaxes of the language.
Programming is not about cramming. Having mastered the syntaxes you have to practice and use your
experience to solve programming problems.
In the beginning, C was used for developing system applications such as:
i. Database Systems
ii. Language Interpreters
iii. Compilers and Assemblers
iv. Operating Systems
v. Network Drivers
vi. Word Processors
C as a Compiled Language
C is a compiled language. This statement means that C source code is converted to equivalent machine code all
at once. A compiler is a translator that compiles the program and converts it into the object file which is
machine readable. After the compilation process, the linker will combine different object files and creates a
single executable file to run the program. The following diagram shows the execution of a 'C' program
Nowadays, various compilers are available online, and you can download and use any of those compilers.
For the purpose of this course, Netbeans C compiler is recommended. You can download this compiler from
www.netbeans.org. After the download, you can then install the application on your system. Each time
you write a program (as a beginner) in your programming notebook, you can then go ahead and type
in the codes into the netbeans environment, run and execute them in order to obtain the output.
9
It has to be pointed out that C is case sensitive and you should make sure that keywords and variables
are correctly typed and used. The meaning of case sensitivity of C language is that it differentiates
between upper case letters and lower case letters (whether keywords or identifiers).
Note: You are expected to download the version (32 bit or 64bit) that is compatible to the architecture of
your system.
For instance the following are valid variable names because they obey one or all the rules
mentioned above:
(i) sum (ii) studentscore (iii)Totalsalary23 (iv) Manager_Pay (v) StudentAdd4 e.t.c
10
The following variable names are not valid
(i) 34Name (ii) Sum total (iii) President name* (iv)printf (v) getchar (vi) N89}
Escape sequences are used in the programming languages C and C++, and their design was copied in
many other languages such as Java and C#. An escape sequence is a sequence of characters that does not
represent itself when used inside a character or string literal, but is translated into another character or a
sequence of characters that may be difficult or impossible to represent directly. In C, all escape sequences
consist of two or more characters, the first of which is the backslash, \ (called the "Escape character"); the
remaining characters determine the interpretation of the escape sequence. For example, \n is an escape
sequence that denotes a newline character.
The following escape sequences are defined in standard C. This table also shows the values they map to in
ASCII. However, these escape sequences can be used on any system with a C compiler, and may map to
different values if the system does not use a character encoding based on ASCII.
Note: Some of the ways to use these escape sequences go beyond this course. We are only introducing
them for better references.
11
In this course, emphasis will be on FOR LOOP. Mention will also be made of DO WHILE LOOP and
WHILE DO LOOP. In future programming course named, CMP301, you will be exposed to some other
areas.
Like any other program constructs, these loops have their syntax which must be adequately mastered and
put to use for proper practical mastery.
What is Looping?
Looping can be defined as the process of performing certain segment of a program n a repeated manner until
the specified condition is met. The loop allows programmer to write program codes that are able to run
repeatedly.
(ii) int j;
for (j=150;K>=5;j--)
{
Program codes;
}
This codes run repeatedly until the specified value of 5 is reached. The index variable is decremented by 1,
12
from 150 till it reaches 5.
THE WHILE LOOP /WHILE Statement
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:
while (expression)
{
//Program statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates
to true, the while statement executes the statement(s) in the while block. The while statement continues
testing the expression and executing its block until the expression evaluates to false.
Practical Program Example on While DO LOOP
Use the while statement to print the values from 1 through 40.
Solution
The solution to the programming problem can be accomplished as in the following While DO Example
program:
#include <stdio.h>
int man ()
{
int count = 1;
while (count < 11)
{ printf(“%d " +
count); count++;
}
}
Note: The program segment will print the value of variable count while count is less than 11.
scanf("%d",&n);
sum +=n;
}
avg=sum/10.0;
printf("The sum of 10 no is : %d\nThe Average is : %f\n",sum,avg);
Question
Write a C program to convert a temperature given in celcius scale to fahrenheit.
Solution
14
**
* C program to convert temperature from degree celsius to fahrenheit
*/
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
return 0;
}
Question 3:
Write a C program to find the power (exponent) of any number.
Solution
/**
* This is a C program to find power of any number.
*/
#include <stdio.h>
#include <math.h> // For this problem use for pow() function
int main()
{
double base, expo, power;
/* Calculates base^expo */
power = pow(base, expo);
printf("%.2lf ^ %.2lf = %.2lf", base, expo, power);
return 0;
}
15
This section provides some questions and answers so as to improve the understanding of the learners.
Please take time to read through the questions and the answers. You are expected to practice on your
own.
(1b)Write a C Program that can add integer values from 450 to 890
(1c)Mention any four primitive data types supported in C Programming Language
(2a) Define translator and mention any two relevant examples
(2b) Write a C program to find the area of a circle given that Area=∏r2
(3b) Copy and complete the table below by establishing the validity of the identifiers or otherwise
S/N Identifier Status Reason
i sumtotal
ii 3Maverage
iii Agestud123
iv switch
v printf
vi EmployeeDetails
(i) Compiler
(ii) Logical Error
(iii) Syntax Error
(5b) Write a C Program that can accept scores of a student in ten courses and then compute the average
score. Hint: Use array and a suitable Loop structure to perform the task .
1b.
/*A C program to add integer values from 12 to 270 */
5maarks
#include <stdio.h>
int main ()
{
int sum=0;
int j;
for (j=12;j<=270;j++)
{
sum=sum+j;
}
printf(sum);
return 0;
}
1c. The primitive data types supported in C Programming language include: Integer
Float Double
Long Integer
Character and so on
17
Interpreter
3b.
4b. /*A C Program to compute the average score of a student in four courses */ #
include<stdio.h>
int main()
{
int score1,score2,score3,score4; int
scoresum,averagescore;
scanf(“%d %d %d %d”, &score1, &score2,&score3,&score4);
scoresum=score+score2+score3+score4; averagescore=scoresum/4;
printf(“%d”,averagescore);
return 0:
}
20
scanf(“%d”, Score[m]);
Sum=Sum+Score[m];
Avg=Sum/10;
printf(“%d”,avg);
return 0;
}
6a. The term looping refers to as the process of performing some segment of program statements in a
repeated manner until a certain condition is satisfied. Looping is carried out with the use of loop
statements such as FOR LOOP, Do WHILE LOOP and so on.
6b.
Good examples of preprocessing directives in C are:
#include
#define
Study Questions
1. Define each of the following terms: (i) Program (ii) Programming (iii) Problem solving
2. Write a C program to find the perimeter of a rectangle given that P=2(L+B) where L and B are length
and Breath respectively.
1. Paul Deitel and Harvey Deitel (2010). C How to Program 6th Edition, Pearson Education,
Inc.Upper Saddle River, New Jersey
1. Tim Bailey (2005). An Introduction to the C Programming Language and Software Design
2. Paul Deitel and Harvey Deitel (2010). C How to Program 6th Edition, Pearson Education, Inc.Upper
Saddle River, New Jersey
22