Structured Programming Notes
Structured Programming Notes
TERMINLOGIES
I. Computer hardware- It is the physical part of the computer that you can see
and touch.
II. Computer software- It is a set of instructions that instruct the computer
hardware on what to do and how to do it.
III. Program/software- It is a set of instructions that instruct the computer
hardware on what to do and how to do it.
IV. Programming- It is the act of developing software to carry out specific task.
V. Programming language-It is a language used in programming.
SOFTWARES
Application Programming
System Software languages
Software
Application
System Operating Inhouse/Tai Lowlevel High level
Firmware package/off
utilities system lormade languages languages
shelve
VI.
SAVE
COMPILE
OBJECT(OBJ) FILE
FAIL
CORRECT
ERRORS
LINK
These two levels are further sub-classified into 5 generations. The first and the second
generation consist of low level whilst 3rd to 5th generation consist of high level languages
These are classified as low level because they can be easily understood directly or they require
little effort to translate into computer understandable form. There are two types of low level
languages:
(i)Machine languages
(ii)Assembly languages
(I)Machine Language
Digital computers represent and process data instruction using binary numbers (0, 1).Machine
language make use of zeros and ones program statement appearing as a long string of binary
digits.
With Machine language execution is direct since machine language needs no translation. It
occupies little computer memory .Machine language was created by the computer maker and
was sold with machine.
(ii)The program would directly address and control internal circuitry of hardware usage and
control
(i)Writing program was extremely time consuming since each instruction was made up of
binary digits.
(iii)Program modification was cumbersome; it calls for rewriting the whole program.
These were developed in order to overcome the difficulties of understanding and using the
machine language. Assembly language is a language that makes use of Mnemonics. An
Assembler translates assembly language to machine language i.e translate low level language
into high level language.
Examples
(i)Compared to Machine language, Assembly language is much easier to learn and use.
(i)They are machine specific language; programmers to use Assembly language must be an
expert.
These are languages which move from Machine to dependent and focus their strength on
problem oriented and user. Programs are instructions that are written in English or
Mathematical statement e.g if x<=y, x=x+1, x=z.
They are design to reduce ambiguity and has developed in late 1950s.It needs translations by
use of compilers and interpreters.
(ii)They used English like statement hence programmers focus on the functional details of
program rather than h/w detail.
(iii)The data are given names described as variables that are descriptive in nature hence
promote debugging.
(v)The program of high level language can be easy to adapt to a new h/w because there is no
need to worry of h/w designs.
(i)The source program written in high level language needs a compiler which should be loading
to the main memory of the computer language hence occupying a lot of space.
(ii)High level instructions be translated into machine instructions takes a lot of computer time.
(iii)Tends to be less efficient in the use of CPU by being machine oriented i.e more machine
codes instructions are produced so more time is taken to run the program.
N/B: 3rd generation languages are also called Structured or procedural language. A procedural
language makes it possible to break a program into components called modules each
performing a particular task.
(ii)They are mainly used to enquire database system and they are called query language.
(iii)They are easy to learn and understand because they are user based
(vi)Very little training is essential before this language program can be used.
(3)5th generation language:They are the languages that are still in state of development even
source companies have come up with 5th generation language .Programming language
(programming logic) is an example of 5th generation language and is used in the following:
(a)Scientific language: They are languages that contain facilities that support scientific and
Engineering Applications.
(i)General purpose language –These are languages that display features of commercial
e.g Pascal
(iii)Non procedural language –This allows the programmer to specify the closure results
without having to specify the detail procedures need to achieve the results .procedural language
is oriented to how the results can be produced whilst non procedural language is oriented to
what the results is required.
(1) Warranty: When you buy a computer, you do not except to break but sometimes things
do go wrong and it is advisable to have a protection of some kind. A new computer
usually comes with warranty. When you get a warrant, the seller or manufacturer of
the computer agrees to repair or replace it if something go wrong during the given time
frame.
(2) Expansion/Upgrading: When you buy a computer system, the specification are usually
enough to meet the current requirements. But as time goes on you find that it is not big
or fast enough at this point. There are two options:
(a) Buy the entire system which is expensive
(b) Upgrade the existing system which is usually cheaper
(3) User needs: Focus around what the main reasons are for buying the computer system.
(4) Cost: This calls for how much money you are willing to spend in purchasing the
machine.
PROGRAMMING PARADIGMS
The process of designing program without the use of structured steps is referred in strictly
sequential manner, each executed exactly once. In this approach, programmers put all their
code in one place or say in one program. This approach is totally useless if working on large
project.
It helps break it down into smaller chunks (modules) which mean the amount of code that the
programmer has to deal with for any one module is much less than deciding with the system as
a whole.
(3) Visual programming: These are languages that have extra features to allow
programming application to use components of visual language eg Visual
interface, Multiple document and object linking & embedding (OLE). Is the
creation of computer programs by utilizing pictorial element. Visual language
manipulates visual information or support visual interaction or programming
with visual expression.
(1)PROGRAM DEVELOPMENT:
In program you must solve a particular problem or accomplish a task hence therefore
developing a program, the requirement of the eventual user and its expected function should be
fully understood. A program development can be broken into the following stages:-
Explanation:
The downward reversed arrows show a review of one step with previous to see
whether specification has been met.
A program design is an actual development of the program processing or problem solving logics
called a
Algorithm.
Algorithm: It is a step by step instruction that produce a solution to a problem. The design phase
enables the programmer to come up with models of expected programs
The models show the flow of events and data throughout the entire program from the time data
is input to the time program gives out expected information.
(5) Testing: Once the program has been written the program has to be subjected to various
test to check if they have been written out correctly and transcribed correctly at the
same time to check whether it does exactly what is expected to be done (whether it is
correct). It is good practice to test each component of the program produced as well as
testing computed programs.
Types of testing
(1) Unit testing: This involves testing the separate component of the program as they are
produced.
(2) Integrated testing: This involves testing the whole program once it is in the final form.
(3) System testing: This involves testing the whole system after integration.
(4) User acceptance testing: This involves the user of the program testing the program. The
program must do what is expected to do.
(1) Desk checking (Dry-run): It involves going through the program while on paper before
entering it in the program editor. This helps the programmer to detect the most
obvious syntax and logical errors.
(a) Syntax error: Is the error emanating from improper use of language eg
grammatical mistakes, punctuation, improper naming of variables and
spelling of user defined and reserved words.
(b)Logical error: Is an error not detectable by the translator; the program
runs but gives out wrong output and halts during program execution. Such
errors that occur during execution are sometimes called Runtime or
Execution errors.
(2) Using Debugging utilities: After entering the program editor, you can run the debugging
during translation to detect the syntax errors in order to correct them before execution.
(3) Using test data: The programmer carries out trial run of the new program> At each run the
programmer enters various variations and at times including data with errors to test whether
the system will grind to halt.
(6).Documentation: It is very important stage that the work of the programmer is produced in
awritten form. A completed program must be fully documented
All stages of the program development should be documented in order to help during future
modification of the program. Documentation can be either internal or external.
STRUCTURED PROGRAMMING
Structured programming was developed in 1960’s by Nicklaus writh but its use in 1980’s. It is
because as the program became more and more complicated and lack of structuring made it
difficult to understand and maintain into understandable chunks called modules. Structuring
design cannot reduce the overall complexity of the system but it breaks into chunks which can
be dealt with easily. The process of reducing components into sequence of components is
known as structured programming.
Disadvantage of modules:
It is the type of data structure by Michael Jackson. It makes used of 3 Structure diagram called
Notation.
A
Input
Process
Output
B C
stop
Start E
Decision
F X
Test
Loop body
Component box E is iteration. Box F is the iteration component part E is the iteration number of
times (possible) zero of F. The number of F is controlled by specified number
Decision
Y Z
Process Process
Stop
(4) Bottom-up design: It starts solving the smaller tasks till the larger task.
(5) Top-down design: Sub divide the program into major task is solved. The process of
reducing into sequence of smaller components is often called stepwise refinement of the
structured programming. Top- down design approach allows a program to be designed
methodically by providing a complete definition of the program at each level of
complexity.
N/B: An outline program is design first showing the main task or component of the program
and order in which they are to be executed. Each main component is reduced to a number of
smaller, simpler and more manageable components and this process continues at each level
until there is sufficient detail to allow the coding stage to proceed.
Decision/Test
Process
Connectors
Flow direction
Example
A program to calculate an area of rectangle:
Sln:
#include<stdio.h>
Int main( ){
Using Flowchart
Start
Area:=
length*width
Area
Stop
Advantages of flowchart
Disadvantages
Structured chart
They show the overall frame of the program with each level showing progressing more
details .The program is separated into modules one for each main functions
Structured charts are used mainly to show relationship between program modules and
graphics depicts the breakdown of modules
It is often used with other design tools such as pseudo code and flowcharts to express
the process or procedure logics.
It’s aim providing programmers with clear and unambiguous process specification
Pseudo code is usually preceded by hierarchy of module using structured charts
Process logic in pseudo code is express as a combination of sequence of events
decision that needs to be implemented and action that may have to be repeated.
Examples
Start
Area=length*width
Output area
Stop
INTRODUCTION TO C PROGRAM
- C language is basically a very small instruction set, coupled with few standards rules
and predefined formats.
- To make the C programming easy, many programs for primitive functions (that need
to be performed in most of the cases) have already been written and compiled in the
form of libraries (also called header files).
- Programs of these libraries are so commonly used that they are almost considered part
of C language. Stdio.h, string h, stdlib.h etc are the names of few standard libraries.
#include<library-name>
main ()
{
Statement-1;
Statement-2;
.
.
.
.
Statement-n
}
The above illustration structure of C program and note that all the libraries that need
to be used within the program are include at the beginning of the program , using
#include statement. The function from where the execution will start is named as
C programming rules
1. A C program may consist of one or more functions. One of them must be named
as main() . Execution of the program always start from main () function.
2. All the statements of main () function should be written, within the opening and
closing brackets, which mark the beginning and end of the function, respectively.
3. Practically there is no limit to the number of statements that could include in the
main () function. However to make the program manageable, use of multiple
functions should be promoted instead of too many lines in one function.
4. Each statement should be terminated with a semicolon sign (;).
5. C is case sensitive language. A differentiation is always made between upper case
and lower case letters.
6. Comments can always be included in the program by placing the matter in
between /* and*/ delimiters. Following is the general format for placing
comments in the program :
7. /* comments */
e.g. /* this program calculates simple interest*/
Operators used in C
Types of operators used in C
a) Arithmetic operators
b) Assignment operators
c) Comparison operators
d) Logical operators
e) Relational operators
Arithmetic operators
They are used to perform arithmetic operations such as addition and
subtraction
Relational operators
Assignment operators
The assignment operator is used for storing a value at some memory location
(typically denoted by a variable). Its left operand should be a 1 value, and its
right operand may be an arbitrary expression. The latter is evaluated and the
outcome is stored in the location denoted by the 1 value.
Operator
=
+=
-=
*=
/=
%=
&=
!=
^=
<<=
>>=
Logical operators
C++ provides three logical operators for combining logical expression .
Logical operators evaluate to 1 or 0.
Operator Name
! Logical Negation
&& Logical And
|| Logical Or
Logical negation is a unary operator, which negates the logical value of its
single operand. If its operand is nonzero it produces 0, and if it is 0 it produces
1.
Logical and produces 0 if one or both of its operands evaluate to 0.
Otherwise, it produces 1. Logical or produces 0 if its operands evaluate to 0.
Otherwise, it produces 1.
Note that here we talk of zero
Operator Rank
() 1
[]
++ 2
--
! (logical negation)
*(pointer reference)
&(address of)
Size of
* 3
/
%
+ 4
-
< 5
>
<=
>=
= 6
!=
&& 7
|| 8
?= 9
= 10
*=
/=
_=
+=
&=
%=
, 11
UNARY OPERATORS
Example of unary
++m
m++
--m
Example of binary
Arithmetic operators are binary operators
Example
F=m+k
Bitwise operators
C includes operators to manipulate memory at the bit level. This is useful for
writing low level hardware or operating system code where the ordinary
abstractions of numbers , characters , pointers , etc.. are insufficient
bit manipulation code tends to be less “portable”. Code is “portable “ if with
no programmer intervention it compiles and runs correctly on different types
of computers.
The bitwise operators are 1 0 typically used with unsigned types.
~ Bitwise negation (unary) – flip 0 to 1 and 1 to 0 throughout
& Bitwise And
| Bitwise Or
^ Bitwise Exclusive Or
>> Right Shift by right hand side (RHS) (divide by power of 2)
<< Left Shift by RHS (multiply by power of 2)
NB: Do not confuse the Bitwise operators with the logical operators. The
bitwise connectives are one character wide (& , |) while the Boolean
connectives are two characters wide (&&, ||).The bitwise operators have
higher precedence than the Boolean operators. The compiler will never help
you out with a type error if you us & when you meant &&
Meaning of inputting
During inputting , data is obtained from the input device into the computer
memory where it is stored in the memory unit called variable.
The input from the keyboard is usually confirmed when the user presses the
enter key.
Inputting syntax
Scanf(“%t”,&variable_name);
Outputting values
Outputting means sending some data or information from memory to an
output device eg. Monitor.
The data can be :-
a) A message piece of text
Example
b) Value of a variable
Example
Printf(“%f”,b)
c) Value of a constant
Const float pi=3.14
Printf(“%f”,pi);
Printing specific number of characters and decimal places
A number of characters to be printed in the printf() statement
Examples
%5d when used with scanf () specifies that a maximum of five digits
should be entered e.g. scanf
(“%5d”,&k);
%5d when used with printf () specifies that the output integer is
allocated five character positions e.g. printf(“%5d”,k);
%7.2f when used with printf() statement specifies that the output is
allocated seven character positions two of which are fractional part e.g.
printf(“%7.2f”,k);
Escape characters
Escape characters modifies the way the output is presented
Escape sequence meaning
\n new line
\t horizontal tab space
NB
The most commonly used escape characters are:-
\n takes the cursor to the new line
\t leaves the horizontal tab space
Examples
i) Printf(“my first string ”);
Printf (“my second string”);
Output
My first stringmy second string
ii) Printf(“my first string”);
Printf(“\n my second string ”);
Output
My first string
My second string
CONTROL STRUCTURES
A program control structures are block of statements that determine how statements are to be
excuted.In structured program, there are three control structures
(i) Selection
(ii) Sequence
(iii) Iteration(looping)
In selection control structure, execution of statement depends on a condition that returns true
or false. The condition must be a Boolean expression is .one example of Boolean expression is
x>=20. In such case the condition is true, if x is equal to or greater than 20.Any other value that
is less than 20 is therefore false.
Generally the four types of selection control is used in high level program languages are
(I) If….Statements
Expression is evaluated first if it is true, then the body of if is excuted.if the expression is
false, then the body of if is skipped and execution continues with the next statement.
Syntax
IF (Expression)
Statements
flowcharts
start
Exp
False
True
Body of if
Example 1
A program to determine which of the two numbers entered by the user is the greatest
Sln
#include<stdio.h>
Int num (){
Int num1,int num2,greatest;
Printf(“input the first number and second number/n”);
Scanf(“%d%d”,&num1,&num2);
If(num1>num2){
(ii) If…..Else
Expression evaluated first if that is true then the body of if is executed otherwise else body
is executed.
Flowchart
Start
EXP
False
True
Body of if Body of ELSE
Syntax
If (Expression)
Body of if statement
Example
A program to determines which of the two numbers entered by user is the greatest
#include<stdio.h>
Int main(){
Int num1,num2,greatest;
Printf(“input the two numbers/n”)
scanf(“%d%d”, &num1,&num2);
if(num1>num2){
greatest=num1;
}
Else{
greatest=num2;
}
Printf(“greatest is %d”,greatest);
}
Return 0;
}
Example 2
Write a c program to calculate and display the wage of an employee based on the table
below
Hint . wage= no. hours * rate of payment per hour
HOURS RATE(PER HOUR)
1-3 350
4-7 650
7-10 740
11 and over 1000
sln
# include<stdio.h>
Int main(){
Int hours, wages;
Printf(“enter the hours/n”);
Scanf(“%d”,&hours);
If(hours>=1 && hours<=34){
Wages=hours *350;
Printf(“wage is %d”,wage);
}
Nested control structure enables us to do multiple selection choosing one item among
alternatives.
Example 1
MARKS GRADE
70-100 A
60-69 B
50- 59 C
40- 49 D
0-39 F
# include<stdio.h>
Int main(){
Int marks;
Char grade;
Printf(“input the marks/n”);
Scanf(“%d”,&marks);
If(marks>=70 && marks<=100){
Grade=’A’;
}
Syntax
Switch (Expression){
Case const1:
Group of statement1;
Break;
Case const 2;
Group of statement 2;
Break;
------------------
------------------
Default:
Statement(s)
Example 1
Write a c-program to prompt the user to input a number in numerals and print the number
in words e.g 1-ONE
sln
i. While…loop
It’s functionality is simply to repeat statement while the condition sets in expression is True.
Syntax
While (condition){
Statements
}
Flowchart
start
true
Test
cond
false
Statements
Statement after
While..loop
Example 1
Write a program to print integers from 1-10
Sln
# include<stdio.h>
Int main (){
Int x;
X=1;
While(x<=10){
Printf(“x is %d”,x);
++x or x=x+1;
}
Example 2
Write a c program to display the number sequence 3,7,11,15,19,23,27,31
Sln
# include<stdio.h>
Int main(){
Int x;
X=3;
While(x<=31){
Printf(“x is %d”,x);
X=x+4;
}
Return 0;
}
Example 3
Write a c program to print all numbers from 1 to 21 that are divisible by 3
Sln
# include<stdio.h>
Int main(){
Int x;
X=3;
While(x<=21){
Printf(“x is %d”,x);
X=x+3;
}
Return 0;
}
start
Test
cond False
True
Example 1
Write a c program to print integers 1-100
Sln
#include<stdio.h>
Int main(){
Int x;
X=1;
Do {
Printf(“x is %d”,x);
X=x+1;
}
While(x<=100);
Return 0;
}
Example 2
iii. FOR…LOOP
It’s main function is to repeat a statement while condition remains true.
Operation in for..loop
i. Initialization of the counter
ii. Testing the condition
iii. Changing the value of the counter(counter change)
iv. The loops body(statements)
Flowchart
start
Init
Test
cond false
True
Loop body
Reinit
Syntax
For(initialization; condition; counter change){
………………………………………………………………
……………………………………………………………… statements
………………………………………………………………
}
Example1
Write a c program to display numbers 1 to 10
Sln
#include<stdio.h>
Int main(){
For (int y=1; y<=10; y++){
Printf(“y is %d”,y);
}
Return 0;
}
Example 2
Rewrite the above program to display numbers 10 decrement 1 i.e 10, 9,8,7,6,5,4,3,2,1
Sln
# include<stdio.h>
Int main(){
For(int y=10; y>0; y--){
Printf(“y is %d”,y);
}
Return 0;
}
Example 3
Write a c program to print even numbers from 2 to 20
Sln
#include<stdio.h>
For(int c=2; c<=20; c++){
Example 4
Write a c program to output the following pattern
S
S s
S s s
S s s s
S s s s s
Sln
#include<stdio.h>
Int main(){
For(int i=1; i<=5; i++){
For(int j=1; j<=I; j++){
Printf(“s\t is %d”,s);
}
Printf(“\n”);
}
Return 0;
}
Example 4
Write a c program to output the following pattern
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
Sln
#include<stdio.h>
Int main(){
Example 5
Write a c program to output the following pattern
S S S S S
S S S S
S S S
S S
S
Sln
#include<stdio.h>
Int main(){
Int i,j;
For(i=5; i<=i; i--){
For(j=1; j<=i; j++){
Printf(“s\n”);
}
}
Return 0;
}
Example 6
Write a c program using for loop to add and display the sum of all odd numbers between 0
and 100
Sln
#include<stdio.h>
Int main(){
Int sum,Rem;
Example 7
Write a c program to input 5 integers, compute the total, average and print the output using
for..loop
Sln
#include<stdio.h>
Int main(){
Int total;
Float Average;
Total=0;
For( int x=0; x<=5; x++){
Total=total + x;
Total=total/5;
}
Printf(“Total is %d”,total);
Printf(“Average is %f”,Average);
Return 0;
}
FUNCTIONS
Using functions we can structure a program in a more modular way. function also is a group
of statement that is excuted when it is called from source joint of the program.
Syntax
Type Name(parameter 1,parameter 2……….){
Statements
}
i. Type- is a datatype that specify for the data return by the function.
ii. Name-it is the identifier by which it will be possible to each function
iii. Parameter- Each parameter consists of datatype specifier followed by an identifier
like any regular variable declaraction.The parameter acts within the function as a
regular local variable.parameters allow to pass arguments to the function which it is
called.
Example 1
Write a c program to prompt the user for two values,add and display the results
using function
Sln
#include<stdio.h>
Int addition(int a,int b){
Int R;
R=a+b;
Return(R);
}
Int main(){
Int x, y, sum;
Printf(“input the value of y and x\n”);
Scanf(“%d%d”,&x,&y);
Sum=addition(x,y);
Printf(“sum is %d”,sum);
Return 0;
}
From the above declaraction,you will find it begins with a type i.e the type of data
that will be returned by the function with the return statement.
But what if we want to return no value? e.g Assume we want to make a function just
to show a message on the screen.In such situation we do not need to return any
value.In this case we should use void type specifier that indicates absences of type.
Example 1
Write a c program to display a message using function
Sln
#include<stdio.h>
Void printmessage(){
Printf(“A function without a return type\n”);
}
Int main(){
Example 2
Write a c program containing a function called circleArea() to compute Area of the
circle given that Radius =7cm
sln
#include<stdio.h>
Float circleArea(float r){
Const float pi=3.142;
Float A;
A=pie*r*r;
Return(A);
}
Int main(){
Float radius,Area;
Printf(“input the radius\n”);
Scanf(“%F”,&Radius);
Radius=7;
Area=circleArea(Radius);
Printf(“Area is %F ”,Area);
Return 0;
}
Example 3
Write a c program using function that would accept the radius and height of a
closed cylinder and calculate its volume and the value of the volume to be
displayed in the body of the program
Sln
#include<stdio.h>
Double volume1(int r,int h){
Double v;
V=3.142*r*r*h;
Return(v);
}
Int main(){
Example 3
Write the c program to accept a number enter through function ,the function then
determines whether number passed is odd or even
sln
#include<stdio.h>
Int number(int num){
Int Rem;
Rem=num%2;
If(Rem==0){
Printf(“even is %d”,even);
}
Else if{
Printf(“odd is %d”,odd);
}
Return(Rem);
}
Int main(){
Int a;
Printf(“input the value of a\n”);
Scanf(“%d”,&a);
Number(a);
Return 0;
}
Example 4
Write a c program to accept two numbers. determine which number is greatest using
function .Write the said program such that on the termination the sum value passed to a
notation function to be displayed
Sln
#include<stdio.h>
Int greatest(int a,int b){
Int max;
If(a>b){
Max=a;
Function of void-Void is function which only brings a message and have no value to return.
Scope of variables
The scope of variables declared within the function or any other inner block is only their
own function or their own block and cannot be called outside there[Local variables] e.g in
the previous example it could have been impossible to use the variables a,b or r dmoctly in
the function main since they were variables local the function addition.
Therefore the scope of block of variables is limited to the same block levels in which they
are declared .N/B we have 2 types of scope of variables
[1]Global variables
[2]Local variables
We also have possibility to declare global variables. These variables are visible from any
point of the code inside and outside all functions.
In order to declare global variables you need to declare outside any functions or block.This
means directly on the body of the program as shown below.
Example 1
#include<stdio.h>
Int integer;
Char character; Global
Char string [20] variables
Unsigned int number of sons;
Int Addition(int a,int b){
Local
Int r;
variables
}
Types of functions
[1] In build function
[2] user defined function
[1]In build function These are functions which have been written and the one that exist in the
library of codes.
If you want to use this functions you include them in the header file.
Example 1
Inbuilt functions
#Include< stdio.h>
#Include<CMath> Header file
This means that you are including math .h which is a header file in you program.
This c math contains different functions e.g sqrt(), sin(), cos(), tan(), pow(). Inbuilt mathematical
functions.
Syntax arguments
X=SQRT(40)
Keyword
Identifier
Example 1
A program to compute the power of number and value to false and must be entered by user.
Sln
#include<stdio.h>
#include<cmath>
Int main(){
Int m,n,power;
Example 2
Write a c program to solve formula and display the possible roots of the quadratic
equation
ax2+bx+c=0;
sln
#include<stdio.h>
#include<cmath>
Int main(){
Float x,x1,x2;
Printf(“enter the value a,b,c\n”);
Scanf(“%d”,&a,&b,&c);
X=SQRT(b*b-4*a*c);
If(x>0){
X1=-b-(x)/2*a;
X2=-b+(x)/2*a;
Printf(“x1 is ”,x1);
Printf(“x2 is”,x2);
If(x==0){
X3=-b/2*a;
Printf(“x3 is%d”,x3);
}
Return 0;
}
DATA STRUCTURES
Is a specialised format of organizing data storing. Data structure is a way of organising data
in a computer so that it can be used effectively.
Data structure are methods and techniques for efficient use.
Example of data structures
i. Arrays
1. ARRAYS
An array is data structure consisting of elements of the same type,each of which directly
access using the same name i.e Array name.
Array is a series of elements of the same type placed contiguous/consequently in a
memory and can be individually referenced by adding an index to unique name
Application of Arrays
1.used for storing marks of students
Types of arrays
i. one/single dimensional array
ii. multi-dimensional array
Example 1
Int X[5];
0 1 2 3 4
ARRAY
NAME X 20 50 90 -10 0
EXAMPLE 2
Char X[6];
Index
0 1 2 3 4 5
Value
Example 2
A program to prompt the user for an array of five elements to be stored in a
variable num.the program then display the elements in the array
Example 3
Write a c program to display an array of three elements entered by the user in
reverse order
Sln
#include<stdio.h>
Int main(){
Int num[3];
For(int i=0; i<2; i++){
Printf(“enter the elements\n”);
Scanf(“%d”,&num[i]);
}
Printf(“the elements in reverse are\n”);
For(int j=2; j>0; j--){
Printf(“numbers are\n”,num[j]);
}
Return 0;
}
Example 4
#include<stdio.h>
Int main(){
Int scores[10];
Int sum,average;
Sum=0;
For(int i=0; i<=9; i++){
Printf(“enter the scores\n”);
Syntax/format Student
scores
Type
ArrayName (max Rowsize) with (max columnsize)
0 1 2 3 4
0
Student
1
scores 2
[1] [3]
Row column
The way to declare this Array in C-programming would be: int student scores (3) (5)
.The way to reference the second elements vertically and fourth horizontally (the
second student fouth score) in the expression would be:
Student scores [1][3];
To insert a value of fourth it score for the second student, you would use the
statement:
Student score [1][3]=60;OR
Printf( student score[1][3]);
Arrayname [Rowindex] [columuindex]=value;
0 1
45 45
45 45
Sln
#include<stdio.h>
Int main(){
Int num[2][2];
Int row,cols;
For(row=0; row<1; row++){
For(cols=0; cols<=1; cols++){
Num[row][cols]=45;
}
}
For(row=0; row<=1; row++){
For(cols=0; cols<=1; cols++){
Printf(“num[row][cols]/t”);
Printf(“\n”);
}
Return 0;
}
Assignment
1.Write a c program to prompt the user for an array of 2 scores for 2 students add
and display their sum as per the table below
scores
0 1 2
maths english total
students
Sln
#include<stdio.h>
Int main(){
Int studscore[2][2];
Structs/structures
Student: structure
Roll no- int datatype
Age-int datatype Member of
Religion- string datatype structure
Fees-float datatype
Declaration/syntax
Struct structName
Members declarations
};
EXAMPLE 1
Struct Num{
Int x;
Int y;
EXAMPLE 2
EXAMPLE 2
Store values;
P . x =values;
1) Print f(“p.x”);
2) If (p.x>10)
Statement;
3) Y=(P.X =3)/2
4) Y =P.X
Example 3
#include<stdio.h.>
Struct x {
Char a;
Int b;
}
Int main (){
Struct xq structure variable
//Store values to struct
Printf(“Enter the value of member a character\n”);
Scanf(“%c”,&q.x);
Printf(“Enter the value of member b integer\n”);
Scanf(“%d”,&q.b);
SOLUTION
#include<stdio.h>
Struct Employee{
Int empno;
Int age;
Int experience
Float salary;
} Aloak;
Scanf(“%d,& Alok.empno);
Printf(“Give Name”)
Scanf(“%c”,Alok.Name);
Printf(“Give experience”);
Scanf(“%f” alok.salary);
Intmain(){
Struct student stud1={“jane “,90,25,30};
Struct student stud 2={“Ken”,80,50,70”};
Member function of a structure
These are just function declared within function; they define operation
within a structure.
It define what are the function within the structure
Example
#include<stdio.h>
Struct x{
Int b;
Void ReadData(){
Printf(“enter the value of a\n”);
Scanf(“%c”,&a);
Printf(“enter the value of b\n”);
Scanf(“%b”,& b);
Member function }
Array of structs
i. Employee
ii. Name
iii. Earnings
iv. Expenditure
Write a program that accepts the data of all employees and print saving amount
for them.
SOLUTION
#include <stdio.h>
Void Readdata(int);
Void calculate(int);
Struct Employee {
Int empno;
Char Name[30];
int earning;
int spend;
}emp[25];
Int main(){
Int n;
Printf(“\n How many employees are there”);
Scanf(“%d”, &n);
Readdata(n);
Calculate(n);
}
Void.Readdata(int n){
int i ;
For (i=0; i<n; i++){
Printf(“Give employee.Number”);
Scanf(“% I”,& emp[i].empno);
Printf(“Give employee Name”);
Scanf (“%[^\n]”, emp[i].Name);
Printf(“Give earning amount”);
Scanf(“%i”&emp[i].earning);
Printf(“Give expenditure amount”);
Scanf(“% I”, & emp[i].Spend);
}
Return;
}
Void calculate (int n){
int i,diff;
For(i=0; i<n; i++){
Diff =emp[i].earning –emp[i].spend;
Example of deference
Int * p;
P=&a; Since p is pointing to a variable a then print (“*p”)
A=50
ii) Referencing operator -Returns the memory address of a variable
.The address that locate the variable within memory is what we
called Reference to that variable.The reference to a variable with
Int * p;
Int a;
P=&a;
The statement p is equal to reference a, would assign to p the address of variable a, since when
proceding the name of avariable a with the reference operator(&) we are talking about the content
of the variable itself but about its record ie (its address memory)
N/B To differentiate pointers with normal variable they are prefixed with Asterik(*) sign.
Int* P speed
Char*pstatus
Float *point
EXAMPLE 1
#include<stdio.h>
Int main(){
Int speed=250;
Int*p speed.
Printf(“%d the value of speed variable\n” speed);
Printf(“% d the address of speed variable\n” pspeed);
Printf (“%d value attained trough operator\n” p speed);
Return 0;
}
OUTPUT
The value of speed variable is 250
Example 2
A program to add two numbers using pointers
#include<stdio.h>
Int main()}
Int a,b,s.
Int *p1,*p2,*sum;
P1=&a:
P2=&b;
Sum=&s;
Printf(“enter the value of a\n”);
Scanf(“%”,&*p1);
Printf(“enter the value of b\n”);
Example
Int Number[20];int *p;then the following assignment operators will be equivalent and
would have the same properties.They only difference is that it could change the value of
pointer P by another one wheares numbers would always point to the first twenty element
of type int with which it was defined.
Example 1
Due to xtrics of the variable all the expression that include pointers in the following example
on perfectly valid
s\n
Int main(){
Int numbers[5];
Int *p,
P=numbers;
*p=10;
p++;
*p=20;
P=&numbers[2];*p=30;
P=numbers;*(p+4)=50;
Return 0;
Output
10, 20,30,40,50
Example 2
s\\n
#include <stidio.h>
Int total;
Total=0;
For(int=0;j<5;j++){
Total=total+*(n+j);
Int main()
Int number[5];
Int s;
S=sum(numbers);
Return 0;
Example 4
Write a c program using a function and a pointer to accept the array of number 1 to 10 and
display in reverse order.
s\n
#include<stdio.h>
For(int j=10;j.=0;j--){
Int main ()
Reverse (number);
Return 0;
Pointers to pointers
C programming allows the use of pointers that point to pointers i.e. that this will return
pointers to data or even to other pointers
- In order to do that we only need to add an asterisk for each of level reference in
their declaration
Example
Char a,
Char *b;
Char **c;
a=’z’;
b=&a;
c=&b;
- Supposing the randomly chosen memory location for variable a,b,c are
7230,8032,10502 respectively then the above declaration will be represented as;
8032 10502
7230
The value of each variable is written inside each cell,under the cells,there are respective
address in memory.
From the above example,the variable can be used in three different levels of directions each
one of them will correspond to different values eg c has value 8032
SORTING TECHNIQUES
1. BUBBLE SORT
It is a simple sorting algorithm .The bubble sort work by iterating down an array to be sorted
from the first element to the last comparing each pair of element of switching their position
if necessary .This process is reapeted as many times as necessary until the aerray is sorted.
ILLUSTRATION;
5 4 3 1 2
4 5 3 1 2
4 3 5 1 2 1st pass
4 3 1 5 2
4 3 1 2 5
4 3 1 2 5
3 4 1 2 5
3 1 4 2 5 2nd pass
3 1 2 4 5
3 1 2 4 5
3 1 2 4 5
1 3 2 4 5
1 2 3 4 5 3rd pass
1 2 3 4 5
Example 1
A program to sort a list of 5 element entered by the user in ascending order using bubble sort
technique
Sln
#include <stdio.h>
#define n 5
Int main(){
Int num(n);
Int I,pass,compar;
For(pass=0;compare,n-1;compar++]{
For(compare=0;compar<n-1;compar++){
If(num[compare]>num[compar+1){
Int temp=num[compare];
}//if
Return 0;
Ii SELECTION SORT
Selection sort works by selecting the smallest(or largest).If you want to sort from big to small
)It works by selecting small and placing it at the head.Then the process is reapeted for the
remainder of the array.The next largest element is selected and put array .The next largest
element is selected and put into the next slot and so on down the line .
Because a selection sorts looks at pproccessing smaller part of an array each time (it knows
to ignore to infront of the varray because it is already inorde)
Then the selection sort is likely faster than bubble sort.
Loc
0 5 4 3 1 1
1 4 5 5 5 5
2 3 3 4 4 4 1st pass
3 1 1 1 3 3
4 2 2 2 2 2
Loc 0 1 1 1 1
1 5 4 3 2
2 4 5 5 5 2nd pass
3 3 3 4 4
4 2 2 2 3
Loc 0 1 1 1
Loc
1 1 1
2 2 2
3 3 3 4th pass
4 5 4
5 4 5 the element are already sorted
Example 1
A program to sort a list of 5 elements entered by user in ascending order using
selection sort technique
s/n
#include<stdio.h>
#define n5
Int main() {
Int num[n];
Int pass, compare, temp;
For(i=0,I<n,i++}
Printf(‘’key element to sort/n”);
Scantf(“%d,” &num[i];
}
For(pass=0;pass<n-1;pass++){
For(compare=pass+1;compare<n;compare++){
If(num[pass]>num[compare]){
Temp=num[pass];
Num[pass]=num[compare];
Num[compare]=temp;
}//endif
}//end inner for
}//end outer for
Printf(‘’sorted list is %d,”sorted list/n’’);
For(i=0;i<n;i++){
Printf(“numbers are &d,’’num[i]/n’’);
}
Return 0;
}
SEARCHING TECHNIQUES
(1) LINEAR SEARCH
-This is a very straight forward searching techniques that compares every
element in the array with key element being search. As soon as the equal
II BINARY SEARCH;
DIVIDE IN HALF;
- It is first way to search a sorted array. The idea is to look at element in the
middle. If the key is equal to that then the search is finished because the
element has been found.If the key ie less than the middle element.Do a
binary search on the first half of the array.If the key is greater.Do a binary
search on the second half of the array.
Example:
Search for 36 using a binary search
1,16,19,24,36,4,7,9,13
1,4,7,9, 13 16,19,24,36
Lower half upper half
middle
Example 1
A program to implement binary search
#include<stdio.h>
Int main () {
Int array [n];
Int first last key;
Prinf(“enter the element to search from the list\n”);
Scanf(“%d”, & key);
For (int i=0; i<n; i++) {
Printf(“enter the element to search from\n”);
Scanf(“%d”,& array [i]);
}
First =0
Last=n-1
While (first<=last){
Int mid=(first+last)/2;// compare mid points
If(key=array[mid]{
Prinf(“elements found\n”);
}
If(key>array[mid]{
First=mid+1;// repeat search in top half
}
If(key<array[mid]{
Last=mid-1;//repeat search in bottom half
}
}//end while
Print (“element not found\n”);
Return o;
}
Description of commands
i. Open a file
Inoder to open a file with stream object we used its members functions
toi open ()
Eg myfile .open (“c:\example.text”);
Internal name of part and external file name of file
A file and a command to write the same file
Ii closing a file
- When we are finished with our input and output of our files we
shall,closed it so that its resources became available again .This is done by
use of stream member function close()
Syntax
Myfile.close () take an argument
Example
-Ensure that the whole line of sentence consisting of string characters,spaces and special symbols is
read and stored in a particular variable in our case line.
E.O.F:
This last example read atxtfiles and brings out its content on the screen.We have used a new
member function called eof that returns true in the case that the end of the line has been Reached.
We have also created a while () loop that finishes when indeed myfile.eof() has become true i.e the
end of the file has been reached i.e e.of has been reached.
PROGRAM DOCUMENTATION
Program documentation even has the capability to sustain any later maintenance or development of
the program.
With proper documentation you can share the business goals and requirements with your managers
and team –mates so that they have clear vision and goals and the activity they perform will be more
towards the success.
This comes in architectural design documents and it gives you complete overview of how your
product taste like
When you make end user documentation of the product of s\w you have to explain each and
everything about its working,It describers features of the program and assist the user in realizing
these features.
If you are a developer, it is not sufficient toi write good codes only but also need to take care about
the documentation part, which can be helpful to other developers while working in a team.
A good s\w documentation is helpful in proper communication the written procedure helps you to
make interaction with several departments.
S\w documentation is also reffered to as source code documentation and is a text that describes a
computer s\w.It explains how a s\w works but it can also explains how to use the s\w
properly.Several types of s\w documentation exist and can classified into:
I. User documentation
-Also known as s\w manuals user documentation intended for end-user and aims to help them use
s\w properly.It is usually arranged in a book style and typically also featured table of contenmts,
index and of course, the body which can be arranged different ways, depending on whom the s\w is
intended for.S\w manuals which is intended for immediate users on the other hand, are typically
arranged matricatically,while manuals for advanced users follow reference style.
Technical documentation is a very important part of s\w documentation of many programmers use
both terms interchangeably despite the fact technical documentation is only one of the several types
of s\w documentation.It describes codes but it is also addresses Algorithm,interfaces and other
technical aspects of s\w development and application .Technical documentation is usually created
by the programmers with the Aid of Auto-generating tools.
iii.Requirement document
Requirement documentation,also reffered to simply .As requirements explain what s\w does and
shall be able to do several types of requirements exists which may or may not be included in
documentation depending on purpose of complexity of the sytem.Eg application that don’t have any
safety implication and are not intended to be used for a longer period of time may be accompanied
at all.Those that affect human safety/or that are created to be used over a long period of time on
the other hand come with an exhausting documentation.
It mainly deals with technical issues including online marketing and services but vital also covers
non-technical issues inorder to provide guidance to sytem developers,maintance,technicals and
others involved in the development or used of architecture including end users.
-Architecture documentation is usually arranged into architectural models which inturn may be
arranged into different views,each of which deals with specific issues.