Course
Course
STRUCTURED PROGRAMMING
By
AZANGUE Brice Arthur
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:
Explain the importance of header file, module implementation and main program in C
programming language.
Arthur Brice A
2
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.
A programming language is a vocabulary and set of grammatical rules designed for instructing a
computer to perform specific tasks.
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.
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.
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.
Examples:
Most Modern General Purpose Languages such as C, C++, C#, Java, Basic, COBOL, Lisp and ML.
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
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.
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.
C
Pascal
Fortran
Cobol
ALGOL
Ada
dBASE etc.
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.
This is programming oriented to the development of internet applications using languages and tools
Arthur Brice A
6
Structured Programming
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
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
1.0 INTRODUCTION
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.
There are two major types of computer programming languages: the low-level language and high-
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.
Very bulky.
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.
It is machine dependent; the programmer must be knowledgeable in both subject area and the
operations of the machine.
Arthur Brice A
9
Structured Programming
It consumes time
High level programs are comparatively slower than low level programs.
Compared to low level programs, they are generally less memory efficient.
Machine independent
Problem oriented
Readability
Examples of High-level Languages are FORTRAN, COBOL, QBASIC, VISUAL BASIC, JAVA,
PASCAL etc.
SELF-ASSESSMENT EXERCISE
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
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.
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.
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,
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
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 . ..
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).
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.
i. What is Abstraction?
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
#include <stdio.h>
else return c; }
int main()
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
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.
Describe the sample input/ output steps used in program compilation and execution.
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.
Here is a simple table showing input and output of each step in the compilation and execution process:
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
Unit 1 Element of C
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.
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.
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
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.
exponential form
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.
Arthur Brice A
22
Structured Programming
o The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
Arthur Brice A
23
Structured Programming
SELF-ASSESSMENT EXERCISE
Solution:
A variable is a programming element that can change during program execution where as
constant do not change.
positive.
constant.
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.
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.
exponential form
Arthur Brice A
25
Structured Programming
Eg:
int page_no;
char grade;
float salary;
long y;
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()
2. main()
char first;
char middle;
char last;
Arthur Brice A
26
Structured Programming
Eg.,
int pageno=10;
char grade=‟A‟;
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 – logical operation
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
legs = 4;
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.
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.
int main()
return 0;
Output:
C Programming
Explanation:
main() function.
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.
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.
int main()
float a;
Arthur Brice A
30
Structured Programming
scanf("%f",&a);
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.
int main()
char var1;
scanf("%c",&var1);
return 0;
Output
Enter character:
You entered g.
Arthur Brice A
31
Structured Programming
displayed.
#include <stdio.h>
int main()
char var1;
scanf("%c",&var1);
return 0;
Output:
Enter character:
103
You can display character if you know ASCII code only. This is shown by following example.
#include <stdio.h>
int main()
int var1=69;
return 0;
Output
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,
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.
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:
scanf("%d",&c);
Example:
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;
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.
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.
int main()
printf("Case 1:%6d\n",9876);
Arthur Brice A
35
Structured Programming
printf("Case 2:%3d\n",9876);
printf("Case 3:%.2f\n",987.6543);
printf("Case 4:%.f\n",987.6543);
*/
printf("Case 5:%e\n",987.6543);
return 0;
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002
int main()
Arthur Brice A
36
Structured Programming
int a,b;
float c,d;
scanf("%d%d",&a,&b);
below*/
scanf("%d%f",&a,&c);
return 0;
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;
Arthur Brice A
37
Structured Programming
#include<stdio.h>
float a;
double b;
B. Files
C. Command-line
int main()
int i = 10, j = 2;
B. 10 2 4
C. 10 2 2
D. 10 2 5
Arthur Brice A
38
Structured Programming
int main()
int i = 10, j = 3;
B. 10 3
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
STATEMENTS
Unit 1 Operators
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
Arthur Brice A
40
Structured Programming
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
The following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:
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 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
Arthur Brice A
44
Structured Programming
Arthur Brice A
45
Structured Programming
When i++ is used as prefix(like: ++var), ++var will increment the value
operator will return the value of operand first and then only increment it.
#include <stdio.h>
int main()
int c=2,d=2;
by 1 to 3.
displayed.
Return 0;
Output
2
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
int x, y;
y = ( x> 5 ? 3 : 4 ) ;
if ( x > 5 )
y = 3;
else
y = 4;
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?
{int x, y;
y = ( x> 5 ? 1 : 4 ) ; }
Solution
1. What are the operators used in C programming language?
{int x, y;
y = ( x> 5 ? 1 : 4 ) ; }
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
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.
Arthur Brice A
50
Structured 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
Syntax of if statement:
if (condition )
Statement 1;
Statement 2;
…………..
…………..
…………..
Statement n;
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)
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++;
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:
#include<stdio.h>
int main()
int no;
printf("Enter a no : ");
scanf("%d", &no);
if(no<0)
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
#include<stdio.h>
int main()
int a,b;
float c;
if(b == 0)
c = a/b;
printf("quotient is %f \n",c);
return 0;
Output:
Enter 2 nos:
6 2
quotient is 3
6 0
Arthur Brice A
54
Structured Programming
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:
#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;
Odd
Even
#include <stdio.h>
int main()
int year;
scanf("%d", &year);
else
return 0;
Output:
Enter a year to check if it is a leap year 1996
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
#include <stdio.h>
int main()
int m=40,n=20;
if (m>n)
else if(m<n)
Arthur Brice A
57
Structured Programming
else
Output:
m is greater than n
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.
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:
#include <stdio.h>
int main()
Arthur Brice A
58
Structured Programming
if (m>n)
else
else
return 0;
Output
40 is greater than 20
Arthur Brice A
59
Structured Programming
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.
main( )
int i = 2;
switch ( i )
case 1:
case 2:
case 3:
default :
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:
break ;
case 2:
break ;
case 3:
break ;
default:
I am in case 2
Program
#include <stdio.h>
int main ()
Arthur Brice A
61
Structured Programming
char grade;
scanf(“%c”, &grade);
switch(grade)
break;
case 'B' :
printf("Excellent!\n" );
break;
break;
break;
break;
return 0;
Output
Excellent
Your grade is B
Arthur Brice A
62
Structured Programming
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.)
main( )
int p, t, count;
float r, si;
count = 1;
si=p * t * r / 100;
count = count+1;
Arthur Brice A
63
Structured Programming
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.
*/
#include <stdio.h>
int main()
scanf("%d",&n);
temp = n;
while( temp != 0 )
temp = temp/10;
if ( n == reverse )
else
return 0;
Arthur Brice A
64
Structured Programming
Output:
12321
12321 is a palindrome
12000
do
The test expression must be enclosed within parentheses, just as it does with a while statement.
#include <stdio.h>
int main()
int sum=0,num;
do
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
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
#include <stdio.h>
int main()
int n,count=0;
scanf("%d", &n);
do
n/=10;
/* n=n/10 */
count++;
} while(n!=0);
Arthur Brice A
67
Structured Programming
Output
Number of digits: 5
The for is the most popular looping instruction. The general form of for statement is
shown below:
do this;
and this;
and this;
The for keyword allows us to specify three things about a loop in a single
line:
int num;
printf(" n n cubed\n");
Arthur Brice A
68
Structured Programming
return 0;
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.
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
Programs:
#include <stdio.h>
int main()
int n, i, sum=0;
scanf("%d", &n);
for(i=1;i<=n;i++)
Output
Enter the limit: 5 Sum of N natural numbers is 15.
#include<stdio.h>
int main()
int num,r,reverse=0;
scanf("%d",&num);
for(num!=0;num=num/10)
r=num%10;
Arthur Brice A
70
Structured Programming
reverse=reverse*10+r;
return 0;
Output:
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);
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 ()
int i, j;
if(!(i%j))
break;
Arthur Brice A
72
Structured Programming
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()
scanf("%d",&n);
temp = n;
Arthur Brice A
73
Structured Programming
printf(" ");
temp--;
printf("*");
printf("\n");
return 0;
#include<stdio.h>
void main ()
{ int a;
a=10;
for (k=1;k=10;k++)
while (a>=1)
} 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
The break statement provides an early exit from for, while, and
do, just
main( )
int i = 1 , j = 1 ;
Arthur Brice A
75
Structured Programming
if ( j == 150 )
break ;
else
In this program when j equals 150, break takes the control outside theinner while only, since it is
placed inside the inner while.
main( )
int i, j ;
if ( i == j)
continue ;
Arthur Brice A
76
Structured Programming
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).
goto a;
goto b;
flag = 2;
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