Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

STRUCTURED PROGRAMMING (45 CREDIT HOURS)

Pre-requisite: None

Moses Wainaina
0707691430

Purpose

An introduction to programming techniques to understand the concepts and principles of


Procedural programming language, formulate basic problem solving techniques, analyze problems
and implement basic algorithms for their solution. The unit also aims to show ability in testing and
debugging of programs.

TOPICS

TOPIC 1 : AN OVERVIEW OF PROGRAMMING LANGUAGES: CLASSIFICATION,


CHARACTERISTICS. ................................................................................................................... 4
1.1 Definition of Some Terms ..................................................................................................... 4
1.2 Classification of programming languages ............................................................................. 4
PROGRAMMING PARADIGMS. ............................................................................................. 8
PROGRAM DEVELOPMENT CYCLE .................................................................................. 11
TOPIC 2: DESIGN TOOLS ......................................................................................................... 13
Algorithm .................................................................................................................................. 13
Qualities of a good algorithm ................................................................................................. 13
Algorithm .................................................................................................................................. 14
Pseudocode .................................................................................Error! Bookmark not defined.
Find the sum of the first 50 numbers ..................................................................................... 20
TOPIC 3: PROGRAMMING CONCEPTS ................................................................................. 23

1|Page Moses Wainaina 0707691430


BASIC BUILDING BLOCK OF A PROGRAM ..................................................................... 23
Data type in programming......................................................................................................... 24
Meaning ........................................................................................................................................ 24
RULES FOR CONSTANT AND VARIABLES ...................................................................... 28
3. INSTRUCTIONS .................................................................................................................. 28
STRUCTURE OF A C PROGRAM ......................................................................................... 31
RULE OF C PROGRAM .......................................................................................................... 32
INPUT AND OUTPUT MANAGEMENT ............................................................................... 32
EXAMPLES OF C PROGRAMS ............................................................................................. 35
TOPIC 4 - CONTROL STRUCTURES ....................................................................................... 39
Types of Control Structures ...................................................................................................... 39
Topic 5 POINTERS, ARRAYS AND STRUCTURES IN C ....................................................... 59
POINTERS ................................................................................................................................ 59
ARRAYS................................................................................................................................... 61
STRUCTURE............................................................................................................................ 64
FUNCTION IN C ...................................................................................................................... 66

Learning Outcomes: Upon successful completion of this course, the student should be able to:

1. Discuss the concepts and principles of procedural programming language

2. Apply basic problem solving techniques

3. Analyze problems and implement basic algorithms for their solution.

4. Demonstrate the ability in testing and debugging programs

2|Page Moses Wainaina 0707691430


Course description

i. An overview of programming languages: classification, Characteristics.


ii. Program development cycle. Introduction to modules and modularity.
iii. Algorithmic problem solving: flow charts, pseudo code. Problem solving strategies: top-
down and bottom-up decomposition.
iv. Programming concepts: variables, functions, data types, expressions, operators, control
structures, functions, arrays, pointers, unions and structures.
v. Good programming practices: style and conventions. Libraries, testing and debugging
programs. Use languages such as C, Pascal etc.
vi. Sub programs
vii. File handling
viii. Program Documentation
ix. Emerging trends in Programming

Reference TextBooks

1. H.M. Deitel and P.J. Deitel, C: How to Program, 2nd ed Prentice Hall, ISBN 3417600455
2. Bjarne Stroustrup (2008) Programming: Principles and Practice Using C++ Prentice Hall
ISBN 341-6780027
3. B.Kernighan's .D.M. Ritchie's, C Programming Language (2nd Edition) ISBN 345895840

Course Journals

1. Advances in Computational Mathematics ISSN 1019-7168


2. Advances in data Analysis and Classification ISSN1 1862-5347
3. Annals Of software Engineering ISSN 1022-7091

Reference Journals

1. Journal of computer science and Technology ISSN 1000-9000


2. Journal of Science and Technology ISSN 1860-4749
3. Central European Journal of Computer Science ISSN 1896-1533

3|Page Moses Wainaina 0707691430


TOPIC 1 : AN OVERVIEW OF PROGRAMMING LANGUAGES: CLASSIFICATION,
CHARACTERISTICS.
1.1 Definition of Some Terms
Program

This is a complete set of step-by-step instructions that control and direct the computer hardware in
carrying out a given task. Tasks may vary from very simple e.g. computing surface area to
complex ones like statistical analysis.

Programs are usually written to solve user problems on a computer.

Programming Language

This is a set of symbols and the rules that govern their rules that are employed in the construction
of a computer program.

Syntax

These are the rules of a language that govern the ways in which words, symbols, expressions and
statements may be formed and combined in that language.

Semantics

These are the rules of language that govern meaning of statements in any language.

Programmer

This is a person who is trained and/or specializes in the technique of creating, maintaining and
modifying computer programs.

Programming Languages

A programming language is a tool for developing executable models for a class of problem
domains.

Programming languages provide the basic building block for all software. They are the means by
which people can tell the computer how to carry out a task.

1.2 Classification of programming languages


A program can be written in a variety of programming languages. The languages can broadly be
classified into two categories:

4|Page Moses Wainaina 0707691430


1. Low-level language – which refers to the machine language and assembly language.
2. High-Level languages: - which refers to languages such as COBOL, FORTRAN, BASIC

LOW LEVEL LANGUAGES

a. Machine Language (First Generation Language)

Digital computers represent and process data and instructions as binary numbers. This
representation of instructions and data is called machine language. Program instructions were
written as a series of binary digits (0’s and 1’s). When the program was entered into the computer
execution was direct since machine language needs no translation. The binary combination
allowed the program to have full access to and control the computer’s internal circuitry and
memory addresses.

Advantages

i. Program translation was fast because no conversion was required.


ii. The program could directly address and control the internal circuitry meaning that these
programs were more effective in hardware usage and control.

Disadvantages

i. Writing programs was time consuming


ii. Tracing errors in a program was extremely difficult.
iii. Difficult to learn and use.
iv. Program modification was cumbersome.
v. They were machine dependent i.e. a program created for one type of machine would not
work on a different type of machine.
vi. To write an effective program the programmer had to have expert knowledge on the
computer’s internal workings.
b. Assembly Language (Second Generation)

5|Page Moses Wainaina 0707691430


This language was more users’s oriented than machine language. Instructions are represented
using mnemonic code and symbolic addresses. Words like ADD, SUM, and DIV etc could be
used in programs. An assembler translated these codes into machine language.

Advantages

i. Much easier to learn compared to machine language.


ii. Coding took less time than coding using machine language.
iii. Error correction was less cumbersome.

Disadvantages

i. Were also machine specific


ii. Execution took longer than machine language programs due to the translation process.

HIGH LEVEL LANGUAGES

These languages are user friendly and problem oriented compared to the low level languages.
Programs written in high level languages are shorter than the machine language programs.

They have an extensive vocabulary of words and symbols therefore program instructions are
written using familiar English-like statements and mathematical statements.

A single high-level language program is translated into multiple machine code instructions.

Advantages

i. They are portable i.e. they can be used on more than one type of machine.
ii. Creating program and error correction takes less time.
iii. Are relatively easy to learn and use.
iv. The programmer does not have to be an expert on the internal workings of the machine.

6|Page Moses Wainaina 0707691430


Disadvantages

i. Program execution takes more time due to the translation process.


ii. They do not address the internal circuitry of computers as effectively as the low level
languages.
iii. A translated program will occupy more space.

High level languages can further be classified into:

a. Procedural languages (Third Generation)


b. Non-Procedural Languages (Fourth Generation Languages or 4GLs)
a. Procedural languages (Third Generation).

They require the programmer to specify step-by-step how the computer will accomplish a specific
task. Program execution follows the exact sequence laid down by the programmer during coding.
Examples include FORTRAN, PASCAL, BASIC,

b. Non-Procedural Languages (Fourth Generation Languages or 4GLs).

They allow the programmer to specify the desired result without having to specify the detailed
procedure needed to achieve the result.

They are more users’ oriented and allow programmers to develop programs with fewer commands
compared with 3rd generation languages. They are called non procedural because programmers
can write programs that need only tell the computer what they want done, not all the procedures
of doing it.

4GL consists of:

Report Generators: also called report writers. This is a program for end users that is used to
produce reports.

Query Language: This is an easy to use language for retrieving data from a database management
system.

7|Page Moses Wainaina 0707691430


Application Generators: This is a program’s tool that allows a person to give a detailed
explanation of what data to be processed. The software then generates codes needed to create a
program to perform the tasks.

Fifth-generation programming language

A fifth generation (programming) language (5GL) is a grouping of programming languages build


on the premise that a problem can be solved, and an application built to solve it, by providing
constraints to the program (constraint-based programming), rather than specifying algorithmically
how the problem is to be solved (imperative programming).

In essence, the programming language is used to denote the properties, or logic, of a solution,
rather than how it is reached. Most constraint-based and logic programming languages are 5GLs.
A common misconception about 5GLs pertains to the practice of some 4GL vendors to denote
their products as 5GLs, when in essence the products are evolved and enhanced 4GL tools.

PROGRAMMING PARADIGMS.
Programming paradigms are a way to classify programming languages according to the style of
computer programming.

Features of various programming languages determine which programming paradigms they belong
to; as a result, some languages fall into only one paradigm, while others fall into multiple
paradigms.

. A programming paradigm is an approach to solving programming problems.

1) Un structured programming.

An unstructured program is a procedural program – the statements are executed in sequence as


written. But this type of programming uses the goto statement. A goto statement allows control to
be passed to any other place in the program. When a goto statement is executed, the sequence
continues from the target of the goto.

2) Structured programming

8|Page Moses Wainaina 0707691430


Structured programming (sometimes known as modular programming) is a subset of procedural
programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Pascal are designed with
features that encourage or enforce a logical program structure.

A technique for organizing and coding computer programs in which a hierarchy of modules is
used, each having a single entry and a single exit point, and in which control is passed downward
through the structure without unconditional branches to higher levels of the structure. Three types
of control flow are used: sequential, test, and iteration.

3) Object Oriented Programming

Object Oriented Programming (OOP) is a paradigm in which real-world objects are each viewed
as seperate entities having their own state which is modified only by built in procedures, called
methods. Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done by message
passing.

Object-oriented programming (OOP) is a programming language model organized around objects


rather than "actions" and data rather than logic. Historically, a program has been viewed as a
logical procedure that takes input data, processes it, and produces output data.

4) Visual Programming.

In computing, a visual programming language (VPL) is any programming language that lets users
create programs by manipulating program elements graphically rather than by specifying them
textually. A VPL allows programming with visual expressions, spatial arrangements of text and
graphic symbols used either as elements of syntax or secondary notation.

9|Page Moses Wainaina 0707691430


5) Internet Based programming.

Web programming refers to the writing, markup and coding involved in Web development, which
includes Web content, Web client and server scripting and network security. The most common
languages used for Web programming are XML, HTML, JavaScript, Perl 5 and PHP. Web
programming is different from just programming, which requires interdisciplinary knowledge on
the application area, client and server scripting, and database technology.

HTML5 and CSS3 support most of the client-side functionality provided by other application
frameworks.

10 | P a g e Moses Wainaina 0707691430


PROGRAM DEVELOPMENT CYCLE
Program Development and design

Software development is the process of computer programming, documenting, testing, and bug
fixing involved in creating and maintaining applications and frameworks resulting in a software
product. Software development is a process of writing and maintaining the source code, but in a
broader sense, it includes all that is involved between the conception of the desired software
through to the final manifestation of the software, sometimes in a planned and structured process.

2.2 Program Development Life Cycle

1. Design program objectives

It involves forming a clear idea in terms of the information you want to include in the program,
computations needed and the output. At this stage, the programmer should think in general terms,
not in terms of some specific computer language.

2. Design program

The programmer decides how the program will go about its implementation, what should the user
interface be like, how should the program be organized, how to represent the data and what
methods to use during processing.

3. Write the Code

It is the design Implementation by writing the code i.e. translating your program design into
language instructions.

4. Compile the code

11 | P a g e Moses Wainaina 0707691430


A compiler converts the source code into object code. Object codes are instructions in machine
language. Computers have different machine languages.. The libraries contain standard routines.
The end result is an executable file that the computer can understand.

The compiler also checks errors in your program and reports the error to you for correction. The
object code can never be produced if the source code contains syntax errors.

5. Run the program

This is the actual execution of the final code. Once the executable code is complete it can be
invoked in future by typing its name in a ‘run’ command.

6. Test the program

This involves checking whether the system does what it is supposed to do. Programs may have
bugs (errors). Debugging involves the finding and fixing of program mistakes.

7. Maintain and modify the program

Occasionally, changes become necessary to make to a given program. You may think of a better
way to do something in a program, a clever feature or you may want to adapt the program to run
in a different machine. These tasks are simplified greatly if you document the program clearly and
follow good program design practices.

12 | P a g e Moses Wainaina 0707691430


TOPIC 2: DESIGN TOOLS

Algorithm
An algorithm is a sequence of steps which results to a plan or strategy on how to go about
solving a problem.

Algorithms

In programming, algorithm is a set of well defined instructions in sequence to solve the problem.

Qualities of a good algorithm

1. Input and output should be defined precisely.


2. Each step in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages.

Write an algorithm to find the factorial of a number entered by user.

Step 1: Start

Step 2: Declare variables n,factorial and i.

Step 3: Initialize variables

factorial←1

i←1

Step 4: Read value of n

Step 5: Repeat the steps until i=n

5.1: factorial←factorial*i

5.2: i←i+1

Step 6: Display factorial

Step 7: Stop

13 | P a g e Moses Wainaina 0707691430


To find whether a number is odd or even

Algorithm
START
Step 1 → Take integer variable A
Step 2 → Assign value to the variable
Step 3 → Perform A modulo 2 and check result if output is 0
Step 4 → If true print A is even
Step 5 → If false print A is odd
STOP

Write an algorithm to add two numbers entered by user.

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop

1) Start.

2) Accept Number one.

3) Accept Number two.

4) Add both the numbers.

5) Print the result.

6) End

14 | P a g e Moses Wainaina 0707691430


Algorithm to find whether a number is even or odd

Step 1: Start

Step 2: [ Take Input ] Read: N

Step 3: Check: If N%2 == 0 Then

Print : N is an Even Number.

Else

Print : N is an Odd Number.

Step 4: Exit

Pseudo code

Pseudocode is the statement in plain English which may be translated later into a programming
language (program).
This is a case where an algorithm is expressed in English like statements (descriptions). For
example the following pseudocode calculates the pay amount for five employees.

BEGIN

NUMBER s1, s2, sum

OUTPUT("Input number1:")

INPUT s1

OUTPUT("Input number2:")

INPUT s2

sum=s1+s2

OUTPUT sum

END

15 | P a g e Moses Wainaina 0707691430


To determine whether the number is odd or even

1. START

2. DISPLAY "Enter the Number - "

3. READ number

4. IF number MOD 2 = 0 THEN

DISPLAY "Number is Even"

ELSE

DISPLAY "Number is Odd"

END IF

5. STOP

Area of a triangle
begin
numeric nBase, nHigh, nArea
display "ENTER THE BASE OF TRIANGLE : "
accept nBase
display "ENTER THE HEIGHT OF TRIANGLE : "
accept nHigh
nArea=nBase*nHigh
display "AREA OF TRIANGLE : " nArea
end

//WRITE A PSEUDOCODE TO FIND THE PERIMETER OF SQUARE.

begin
numeric nSide,nPeri
display "ENTER THE SIDE OF SQUARE : "
accept nSide
nPeri=nSide*nSide
display "AREA OF SQUARE : " nPeri
end

16 | P a g e Moses Wainaina 0707691430


//WRITE A PSEUDOCODE TO FIND THE AREA OF CIRCLE.

begin
numeric nRad, nAre
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nAre = nRad*nRad*22/7
display "AREA OF CIRCLE : " nAre
end

//WRITE A PSEUDOCODE TO FIND THE CIRCUMFERENCE OF CIRCLE.

begin
numeric nRad,nCir
display "ENTER THE RADIUS OF CIRCLE : "
accept nRad
nCir=2*nRad*22/7
display "CIRCUMFERENCE OF CIRCLE : " nCir
end

//WRITE A PSEUDOCODE TO FIND THE PERIMETER OF RECTANGLE.

begin
numeric nLen,nBrd,nAre
display "ENTER THE LENGTH OF RECGTANGLE : "
accept nLen
display "ENTER THE BREADTH OF RECTANGLE : "
accept nBrd
nAre=2*(nLen+nBrd)
display "PERIMETER OF RECTANGLE : " nAre
end

Flow Chart

This is a symbolic representation of an algorithm sequence. A flow chart uses predefined


symbols to represent the various actions in an algorithm. The arrangement of the symbols
indicates the flow of logic in the algorithm.

17 | P a g e Moses Wainaina 0707691430


Flow chart symbols

Symbol Purpose Description

Used to indicate the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/output Used for input and output operation.

Used for arithmetic operations and data-


Processing
manipulations.

Used to represent the operation in which there are


Decision
two alternatives, true and false.

On-page Connector Used to join different flowline

Used to connect flowchart portion on different


Off-page Connector
page.

Predefined Used to represent a group of statements


Process/Function performing one processing task.

Examples of flowcharts in programming

Draw a flowchart to add two numbers entered by user.

18 | P a g e Moses Wainaina 0707691430


Flowchart for a program to check whether a number is odd or even

Draw flowchart to find the largest among three different numbers entered by user.

19 | P a g e Moses Wainaina 0707691430


Find the sum of the first 50 numbers

20 | P a g e Moses Wainaina 0707691430


Advantages and Disadvantages of Flowchart

Advantages of using flowcharts:


 Communication: Flowcharts are better way of communicating the logic of a system to all
concerned or involved.
 Effective analysis: With the help of flowchart, problem can be analyzed in more effective
way therefore reducing cost and wastage of time.
 Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes, making things more efficient.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program becomes easy
with the help of flowchart. It helps the programmer to put efforts more efficiently on that
part
Disadvantages of using flowcharts:
 Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy. This will become a pain for the user, resulting
in a waste of time and money trying to correct the problem
 Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely. This will usually waste valuable time.

21 | P a g e Moses Wainaina 0707691430


 Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.

22 | P a g e Moses Wainaina 0707691430


TOPIC 3: PROGRAMMING CONCEPTS
Program: These are written instruction for computer to do a task

BASIC BUILDING BLOCK OF A PROGRAM


1) Character set

2) Constant

3) Instruction

4) Programme

1. CHARACTER SET

It includes the following:

1) Digits: They include: 0-9

2) Alphabet: They include: A-Z, a-z

3) Special character e.g

, Comma * Asterisk

? Question Mark - Minus sign

: Colon + Plus Sign

; Semi Colon ! Exclamation mark

( Left parenthesis / Slash

) Right Parenthesis \ Backslash

“ Quotation marks

$ Dollar sign

4) White spaces

WHITE SPACES

They are commonly used to format output. They include:

i. Horizontal Tab \t

ii. Carriage Return \c

23 | P a g e Moses Wainaina 0707691430


iii. New Line \n

iv. Form Feed \f

2. Constants and variables

Constant is an entity that do not change e.g pie while variable is an entity that keeps on

Changing e.g. interest rate, money value, degree etc

We don’t work directly with values so values are stored in the computer memory

Constant name is a memory location that hold a value that don’t change

Variable name is a memory location that holds a value that keeps on changing

Data type in programming


A data type or simply type is a classification of data which tells the compiler or interpreter how
the programmer intends to use the data. A Data type provides a set of values from which an
expression (i.e. variable, function ...) may take its values. The type defines the operations that
can be done on the data, the meaning of the data, and the way values of that type can be stored.

TYPES OF DATA TYPE

1) Primary data type built within the compiler

2) Secondary type use primary data type to form user defined include the arrays and

Structures

The primary constants are: -

Type Keyword

Meaning
Character Character data Char

Integer Signed whole number Int

Float floating-point numbers Float

Double double precision floating- Double


point numbers

24 | P a g e Moses Wainaina 0707691430


Void Valueless Void

1. Void

Description:

Used to specify empty set containing no values.

Storage Space: 0 byte.

Format: (void).

Range of values: ______.

2. Character (Denoted as “char” in C programming language)

Description:

A character denotes any alphabet, digit or special symbol used to represent in formation and it is
used to store a single character.

Storage space: 1 byte

Format: %c

Range of Values: ASCII Character Set.

3. Integer (Denoted as “int” in C programming language)

Description:

Integer type is used to store positive and negative integer.

Storage space: 2 bytes.

Format: %d

Range of values: -32768 to +32767.

4. Float

Description:

It is used to store real number, with single precision floating point number (precision of 6 digits
after decimal points.)

Storage space: 4 bytes.

25 | P a g e Moses Wainaina 0707691430


Format: %f

Range of values: -3.4*1038 to +3.4*1038.

5. Double

Description:

It stores real numbers with double precision. The use of double doesn’t guarantee to double the
number of significant digits in our result, but it improves the accuracy of the arithmetic and
reduces the accumulation of rounding errors.

Storage Space: 8 bytes.

Format: %ld

Range of values: -1.7*10308 to +1.7*10308.

The secondary constants include:

1. Array:

It is a collection of data of similar data type.

e.g. Int num [5];

Reserve a sequence of 5 locations of two bytes each for storing integers.

2. Pointer:

Pointer is a variable that stores the address of some other variable.

e.g. int *i;

The above statement declares i as pointer to integer data type.

3. Structure:

A structure is a collection of data of different data types under one name.

e.g.

Struct employees

26 | P a g e Moses Wainaina 0707691430


char Name[10];

int Age;

int Salary;

4. Union:

It is a collection of data of different types sharing common memory space.

e.g. Union item

int m;

float x;

char c;

};

5. Enumerated Data types:

This data types gives us an opportunity to invent your own data type and define what values the
variable of this data type can take.

Example: enum colors

red, green, blue, cyan

};

colors foreground, background;

Here the declaration has two parts:

a) The first part declare the data type and specifies its possible values.

b) The second part declare variable of this data type.

27 | P a g e Moses Wainaina 0707691430


Now we can give the values to these variables:

foreground=red;

background=blue;

RULES FOR CONSTANT AND VARIABLES


1) Variable or constant name shouldn’t be a keyword it should be a user defined

2) Every variable or constant name should start with either underscore or alphabet

3) A variable or constant name can be made up of either underscore or alphabet as well as


numerals and combination of both.

4) No special character are allowed within either constant or variable name except underscore

5) In case a variable or a constant name is made up of more than one word, the words can either
be fully joined or joined by use of underscore

Keyword. (Reserved words)

These are words which has special meaning to the compiler

.auto .else .register .union

.break .enum .return .unsigned

.case .extern .short .void

.char .float .signed .volatile

.const .for .size of .while

.continue .goto .static .

.default .if .struct

3. INSTRUCTIONS
Instructions are of three types:

1) Declarative instruction

2) Arithmetic instruction

3) Control instruction

28 | P a g e Moses Wainaina 0707691430


1) DECLARATIVE INSTRUCTION

It is made to introduce the value to be used when solving a problem. It’s done by use of variable
and constant names associated with respective data types e.g. integer, constant number.

The following are examples of type declaration instructions: -

Example .: int bas ; float rs, grosssal ; char name, code ;

NB: Identifiers name of user defined names such as variables, array and function

2) ARITHEMETIC INSTRUCTION

They are for performing computational instruction. There are different operators in C

a) Arithmetic operator

b) Relational operator

c) Logical operator

A) ARITHEMETIC OPERATOR

They are used for basic mathematical operation

They include

B) RELATIONAL OPERATOR

29 | P a g e Moses Wainaina 0707691430


Operators used for comparison purpose.

C) LOGICAL OPERATOR

It is used to combine different computation and results into a Boolean value

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

3) CONTROL INSTRUCTION

They are the instruction that affect the flow of execution. They are of three types

A) Sequence flow

B) Selective or decision making or conditional control instruction

C) Iterative control statement

a) SEQUENCE FLOW

They allow the statements to be executed as they are appearing in a program.

B) SELECTIVE INSTRUCTION

30 | P a g e Moses Wainaina 0707691430


They allow execution of set of instruction depending on set condition

c) ITERATIVE CONTROL STATEMENT

They are statement that allow set of instruction to executed repeatedly until a certain condition is
met

STRUCTURE OF A C PROGRAM
Structure of C program is made of four component:

1) Header file

2) Main()

3) Body

i.e.

# include <stdio.h>

#include<conio.h> Header file


main ( )

Instruction; Body
}

Header files –these are collection of function which perform a predefined task. Every header file
has extension .h e.g. <stdio.h>- this is a header file that contains input and output function
(functions that manage input and output). <conio.h > this is a header file that hold function that
manage the console.

The main () indicates the beginning of the executable code. The body begins with opening curly
brackets and ends with closing curly brackets. This entails the source code. The general syntax is
as follows:

#include<stdio.h>
#include<conio.h>
main()
{

31 | P a g e Moses Wainaina 0707691430


instructions
}

RULE OF C PROGRAM
1) Each instruction in c program is written as separate statement
N/B first statement should be declarative instruction where needed
2) Statement in a program must appear in systematic order in which one wishes them to be
executed
3) Blank spaces may be inserted between words to improve readability of statement
4) All statement are entered in lower case
5) Ever C statement must be terminated with semicolon

Write a program to print the message my first c code


#include<stdio.h>
main ()
{
printf(" my first c code");
getch ();
}
INPUT AND OUTPUT MANAGEMENT
1. INPUT MANAGEMENT
How a variable name or a constant name can acquire a value

a) Assignment operator (=)


used to assigning value to a variable. The left side operand of the assignment operator is a
variable and right side operand of the assignment operator is a value.
E.g.
int a;
a =5;
Assigning a variable or constant name a value can either be direct assignment or
calculated value from already existing variable or constant name. For example:

32 | P a g e Moses Wainaina 0707691430


int a, b, c;
NB Every variable one declares is given garbage value.
a =10;
b = 16;
c = a + b;

b) scanf()
This function allows an end user input values to work within the program in the respective
variable names and constant names. They should have already been declared.
E.g. int a;
scanf (“%d”, &a);
Thus &a means address location of a
int a, b, c;
scanf (“%d %d”, &a, &b);
c: =a+ b
NB: the format specifiers should be as many as the variable or constant names whose values are
being captured.

2. MANAGING OF OUTPUT
This is to display outputs. This can be with the help of printf (). It can take the following forms:

a) To display values.
In this case the values are represented by their respective variable or constant names.
For example:
int a;
a =5;
print f(“%d”, a);
b) To display a statement
# include <stdio.h>
#include<conio.h>
main ( )

33 | P a g e Moses Wainaina 0707691430


{
printf (“ my first c code”);
getch();
}
COMMENTS IN C
A comment is an explanation or description of the source code of the program. It helps a
developer explain logic of the code and improves program readability.
1) A comment that starts with a slash asterisk /* and finishes with an asterisk slash */ and you
can place it anywhere in your code, on the same line or several lines. It is considered to be a
multiline type of writing comments in C Programming.

Example:
#include <stdio.h>
int main() {

/* in main function I can write my principal code


And this in several comments line */
int x = 42;
printf("%d", x);
return 0;}
2) Single-line Comments which uses a double slash // dedicated to comment single lines. It is
considered to be a single line comment.

// C program to demo
// Single Line comment
#include <stdio.h>
int main(void)
{

// This is a single line comment


printf("Guru99");
return 0; // return zero
}

34 | P a g e Moses Wainaina 0707691430


EXAMPLES OF C PROGRAMS
Example 1: To Add two Numbers
#include<stdio.h>
main() {
int a, b, sum;
printf("\nEnter Fast Number number: ");
scanf("%d", &a); // we use %d when we use data type int
printf("\nEnter Second Number:");
scanf("%d",&b);
sum = a + b;
printf("Sum is : %d", sum);
return 0;
}

Output
Enter Fast Number number: 4
Enter Second Number:5
Sum is : 9

Example 2: To find area of Circle


#include <stdio.h>
int main()
{
float radius, area;
printf("Enter the radius of a circle\n");
scanf("%f", &radius);
area = 3.14159*radius*radius;
printf("Area of the circle = %.2f\n", area); // .2f means printing upto two decimal places
return 0;
}

35 | P a g e Moses Wainaina 0707691430


Output
Enter the radius of a circle 8
Area of the circle = 201.06

Example 3: C program for arithmetic operations


#include <stdio.h>
int main()
{
int first, second, add, subtract, multiply;
float divide;
printf("Enter first number\n");
scanf("%d", &first);
printf("Enter Second number\n");
scanf("%d", &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting, you can also write: divide = (float)first/second
printf("Sum = %d\n", add);
printf("Difference = %d\n", subtract);
printf("Multiplication = %d\n", multiply);
printf("Division = %.2f\n", divide); // "%.2lf" to print two decimal digits, by default (%lf) we
get six
return 0;
}

36 | P a g e Moses Wainaina 0707691430


Output:
Enter two integers
79
Sum = 16
Difference = -2
Multiplication = 63
Division = 0.78

Example 4: C Program to calculate sum of 5 subjects and find percentage


#include<stdio.h>

int main() {

int Eng, Kisw, Math, Sci, ss, sum, total = 500;

float per; // we a using float data type because percentage must have decimal number / fraction

printf("\nEnter English Marks : ");

scanf("%d",&Eng);

printf("\nEnter Kiswahili Marks : ");

scanf("%d",&Kisw);

printf("\nEnter Mathmatics Marks : ");

scanf("%d",&Math);

printf("\nEnter Science Marks : ");

scanf("%d",&Sci);

printf("\nEnter Social Studies Marks : ");

scanf("%d",&ss);

sum = Eng + Kisw + Math + Sci + ss;

printf("\nSum : %d", sum);

per = (sum * 100) / total;

37 | P a g e Moses Wainaina 0707691430


printf("\nPercentage : %f", per); // we use %f when use data type float

return 0;

}Output:

Enter marks of 5 subjects :

45 67 89 23 90

Sum : 314

Percentage : 62.000000

Example 5: C Program to find the simple interest

#include<stdio.h>

int main() {

int amount, rate, time, si;

printf("\nEnter Principal Amount : ");

scanf("%d", &amount);

printf("\nEnter Rate of Interest : ");

scanf("%d", &rate);

printf("\nEnter Period of Time : ");

scanf("%d", &time);

si = (amount * rate * time) / 100;

printf("\nSimple Interest : %d", si);

return();

Output:

Enter Principal Amount : 4500

Enter Rate of Interest : 5

38 | P a g e Moses Wainaina 0707691430


Enter Period of Time : 3

Simple Interest : 675

TOPIC 4 - CONTROL STRUCTURES


Control structures represent the forms by which statements in a program are executed. A control
structure is a block of programming that analyzes variables and chooses a direction in which to
go based on given parameters.

Importance of Control Structures

The term flow control details the direction the program takes (which way program control
"flows"). Hence it is the basic decision-making process in computing; flow control determines
how a computer will respond when given certain conditions and parameters.

Types of Control Structures


Three structures control program execution:

i. Sequence
ii. Selection or decision structure
iii. Iteration or looping structure

1) SEQUENCE CONTROL STRUCTURE

This is the simplest control structure. It dictates the order of execution from one statement to the
next within the program. In the absence of repetition or branching, the program instructions will
be executed in the order in which they were coded.

Basically, program statements are executed in the sequence in which they appear in the program.
The sequence control structure is the default or overriding structure.

39 | P a g e Moses Wainaina 0707691430


The sequence structure indicates instructions are to be executed one statement at a time in the
order they occur from top down unless a different control structure dictates otherwise.

2) SELECTION CONTROL STRUCTURE

The structure is used for decision making within a program. It allows alternative actions to be
taken according to conditions that exist at particular stages within a program.

The structure uses a test condition statement, which upon evaluation by the computer gives rise
to certain conditions which may evaluate to a Boolean true or false. Based on the outcome of the
test condition, the computer may execute one or more statements.

Types of Selection Structure

a) The if statement
b) The if – Else statement
c) Nested If
d) Switch-case statement

a) The If statement

If statement is a programming conditional statement that display the statement or information


only when the condition is true

Syntax

The syntax of if statement in C programming language is:

If (Condition)

(Statement); /* statement(s) will execute condition is true */

Note: If expression is true, the statement is executed, otherwise it is skipped

Flowchart diagram for If statement

40 | P a g e Moses Wainaina 0707691430


Example: 1

#include <stdio.h>
int main()
{

int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
return 0;
}

We can use multiple if statements to check more than one conditions

#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");

41 | P a g e Moses Wainaina 0707691430


scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
return 0;
}

Output

enter the value of x:20

enter the value of y:20

x is equal to y

b) If – else statement

The if else statement lets the programmer choose between two statements as opposed to the
simple if statement which gives you the choice of executing a statement or skipping it.

The syntax of an if...else statement in C programming language is:

if(Condition)
{
(Statement (s)) ; /* statement(s) will execute if the condition is true */
}
else
{

42 | P a g e Moses Wainaina 0707691430


(Statement (s)) ; /* statement(s) will execute if Condition is false */
}

Flowchart of If –Else Statement

Examples

To check which number is greater between two numbers entered by the user

#include<stdio.h>
main()
{
int a, b;
printf("Please enter the value for a:");
scanf("%d", &a);
printf("\nPlease the value for b:");
scanf("%d", &b);
if(a>b){
printf("\n a is greater");
} else {
printf("\n b is greater");
}

43 | P a g e Moses Wainaina 0707691430


}
Output

Example 2

To get the greatest number between three number entered by the user

#include<stdio.h>
int main()
{
int num1,num2,num3;
//Ask user to input any three integer numbers
printf("\nEnter value of num1:");
//Store input values in variables for comparsion
scanf("%d ",&num1);
printf("\nEnter value of num2:");
//Store input values in variables for comparsion
scanf("%d ", num2);

printf("\nEnter value of num3:");


//Store input values in variables for comparsion
scanf("%d ",& num3);

if((num1>num2)&&(num1>num3))
printf("\n Number1 is greatest");
else if((num2>num3)&&(num2>num1))
printf("\n Number2 is greatest");
else
printf("\n Number3 is greatest");
return 0;
}
Output

44 | P a g e Moses Wainaina 0707691430


Enter value of num1, num2 and num3: 15 200 101

Number2 is greatest

c) Nested if statement

Writing an if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows

The nested if statement can be defined using any combination of simple if & if-else statements

Example 1: Test whether given number is even or odd if it is below 100.

#include <stdio.h>
int main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}

45 | P a g e Moses Wainaina 0707691430


else
printf("Given number is not below 100") ;
return 0;
}

e) The ‘switch’ and ‘break’ statements


Consider a situation in which we have more number of options out of which we need to select only
one option that is to be executed. Such kind of problems can be solved using nested if statement.
But as the number of options increases, the complexity of the program also gets increased. This
type of problems can be solved very easily using switch statement. Using switch statement, one
can select only one option from more number of options very easily. In switch statement, we
provide a value that is to be compared with a value associated with each option. Whenever the
given value matches with the value associated with an option, the execution starts from that option.
In switch statement every option is defined as a case.

The switch statement contains one or more number of cases and each case has a value associated
with it. At first switch statement compares the first case value with the switchValue, if it gets
matched the execution starts from the first case. If it doesn't match the switch statement compares
the second case value with the switchValue and if it is matched the execution starts from the second
case. This process continues until it finds a match. If no case value matches with the switchValue
specified in the switch statement, then a special case called default is executed.

When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the switch
statement. However it is optional.

The structure of a switch is as follows:

switch (integer expression)

46 | P a g e Moses Wainaina 0707691430


{
case constant 1:
statement; optional
case constant 2:
statement; optional
…………
default: (optional)
statement; (optional)
}

Flowchart of switch – case statement

Example 1. Displaying the days of a week using switch case statement

#include <stdio.h>
int main()
{
int week;
/* Input week number from user */
printf("Enter week number(1-7): ");
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;

47 | P a g e Moses Wainaina 0707691430


case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}

Output

Enter week number (1-7): 1

Monday

Example 2 : To display Month of the year using switch case statement

#include <stdio.h>
int main()
{
int month;
printf("Input Month No 1-12 : ");
scanf("%d",&month);
switch(month)
{
case 1:
printf("January\n");
break;
case 2:
printf("February\n");
break;
case 3:
printf("March\n");
break;
case 4:

48 | P a g e Moses Wainaina 0707691430


printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");
break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");
break;
case 9:
printf("September\n");
break;
case 10:
printf("October\n");
break;
case 11:
printf("November\n");
break;
case 12:
printf("December\n");
break;
default:
printf("invalid Month number. \nPlease try again ....\n");
break;
}
Return 0;
}

Output:

Input Month No: 4

April

NOTE thee following

MOST IMPORTANT POINTS TO BE REMEMBERED

 When we use switch statement, we must follow the following...

49 | P a g e Moses Wainaina 0707691430


 Both switch and case are keywords so they must be used only in lower case letters.
 The data type of case value and the value specified in switch statement must be same.
 Switch and case values must be either integer or character but not float or string.
 A switch statement can contain any number of cases.
 The keyword case and its value must be separated with a white space.
 The case values need not be defined in sequence, they can be in any order.
 The default case is optional and it can be defined anywhere inside the switch statement.
 The switch value might be a direct value, a variable or an expression.

3. ITERATION OR LOOPING STRUCTURE

Consider a situation in which we execute a single statement or block of statements repeatedly for
required number of times. Such kind of problems can be solved using looping statements in C. For
example, assume a situation where we print a message for 100 times. If we want to perform that
task without using looping statements, we have to either write 100 printf statements or we have to
write the same message for 100 times in a single printf statement. Both are complex methods. The
same task can be performed very easily using looping statements.

The looping statements are used to execute a single statement or block of statements repeatedly
until the given condition is FALSE.

C language provides three looping statements...

a) while statement
b) do-while statement
c) for statement

a) While statement

The while statement is used to execute a single statement or block of statements repeatedly as long
as the given condition is TRUE. The while statement is also known as Entry control looping
statement

Syntax
50 | P a g e Moses Wainaina 0707691430
The syntax of a while loop in C programming language is:

while(condition)
{
statement(s);
}

Flowchart

Example 1: To Display even numbers between 0-10 using while loop

#include<conio.h>
int main(){
int n = 0;
printf("Even numbers up to 10\n");

while( n <= 10 )
{
if( n%2 == 0) //This is to check if the number is divisible by 2
printf("%d", n) ;
n++ ; //this is increment operator
}

return 0;
}

Output
Even numbers up to 10
0 2 4 6 8 10

51 | P a g e Moses Wainaina 0707691430


Example 2: Testing multiple conditions using logical operator inside while loop
#include <stdio.h>
int main()
{
int i=1, j=1;
while (i <= 4 && j <= 4)
{
printf("%d %d\n",i, j);
i++;
j++;
}
return 0;
}

Output
11
22
33
44

Example 3: Program to find Sum of N Numbers using While Loop

#include<stdio.h>
int main()
{
int Number, i = 1, Sum = 0;

printf("\nPlease Enter any Integer Value\n");


scanf("%d", &Number);

while(i <= Number)


{
Sum = Sum + i;
i++;
}

printf("Sum of Natural Numbers = %d", Sum);

52 | P a g e Moses Wainaina 0707691430


return 0;
}

Output
Please enter the number of integer value 10
Sum of Natural Numbers = 55

Note the following


 When we use while statement, we must follow the following...
 While is a keyword so it must be used only in lower case letters.
 If the condition contains variable, it must be assigned a value before it is used.
 The value of the variable used in condition must be modified according to the requirement
inside the while block.
 In while statement, the condition may be a direct integer value, a variable or a condition.
 A while statement can be an empty statement

b) Do –while loop
In this structure the test condition is placed after the block of code that is to be repeatedly
executed. The computer first executes the block of code then evaluates the test condition
statement.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );

Flowchart

53 | P a g e Moses Wainaina 0707691430


Example 1 : C Program to find Sum of N Numbers using Do While Loop
#include<stdio.h>
int main()
{
int Number, i = 1, Sum = 0;

printf("\nPlease Enter any Integer Value\n");


scanf("%d", &Number);

do
{
Sum = Sum + i;
i++;
} while(i <= Number);

printf("Sum of Natural Numbers = %d", Sum);


return 0;
}

Output
Please enter the number of integer value 10
Sum of Natural Numbers = 55

Example 2 : To Display even numbers between 0-10 using Do-while loop

#include<stdio.h>
int main(){
int n = 0;
printf("Even numbers up to 10\n");
do

54 | P a g e Moses Wainaina 0707691430


{
if( n%2 == 0) //This is to check if the number is divisible by 2
printf("%d", n) ;
n++ ; //this is increment operator
}

while( n <= 10 );
return 0;
}

Output
Even numbers up to 10
0 2 4 6 8 10

c) The ‘for’ loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax

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

For ( init; condition; increment ) {

Statement(s);

Flow of control in a 'for' loop

The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just after the
'for' loop.

After the body of the 'for' loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.

55 | P a g e Moses Wainaina 0707691430


Example 1 : To display numbers 10 – 20 using for loop

#include <stdio.h>

int main () {

int a;

/* for loop execution */


for( a = 10; a < 20; a++ )
{
printf("value of a: %d\n", a);
}

return 0;
}

56 | P a g e Moses Wainaina 0707691430


Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Example 2: To display 10 9 8 7 6 5 4 3 2 1

#include<stdio.h>
int main()
{
int n;

for(n=10;n>=1;n--)
{
printf(" %d",n);
}
return 0;
}

Example 3:

#include<stdio.h>
int main()
{
int n, m; Output
for(n=0;n<5;n++){
for (m=0;m<=n;m++){
printf("*");
}
printf("\n");
}
return 0;
}

57 | P a g e Moses Wainaina 0707691430


Example 4:
#include<stdio.h>
int main()
{ Output
int n, m;

for(n=1;n<5;n++){
for (m=5;m>=n;m--){
printf("*");
}
printf("\n");
}
return 0;
}

Example 5 :

#include <stdio.h>
int main() {
Output
int i,j,k;
for (i=1; i<=5; i++) {
for (j=5; j>=i; j--) {
printf(" ");
}
for (k=1; k<=i; k++) {
printf("*");
}
printf("\n");
}
}

Example 6:

#include<stdio.h>
int main() Output
{
int n;

for(n=10;n>=1;n--)
{
printf(" %d",n);
}
return 0;
}

58 | P a g e Moses Wainaina 0707691430


Topic 5 POINTERS, ARRAYS AND STRUCTURES IN C
POINTERS
What is a Pointer?

A pointer is a secondary data type (also known as derived data type) in C. It is built from one of
the primary data types available in C language. Basically pointer contains memory address of
other variable or function as their value. As pointer deals with memory address, it can be used to
access and manipulate data stored in memory.

Benefits of using Pointer in C Program

Pointer is one of the most exciting features of C language and it has added power and flexibility
to the language. Pointer is in C language because it offers following benefits to the programmers:

1. Pointers can handle arrays and data table efficiently.

2. Pointers support dynamic memory management.

3. Pointer helps to return multiple values from a function through function argument.

4. Pointer increases program execution speed.

5. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc. We can
achieve these and much more benefits from pointer only if we can use it properly.

Pointer Declaration

To declare a pointer variable, use this general form:

type *var_name;

Here, type is the base type of the pointer. The base type specifies the type of the object that the
pointer can point to. Notice that an asterisk precedes the variable name. This tells the computer
that a pointer variable is being created. For example, the following statement creates a pointer to
an integer.

int *p;

Pointer Operators

C contains two special pointer operators: * and &. The operator returns the address of the
variable it precedes. The * operator returns the value stored at the address that it precedes. The *
pointer operator has no relationship to the multiplication operator, which uses the same symbol).
For example, examine this short program.

59 | P a g e Moses Wainaina 0707691430


#include<stdio.h>
main()
{
int *p, q;
q = 100; /* assign q 100 */
p = &q; /* assign p the address of q*/
printf(“%d”, *p);/* display q’s value using pointer*/
return 0;
}

This program prints 100 on the screen.

Explanation

First, the line int *p, q; defines two variables: p, which is declared as an integer pointer, and q,
which is an integer. Next, q is assigned the value 100.

In the next line, p is assigned the address of q. You can verbalize the & operator as “address of.“
Therefore, this line can be read as: assign p the address of q. Finally, the value is displayed
using the * operator applied to p. The * operator can be verbalized as “at address”.

Therefore the printf( ) statement can be read as “print the value at address q,” which is 100.

When a variable value is referenced through a pointer, the process is called indirection. It is
possible to use the * operator on the left side of an assignment statement in order to assign a
variable a new value using a pointer to it.

Example 1:

Program that uses a for loop that counts from 0 to 9. It puts in the numbers using a pointer.

#include<stdio.h>
main()
{
int i,*p;
p = &i;
for ( i =0; i <10; i++)
printf (“ %d ”, *p);
return 0;
}

60 | P a g e Moses Wainaina 0707691430


ARRAYS
What is an Array?
An array in C language is a collection of similar data type, means an array can hold value of a
particular data type for which it has been declared. Arrays can be created from any of the C data
type’s int, float, and char. So an integer array can only hold integer values and cannot hold
values other than integer. When we declare array, it allocates contiguous memory location for
storing values whereas 2 or 3 variables of same data type can have random locations. So this is
the most important difference between a variable and an array.

Types of Arrays:
1. One dimension array (Also known as 1D array).
2. Two dimension array (Also known as 2D array).
3. Multidimensional array.

1. One dimension array (Also known as 1D array)


A one-dimensional array requires a single index e.g. int numbers [10];
Resembles a single list of values and therefore requires a single index to vary between 0 to (array
size -1).
Explanation

int i[5] = {1, 4, 9, 16, 25};

This means that i [0] will have the value 1 and i [4] will have the value 25.

You can initialize character arrays in two ways. First, if the array is not holding a null -
terminated string, you simply specify each character using a comma separated list. For example,
this initialize a with the letters ‘A’, ‘B’, and ‘C’.

char a[3] = { ‘A’, ‘B’, ‘C’};

If the character array is going to hold a string, you can initialize the array using a quoted string,
as shown here.

char name[6] = “Peter”;

Notice that no curly braces surround the string. They are not used in this form of initialization.
Because strings in C must end with a null, you must make sure that the array you declare is long
enough to include the null. This is why name is 6 characters long, even though “Peter” is only 5
characters. When a string constant is used, the compiler automatically supplies the null
terminator
Example 1

61 | P a g e Moses Wainaina 0707691430


#include<stdio.h>
int main()
{
int n[5]={9, 7, 8, 0, 4};
printf("%d", n[0]);
printf("%d", n[1]);
printf("%d", n[2]);
printf("%d", n[3]);
printf("%d", n[4]);
}

Output
The output will be 9 7 8 0 4

Example 2
#include<stdio.h>
main()
{
char str1[80],str2[80];
printf( " Enter your name: \n");
gets(str1);
printf( " Enter your home county: \n");
gets(str2);
printf("Your name is %s\n",str1);
printf("Your home county is %s\n",str2);
return 0;
}

Output

2. Two – dimensional array

62 | P a g e Moses Wainaina 0707691430


An m by n two-dimensional array can be thought of as a table of values having m rows and n
columns. The number of elements can be known by the product of m (rows) and n(columns).

Syntax:

data_type array_name[row_size][column_size];

Example:1

int arr[3][3];

So the above example declares a 2D array of integer type. This integer array has been named

arr and it can hold up to 9 elements (3 rows x 3 columns)

Example 2

#include<stdio.h>
int main()
{
int i, j;
int arr[3][3]={{12,45,63},{89,34,73},{19,76,49}};
printf(" 2D Array Elements \n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
Return 0;
}

Output

63 | P a g e Moses Wainaina 0707691430


So in the above example we have declared a 2D array named arr which can hold 3x3 elements.
We have also initialized that array with values, because we told the compiler that this array will
contain 3 rows (0 to 2) so we divided elements accordingly. Elements for column have been
differentiated by a comma (,). When compiler finds comma in array elements then it assumes
comma as beginning of next element value

3. Multidimensional arrays
Multidimensional arrays are initialised the same way as one-dimensional ones.

For example, here the array sqr is initialised with the values 1 though 9, using row order.

int sqr [3][3] = {


1, 2, 3,
4, 5, 6,
7, 8, 9
};

This initialization causes sqr[0][0] to have the value 1, sqr[0][1] to contain 2, sqr[0][2] to
contain 3, and so forth.

If you are initializing a one-dimensional array, you need not specify the size of the array; simply
put nothing inside the square brackets. If you don’t specify the size, the compiler simply counts
the number of initialization constants and uses that that value as the size of the array.

Arrays that don’t have their dimensions explicitly specified are called unsized arrays. An unsized
array is useful because it is easier for you to change the size of the initialization list without
having to count it and then change the array dimension. This helps avoid counting errors on long
lists, which is especially important when initializing strings.

Here an unsized array is used to hold a prompting message.

char prompt[ ] = “Enter your name: “;

STRUCTURE
Suppose you want to write a program that keeps tracks of students [Name, Marks] i.e. a variety
of information to be stored about each student. This requires;
• An array of strings (for the Names).
• Marks in an array of integers

64 | P a g e Moses Wainaina 0707691430


What Is A Structure?

A structure is an aggregate data type that is composed of two or more related elements. If we are
using C structure then we are combining different related data types in one group so that we can
use and manage those variables easily

Setting up A Structure
In our example, we can have the following template;

struct student
{
char name[SIZE];
int marks;
};
The above describes a structure made up of a character array name, and int variable marks.

Explanation
• The keyword struct announces to the computer that what follows is a structure data type
template.
• The tag follows: which is a shorthand label that can be used later to refer to this structure. In the
above example, the tag name is student.
• A list of structure members enclosed in a pair of braces. Each member is described by its own
declaration. For example; the name portion is a character array of SIZE elements.

Example: Bank Account


Account number (integer)
Account type (character)
Account holder name [30]
Account balance (float)

struct Bank_ account


{
int acc_number;
char acc_type;
char holder_name [30];
float balance;
};
Example 1:
#include<stdio.h>
#define SIZE 40
struct student
{

65 | P a g e Moses Wainaina 0707691430


char name[SIZE];
int marks;
};

main()
{
struct student mystudent; /* declare mystudent as a student type */
printf("Please enter the name of the student \n");
scanf("%s", mystudent.name);
printf("Enter the marks obtained \n");
scanf("%d", &mystudent.marks);
printf("%s: got %d ", mystudent.name, mystudent.marks );
printf("\n");
system("pause");
return 0;
}

Output

Use of Structures
The immediate application that comes to mind is database management. For example, to
maintain data about employees in an organization, books in a library, items in a store, financial
transactions in a company. Their use however, stretches beyond database management. They can
be used for a variety of applications like:
• Checking the memory size of the computer.
• Hiding a file from a directory
• Displaying the directory of a disk.
• Interacting with the mouse
• Formatting a floppy
• Drawing any graphics shape on the screen.

FUNCTION IN C
A function is a set of instruction that performs a specific task.

There are two types of function. These are:

66 | P a g e Moses Wainaina 0707691430


1) Inbuilt function

2) User defined function

Inbuilt function are declared and defined within the compiler. For example:

e.g printf ( ), scanf( ), main( )

User defined

These are the functions which are declared and defined by the programmer.

There are different types of user defined functions

1) Function with no return value and with no argument

2) Function with argument and no return value

3) Function with return value and argument

4) Function which return more than one value

Properties of functions

Whether user defined or inbuilt functions can exhibit the following properties:

1) Every function has a unique name

2) Every function perform a specific task

3) Every function may or may not return a value to the calling function

Benefits of function:

1) Makes possible for top down modular programming

2) Reduce the length of the source code

3) It reduces the aspect of rewriting the source code of statement again and again within the same
programme

4) It simplifies the way to trace errors within the code

5) It reduces developing time of any application since a function can be reused in different
application

No Return Without Argument Function in C

67 | P a g e Moses Wainaina 0707691430


When a function has no arguments, it does not receive any data from the calling function.
Similarly when it does not return a value, the calling function does not receive any data from the
called function.

Syntax:
Return_Type Function_Name ( ) // Function Definition
{
// body of Statement;
}

//No Return Without Argument Function in C


/*
1.Function Declaration
2.Function Definition
3.Function Calling

*/
#include<stdio.h>

//Function Declaration
void add();

int main()
{
//Function Calling
add();
return 0;
}
//Function Definition
void add()
{
int a,b,c;
printf("\nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);
}
Output

Enter The Value of A & B :12

34

68 | P a g e Moses Wainaina 0707691430


Total : 46

No Return With Argument Function in C

When a function has arguments, it receive any data from the calling function but it returns no
values.

Syntax :
Return_Type Function_Name ( Parameters ) // Function Definition
{
// body of Statement ;
}

Example :
void add ( int x , int y )
{
// body of Statement ;
}

Source Code

//No Return With Argument Function in C


#include<stdio.h>

//Function Declaration
void add(int,int);

int main()
{
int a,b;
printf("\nEnter The Value of A & B : ")l
scanf("%d%d",&a,&b);
//Function Calling
add(a,b); // Actual Parameters
return 0;
}
//Function Definition
void add(int a,int b) //Formal Parameters
{
int c;
c=a+b;

69 | P a g e Moses Wainaina 0707691430


printf("\nTotal : %d",c);
}

Output

Enter The Value of A & B : 23

34

Total : 57

Return without Argument Function in C

There could be occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. A example for this is getchar function it has
no parameters but it returns an integer an integer type data that represents a character.

Syntax :
Return_Type Function_Name ( ) // Function Definition
{
// body of Statement ;
}

Example :
int add ( )
{
// body of Statement ;
}

Source Code

//Return Without Argument Function in C


#include<stdio.h>

int add();

int main()
{
int a;
a=add();
printf("\nTotal : %d",a);
return 0;
70 | P a g e Moses Wainaina 0707691430
}

int add()
{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
return a+b;
}

Output

Enter The Value of A & B : 6

45

Total : 51

Return with Argument Function in C

Here this function is taking any input argument, and also returns value.

Syntax :
Return_Type Function_Name ( Parameters ) // Function Definition
{
// body of Statement ;
}

Example :
int add ( int x , int y )
{
// body of Statement ;
}

Source Code

//Return With Argument Function in C


#include<stdio.h>
int add(int,int);
int main()

71 | P a g e Moses Wainaina 0707691430


{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
a=add(a,b);
printf("\nTotal : %d",a);
return 0;
}

int add(int a,int b)


{
return a+b;
}

Output

Enter The Value of A & B : 2

Total : 11

72 | P a g e Moses Wainaina 0707691430

inprotected.com

You might also like