Structured Programming
Structured Programming
General Objectives: After completing this course, you should be able to:
1
..23v2
LANGUAGE
Explain the notions of variables and constant and properly used them with C program
2
INTRODUCTION TO PROGRAMMING
PROGRAM
A computer program is a series of organized instructions that directs a computer to perform tasks. Without
programs, computers are useless. A program is like a guideline. It contains a list of variables (called
ingredients) and a list of statements (called directions) that tell the computer what to do with the variables.
Programs are written to instruct the computer to carry out specific task or to solve particular problems.
PROGRAMMING
Programming is a creation of a set of commands or instructions which directs a computer in carrying out a
task.
PROGRAMMING LANGUAGE
A programming language is a set of words, symbols and codes that enables humans to communicate with
computers.
ASSEMBLER
An assembler is a computer program for translating assembly language — essentially, a mnemonic
representation of machine language — into machine language. For example in intel 80836, the assembly
language for the ’no operation’ command is NOP and its machine code representation is 10010000.
INTERPRETER
The interpreter will read each codes converts it to machine code and executes it line by line until the end of
the program. Examples of interpreter-based language are BASIC, Logo and Smalltalk.
COMPILER
The compiler converts the source code (written program) into machine code which is a file consisting of
binary machine code that can be executed on a computer. If the compiler encounters any errors, it records
them in the program-listing file. When a user wants to run the program, the object program is loaded into the
memory of the computer and the program instructions begin executing. A compiled code generally runs
faster than programs based on interpreted language. Several programming languages like C++, Pascal and
COBOL used compilers as their translators.
3
There are two main categories of programming levels; these are low-level and high-level languages. The
terms 'low' and 'high' does not mean that a group of 'low-level' languages are inferior to the 'high' ones. A
low-level language consists of machine-oriented programming. For example, Machine code and assembly
language are referred to as Low-Level-Languages.
Machine code is a language which uses binary coding in its source codes , it uses binary code to
interact with a specific computer system. It is machine dependent language i.e. it is code is decided by the
manufacturers when and is relevant or applicable on to to that computer. Machine code is the only
language with which the CPU understands.
Assembly language uses word or symbolic codes called mnemonics instead of binary numbers to program a
specific computer system ( Low Level Languages are difficult to use.) . The Assembly language has a
structure of machine-oriented programming. The Assembly Language, in other words, has a major
control of the computer hardware. The Assembly Language makes use of mnemonics and has a
better relationship with the memory and the CPU unit far more than that of other programming
languages. The Assembly language is sometimes used as part of the source code written in Pascal.
Programming in terms of mnemonics is called assembly language programming both machine code and
assembly languages are specific to the CPU design of a particular machine so they are machine dependent.
A high-level language consists of all those languages which are human problem-oriented. A low-level
language is not user-friendly, that is, makes it hard for the user to understand the structure of the program.
High Level Languages
A high-level programming language allows programmers to use words and symbols closer to human language for
software codes because they reflect the way that we humans are thinking as opposed to a low-level language which
reflects to the way internal working of a particular machine is organized. A high level language is a machine
independent language i.e it works on different computer systems regardless to their components. Every high-level
language has its own source which needs to be translated into the CPU's language - machine code. These
translators are referred to as interpreters and compilers. A high-level language package contains either an
interpreter, or a compiler, with which a high-level language uses to translate the source code into object
code.
Characteristics
4
Lisp: This language was developed in the late 1950s. Lisp is base on lists; List processing”. Very popular in AI
(Artificial Intelligence) circles.
FORTRAN: FORTRAN derived its name from FORmular TRANslation, sometimes FORmular TRANslator and it is
a mathematical based language.
C/C++ etc
Software Development Tools
These are software that are used to develop applications and system software. Examples include translator,
editors, DBMS, debuggers, linkers.
I. Translators
Translators are program that convert source code into object (machine) code compilers, interpreters, and
assemblers are examples of translators.
The Assembler
The assembler is software supplied by the computer manufacturer that converts the mnemonics into machine code
for execution. Without an assembler, each assembly language mnemonics would be translated into machine code by
hand.
The listing of the assembly language mnemonics is called the source code or source program. After the assembly
process has been carried out, we end up with machine code called object code or object program.
Compiler
A compiler is a program that converts an entire program code written in high level language into machine language
for execution by the CPU. The original program is called source program and its translation is called the object
program.
Interpreter
An interpreter converts one instruction into a machine code then executes it before going to the next instruction.
Some examples include: BASIC, Lisp, Logo.
Differences between Interpreters and Compilers
An interpreter is slower than a compiler, the fact that it has to be loaded into memory till the end of the
translation of the program. It is less practical than the compiler. However, the interpreter can be helpful for
correcting out errors in programs i.e. it is ideal for debugging. A compiler is faster due to its single,
complete translation of the program into object code. A compiler, compiles the source code (with no syntax
errors) and makes a copy of it. This copy is called the 'object code'. After it has been compiled, it does not
need a recompilation (unless the source code is changed and a recompilation is required to affect the
change).
Loader
A loader is a program that takes object code (the machine code produced by the assembler) and loads into the
computer’s main memory in the correct place. Examples of a loader is the bootstrap loader. This is the loader that
loads itself by using the instructions at the beginning to load the rest of itself during the booting process.
5
Translator Advantage Limitations
II. Editor
An editor is a piece of computer software for creating and editing plain text. It is distinguish from a word processor in
that it does not manage document formatting or other features commonly used in desktop publishing. A text editor
can be used to write email, compose Web pages, create computer programs. Email messages, and HTML Web pages
are plain text, that is, not formatted.
Text editor are often provided with operating systems or software development packages, and can be used to change
configuration files and programming languages source code. For example, Microsoft Windows Systems come with
Notepads.
6
A Database Management System is a set of computer programs that controls the creation, maintenance, and the use
of database with computer as a platform of an organization and its end users. DBMS are controlled by database
administrators (DBAs) and other specialists.
Debugger
Bug: Software bug is the common term used to describe an error, f law, mistake, failure, or fault in a computer
program that produces an incorrect or unexpected result, or causes to behave in unintended ways. A debugger is a
software that is used to identify and remove bugs from a program. Most bugs arise from mistakes and errors made
by people in either a program’s source code or its design, and a few are caused by compilers producing incorrect
code.
A program that contains a large number of bugs, and / or bugs that seriously interfere with its functionality, is said to
be buggy. Reports retailing bugs in a program are commonly referred to as bug reports, fault reports, problem
reports, trouble reports, or change requests.
Debugging refers to the process of removing bugs or faults or mistakes from a program
Integrated Development Environment (IDE)
An IDE is software application that provides comprehensive facilities to computer programmers for software
development. An IDE is also known as integrated design environment or integrated debugging environment. An IDE
normally consists of:
A source code editor
A compiler and / or an interpreter,
Automation tools,
A debugger.
An IDE is dedicated to a specific programming language, so as to provide a feature set which must closely matches
the programming paradigms of the language.
However, some multiple-language IDEs are in use, such as Eclipse, recent versions of NetBeans, Microsoft Virtual
Studio, WinDev, and Xcode
Stage Description
Problem definition At the problem development phase, the
(specifying the problem is analyzed in order to obtain a
task precise specification. The specification
should include the input that is required
and the type of output that must be
produced. Input refers to a specific data
that is used by a program. Output refers to
the exact answer that must be produced by
the program. Thus, specify problem is
being solved (validation)
Designing a The algorithm is devised at this stage and
solution the programmer must ensure:
The problem is being solved correctly
(verification) and that the correct problem
is being solved (validation).
Writing a program During this stage the program code is
(code) written. This process involves implementing
7
an algorithm using some programming
language. An appropriate programming
language must be selected based on the
problem domain. Program code is well-
structured with adequate documentation
included.
Program The purpose of testing is to
testing discover any errors that might be
present in the program.
The most basic testing can be done
by running the program and
manually checking the results. The
type of testing normally carried out
during this step include: Unit
testing, White box testing and
Black box testing, etc
Documentation This is the action of making
and changes to a program to enhance
Maintenance functionality or in respond to
specification changes. The
programmer maintains the
program by modifying the code to:
Increase performance, add new
features and adapt the program to
a new environment
Algorithm design
Mistakes hear result in logic errors. The program will run, but will not perform the intended task for example a
program to add numbers which return to 6 when given 3 + 2 has a logic error.
8
A logic error is the mistake in the way an algorithm solves a problem. It includes errors that do not prevent execution
of program and it is difficult to detect for large and complex algorithms. The sign of this error can be seen through
incorrect program output. This problem can be solved by imputing test data and comparing with expected results.
Syntax Error
Syntax errors are mistakes in a software code’s grammar. This type of error is detected by the compiler where by the
source code does not conform to one or more of the programs’ grammar rules.
Examples of syntax errors include:
Undeclared variable
Missing semicolon at the end of a statement.
Comment not closed.
Misspelling a command word or forgetting to close a module.
A semi-colon (;) instead of a colon (:)
Run-Time Error
Run-time errors are mistakes that occur when you run the software code and it directs the computer to perform an
illegal operation.
Corrective maintenance
This is the action taken when a program is not working correctly or as a specified due to logic error or because of a
run-time error. Identified error such as flaws, bugs, and security vulnerabilities are fixed.
A low-level programming language is a programming language that provides little or no abstraction from
computer’s microprocessor. A high-level programming language is a programming language that is more
abstract, easier to use, and more portable across platforms.
Code can make use of specific processor features such as special registers
9
And of course drawbacks
As you can imagine, writing in 1s and 0s all day will leave you prone to mistakes. Second-generation
programming languages or 2GL are a way of describing Assembly code which you may have already met.
By using codes resembling English programming becomes much easier. The use of these mnemonic codes
such as LDA for load and STA for store means the code is easier to read and write. To convert an assembly
code program into object code to run on a computer requires an Assembler and each line of assembly can be
replaced by the equivalent one line of object (machine) code:
Assembly code has similar benefits to writing in machine code, it is a one to one relationship after all. This
means that assembly code is often used when writing low level fast code for specific hardware. Until
recently machine code was used to program things such as mobile phones, but with the speed and
performance of languages such as C being very close to Assembly, and with C's ability to talk to processor
registers, Assembly's use is declining.
As you can hopefully see there are benefits to using Second-Generation Languages over First-Generation,
plus a few other things that makes Assembly great:
Code can make use of specific processor features such as special registers
As it is closer to plain English, it is easier to read and write when compared to machine code
10
generation (High Level Languages) codes are imperative. Imperative means that code is executed line by
line, in sequence.
The third generation of programming language, 3GL, or procedural language uses a series of English-like words, that
are closer to human language, to write instructions.
High-level programming languages make complex programming simpler and easier to read, write and maintain.
Programs written in a high-level programming language must be translated into machine language by a compiler or
interpreter. PASCAL, FORTRAN, BASIC, COBOL, C and C++ are examples of third generation programming languages.
Third generation languages can be platform independent, meaning that code written for one system will work on
another. To convert a 3rd generation program into object code requires a Compiler or an Interpreter.
To summarize:
Time saving programmer friendly, one line of 3rd gen is the equivalent of many lines of 1st and 2nd gen
However
Code produced might not make the best use of processor specific features unlike 1st and 2nd generation.
Fourth-generation languages are designed to reduce programming effort and the time it takes to develop software,
resulting in a reduction in the cost of software development. They are not always successful in this task, sometimes
resulting in inelegant and hard to maintain code. Languages have been designed with a specific purpose in mind and
this might include languages to query databases (SQL), languages to make reports (Oracle Reports) and languages to
construct user interface. An example of 4th generation programming type is the declarative language. Declarative
languages - describe what computation should be performed and not how to perform it. Not imperative
An example of a declarative language is CSS which you might learn more about when completing any web
design unit
The fourth generation programming language or non-procedural language, often abbreviated as 4GL, enables
users to access data in a database. A very high-level programming language is often referred to as goal-
oriented programming language because it is usually limited to a very specific application and it might use
syntax that is never used in other programming languages. SQL, NOMAD and FOCUS are examples of
fourth generation programming languages.
11
FIFTH GENERATION PROGRAMMING LANGUAGE
The fifth generation programming language or visual programming language, is also known as natural
language. Provides a visual or graphical interface, called a visual programming environment, for creating
source codes. Fifth generation programming allows people to interact with computers without needing any
specialised knowledge. People can talk to computers and the voice recognition systems can convert spoken
sounds into written words. Prolog and Mercury are the best known fifth-generation languages.
PROGRAMING APPROACHES
STRUCTURED PROGRAMMING
Structured programming often uses a top-down design model where developers map out the overall program
structure into separate subsections from top to bottom. In the top-down design model, programs are drawn as
rectangles. A top-down design means that the whole program is broken down into smaller sections that are
known as modules.A program may have a module or several modules. Structured programming is beneficial
for organising and coding computer programs which employ a hierarchy of modules. This means that control
is passed downwards only through the hierarchy.
OBJECT-ORIENTED PROGRAMMING
The object-oriented approach refers to a special type of programming approach that combines data with
functions to create objects. In an object-oriented program, the object have relationships with one another.
One of the earliest OOP languages is Smalltalk. Java, Visual Basic and C++ are examples of popular OOP
languages.
12
Programming paradigm
A programming paradigm is a fundamental style of computer programming, a way of building the structure
and elements of computer programs. Capabilities and styles of various programming languages are defined
by their supported programming paradigms; some programming languages are designed to follow only one
paradigm, while others support multiple paradigms.
There are six main programming paradigms: imperative, procedural , declarative, functional, object-
oriented, logic and symbolic programming.
In computer science, imperative programming is a programming paradigm that describes computation in terms of
statements that change a program state. In much the same way that imperative mood in natural languages expresses
commands to take action, imperative programs define sequences of commands for the computer to perform. The
term is used in opposition to declarative programming, which expresses what the program should accomplish
without prescribing how to do it in terms of sequences of actions to be taken. Programs are written using sequences
of instructions that are executed by the processor in the order the programmer designed. Imperative Programming
manipulates variables and data structures. Examples: C, Pascal, Ada, FORTRAN.
Procedural programming is imperative programming in which the program is built from one or more
procedures (also known as subroutines or functions). The terms are often used as synonyms, but the use of
procedures has an impressive effect on how imperative programs appear and how they are constructed.
Procedural programming could be considered a step towards declarative programming. Examples: C, Pascal,
C++ etc.
In computer science, declarative programming is a programming paradigm, a style of building the structure
and elements of computer programs, that expresses the logic of a computation without describing its control
flow. Many languages applying this style attempt to minimize or eliminate side effects by describing what
the program should accomplish in terms of the problem domain, rather than describing how to go about
accomplishing it as a sequence of the programming language primitives[2] (the how is left up to the
language's implementation). This is in contrast with imperative programming, in which algorithms are
implemented in terms of explicit steps. Declarative programming is often defined as any style of
programming that is not imperative. Common declarative languages include those of database query
languages (e.g., SQL, XQuery), regular expressions, logic programming, functional programming, and
configuration management systems.
13
In computer science, functional programming is a programming paradigm style in which program development is
the construction of mathematical functions. A solution to a problem consists of a series of function calls with no
variables or assignment statements. Examples: LISP, ML, Heskell.
Logic programming is a programming process that consists of a set of facts and rules. A knowledge base is built up
through writing facts and rules about a specific area of expertise. Example: Prolog.
With OOP a software system is viewed as a collection of units, called objects, each of which is capable of performing
the actions that are immediately related to itself as well as requesting actions of other objects. Together, these
objects interact to solve the problem.
For example if we consider the task of developing a graphical user interface, the icons that appear on the screen
would be implemented as objects. computer programs. C++, Objective-C, Smalltalk, Java, C#, Perl, Python, Ruby and
PHP are examples of object-oriented programming languages.
In computing, symbolic programming is computer programming in which the program can manipulate
formulas and program components as data.
Through symbolic programming, complex processes can be developed that build other more intricate
processes by combining smaller units of logic or functionality. Programs can thus effectively modify
themselves, and appear to "learn", making them suited for applications such as artificial intelligence, expert
systems, natural language processing and computer games. Languages that support the symbolic
programming paradigm include LISP and Prolog.
C Programming language
C is one of the older programming languages—it was developed in the 70s—but it is still very powerful
thanks to how low-level it is. Learning C is a great way to introduce yourself to more complex languages as
well, and the knowledge you gain will be useful in almost every programming language and can help you get
into application development. To learn how to start programming in C, see Step 1 below.
The C is the most widely used computer language; it keeps fluctuating at number one scale of popularity
along with Java programming language, which is also equally popular and most widely used among modern
software programmers.
14
Why to use C?
C was initially used for system development work, in particular the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast as
code written in assembly language. Some examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
1. C compiler
C code needs to be compiled by a program that interprets the code into signals that the machine can
understand. Compilers are usually free, and different compilers are available for different operating systems.
C can be very powerful. It was designed for Unix operating systems, but has been ported and expanded for
nearly all operating systems. The modern version of C is C++. C is essentially comprised of functions, and
in these functions you can use variables, conditional statements, loops to store and manipulate data.
Take a look at the (very) basic program below to get a good idea about how some of the various
aspects of the language work together, and to get an idea of how programs function.
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
15
system("PAUSE");
return 0;
}
o The #include command occurs before the program starts, and loads libraries that contain
the functions you need. In this example, stdio.h lets us use the printf() and
system() functions.
o The int main() command tells the compiler that the program is running the function
called "main" and that it will return an integer when it is finished. All C programs run a
"main" function.
o The brakes { } indicate that everything inside them is part of the function. In this case, they
denote that everything inside is a part of the "main" function.
o The printf() function displays the contents of the parentheses on the user's screen. The
quotes ensure that the string inside is printed literally. The \n sequence tells the compiler to
move the cursor to the next line.
o The ; denotes the end of a line. Most lines of C code need to end with a semicolon.
o The system (“pause”) or getchar() command tells the compiler to wait for a keystroke
input before moving on. This is useful because many compilers will run the program and
immediately close the window. This keeps the program from finishing until a key is pressed.
o The return 0 command indicates the end of the funciton. Note how the "main" function
is an int function. This means that it will need an integer to be returned once the program is
finished. A "0" indicates that the program has performed correctly; any other number will
mean that the program ran into an error.
Comments are part of the code that is not compiled, but allows you to explain what is happening.
This is useful for reminding yourself what your code is for, and for helping other developers who
might be looking at your code.
o Comments can be used to quickly remove parts of your code without deleting them. Simply
enclose the code you want to exclude with comment tags and then compile. If you want to add
the code back, remove the tags.
2. Using Variables
Variables allow you to store data, either from computations in the program or from user input.
Variables need to be defined before you can use them, and there are several types to choose from.
o Some of the more common variables in C programming include int , char , and float .
Each one stores a different type of data.
16
Learn how variables are declared. Variables need to be established, or "declared", before they can
be used by the program. You declare a variable by entering the data type followed by the variable's
name. For example, the following are all valid variable declarations:
float x;
char name;
int a, b, c, d;
o Note that you can declare multiple variables on the same line, as long as they are the same
type. Simply separate the variable names with commas.
o Like many lines in C, each variable declaration line needs to end with a semicolon.
Know where to declare variables. Variables must be declared at the beginning of each code block
(The parts of your code that are enclosed in {} brackets). If you try to declare a variable later in the
block, the program will not function correctly.
Use variables to store user input. Now that you know the basics of how variables work, you can
write a simple program that will store the user's input. You will be using another function in the
program, called scanf . This function searches and takes the input that is provided for specific
values.
#include <stdio.h>
int main()
{
int x;
2. Learn the basic conditional operators. Conditional statements revolve around the use of
mathematical operators that compare values. The following list contains the most commonly used
conditional operators.
3. = /*assignment */
4. > /* greater than */
5. < /* less than */
6. >= /* greater than or equal to */
7. <= /* less than or equal to */
8. == /* equal to */
17
9. != /* not equal to */
10. % MOD
11. && AND
12. || OR
You can use mathematical expressions to manipulate the data that you have stored in your variables. The
most important distinction to remember for mathematical expressions is that a single = sets the value of the
variable, while == compares the values on either side to see if they are equal.
x = 3 * 4; /* sets "x" to 3 * 4, or 12 */
x = x + 3; /* adds 3 to the original value of "x", and sets the new value
as the variable */
x == 15; /* checks to see if "x" equals 15 */
x < 10; /* checks if the value of "x" is less than 10 */
3. Using Conditional Statements
Conditional statements are what drive most programs. They are statements that are determined to be
either TRUE or FALSE, and then acted upon based on the result. The most basic of the statements is
the if statement.
o TRUE and FALSE work differently in C than what you might be used to. TRUE statements
always end up equaling a nonzero number. When you perform comparisons, if the result is
TRUE then a "1" is returned. If the result is FALSE, then a "0" is returned. Understanding this
will help you see how IF statements are processed.
Write a basic IF statement. You can use IF statements to determine what the program should do
next after the statement is evaluated. You can combine it with other conditional statements later to
create powerful multiple options, but for now write a simple one to get used to them.
#include <stdio.h>
int main()
{
if ( 3 < 5 )
printf( "3 is less than 5");
getchar();
}
Use ELSE/ELSE IF statements to expand your conditions. You can build upon IF statements by
using ELSE and ELSE IF statements to handle different results. ELSE statements run if the IF
statement is FALSE. ELSE IF statements allow you to include multiple IF statements into one code
block to handle various cases. See the example program below to see how they interact.
18
#include <stdio.h>
int main()
{
int age;
4. Learning Loops
Loops are one of the most important aspects of programming, as they allow you to repeat blocks of
code until specific conditions are met. This can make repeating actions very easy to implement, and
keeps you from having to write new conditional statements each time you want something to happen.
o There are three main types of loops: FOR, WHILE, and DO...WHILE.
2. 2
This is the most common and useful loop type. It will continue running the function until the
conditions set in the FOR loop are met. FOR loops require three conditions: initializing the variable,
the condition to be met, and the way the variable is updated. If you don't need all of these conditions,
you will still need to leave a blank space with a semicolon, otherwise the loop will run forever.
#include <stdio.h>
int main()
{
int y;
19
for ( y = 0; y < 15; y++;){
printf( "%d\n", y );
}
getchar();
}
o In the above program, y is set to 0, and the loop continues as long as the value of y is less than
15. Each time the value of y is printed, 1 is added to the value of y and the loop is repeated.
Once y = 15, the loop will break.
3. 3
WHILE loops are more simple than FOR loops. They only have one condition, and the loop acts as
long as that condition is true. You do not need to initialize or update the variable, though you can do
that in the main body of the loop.
#include <stdio.h>
int main()
{
int y=0;
while ( y <= 15 ){
printf( "%d\n", y );
y++;
}
getchar();
}
o The y++ command adds 1 to the y variable each time the loop is executed. Once y hits 16
(remember, this loop goes as long as y is less than or equal to 15), the loop breaks.
4. 4
Use a DO...WHILE loop. This loop is very useful for loops that you want to ensure run at least once.
In FOR and WHILE loops, the condition is checked at the beginning of the loop, meaning it could
not pass and fail immediately. DO...WHILE loops check conditions at the end of the loop, ensuring
that the loop executes at least once.
#include <stdio.h>
int main()
{
int y;
y = 5;
do {
printf("This loop is running!\n");
} while ( y != 5 );
getchar();
20
}
o This loop will display the message even though the condition is FALSE. The variable y is set
to 5 and the WHILE loop is set to run when y does not equal 5, so the loop terminates. The
message was already printed since the condition is not checked until the end.
o The WHILE loop in a DO...WHILE set must be ended with a semicolon. THis is the only
time a loop is ended with a semicolon.
5. Using Functions
Understand the basics of functions. Functions are self-contained blocks of code that can be called
upon by other parts of the program. They make it very easy to repeat code, and they help make the
program simpler to read and change. Functions can include all of the previously-covered techniques
learned in this article, and even other functions.
o The main() line at the beginning of all of the above examples is a function, as is
getchar()
o Functions are essential to efficient and easy-to-read code. Make good use of functions to
streamline your program.
Start with an outline. Functions are best created when you outline what you want it to accomplish
before you begin the actual coding. The basic syntax for functions is "return_type name ( argument1,
argument2, etc.);". For example, to create a function that adds two numbers:
Add the function to a program. You can use the outline to create a program that takes two integers
that the user enters and then adds them together. The program will define how the the "add" function
works and use it to manipulate the inputted numbers.
#include <stdio.h>
int main()
{
int x;
int y;
o Now the add() has been defined, it can be called anywhere in the program.
Declaring Arrays in C
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and
type can be any valid C data type. For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ].
Declaring Arrays in C
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and
type can be any valid C data type. For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
22
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ].
C–STRUCTURES
Carraysallowyoutodefinetypeofvariablesthatcanholdseveraldataitemsofthesamekind but
structureisanotheruser defineddatatypeavailableinCprogramming,whichallowsyouto
combinedataitemsofdifferentkinds.
Structuresareusedtorepresentarecord,Supposeyouwanttokeeptrackofyour booksina
library.Youmightwanttotrackthefollowingattributesabouteachbook:
Title
Author
Subject
Book ID
DefiningaStructure
Todefineastructure,youmustusethestructstatement.Thestructstatementdefinesanewdata
type,withmorethanonemember foryourprogram.Theformatofthestructstatementisthis:
structstructure_name
{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormorestructurevariables];
eachmemberdefinitionisanormalvariabledefinition,suchas
inti;orfloatf;oranyothervalidvariabledefinition.Attheendofthestructure'sdefinition,before
thefinalsemicolon,youcanspecifyoneormorestructurevariablesbutitisoptional.Hereisthe
wayyouwoulddeclaretheBook structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
AccessingStructureMembers
Toaccess anymemberofastructure,weusethememberaccessoperator ..Themember
accessoperatoriscodedasaperiodbetweenthestructurevariablenameandthestructure member
thatwewish to access.Youwouldusestructkeywordtodefinevariablesofstructure
type.Followingistheexampleto explainusageofstructure:
23
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming"); or Book1.title, = "C Programming";
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
24
Youcanpassastructureasafunctionargumentinverysimilarwayasyoupassanyothervariable
orarray.Youwouldaccessstructurevariablesinthesimilarwayasyouhaveaccessedinthe aboveexample:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
Array of Structures
In programming, structure is a composite datatype with a collection of variables. These variables can have
different data types and collectively form a structure of a composite datatype. An array of structures is a
sequential collection of structures. With structures, you can store mixed record types, and with an array
supporting this, you can have a list of mixed record types. The following example shows a structure called
student that takes the roll number and name of a student as an input, then stores each record in an array st,
which stores three elements. Each element will hold a mixed record.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
25
5. char name[10];
6. };
7. int main(){
8. int i;
11. for(i=0;i<3;i++){
13. }
16. }
17. return 0;
18. }
#include<stdio.h>
int main (){
int var1;
char var2[10];
printf("Address of var1 variable: %x\n",&var1 );
printf("Address of var2 variable: %x\n",&var2 );
26
return0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using
it to store any variable address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Take a look at some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to.
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done
by using unary operator * that returns the value of the variable located at the address
specified by its operand. The following example makes use of these operations −
#include<stdio.h>
int main (){
intvar=20;/* actual variable declaration */
int*ip;/* pointer variable declaration */
ip =&var;/* store address of var in pointer variable*/
printf("Address of var variable: %x\n",&var);
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n",*ip );
27
return0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program −
#include<stdio.h>
int main (){
int*ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0
has special significance; it signals that the pointer is not intended to point to an accessible
memory location. But by convention, if a pointer contains the null (zero) value, it is assumed
to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
EXERCISES
Exercise 1
1. What is programming?
2. What is a programming language?
3. Give examples of programming languages?
4. What do understand by paradigm?
5. List the six main programming paradigms
28
6. Define and give examples of each of the following programming paradigms
A. imperative programming D. object-oriented programming
B. declarative programming E. logic programming
C. functional programming F. symbolic programming
Exercise 5
a) Define each of the following terms as used in algorithms
Computational thinking
Stepwise refinement
Top-Down design
b) Define data types and give five examples
c) Define each of the following data type given examples
Character
Integer
Real number
Boolean
Strings
d) Define data structure and give four examples
e) Define each of the following data structures
Arrays
Records
List
Stalks
Queue
Exercise 6
Convert all the algorithms written in exercises 3 above into Pascal programming type, compile and run each
of them
Exercise 7
1) Define Low level language and give the two common examples
2) Define each of the following as used with low level programming language
Instruction set
Mnemonics
Translators
Compilers
Interpreters
Assemblers
Loader
29
3) Define high level language and given any four characteristics and four examples
4) Give the full meaning of the following high level programming language
Basic
FORTRAN
COBOL
5) Define Software development tools and give any four examples
6) Define the following and give examples for each
Editors
DBMS
Linkers
Debuggers
Integrated development environment (IDE)
7) A)State and briefly the five main steps in program developments cycle
B) Briefly explain the following as used in program developments cycle
Problem definition (specifying task)
Designing a solution
Writing program (coding)
Program testing
Documentation and maintenance
8) Explain each of the following types of errors occurring in programming, given examples
for each
Logic error
Syntax error
Run-time errors
Exercise 2
In each of the exercises below, be careful to include prompts for any input
required and to present output neatly with headings where possible
a. Write a program which takes three numbers as input, calculates their total and
average and prints them on the screen. Use suitable prompts and headings.
b. Write a program which takes a person's age in years as input and outputs the
person's approximate age in months and in days (ignore leap years).
c. Write a program which takes as input the name of a customer, the quantity
and name of
an item ordered by the customer, and the price per item, and prints out a letter
acknowledging receipt of the order as follows:
Dear <name> ,
Thank you for your order of <quantity> of <item name> .
Your order will be dispatched on receipt of <total cost> .
The information within <> should automatically be filled in by the program
from data
input.
d. For a right-angled triangle having sides a, b, c, where c is the hypotenuse,
Pythagoras
discovered that c2 = a2 + b2 . Write a program which reads values for a and b
and
calculates the length of the hypotenuse.
e. Write a program which calculates and outputs the diameter, circumference
and area of a
circle whose radius is input at run-time.
f. Write a Fahrenheit to Centigrade conversion algorithm which takes a
Fahrenheit
temperature as input and outputs the corresponding temperature in Centigrade
(or
Celsius). Use the formula F = 9/5 C + 32
g. Write an algorithm that prompts the user to enter number in two variables
and Swap the contents of the variables.
h. Write an algorithm that prompts the user to input a number and display if the
number is even or odd.
i. Write an algorithm that prompts the user to input two integers and outputs the
largest.
j.Write an algorithm that prompts the user to input three integers and outputs the
largest.
k. i. Write an algorithm that prompts the user to input two integers and outputs
the smallest.
Exercise3
a. In an election, people under 18 years old are not eligible to vote. Input a
person's age and output a message stating whether he can vote or not.
b. Write a program which accepts a number as input and outputs a message
stating whether the number lies between 1 and 100 or not. Do you think that a
CONST declaration would be appropriate in this program? Why ?
c. Write a program which asks the user to input 3 numbers, and outputs the
largest.
d. Input a number representing a year and output a message stating whether it is
a leap year or not. Note that a leap year is EITHER divisible by 400
OR ((divisible by 4) BUT NOT (divisible by 100)).
e. A company has three vans which are used to transport its products
f.Write a program which asks for the number of items to transport, validates this
number
(must be between 1 and 170) and suggests which vans should be used for the
job. A van
should not be used where a smaller one would be sufficient.
The roots may fall into one of the following three categories:
i. They are real and equal if b2 - 4ac = 0 .
ii. They are real and distinct if b2 - 4ac > 0 .
iii. There is no solution if b2 - 4ac < 0 .
Write a program which first accepts the values for a, b, c, where a should be
checked to
ensure that it is NOT zero. Next the program should test the value of (b2 - 4ac) to
determine which category the roots fall into. Finally the roots should be
calculated and
output (if in category i or ii).
Exercise 3
a. Write an algorithm that prompts the user to input a number. The
algorithm should display the corresponding days to the number
b. Write a simple calculator program which first takes two INTEGERS
num1 and num2 as
input and then presents a menu of five arithmetic operations: addition,
subtraction,
multiplication, division, quotient and modulo:
The option should be handled using a CASE statement (which should treat
upper and lower case characters as equivalent), and the corresponding result
displayed. Your program should ignore invalid choices.
c. The marks obtained by a student in 3 different subjects are their
respective coefficient is input by the user. Your algorithm should calculate
the average of subjects and display the grade. The student gets a grade as
per the following rules:
Average Grade
>=18 A
>=15 B
>=13 C
>=10 D
< 10 U
d. Write a program that prompts the user to input a character and determine
the character is vowel or consonant.
Exercise 4
Use the For loop, the while and the repeat until loop to answer the following
questions
1. Write an algorithm to display the first 10 natural numbers.
2. Write an algorithm to find the sum of first 10 natural numbers.
3. Write an algorithm to display n terms of natural number and their sum.
4. Write an algorithm to read 10 numbers from keyboard and find their sum
and average.
6. Write an algorithm to display the multiplication table of a given integer.
7. Write an algorithm that asks the user for a number n and prints the sum of the
numbers from 1 to n
8) Modify the previous algorithm such that only multiples of three or five are
considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
9) Write an algorithm that asks the user for a number n and gives him the
possibility to choose between computing the sum and computing the product of
1,…,n.
10. Write Pascal program that a an integer n and calculate its factorial
11. Write Pascal program that takes an number a as base then n as power and
calculate an
Exercise 2 (8 marks)
You are asked to write a program that will allow a user to interact with your computer, by guessing a
number chosen randomly by the computer. The computer will tell the user that he is thinking of a
number between 1 and 100, and then prompts the user to guest that number. The user will then be
given as many guesses as required to find the number the computer is thinking about. To narrow the
guesses, the computer will tell the user ‘too high’ or ‘too low’ when the user guesses wrong. When
the user guesses the right number, the computer displays correct and the game stops.
Question: write an algorithm that will enable you to implement your game
Note: You may need to use a statement of the form num : = RANDOM (x); where num is an
integer variable, and x is an integer-value. RANDOM returns a random integer between 0 and x-1.
Exercise 3 (7 marks)
In a certain two players guessing game, the computer prompts the first player to enter 10 even
numbers. For each number entered by the player, the computer checks, if it is correct then the player
scores one more point or zero if the answer is wrong. After then 10 numbers inputted the computer
gives the score of the first player and gives the way for the second player to take over.
Question: write an algorithm to implement this game.
4. Write Pascal program to read n number of values in an array and display it in reverse order.
5. Write Pascal program to find the sum of all elements of the array
6. Write Pascal program to copy the elements from one array into another array.
8. Write Pascal program that multiplies elements from two arrays of the same size and store
the result in third array.
9. Write Pascal program that adds elements from two arrays of the same size and store the
result in third array.
15. Write Pascal program to find the minimum element in an array and swap it with the first
element
16. Write Pascal program to find the maximum element in an array and swap it with the first
element
uses Crt;
type
MarksType = array[?] of ?;
var
i : integer;
marks : ?; {Array of marks}
passOrFail : string[?]; {For one word ‘passed’ or ‘failed’}
begin
clrscr;
for i := ? to ? do {Input marks of a group of 20 students}
begin write ('Please enter marks of student ',i,': ');
readln(marks ?);
end;
for i := ? to ? do
begin
if (marks ? < 50) then
passOrFail := ?;
else
passOrFail := ?;
writeln (num of student and passed or failed);
end;
end.
The program should perform the following operations in the external loop (with a cycle
for each student):
[1] Input student ID, name, gender character (‘M’ or ‘F’) and store these data in fields
IDnumber, Name, Gender of record Student.
[2] In an internal loop, input NumTest marks (4 marks) of this student and store them in
the array field Marks of the record Student. That is, Student.Marks[1] should store the
first quiz mark, Student.Mark[2] the second quiz mark and so on.
[3] Calculate the average of NumTest marks of this student. Assume for simplicity that
all marks have the same weight.
[4] Output in separate lines studentID, name, gender and the average mark.
Steps [1] – [4] must be performed sequentially for each student.
Exercise 1
1. Define a recursive function that evaluates the sum of the first n integers. E.g.
Sum(4)=1+2+3+4 Or Sum(4)=10.
2. Write a recursive power function that calculates the value of x raised to the power y
i.e. (xy). The power function multiplies x y-times.
Exercise 2
Print a final copy of your program and insert in your answer booklet. Also save a
copy of it as AVERAGE in the Location indicated by your instructors.
TASK D
You are to modify your program in Task2 (a) and3(c) so that they are combined into
a single program, with a single main program section.
NOTE NOT COPY IMPLEMENTED CODE. (a) Convert your program into 2(a) into a
programming language (PL) procedure. Give the procedure header and stare which
implemented code will constitute the procedure body
(b) Convert your in 3(c) into a PL function. It return the average value calculated.
Instead of printing it. Give the function header and state which implemented code
will constitute the procedure body.
(c) Give the code fragments to call your procedure and function from the main
program, and print the value of average, as before.
(d) State how you would ensure that the value of TOTAL is never divided by zero.
Exercise 3
When the total number of units consumed in a month is far greater than 100 units,
the electricity consumption is considered industrial? Otherwise it remains
domestic .SONEL also charges fixed rent of 500cfa per month on each of its
electricity meters.
Value added tax (VAT) is charged on the total amount payable for consumption
(that is not including taxes). The VAT is 1.8% of this amount. That is, if number of
unit consumed is x and rate per unit is y then the total on taxed amount (TUA)=xy
and VAT=1.8% of XY.
The net amount payable (NET) BY clients is the sum of rent TUA and VAT that is
NET=TUA+VAT+RENT.
To calculate the units consumed in a month, previous meter reading (R1) below ,
subtracted from the current readings (R2).
Meter N° 1 2 3 4 5 6
Reading 1103 1225 1110 1203 1210 2100
In your answer booklet produce a histogram of the consumption of this meter.
(4marks)
TASK 2: ABSRACTION
Using either C or Pascal program environment, write a program that has the tables
(arrays): R1R2 and R3 to hold units consumed for the six meter readings. Each
array should be able to hold six elements.
The program should prompt the user to enter the previous and current reading for
the each meter. It reads this entries into R1 and R2 respectively, and then print a
table with columns for the previous readings, the current reading and the unit
consumed, in that order. For example, for the first two meter we have the table:
1123 1103 80
1101 1225
124
Copy the code of your program and paste in your text editor and save the file as
task 2. txt. Capture the (terminal) output of your program and store the pdf file as
task 2. Pdf append to your program code. Save the files as task 2 but txt. And task
2. Pdf in your candidate folder and printer a copy. (File could also be saved in a
single file that is in odt or Microsoft docx format)
TASK3
Write a programming language function that take as parameter the number of units
consumed (UC) and then calculate and return to the net amount payable by clients.
Text this function by calling it in your program from task 2, using UC, as
parameter. Update the program to print the net amount payable in a fourth column
of the table (see task 2), for various units consumed (element of R3).
Using your text editor, copy the modified code of your program in to a new file
called task 3.txt. Copy and save terminal outputs to the code in the pdf file, task
3.pdf. Save the file task 3.txt and task 3. Pdf in your candidate folder and print a
copy (file could also be saved in a single file that is in a odt or Microsoft docx
format).
TASK 4
Write down in your answer booklet a spread sheet formula for each of the following
quantities
a) Unit consumed
b) Amount per unit
c) Gross amount
d) VAT
e) Net amount payable
Write the formula for meter 1 using cell numbers corresponding to those form
meter in table below
Meter 1 Meter 2 Meter 3
Current reading 1103 1225 1110
Previous reading 1023 1101 1011
a) Units consumed
b) Amount per unit
c) Gross
amount(consumption
*unit price)
d) VAT
e) Net amount payable
Implement the formulae from (V) in a spread sheet package and copy in other
cells needing similar calculations. Save your work in a spread sheet file, TASK 4.
Print your output.
EXERCISE 1 (20 marks)
1) Write an algorithm that takes integer marks of a group of 40
students on a course, then decide who has passed or failed and
display the number of students who passed and the number of those
who failed. (5marks)
ii) Call the function above from an algorithm and print the biggest of
three numbers number entered by the user. (3marks)
ii) Call the procedure from an algorithm and print the sum and
average of the 50 element entered by the user. (5marks)
Define a structure, student, to store the following data about a student: rollno (integer),
name (string) and markstu (integer). Where the field marks is a two dimensional array.
(1mark)
Suppose that the class has 20 students. Use an array of 20 elements of type Student perform
the following
i. request and store information about the 20 students , taking into account that the
field markstu will store 5 marks for five courses in the first row of the array and their
ii. display the rollno , name and average of all the 20 students (4 marks)