0% found this document useful (0 votes)
2 views

Course

The document provides an overview of structured programming, detailing its objectives, history, and classifications of programming languages from low-level to high-level. It emphasizes the importance of modular programming, the characteristics of good programs, and various programming paradigms. Additionally, it discusses the advantages of the C programming language and outlines the phases of program development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Course

The document provides an overview of structured programming, detailing its objectives, history, and classifications of programming languages from low-level to high-level. It emphasizes the importance of modular programming, the characteristics of good programs, and various programming paradigms. Additionally, it discusses the advantages of the C programming language and outlines the phases of program development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Structured Programming

STRUCTURED PROGRAMMING
By
AZANGUE Brice Arthur

Phone: 675 86 06 34 /695 50 16 10

Email: [email protected]

Arthur Brice A
1
Structured Programming

COURSE OBJECTIVES

Below are the overall objectives of this course. On completing the course, you should be able to:

 Define programs and classify programming languages

 State the advantages and disadvantages of high and low–level languages

 State the characteristics of a good program

 List the various phases of program development.

 Explain the steps involved in problem definition and analysis

 Describe functions and Procedures in program

 Illustrate a typical function structure for sorting numerical arrays in C language.

 Define a class in Object–oriented programming

 Explain the abstraction costs and benefits

 Define modularity in programming.

 State the advantages of modular programming approach

 Describe the real-life application of modularity concept.

 Explain the importance of header file, module implementation and main program in C
programming language.

 Illustrate the structure of interface file in C language declarations

Arthur Brice A
2
Structured Programming

INTRODUCTION TO STRUCTURED PROGRAMMING

Programming means to convert problem solutions into instructions for the computer. It also refers
to the process of developing and implementing various sets of instructions to enable a computer to
do a certain task.

Structured programming (sometimes known as modular programming) is an approach to writing


programs that are easier to test, debug, modify and maintain by enforcing a modular approach
which breaks a large complex problem into sub-problems.

A programming language is a vocabulary and set of grammatical rules designed for instructing a
computer to perform specific tasks.

1. HISTORY OF PROGRAMMING LANGUAGES

1.1 First-Generation Programming Languages – Machine Language

A first-generation of programming languages includes machine-level programming languages.


These languages were introduced in the 1940s and had the following characteristics:

 Instructions were entered directly in binary format (1s and 0s) and therefore they were
tedious and error prone. Programmers had to design their code by hand then transfer it to a
computer using a punch card, punch tape or flicking switches.
 Instructions were executed directly by a computer's central processing unit (CPU) i.e. they
were executed very fast.
 Memory management was done manually.
 Programs were very difficult to edit and debug.
 Used to code simple programs only.

1.2 Second-Generation Programming Languages (2GL) – Low Level Programming


Languages/Assembly Languages

 They were introduced to mitigate the error prone and excessively difficult nature of binary
programming. Introduced in the 1950s
 Improved on first generation by providing human readable source code which must be
compiled/assembled into machine code (binary instructions) before it can be executed by a
CPU
 Specific to platform architecture i.e. 2GL source code is not portable across processors or
processing environments.
 Designed to support logical structure and debugging.

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

Arthur Brice A
3
Structured Programming

Assemblerand each line of assembly can be replaced by the equivalent one line of object (machine)
code:

Such languages are sometimes still used for kernels and device drivers, i.e. the core of the operating
system and for specific machine parts. More often, such languages are used in areas of intense
processing, like graphics programming, when the code needs to be optimized for performance.

Almost every CPU architecture has a companion assembly language. Most commonly used are the
assembly languages today like Autocoder for IBM mainframe systems, Linoreum, MACRO -11,etc.

1.4 Third-Generation Languages (3GL) – High-Level Languages

Third generation languages are the primary languages used in general purpose programming today.
They each vary quite widely in terms of their particular abstractions and syntax. However, they all
share great enhancements in logical structure over assembly languages.

 Introduced in the 1950s


 Designed around ease of use for the programmer (Programmer friendly)
 Driven by desire for reduction in bugs, increases in code reuse
 Based on natural language
 Often designed with structured programming in mind
 The languages are architecture independent e.g. C, Java etc.

Examples:

Most Modern General Purpose Languages such as C, C++, C#, Java, Basic, COBOL, Lisp and ML.

1.5 Fourth Generation Languages

Fourth-generation programming languages are high-level languages built around database systems.
They are generally used in commercial environments.

 Improves on 3GL and their development methods with higher abstraction and statement
power, to reduce errors and increase development speed by reducing programming effort.
They result in a reduction in the cost of software development.
 A 4GL is designed with a specific purpose in mind. For example languages to query
databases (SQL), languages to make reports (Oracle Reports) etc.
 4GL are more oriented towards problem solving and systems engineering.

Examples: Progress 4GL, PL/SQL, Oracle Reports, Revolution language, SAS, SPSS, SQ

Arthur Brice A
4
Structured Programming

1.6 Fifth Generation Languages

Improves on the previous generations by skipping algorithm writing and instead provide
constraints/conditions.

While 4GL are designed to build specific programs, 5GL are designed to make the computer solve a
given problem without the programmer. The programmer only needs to worry about what
problems needed to be solved and only inputs a set of logical constraints, with no specified
algorithm, and the Artificial Intelligence (AI)-based compiler builds the program based on
these constraints.

Examples: Prolog, OPS5, Mercury

Low-Level Languages Versus High-Level Languages

Low-level languages such as machine language and assembly language are closer to the
hardware than are the high-level programming languages, which are closer to human languages.
Low-level languages are converted to machine code without using a compiler or interpreter, and the
resulting code runs directly on the processor. A program written in a low-level language runs very
quickly, and with a very small memory footprint; an equivalent program in a high-level language
will be more heavyweight. Low-level languages are simple, but are considered difficult to use, due
to the numerous technical details which must be remembered.

High-level languages are closer to human languages and further from machine languages. The
main advantage of high-level languages over low-level languages is that they are easier to read,
write, and maintain. Ultimately, programs written in a high-level language must be translated into
machine language by a compiler or interpreter.

The first high-level programming languages were designed in the 1950s. Now there are dozens of
different languages, including Ada, Algol, BASIC, COBOL, C, C++, FORTRAN, LISP, Pascal,
and Prolog.

2. PROGRAMMING PARADIGMS

A programming paradigm is a fundamental style of computer programming, a way of building the structure
and elements of computer programs. There are four main paradigms:

a) Unstructured Programming

In unstructured programs, the statements are executed in sequence (one after the other) as written. This type
of programming uses the GoTo statement which allows control to be passed to any other section in the
program. When a GoTo statement is executed, the sequence continues from the target of the GoTo. Thus, to
understand how a program works, you have to execute it. This often makes it difficult to understand the logic
of such a program.

b) Structured Programming

The approach was developed as a solution to the challenges posed by unstructured/procedural programming.
Structured programming frequently employs a top-down design model, in which developers break the
overall program structure into separate subsections. A defined function or set of similar functions is coded

Arthur Brice A
5
Structured Programming

in a separate module or sub-module, which means that code can be loaded into memory more efficiently
and that modules can be reused in other programs. After a module has been tested individually, it is then
integrated with other modules into the overall program structure.

Program flow follows a simple hierarchical model that employs looping constructs such as "for," "repeat,"
and "while." Use of the "GoTo" statement is discouraged.

Most programs will require thousands or millions of lines of code. (Windows 2000 – over 35 millions lines
of code). The importance of splitting a problem into a series of self-contained modules then becomes
obvious. A module should not exceed 100 lines, and preferably short enough to fit on a single page or screen.

Examples of structured programming languages include:

 C
 Pascal
 Fortran
 Cobol
 ALGOL
 Ada
 dBASE etc.

c) Object-oriented programming (OOP)

This is a programming paradigm that represents concepts as "objects" that have data fields
(attributes that describe the object) and associated procedures known as methods. Objects, which
are usually instances of classes, are used to interact with one another to design applications and
computer programs.

d) Visual Programming

A visual programming language uses a visual representation (such as graphics, drawings, animation
or icons, partially or completely). A visual language manipulates visual information or supports
visual interaction, or allows programming with visual expressions

A VPL allows programming with visual expressions, spatial arrangements of text and graphic
symbols, used either as elements of syntax or secondary notation. For example, many VPLs (known
as dataflow or diagrammatic programming) are based on the idea of "boxes and arrows", where
boxes or other screen objects are treated as entities, connected by arrows, lines or arcs which
represent relations. An example of visual programming languages is Microsoft Visual Basic which
was derived from BASIC and enables the rapid application development (RAD) of graphical user
interface (GUI) applications.

Programming in VB is a combination of visually arranging components or controls on a form,


specifying attributes and actions for those components, and writing additional lines of code for
more functionality.

e) Internet Based Programming

This is programming oriented to the development of internet applications using languages and tools

Arthur Brice A
6
Structured Programming

such as PHP, ASP, Perl, JavaScript, HTML, Java etc.

3. SOFTWARE CONSIDERATIONS

Before you can start programming in C, you will need text editor such as a plain text Notepad
Editor though it does not offer code completion or debugging. Many programmers prefer and
recommend using an Integrated Development Environment (IDE) instead of a text editor on which
to code, compile and test their programs.

Memory requirements

Disk space required

4. ADVANTAGES C LANGUAGE

1. Modularity: modularity is one of the important characteristics of C. we can split the C program
into no. of modules instead of repeating the same logic statements (sequentially). It allows
reusability of modules.

2. General purpose programming language: C can be used to implement any kind of applications
such as math‘s oriented, graphics, business oriented applications.

3. Portability: we can compile or execute C program in any operating system (UNIX, dos,
windows).

4. Powerful and efficient programming language: C is very efficient and powerful programming
language; it is best used for data structures and designing system software. Efficient in that it is a
modular programming language and thus makes efficient use of memory and system resources

Arthur Brice A
7
Structured Programming

MODULE 1 PROGRAMING LANGUAGES

Unit 1 Computer Programming

Unit 2 Characteristics of a Good Program

Unit 3 Phases of Program Development (Programming)

UNIT 1 COMPUTER PROGRAMMING

1.0 INTRODUCTION

A program is a finite set of sequenced instructions or commands given to a computer in order to


carry out a particular task. To write a program for the computer to carry out these instructions, there
must be a means of communication. Humans communicate via natural languages such as English,
French, Chinese etc. Likewise, to communicate with the computer, we also use languages known as
programming languages. Programming is the art of program writing using a particular programming
language. It can also be said to be the process of writing a set of instructions in sequential manner
using programming language to control the activity of a computer system. A computer
programming language is an artificial language which is used in writing a set of formal instructions
to control the activities of a computer system.

There are two main types of computer programming languages; these are: Low-level language and
High-level language. Low-level languages also known as machine language, are machine dependent
and makes fast and efficient use of the computer. It requires no translator to translate the code. It is
directly understood by the computer. On the contrary, writing a program in high-level language
does not require knowledge of the computer in which the program is run. Hence, high-level
languages are machine independent, and which programs are portable to other computers, and very
easy to learn and write.

2.0 INTENDED LEARNING OUTCOMES (ILOS)

By the end of this unit, you should be able to:

 Define programs and classify programming languages

 State the advantages and disadvantages of high- and low-level languages

3.0 MAIN CONTENTS

3.1 Classification of Programming Languages

There are two major types of computer programming languages: the low-level language and high-
level language.

3.2 Low level language

This type of language is closer to the machine compared with the human or natural language. The

Arthur Brice A
8
Structured Programming

two major examples are the Machine language and the Assembly language.

Machine Language: This is the only language computer understands. It is the native language of
the computer. The computer directly executes a program written in machine language. These
programs are coded using strings of 0‘s and 1‘s. It doesn‘t need a translator.

Advantages of Machine Language

 Machine language makes fast and efficient use of the computer.

 It requires no translator to translate the code. It is directly understood by the computer.

Disadvantages of Machine Language

 Very bulky.

 They require much time for writing and reading.

 They are prone to error which is difficult to detect and correct.

 Very difficult to learn.

 Can only run on the computer it is designed (i.e., it is machine dependent) Assembly Language:
Assembly Language uses MNEMONICS (symbols) to represent data and instructions. Such
program eliminates problems associated with machine language. Computer cannot execute directly
a program written in assembly language; it requires a translator called assembler. Assembler is a
special program designed to translate a program written in assembly language to a machine
language equivalent.

Advantages of Assembly Language

 It allows complex jobs to run in a simpler way.

 It is memory efficient, as it requires less memory.

 It is faster in speed, as its execution time is less.

 It is mainly hardware oriented.

 It requires less instruction to get the result.

 It is used for critical jobs.

Disadvantages of Assembly Language

 It is machine dependent; the programmer must be knowledgeable in both subject area and the
operations of the machine.

 It is cumbersome though less cumbersome than that of machine language.

Arthur Brice A
9
Structured Programming

 Very expensive to develop

 It consumes time

3.3 High Level Language

A high-level language is a problem-orientated programming language. The source programs are


written in human readable languages like English instead of mere symbols. In other words, a high-
level language is a convenient and simple means of describing the information structures and
sequences of actions required to perform a particular task. Advantages of High-Level Language

 No knowledge of the computer in which the program will be run is required

 The programs are portable

 Very easy to learn and write

Disadvantages of High-Level Language

 It takes additional translation times to translate the source to machine code.

 High level programs are comparatively slower than low level programs.

 Compared to low level programs, they are generally less memory efficient.

 Cannot communicate directly with the hardware

3.4 Features of High-Level Language

 Machine independent

 Problem oriented

 Ability to clearly reflect the structure of program written in it.

 Readability

 Programs are portable.

Examples of High-level Languages are FORTRAN, COBOL, QBASIC, VISUAL BASIC, JAVA,
PASCAL etc.

SELF-ASSESSMENT EXERCISE

Classify programming languages and explain the different categories Solution:

Programming languages are basically classified into two main categories, that is Low-level
language and High-level language. Every programming language belongs to one of these categories

Arthur Brice A
10
Structured Programming

and subcategory.

Low level languages: Low-level languages are used to write programs that relate to the specific
architecture and hardware of a particular type of computer. They are closer to the native language of
a computer (binary), making them harder for programmers to understand. Programs written in low-
level languages are fast and memory efficient. However, it is very difficult to write and debug and
maintain. It is equally difficult to read and understand. Low level program developers must be
acquainted with the particular machine architecture. Low level languages are subdivided into
Machine language and Assembly language.

Machine language: This is the native language of the computer. It consists of 0s and 1s. These 0s
and 1s (i.e., sequence of binary bits) constitutes a set of instructions that are directly executed by the
computer. Each instruction performs a very specific and small task. These instructions are machine
dependent and varies from computer to computer.

Assembly language: Assembly language uses mnemonics instead of bits. Assembly language
instructions interacts directly with the computer. Assembly language instructions are translated into
object code (i.e., specific machine code) by a special program known as assembler.

High-level languages are similar to the human or natural language. highlevel languages are
programmers friendly, easy to code, debug and maintain. It provides a higher level of abstraction
from machine language. They do not interact directly with the hardware. Rather, they focus more on
the complex arithmetic operations, optimal program efficiency and easiness in coding. Programs in
a high-level language are written using English statements (e.g., Pascal, Java, C, BASIC, etc.).
High-level programs require compilers/interpreters to translate source code to machine language.
We can compile the source code written in the high-level language to multiple machine languages.
Thus, they are machine independent language. High-level languages are grouped into two
categories based on the execution model – compiled or interpreted languages

3.0 CONCLUSION

This unit introduced the students to the basic knowledge of computer programming. It defined
computer program and discussed the two major classifications of programming languages (the low-
and high-level programming languages).

4.0 SUMMARY

A computer program is a set of instruction given to a computer to carry out a particular task.
Computer programs are written using programming languages. These languages can be classified
into low-level (i.e., machine and assembly languages) and high-level languages. Machine language
uses 0s and 1s while assembly uses mnemonics. The highlevel languages use mathematical symbols
in combination with Englishlike words. Both the low-level and high-level programming languages
have their advantages and disadvantages.

Arthur Brice A
11
Structured Programming

MODULE 2 ABSTRACTION AND MODULARITY

Unit 1 Introduction to Abstraction

Unit 2 Modular Programming

Unit 3 Modular Interface

UNIT 1 INTRODUCTION TO ABSTRACTION

1.0 INTRODUCTION

As programmers began to write instructions that were equivalent to a few bytes, the level of
thinking in terms of what the computer was doing on a functional level raised the level of
abstraction. Statements and structured code can be thought of as assembly language operations, at a
higher level of abstraction. Statements are collected to form functions, procedures, subroutines, or
methods. The abstraction or grouping code and its data structures is called object-oriented
programming.

2.0 INTENDED LEARNING OUTCOMES (ILOS)

By the unit of this unit, you should be able to:

 Describe functions and Procedures in program

 Illustrate a typical function structure for sorting numerical arrays in C language.

 Define a class in Object–oriented programming

 Explain the abstraction costs and benefits

3.0 MAIN CONTENTS

3.1 Abstraction

The history of programming has experienced rising levels of granularity. Decades ago,
programmers manipulated individual bits of codes. Then the assembly language was invented, and
programmers began to write instructions that were equivalent to a few bytes. The advantage was
clear: Instead of thinking in terms of essentially meaningless 1s and 0s, you could think in terms of
what the computer was doing on a functional level—move this value to that memory location,
multiply these two bytes together.

This is called raising the level of abstraction. Every time you raise the level of abstraction in a
programming language, you get more clearer, structured program (as measured in terms of bits) for

Arthur Brice A
12
Structured Programming

less work. The language at which you communicate with the computer can also be altered into
something closer to the way we communicate in English.

Each unit of the level of abstraction has a contract or agreement: The language makes an exact
promise of what the computer will do when the unit is executed. For the following assembly
language instruction: LD (BC), A

the language promises that it will move the value from the register named A into the place in
memory pointed to by registers B and C. Obviously, this is only a very small piece of what you
want the computer to do, such as word processing, video processing, etc. but it‘s a lot clearer and
easier to use than its binary equivalent: 00000010

It may not seem any shorter or easier to remember LD (BC), A; but each of the letters here has an
explicit and easily remembered meaning: LD is short for LOAD; A, B, and C refer to some
registers, and (BC) refers to a way to do indirection into memory. 00000010 may be just seven 0s
and a 1, but the order is both critical and hard to memorize. Swapping two of the bits to 00000100
means INC B (increment the B register), which is totally different.

3.2 Functions and Procedures

Statements and structured code can be thought of as assembly language operations, at a higher
level of abstraction. The next level of abstraction is to group statements into operational units with
contracts of their own. Statements are collected to form functions, procedures, subroutines, or
methods, as they are called in various languages. The beauty about functions is that they limit even
further the amount of code required to understand a piece of code.

A typical function structure for sorting a numerical array in C programming language, is given
below:

/** This function takes the array and returns a sorted version,

* removing duplicates. It may return the same array, or it

* may allocate a new one. If there are no duplicates, it'll

* probably return the old array. If there are, it'll have to

* create a new one. */

int[ ] sort(int[ ] array)

{ ... the body ...}

You can learn a lot about the function without even seeing the body. The name sort, and the fact
that it takes an array of integers and returns a (possibly different) array of integers, tell you a lot
about what the function is supposed to do. The rest of the contract is described in the comment,
which talks about other things such as memory allocation. That‘s even more important in C and
C++ than in Java, where it‘s often up to the contract to express who‘s responsible for freeing

Arthur Brice A
13
Structured Programming

memory allocated in the function.

The maintenance programmer‘s life is made simpler because the program is chopped up into these
functional units. A common rule is that a function should be only as long as a screenful of code.
That makes it possible to visualize, all at once, a complete, nameable, understandable unit of the
program you‘re maintaining. That rule turns out to be a little bit too strict, though.

The names of functions and procedures are a critical part of the abstraction. It takes a chunk of code
and allows you to refer to it later with a single word (or a short collection of words,
strungTogetherLikeThis or _like_this). This strategy focuses every line in the function on achieving
the goal with that name. Once the scope of your function grows beyond the name you‘ve assigned
to it, it‘s time to consider breaking the function into pieces with better names. If you find yourself
writing code like this:

void sortNamesAndSendEmail()

{ // Sort names ... Spend 100 lines sorting the names ...

// Send email . ..

Spend 500 lines sending out emails ...}

it‘s a good indicator that it‘s time to start breaking the function into pieces. In effect, you‘ll
probably write two functions:

sortNames()

sendEmail()

which allows you to eliminate the verbose and weird function name sortNamesAndSendEmail.

3.3 Classes

Structured programming and functions neatly solve some of the problems of maintenance by
limiting the amount of code you must look at in order to understand any given line. There‘s still one
way that faroff pieces of code can affect a particular line of code, however.

The sort example given earlier sorts only integers, which is not a particularly interesting job. Why
would you ever want to sort just a list of numbers? More likely, you want to be able to sort a list of
objects of some kind, based on an integer key. Or, more generally, you‘d like to be able to sort on
any key, so long as you can reliably compare any two objects.

Even before object-oriented programming, there were ways to group chunks of data into functional
units. In C, these units are called structs. However, structs don‘t have any reliable way to compare
them. You need some level of abstraction a little higher than provided by structs that allows you to
tell which of two structs should come first. The abstraction of grouping code and its data structures
is called objectoriented programming. The clump of code and data definitions is called a class in
most programming languages.

Arthur Brice A
14
Structured Programming

C++ is an object-oriented language. It provides a higher level of abstraction than C does. In general,
higher levels of abstraction come at a performance penalty, and many people criticize C++ for its
performance cost relative to C.

Java aims for an even higher level of abstraction than C++ by abstracting away access to locations
in memory. Though not the first language to do so (Lisp and Basic readily come to mind, among
generalpurpose programming languages), it probably has the highest market penetration.

And that level of abstraction also costs performance most of the time. Not always, of course. An
advantage to abstraction is that the intermediary translators are allowed to make any optimizations
they want, so long as they don‘t violate the contracts. The larger the program, the harder it is to
perform all the optimizations and still make the schedule. The longer a language has been around,
the more tricks the compiler writers learn for optimization. Increasingly, languages at higher levels
of granularity perform faster than those at lower levels. There‘s no way you could write a large
program for a Pentium processor and make it as efficient as the same program written in C; the
pipeline stalls would suck up all of your performance gains (even if you knew what they were).

3.4 Abstraction Costs and Benefits

In many software maintenance projects, the cost of the additional performance of low levels of
abstraction is far higher than the cost of the computer cycles that would be required to run the
program. As a maintenance programmer, your time is extremely expensive. The time of your users
is even more expensive (since there are usually more of them than there are for you), so correctness
of the program is key. If users lose work or time waiting for your software to be corrected, that
easily represents lots of money.

Higher levels of abstraction lead to improved maintenance, simply because there‘s less code. The
less code, the less you have to read to understand it. Certainly, there are limits to this, as 50 lines of
clear code is preferable to 10 lines of total obscurity. In general, however, by using higher levels of
abstraction, improved maintainability is gained. Of course, there‘s a downside to these higher levels
of abstraction in terms of performance. The more flexible a program is, the harder it is to optimize.
As a maintainer, you‘ll have to find the balance that works best. The old dictum of C.A.R. Hoare
that ―Premature optimization is the root of all evil‖ is particularly applicable to abstraction. Choose
your levels appropriately and optimize those parts that can‘t be made to function at the level of
abstraction you choose. The payoff is in programming time, both in development and maintenance,
and that makes users happy.

SELF –ASSESSMENT EXERCISE

i. What is Abstraction?

ii. Write a function to select the largest of 3 numbers

1) What is Abstraction?

Data abstraction is the reduction of a particular body of data to a simplified representation of the
whole. Abstraction, in general, is the process of refining or taking away or removing characteristics

Arthur Brice A
15
Structured Programming

from something in order to reduce it to a set of essential characteristics. Abstraction hides some
characteristics of a system leaving only the essential characteristics for reason of simplicity

2) Write a function to select the largest of 3 numbers

#include <stdio.h>

// function to find largest among three numbers

float large (float a, float b, float c)

{ if(a>=b && a>=c) return a;

else if(b>=a && b>=c) return b;

else return c; }

int main()

float num1, num2, num3, largest;

printf("Enter three numbers: ");

scanf("%f %f %f", &num1, &num2, &num3);

largest = large(num1, num2, num3);

printf("Largest number = %.2f",largest); return 0;

SUMMARY

Abstraction is having a global view of the programming task at hand. It hides details of the task.
Abstraction has it costs and benefits. Functions and procedures are ways of splitting a complex task
into smaller units or modules. This makes room for easy design and implementation a program.

Arthur Brice A
16
Structured Programming

UNIT 4 EXECUTING A C PROGRAM

1.0 INTRODUCTION

Program compilation and execution processes are divided into several steps, namely: preprocessing,
compilation, assembly, linking and loading. In each of these input and output are defined during the
compilation and execution process depending on the operating systems e.g., Linux.

2.0 INTENDED LEARNING OUTCOMES (ILOS)

By the end of this unit, you should be able to:

 Explain the processes involved in compilation and execution of C program.

 Describe the sample input/ output steps used in program compilation and execution.

3.0 MAIN CONTENTS

3.1 Compilation and Execution of a C Program

 The compilation and execution process of C can be divided into several steps:

 Preprocessing - Using a Preprocessor program to convert C source code in expanded source code.
"#includes" and "#defines" statements will be processed and replaced source codes in this step.

 Compilation - Using a Compiler program to convert C expanded source to assembly source code

 Assembly - Using an Assembler program to convert assembly source code to object code.

 Linking - Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.

 Loading - Using a Loader program to load the executable code into CPU for execution.

Sample I/O steps

Here is a simple table showing input and output of each step in the compilation and execution process:

Pictorial Diagram of C Compilation and Execution

A pictorial diagram showing the compilation and execution of a C program is shown following.

Arthur Brice A
17
Structured Programming

Arthur Brice A
18
Structured Programming

MODULE 3 INTRODUCTION TO C PROGRAMMING LANGUAGE

Unit 1 Element of C

Unit 2 Data Type

Unit 3 Variables, Statements, Expressions

Unit 1 Element of C

1.0 INTRODUCTION

Every language has some basic elements and grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language.

2.0 INTENDED LEARNING OUTCOMES (ILOS)

By the end of this unit, you should be able to:

 List the character set in C

 Apply the character set in constructing variables and identifiers

 Differentiate between a variable and a keyword

3.0 MAIN CONTENT

Elements of C Every language has some basic elements and grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.

3.1 Character Set

Communicating with a computer involves speaking the language the computer understands. In C,
various characters have been given to communicate. Character set in C consists of:

3.2 Keywords

Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the computer. There are 32 keywords available in
C. The figure gives a list of these keywords for your ready reference.

Arthur Brice A
19
Structured Programming

SELF-ASSESSMENT EXERCISE

i. What are the character sets used C programming language? Put your response in a tabular
format.
ii. ii. List at least 10 key words used in C programming language.

Solution 1. What are the character set used C programming language? Put your response in a
tabular format.

2. List at least 10 key words used in C programming language. The following are some of the key
words used in C programming language: auto, signed, const, extern, register, unsigned, return,
continue, enum, sizeof, struct, typedef, union, etc.

Arthur Brice A
20
Structured Programming

UNIT 2 DATA TYPE

1.0 INTRODUCTION
A data type defines a set of values and the operations that can be defined on those values. Data
types are especially important in C programming language All operations are type checked by
the compiler for type compatibility. Illegal operations will not be compiled. Thus, strong type
checking helps prevent errors and enhances reliability.

2.0 INTENDED LEARNING OUTCOMES (ILOS)


By the end of this unit, you should be able to:

the rules for constructing real constants expressed in

exponential form

3.0 MAIN CONTENT

3.1 Data Types


In the C programming language, data types refer to a domain of allowed values and the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are 4
fundamental data types in C, which are- char, int, float and, double. Char is used to store any single
character; int is used to store any integer value, float is used to store any single precision floating
point number and double is used to store any double precision floating point number. We can
use 2 qualifiers with these basic types to get more types.

There are 2 types of qualifiers

- signed & unsigned

- short & long

The data types in C can be classified as follows:

Arthur Brice A
21
Structured Programming

3.2 Constants
A constant is an entity that doesn‘t change whereas a variable is an entity that may
change. C constants can be divided into two major categories:

Here our only focus is on primary constant. For constructing these different types of
constants certain rules have been laid down.

3.3 Rules for Constructing Integer Constants


o An integer constant must have at least one digit.

o It must not have a decimal point.

Arthur Brice A
22
Structured Programming

o It can be either positive or negative.

o If no sign precedes an integer constant it is assumed to be positive.

o No commas or blanks are allowed within an integer constant.

o The allowable range for integer constants is -32768to 32767.

o Eg.: 426, +782,-8000, -7605

3.4 Rules for Constructing Real Constants

ten in two forms Fractional form and Exponential form.

Rules for constructing real constants expressed in fractional form:

- A real constant must have at least one digit.


- It must have a decimal point.
- It could be either positive or negative.
- Default sign is positive.
- No commas or blanks are allowed within a real constant.
- Ex. +325.34, 426.0, -32.76, -48.5792

3.5 Rules for constructing real constants expressed in exponential form


o The mantissa part and the exponential part should be separated by a letter e. b) The mantissa part
may have a positive or negative sign.

o Default sign of mantissa part is positive.

o The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.

o Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

o Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5

3.6 Rules for Constructing Character Constants

special symbol enclosed within single inverted commas.

um length of a character constant can be 1 character.

Arthur Brice A
23
Structured Programming

SELF-ASSESSMENT EXERCISE

i. Differentiate between a variable and a constant in C programs

ii. What are the rules for constructing an integer constant?

Solution:

1. Differentiate between a variable and a constant in C programs

A variable is a programming element that can change during program execution where as
constant do not change.

2. What are the rules for constructing an integer constant?

An integer constant must have at least one digit.

positive.

constant.

for integer constants is -32768to

32767.

-8000, -7605

4.0 CONCLUSION
Data types in C programming language refer to a domain of allowed values and the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are four
fundamental data types in C, which are- char, int, float and double. Char is used to store any
single character; int is used to store any integer value, float is used to store any single precision
floating point number and double is used to store any double precision floating point number.

5.0 SUMMARY

Arthur Brice A
24
Structured Programming

In this unit, you have learnt about C data types which include char, int, float and double. You have
also learnt about the various classifications of these data types as well as constant and the rules for
constructing the various constants.

UNIT 3 VARIABLES, STATEMENTS, EXPRESSIONS

1.0 INTRODUCTION

A variable is the name given to a memory location that allows values to be stored in
those locations. When declaring variables, the type of value or data to be stored is
also indicated. A statement is an executable instruction given to the computer
to execute. An expression is a combination of operands, operators and constant
for the purpose of evaluation.

2.0 INTENDED LEARNING OUTCOMES (ILOS)


By the end of this unit, you should be able to:

exponential form

3.1 Variables and Variable Declaration


Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. When
you decide your program needs another variable, you simply declare (or define) a new
variable and C makes sure you get it. You declare all C variables at the top of whatever blocks of
code need them. Variable declaration requires that you inform C of the variable's name and data
type.

Syntax: datatype variablename;

Arthur Brice A
25
Structured Programming

Eg:

int page_no;

char grade;

float salary;

long y;

There are two places where you can declare a variable:

code (usually at the top of a function)

Before a function name (such as before main() in the program)

Consider various examples:

Suppose you had to keep track of a person's first, middle, and last initials. Because an initial
is obviously a character, it would be prudent to declare three character variables to hold the three
initials. In C, you could do that with the following statement:

1. main()

char first, middle, last;

// Rest of program follows

2. main()

char first;

char middle;

char last;

// Rest of program follows

3.2 Initialization of Variables


When a variable is declared, it contains undefined value commonly known as garbage value.
If we want, we can assign some initial value to the variables during the declaration itself. This is
called initialization of the variable.

Arthur Brice A
26
Structured Programming

Eg.,

int pageno=10;

char grade=‟A‟;

float salary= 20000.50;

3.3 Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:

a+b – arithmetic operation

a>b- relational operation

a == b – logical operation

func (a,b) – function call

4+21

a*(b + c/d)/20

q = 5*2

x = ++q % 3

q > 3

As you can see, the operands can be constants, variables, or combinations of the two. Some
expressions are combinations of smaller expressions, called sub-expressions. For example, c/d is a
sub-expression of the sixth example.

An important property of C is that every C expression has a value. To find the value, you perform
the operations in the order dictated by operator precedence.

3.4 Statements
Statements are the primary building blocks of a program. A program is a series of statements with
some necessary punctuation. A statement is a complete instruction to the computer. In C, statements
are indicated by a semicolon at the end. Therefore

legs = 4

is just an expression (which could be part of a larger expression), but,

legs = 4;

is a statement. What makes a complete instruction? First, C considers any expression to be a

Arthur Brice A
27
Structured Programming

statement if you append a semicolon. (These are called expression statements.) Therefore, C won't
object to lines such as the following:

8;

3 + 4;

However, these statements do nothing for your program and can't really be considered sensible
statements. More typically, statements change values and call functions:

x = 25;

++x;

y = sqrt(x);

Although a statement (or, at least, a sensible statement) is a complete instruction, not all
complete instructions are statements. Consider the following statement:

x = 6 + (y = 5);

In it, the subexpression y = 5 is a complete instruction, but it is only part of the statement.
Because a complete instruction is not necessarily a statement, a semicolon is needed to
identify instructions that truly are statements.

3.5 Compound Statements (Blocks)


A compound statement is two or more statements grouped together by enclosing them in braces; it
is also called a block. The following while statement contains an example:

while (years < 100)

wisdom = wisdom * 1.05;

printf("%d %d\n", years, wisdom);

years = years + 1;

If any variable is declared inside the block, then it can be declared only at the beginning of the
block. The variables that are declared inside a block can be used only within the block.

3.6 Input-Output in C
When we are saying Input that means we feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement. When we are saying
Output that means to display some data on screen, printer or in any file. C programming language

Arthur Brice A
28
Structured Programming

provides a set of built-in functions to output the data on the computer screen. Functions printf()
and scanf() are the most commonly used to display out and take input respectively.

Let us consider an example:

#include <stdio.h> //This is needed to run printf() function.

int main()

printf("C Programming"); //displays the content inside quotation

return 0;

Output:

C Programming

Explanation:

main() function.

printf() is a library function to display output which only works if #include<stdio.h>


is included at the beginning.

stdio.h is a header file (standard input output header file) and #include is
command to paste the code from the header file when necessary. When compiler encounters
printf() function and doesn't find stdio.h header file, compiler shows error.

return 0; indicates the successful execution of the program.

3.7 Input-Output of integers in C


#include<stdio.h>

int main()

int c=5;

printf("Number=%d",c);

return 0;

Arthur Brice A
29
Structured Programming

Output:

Number = 5

Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this
conversion format string matches with remaining argument, i.e, c in this case, value of c is
displayed.

#include<stdio.h>

int main()

int c;

printf("Enter a number\n");

scanf("%d",&c);

printf("Number=%d",c);

return 0;

Output:

Enter a number

Number=4

The scanf() function is used to take input from user. In this program, the user is asked an input
and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and value is
stored in that address.

3.8 Input-Output of floats in C


#include <stdio.h>

int main()

float a;

Arthur Brice A
30
Structured Programming

printf("Enter value: ");

scanf("%f",&a);

printf("Value=%f",a); //%f is used for floats instead of %d

return 0;

Output

Enter value:

23.45

Value=23.450000

Conversion format string "%f" is used for floats to take input and to display floating value
of a variable.

3.9 Input-Output of characters and ASCII code


#include <stdio.h>

int main()

char var1;

printf("Enter character: ");

scanf("%c",&var1);

printf("You entered %c.",var1);

return 0;

Output

Enter character:

You entered g.

Conversion format string "%c" is used in case of characters.

3.10 ASCII code


When character is typed in the above program, the character itself is not recorded a numeric value
(ASCII value) is stored. And when we displayed that value by using "%c", that character is

Arthur Brice A
31
Structured Programming

displayed.

#include <stdio.h>

int main()

char var1;

printf("Enter character: ");

scanf("%c",&var1);

printf("You entered %c.\n",var1);

/* \n prints the next line(performs work of enter). */

printf("ASCII value of %d",var1);

return 0;

Output:

Enter character:

103

When, 'g' is entered, ASCII value 103 is stored instead of g.

You can display character if you know ASCII code only. This is shown by following example.

#include <stdio.h>

int main()

int var1=69;

printf("Character of ASCII value 69: %c",var1);

return 0;

Output

Character of ASCII value 69:

Arthur Brice A
32
Structured Programming

The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly, ASCII value of 'a' is 97, 'b' is
98 and so on to 'z' is 122.

SELF-ASSESSMENT EXERCISE
i. What is a Variable?

ii. Declare a variable for each of the following C data type: integer,

float, double, and character and assign appropriate data value at

the pointer of declaration

iii. What is a statement? Give few examples.

iv. What is an Expression? Give few examples.

v. Write a program to display the upper- and lower-case letter ―B‖,

using two printf() function

Solution
1 What is a Variable? Give few meaningful examples

Variable is basically a name of a memory location that we use for storing data. We can change the
value of a variable in C or any other language, and we can also reuse it multiple times.

Examples:

rate

salary

product

2 Declare a variable for each of the following C data type: integer, float, double, and character
and assign appropriate data value at the pointer of declaration.

int num = 76;

float = height 4.6;

double amount = 34456677.55;

char singleChar = „a‟;

3 What is a statement? Give few examples.


A statement is a command given to the computer that instructs the computer to take a

Arthur Brice A
33
Structured Programming

specific action, such as display to the screen, or collect input or evaluate an expression. A
computer program is made up of a series of statements.

Examples:

area =length * breadth;

printf (“Structured Programming”);

scanf("%d",&c);

4 What is an expression? Give few examples.


An expression is a combination of operators, operands and/or constants which reduces to a
single value. An operation is performed on a data item which is called an operand. An operator
indicates an operation to be performed on data.

Example:

simpleInt = (principal * time * rate)/100;

sum = num1 + num2;

z = (4 + (4%2)/ 3);

5 Write a program to display the upper- and lower-case letter ―B‖. use two printf () function

#include <stdio.h>

int main()

int var1=66;

int var2=98;

printf("Character of ASCII value 66: %c",var1);

printf("Character of ASCII value 98: %c",var2);

return 0;

4.0 CONCLUSION

A variable is the name given to a memory location that allows values to be stored in those locations.
When declaring variables, the type of value or data to be stored is also indicated. A statement
is an executable instruction given to the computer to execute. An expression is a
combination of operands, operators and/or constant for the purpose of evaluation.

Arthur Brice A
34
Structured Programming

5.0 SUMMARY
In this unit, you have learned about variables, statements and expressions. You have also
learnt how variables are declared and initialized, how expressions are constructed, and what
constitutes a statement including compound statements. All these are well illustrated with
examples.

UNIT 4 FORMATTED INPUT-OUTPUT

1.0 INTRODUCTION
Normally printf() method display output on the screen in an unpleasant and undesirable
manner. It therefore implies that the programmer must format the output to suit his requirements.
For example, he must specify how many places of decimal are required, the space between
two outputs, etc.

2.0 INTENDED LEARNING OUTCOMES (ILOS)


By the end of this unit, you should be able to:

3.0 MAIN CONTENT

3.1 Formatted Input-Output


Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.

3.2 Variations in Output for integer and floats


#include<stdio.h>

int main()

printf("Case 1:%6d\n",9876);

Arthur Brice A
35
Structured Programming

/* Prints the number right justified within 6 columns */

printf("Case 2:%3d\n",9876);

/* Prints the number to be right justified to 3 columns


but, there are 4

digits so number is not right justified */

printf("Case 3:%.2f\n",987.6543);

/* Prints the number rounded to two decimal places */

printf("Case 4:%.f\n",987.6543);

/* Prints the number rounded to 0 decimal place, i.e,


rounded to integer

*/

printf("Case 5:%e\n",987.6543);

/* Prints the number in exponential notation (scientific


notation) */

return 0;

Output
Case 1: 9876

Case 2:9876

Case 3:987.65

Case 4:988

Case 5:9.876543e+002

3.3 Variations in Input for integer and floats


#include <stdio.h>

int main()

Arthur Brice A
36
Structured Programming

int a,b;

float c,d;

printf("Enter two intgers: ");

/*Two integers can be taken from user at once as below*/

scanf("%d%d",&a,&b);

printf("Enter integer and floating point numbers: ");

/*Integer and floating point number can be taken at once


from user as

below*/

scanf("%d%f",&a,&c);

return 0;

Similarly, any number of inputs can be taken at once from


user.

SELF-ASSESSMENT EXERCISE

1. To print out a and b given below, which of the following printf() statement
or statement will you use?
#include<stdio.h>

float a=3.14;

double b=3.14;

A. printf("%f %lf", a, b);

B. printf("%Lf %f", a, b);

C. printf("%Lf %Lf", a, b);

D. printf("%f %Lf", a, b);

Arthur Brice A
37
Structured Programming

2. To scan a and b given below, which of the following scanf()

statement will you use?

#include<stdio.h>

float a;

double b;

A. scanf("%f %f", &a, &b);

B. scanf("%Lf %Lf", &a, &b);

C. scanf("%f %Lf", &a, &b);

D. scanf("%f %lf", &a, &b);

3. For a typical program, the input is taken using.


A. scanf

B. Files

C. Command-line

D. None of the mentioned

4. What is the output of this C code?


#include <stdio.h>

int main()

int i = 10, j = 2;

printf("%d\n", printf("%d %d ", i, j)); }

A. Compile time error

B. 10 2 4

C. 10 2 2

D. 10 2 5

Arthur Brice A
38
Structured Programming

5. What is the output of this C code?


#include <stdio.h>

int main()

int i = 10, j = 3;

printf("%d %d %d", i, j); }

A. Compile time error

B. 10 3

C. 10 3 some garbage value

D. Undefined behavior

Solution
1. A and D

2. C and D

3. D

4. A

5. C

4.0 CONCLUSION

Using the printf() function you can output your result, display the output in a
desirable format. It therefore becomes imperative that the programmer formats
the output to his desired format. This is achieved via some format specifications.

5.0 SUMMARY

In this unit, you have learnt how to format your output to your desired format. You
have also learnt the variations in output for integer and floats as well as the
variations in input for integer and floats.

Arthur Brice A
39
Structured Programming

MODULE 4 OPERATORS AND CONTROL

STATEMENTS

Unit 1 Operators

Unit 2 Overview of Control Statements

UNIT 1 OPERATORS

1.0 INTRODUCTION
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C language is rich in built-in operators and provides the following types
of operators:

Operators Precedence in C

2.0 INTENDED LEARNING OUTCOMES (ILOS)


By the end of this unit, you should be able to:

Arthur Brice A
40
Structured Programming

3.0 MAIN CONTENT


3.1 Arithmetic operators

These are used to perform mathematical calculations like addition, subtraction,


multiplication, division and modulus. The following table shows all the arithmetic
operators supported by C language. Assume variable A holds 10 and variable B holds
20 then:

3.2 Relational Operators:

These operators are used to compare the value of two variables. Following table
shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 20, then:

Arthur Brice A
41
Structured Programming

3.3 Logical Operators:


These operators are used to perform logical operations on the given two variables.

The following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:

3.4 Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are used
in bit level programming. These operators can operate upon int and char but not on float and

Arthur Brice A
42
Structured Programming

double.

Showbits( ) function can be used to display the binary representation of any integer or character
value.

Bit wise operators in C language are; & (bitwise AND), | (bitwise OR),

~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).

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

The Bitwise operators supported by C language are explained in the following table. Assume
variable A holds 60 (00111100) and variable B holds 13 (00001101), then:

Arthur Brice A
43
Structured Programming

3.5 Assignment Operators:


In C programs, values for the variables are assigned using assignment operators.

There are following assignment operators supported by C language:

Arthur Brice A
44
Structured Programming

3.6 Increment and Decrement Operators


In C, ++ and – are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and –
subtracts 1 to operand respectively. For example:

Let a=5 and b=10

a++; //a becomes 6

a--; //a becomes 5

Arthur Brice A
45
Structured Programming

++a; //a becomes 6

--a; //a becomes 5

When i++ is used as prefix(like: ++var), ++var will increment the value

of var and then return it but, if ++ is used as postfix(like: var++),

operator will return the value of operand first and then only increment it.

This can be demonstrated by an example:

#include <stdio.h>

int main()

int c=2,d=2;

printf(“%d\n”,c++); //this statement displays 2 then, only c


incremented

by 1 to 3.

Printf(“%d”,++c); //this statement increments 1 to c


then, only c is

displayed.

Return 0;

Output
2

3.7 Conditional Operators (?)


Conditional operators are used in decision making in C programming, i.e., executes different
statements according to test condition whether it is either true or false.

Syntax of conditional operators: conditional_expression?expression1:expression2

If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false
expression2 is returned.

Arthur Brice A
46
Structured Programming

Let us understand this with the help of a few examples:

int x, y;

scanf ( “%d”, &x ) ;

y = ( x> 5 ? 3 : 4 ) ;

This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

The equivalent if statement will be,

if ( x > 5 )

y = 3;

else

y = 4;

3.8 Misc Operators


There are few other operators supported by c language.

3.9 Operators Precedence in C


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operatorhas higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated
first.

Arthur Brice A
47
Structured Programming

SELF-ASSESSMENT EXERCISE
i. What are the operators used in C programming language?

ii. What will be the value of y, given x is equals 9.

{int x, y;

scanf ( ―%d‖, &x ) ;

y = ( x> 5 ? 1 : 4 ) ; }

3. Given the mathematical expression: S + 3 x Y – 1, where S = 5 and Y = 34. Reconstruct the


expression in C format and evaluate it. Reconstruct the express such that the result will be 271

Solution
1. What are the operators used in C programming language?

The following are the operators used in C:

2, What will be the value of y, given x is equals 9.

{int x, y;

scanf ( ―%d‖, &x ) ;

y = ( x> 5 ? 1 : 4 ) ; }

The value of y will be 1

3. Given the mathematical expression: S + 3 x Y – 1, where S = 5 and

Y = 34. Reconstruct the expression in C format and evaluate it.

Reconstruct the express such that the result will be 271

Arthur Brice A
48
Structured Programming

S + 3 x Y – 1 => S + 3*Y -1

5+ 3*34 -1

107 – 1

106

(S + 3)* Y – 1

(5 + 3) *34 – 1

8 * 34 – 1

272 – 1

271

4.0 CONCLUSION
Operators are symbols or special characters used to perform mathematical, logical, relational
as well as bitwise manipulations. This also includes assignment operators used in assigning values
to variables.

5.0 SUMMARY
In this unit, you have been exposed to the operators used in C programs. This includes
mathematical, logical, relational, bitwise, assignment, increment and decrement operators etc.
These operators are used to manipulate data. The details of these operators are adequately
discussed within the unit.

Arthur Brice A
49
Structured Programming

UNIT 2 OVERVIEW OF CONTROL STATEMENTS

1.0 INTRODUCTION
C programming language has basically three control structures which make C qualify as a
structured programming language. These structures include sequence, selection and repetition
structure. Normally programming are executed sequentially but the last two structures i.e.
selection and repetition allow the sequence to be broken. That is the sequence of execution
is transferred a different line or block of code. These structures will be examined in more
details in this module.

2.0 INTENDED LEARNING OUTCOMES (ILOS)


By the of this unit, you should be able to:

3.0 MAIN CONTENT


In C, programs are executed sequentially in the order of which they appear. This condition
does not hold true always. Sometimes a situation may arise where we need to execute a certain part
of the program. Also, it may happen that we may want to execute the same part more than
once. Control statements enable us to specify the order in which the various instructions in
the program are to be executed. They define how the control is transferred to other parts of the
program. Control statements are classified in the following ways:

Arthur Brice A
50
Structured Programming

3.1 Selection Statements


The selection statements are also known as Branching or Decision Control Statements.
Sometimes we come across situations where we have to make a decision. E.g., If the weather is
sunny, I will go out and play, else I will be at home. Here my course of action is governed by the
kind of weather. If it‘s sunny, I can go out and play, else I have to stay indoors. I choose an option
out of 2 alternate options. Likewise, we can find ourselves in situations where we have to
select among several alternatives. We have decision control statements to implement this
logic in computer programming.

The programmer therefore specifies one or more conditions to be evaluated or tested by the
program, along with a statement or statements to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is determined to be
false.

3.1.1 If Statement
The keyword if tells the compiler that what follows is a decision control instruction. The if
statement allows us to put some decision -making into our programs. A flowchart illustrating the
general form of the if statement is shown below:

Arthur Brice A
51
Structured Programming

Fig 2: if statement construct

Syntax of if statement:

if (condition )

Statement 1;

Statement 2;

…………..

…………..

…………..

Statement n;

//Rest of the code

If the condition is true(nonzero), the statement will be executed. If the condition is false(0), the
statement will not be executed. For example, suppose we are writing a billing program.

if (total_purchase>=1000)

printf("You are gifted a pen drive.\n");

Arthur Brice A
52
Structured Programming

Multiple statements may be grouped by putting them inside curly braces {}. For example:

if (total_purchase>=1000)

gift_count++;

printf("You are gifted a pen drive.\n");

For readability, the statements enclosed in {} are usually indented. This allows the programmer to
quickly tell which statements are to be conditionally executed. As we will see later, mistakes in
indentation can result in programs that are misleading and hard to read.

Programs:

1. Write a program to print a message if negative no is entered.

#include<stdio.h>

int main()

int no;

printf("Enter a no : ");

scanf("%d", &no);

if(no<0)

printf("no entered is negative");

no = -no;

printf("value of no is %d \n",no);

return 0;

Output:

Enter a no: 6

Arthur Brice A
53
Structured Programming

value of no is 6

Output:

Enter a no: -2

value of no is 2

2. Write a program to perform division of 2 nos

#include<stdio.h>

int main()

int a,b;

float c;

printf("Enter 2 nos : ");

scanf("%d %d", &a, &b);

if(b == 0)

printf("Division is not possible");

c = a/b;

printf("quotient is %f \n",c);

return 0;

Output:

Enter 2 nos:

6 2

quotient is 3

Output: Enter 2 nos:

6 0

Division is not possible

Arthur Brice A
54
Structured Programming

3.1.2 If-else Statement


The if statement by itself will execute a single statement, or a group of statements, when the
expression following if evaluates to true. By using else we execute another group of statements if
the expression evaluates to false.

if (a > b)

z = a;

printf(“value of z is :%d”,z);

else

z = b;

printf(“value of z is :%d”,z);

The group of statements after the if is called an ‗if block‘. Similarly, the statements after the else
form the ‗else block‘.

Programs:

3. Write a program to check whether the given no is even or odd

#include<stdio.h>

int main()

int n;

printf("Enter an integer\n");

scanf("%d",&n);

if ( n%2 == 0 )

printf("Even\n");

else

printf("Odd\n");

Arthur Brice A
55
Structured Programming

return 0;

Output: Enter an integer 3

Odd

Output: Enter an integer 4

Even

4. Write a program to check whether a given year is leap year or


not

#include <stdio.h>

int main()

int year;

printf("Enter a year to check if it is a leap year\n");

scanf("%d", &year);

if ( (year%4 == 0) && (( year%100 != 0) || ( year%400 == 0 ))

printf("%d is a leap year.\n", year);

else

printf("%d is not a leap year.\n", year);

return 0;

Output:
Enter a year to check if it is a leap year 1996

1996 is a leap year

Output: Enter a year to check if it is a leap year 2015

2015 is not a leap year

else-if Statement
This sequence of if statements is the most general way of writing a multi−way decision.
The expressions are evaluated in order; if an expression is true, the statement associated with it

Arthur Brice A
56
Structured Programming

is executed, and this terminates the whole chain. As always, the code for each statement is
either a single statement, or a group of them in braces.

if (expression)

statement

else if (expression)

statement

else if (expression)

statement

else if (expression)

statement

else

statement

The last else part handles the ``none of the above'' or default case where none of the other
conditions is satisfied. Sometimes there is no explicit action for the default; in that case the trailing
can be omitted, or it may be used for error checking to catch an ―impossible‖ condition.

Program

6. The above program can be used as an e.g., here.

#include <stdio.h>

int main()

int m=40,n=20;

if (m>n)

printf("m is greater than n");

else if(m<n)

Arthur Brice A
57
Structured Programming

printf("m is less than n");

else

printf("m is equal to n");

Output:

m is greater than n

3.1.3 Nested if-else

An entire if-else construct can be written within either the body of the if statement or the body of an
else statement. This is called ‗nesting‘ of ifs.

This is shown in the following structure.

if (n > 0)

if (a > b)

z = a;

else

z = b;

The second if construct is nested in the first if statement. If the condition in the first if statement
is true, then the condition in the second if statement is checked. If it is false, then the else
statement is executed.

Program:

5. Write a program to check for the relation between 2 nos

#include <stdio.h>

int main()

Arthur Brice A
58
Structured Programming

int m=40, n=20;

if ((m >0 ) && (n>0))

printf("nos are positive");

if (m>n)

printf("m is greater than n");

else

printf("m is less than n");

else

printf("nos are negative");

return 0;

Output

40 is greater than 20

3.1.4 Switch Case


This structure helps to make a decision from the number of choices. The switch statement is a
multi−way decision that tests whether an expression matches one of a number of constant
integer values, and branches accordingly.

switch( integer expression)

Arthur Brice A
59
Structured Programming

case constant 1 : do this;

case constant 2 : do this ;

case constant 3 : do this ;

default : do this ;

The integer expression following the keyword switch is any C expression that will yield an
integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an
integer. If a case matches the expression value, execution starts at that case. All case expressions
must be different. The case labelled default is executed if none of the other cases are satisfied.
A default is optional; if it isn't there and if none of the cases match, no action at all takes place.
Cases and the default clause can occur in any order.

Consider the following program:

main( )

int i = 2;

switch ( i )

case 1:

printf ( "I am in case 1 \n" ) ;

case 2:

printf ( "I am in case 2 \n" ) ;

case 3:

printf ( "I am in case 3 \n" ) ;

default :

printf ( "I am in default \n" ) ;

The output of this program would be:

I am in case 2

Arthur Brice A
60
Structured Programming

I am in case 3

I am in default

Here the program prints case 2 and 3 and the default case. If you want that only case 2 should get
executed, it is up to you to get out of the switch then and there by using a break statement.

main( )

int i = 2 ; switch ( i )

case 1:

printf ( "I am in case 1 \n" ) ;

break ;

case 2:

printf ( "I am in case 2 \n" ) ;

break ;

case 3:

printf ( "I am in case 3 \n" ) ;

break ;

default:

printf ( "I am in default \n" ) ;

The output of this program would be:

I am in case 2

Program

7. Write a program to enter a grade and check its corresponding remarks.

#include <stdio.h>

int main ()

Arthur Brice A
61
Structured Programming

char grade;

printf(“Enter the grade”);

scanf(“%c”, &grade);

switch(grade)

case 'A' : printf("Outstanding!\n" );

break;

case 'B' :

printf("Excellent!\n" );

break;

case 'C' : printf("Well done\n" );

break;

case 'D' : printf("You passed\n" );

break;

case 'F' : printf("Better try again\n" );

break;

default : printf("Invalid grade\n" );

printf("Your grade is %c\n", grade );

return 0;

Output

Enter the grade

Excellent

Your grade is B

Arthur Brice A
62
Structured Programming

3.2 Iterative Statements

3.2.1 while statement

The while statement is used when the program needs to perform repetitive tasks. The general
form of a while statement is:

while ( condition)

statement ;

The program will repeatedly execute the statement inside the while until the condition becomes
false(0). (If the condition is initially false, the statement will not be executed.)

Consider the following program:

main( )

int p, t, count;

float r, si;

count = 1;

while ( count <= 3 )

printf ( "\nEnter values of p, t and r " ) ;

scanf(“%d %d %f", &p, &t, &r ) ;

si=p * t * r / 100;

printf ( "Simple interest = N. %f", si ) ;

count = count+1;

Some outputs of this program:

Enter values of p, t and r 1000000 5 13.5

Simple Interest = N. 675000.000000

Enter values of p, t and r 2000000 5 13.5

Simple Interest = N. 1350000.000000

Arthur Brice A
63
Structured Programming

Enter values of p, t and r 3500000 5 13.5

Simple Interest = N. 612000.000000

The program executes all statements after the while 3 times. These statements form what is
called the ‗body‘ of the while loop. The parentheses after the while contain a condition. As long
as this condition remains true all statements within the body of the while loop keep getting
executed repeatedly.

Consider the following program;

/* This program checks whether a given number is a palindrome or


not

*/

#include <stdio.h>

int main()

int n, reverse = 0, temp;

printf("Enter a number to check if it is a palindrome or not\n");

scanf("%d",&n);

temp = n;

while( temp != 0 )

reverse = reverse * 10;

reverse = reverse +temp%10;

temp = temp/10;

if ( n == reverse )

printf("%d is a palindrome number.\n", n);

else

printf("%d is not a palindrome number.\n", n);

return 0;

Arthur Brice A
64
Structured Programming

Output:

Enter a number to check if it is a palindrome or not

12321

12321 is a palindrome

Enter a number to check if it is a palindrome or not

12000

12000 is not a palindrome

3.2.2 do-while Loop


The body of the do-while executes at least once. The do-while structure is similar to the while loop
except the relational test occurs at the bottom (rather than top) of the loop. This ensures that
the body of the loop executes at least once. The do-while tests for a positive relational test; that
is, as long as the test is True, the body of the loop continues to execute.

The format of the do-while is

do

block of one or more C statements;

} while (test expression)

The test expression must be enclosed within parentheses, just as it does with a while statement.

Consider the following program

// C program to add all the numbers entered by a user until user


enters 0.

#include <stdio.h>

int main()

int sum=0,num;

do

/* Codes inside the body of do...while loops are at least executed

Arthur Brice A
65
Structured Programming

once.

*/

printf("Enter a number\n");

scanf("%d",&num);

sum+=num;

} while(num!=0);

printf("sum=%d",sum);

return 0;

Output:
Enter a number

Enter a number

-2

Enter a number

sum=1

Consider the following program:

#include <stdio.h> main()

int i = 10;

do

printf("Hello %d\n", i );

i = i -1;

Arthur Brice A
66
Structured Programming

}while ( i> 0 ); }

Output

Hello 10

Hello 9

Hello 8

Hello 7

Hello 6

Hello 5

Hello 4

Hello 3

Hello 2

Hello 1

Program

8. Program to count the no of digits in a number

#include <stdio.h>

int main()

int n,count=0;

printf("Enter an integer: ");

scanf("%d", &n);

do

n/=10;

/* n=n/10 */

count++;

} while(n!=0);

Arthur Brice A
67
Structured Programming

printf("Number of digits: %d",count);

Output

Enter an integer: 34523

Number of digits: 5

3.2.3 for Loop

The for is the most popular looping instruction. The general form of for statement is
shown below:

for ( initialize counter ; test counter ; Updating counter )

do this;

and this;

and this;

The for keyword allows us to specify three things about a loop in a single
line:

mine whether its value has reached the


number of repetitions desired.

counter either increment or decrement.

Consider the following program


int main(void)

int num;

printf(" n n cubed\n");

Arthur Brice A
68
Structured Programming

for (num = 1; num <= 6; num++)

printf("%5d %5d\n", num, num*num*num);

return 0;

The program prints the integers 1 through 6 and their cubes.


n n cubed

1 1

2 8

3 27

4 64

5 125

6 216
The first line of the for loop tells us immediately all the information about the loop
parameters: the starting value of num, the final value of num, and the amount that num increases on
each looping Grammatically, the three components of a for loop are expressions. Any of the three
parts can be omitted, although the semicolons must remain.

Consider the following program:

main( )

int i ;

for ( i = 1 ; i<= 10 ; )

printf ( "%d\n", i ) ;

i = i + 1 ;

Here, the increment is done within the body of the for loop and not in the for statement. Note that

Arthur Brice A
69
Structured Programming

in spite of this the semicolon after the condition is necessary.

Programs:

9. Program to print the sum of the first N natural numbers.

#include <stdio.h>

int main()

int n, i, sum=0;

printf("Enter the limit: ");

scanf("%d", &n);

for(i=1;i<=n;i++)

sum = sum +i;

printf("Sum of N natural numbers is: %d",sum);

Output
Enter the limit: 5 Sum of N natural numbers is 15.

10. Program to find the reverse of a number

#include<stdio.h>

int main()

int num,r,reverse=0;

printf("Enter any number: ");

scanf("%d",&num);

for(num!=0;num=num/10)

r=num%10;

Arthur Brice A
70
Structured Programming

reverse=reverse*10+r;

printf("Reversed of number: %d",reverse);

return 0;

Output:

Enter any number: 123

Reversed of number: 321

3.2.4 Nesting of Loops


C programming language allows using one loop inside another loop. Following section shows
few examples to illustrate the concept. Syntax:

The syntax for a nested for loop statement in C is as follows:

for ( init; condition; increment )

for ( init; condition; increment)

statement(s);

statement(s);

The syntax for a nested while loop statement in C programming language is as follows:

while(condition)

while(condition)

statement(s);

Arthur Brice A
71
Structured Programming

statement(s);

The syntax for a nested do...while loop statement in C programming language is as


follows:

do

statement(s);

do

statement(s);

}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example, a for loop can be inside a while loop or vice versa.

Programs: 11. program using a nested for loop to find the prime numbers from 2 to 20:

#include <stdio.h>

int main ()

/* local variable definition */

int i, j;

for(i=2; i<20; i++)

for(j=2; j <= (i/j); j++)

if(!(i%j))

break;

// if factor found, not prime

if(j > (i/j))

Arthur Brice A
72
Structured Programming

printf("%d is prime\n", i);

return 0; }

Output
2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

Programs: 12. Using for loops reproduce the star triangle below

***

*****

*******

*********

#include <stdio.h>

int main()

int row, c, n,I, temp;

printf("Enter the number of rows in pyramid of stars you wish to


see ");

scanf("%d",&n);

temp = n;

for ( row = 1 ; row <= n ; row++ )

Arthur Brice A
73
Structured Programming

for ( i= 1 ; i< temp ; i++ )

printf(" ");

temp--;

for ( c = 1 ; c <= 2*row - 1 ; c++ )

printf("*");

printf("\n");

return 0;

13. Write a program to print series from 10 to 1 using nested loops.

#include<stdio.h>

void main ()

{ int a;

a=10;

for (k=1;k=10;k++)

while (a>=1)

printf ("%d",a); a--;

} printf("\n");

a= 10;

Arthur Brice A
74
Structured Programming

Output:

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

10 9 8 7 5 4 3 2 1

3.3 Jump Statements

3.3.1 The break Statement

The break statement provides an early exit from for, while, and
do, just

as from switch. A break causes the innermost enclosing loop or


switch

to be exited immediately. When break is encountered inside any


loop,

control automatically passes to the first statement after the


loop.

Consider the following example;

main( )

int i = 1 , j = 1 ;

while ( i++ <= 100 )

Arthur Brice A
75
Structured Programming

while ( j++<= 200 )

if ( j == 150 )

break ;

else

printf ( "%d %d\n", i, j );

In this program when j equals 150, break takes the control outside theinner while only, since it is
placed inside the inner while.

3.3.2 The continue Statement


The continue statement is related to break, but less often used; it causes the next iteration of the
enclosing for, while, or do loop to begin. In the while and do, this means that the test part is
executed immediately; in the for, control passes to the increment step. The continue statement
applies only to loops, not to switch.

Consider the following program:

main( )

int i, j ;

for ( i = 1 ; i<= 2 ; i++ )

for ( j = 1 ; j <= 2 ; j++ )

if ( i == j)

continue ;

printf ( "\n%d %d\n", i, j ) ;

Arthur Brice A
76
Structured Programming

The output of the above program would be...

1 2

2 1

Note that when the value of I equals that of j, the continue statement takes the control to the
for loop (inner) by passing rest of the statements pending execution in the for loop (inner).

3.3.3 The goto statement


Kernighan and Ritchie refer to the goto statement as "infinitely abusable" and suggest that it
"be used sparingly, if at all. The goto statement causes your program to jump to a different
location, rather than execute the next statement in sequence. The format of the goto statement is;

goto statement label;

Consider the following program fragment

if (size > 12)

goto a;

goto b;

a: cost = cost * 1.05;

flag = 2;

b: bill = cost * flag;

Here, if the if conditions satisfies the program jumps to block labelled as a: if not then it jumps to
block labelled as b:.

SELF-ASSESSMENT EXERCISES
i. Differentiate between if and if else statements in C programming language using diagram ONLY.

ii. Write a C program to print EVEN or ODD depending on the integer number supplied at
the prompt and simulate the output.

Arthur Brice A
77

You might also like