Structured Programming Overview and Benefits
Structured Programming Overview and Benefits
1 |S C S 2 1 0 4
What is structured programming?
This is a style in programming paradigm of dividing a problem into sub- problems, and sub –
problems into sub-sub- problems, and so on, (top down design) then solving each sub-sub –
problems individually to produce sub sub-solutions, and combining the sub-solutions to form the
solution (bottom up design). Therefore, a complex problem is broken up and made more
understandable, and thus easier to solve.
The most common techniques used in structured programming to solve all problems are called
constructs. Sequence, selection, and repetition constructs. These constructs are also called control
structures. Using these three basic control structures, it is possible to write standardized programs,
which are easy to read and understand.
The final computer program (consisting of all the function) will be the solution.
➢ Structured programming breaks up a problem into sub- problems and this makes
problems more understandable and therefore easy to solve.
➢ The solution to the problem is also modifiable in future. Having sections of something always
makes the whole thing modifiable.
➢ Structured programming also makes the program more efficient. When having many sub –
solutions(functions), we can at one time load.
➢ Having small sections of a program running saves memory space and also CPU’S.
Other programming
paradigms
➢ Another programming paradigm popular nowadays is the object-oriented
programming style.
➢ This style uses the concept of classes and objects in programming, but also uses functions to
implement these concepts. Therefore, it applies structured
programming.
➢ Still another programming paradigm is event driven programming whereby
programs procedures respond to events from the user.
➢ Events include mouse button’s click or double click, mouse, dragging, keyboard key press, etc.
➢ Structured programming is universal starting level of learning programming.
2 |S C S 2 1 0 4
UNIT -1 Syllabus:
Computer fundamentals- Hardware, software, Computer Language, Translators, Compiler,
Interpreter, Loader and Linder, Program Development steps- Algorithms, Pseudo code, flow
charts, Specification for converting Algorithms into Programs basic.
Introduction to C Language – History, Simple C program, Structure of a C Program, Identifiers,
Basic data types, user defined data types, Variables, Constants, type Qualifiers, Managing Input/
Output, Operators, Expressions, Precedence and Associativity, Expression Evaluation, Type
Conversions, Simple C programming Examples.
1. Computer Fundamentals:
What is Computer?
Computer is an advanced electronic device that takes raw data as input from the user and
processes these data under the control of set of instructions (called program) and gives the result
(output) and saves output for the future use. It can process both numerical and non-numerical
(arithmetic and logical) calculations.
A computer has four functions:
a. accepts data Input
b. processes data Processing c. produces
output Output
d. stores results Storage
Input (Data): Input is the raw information entered into a computer from the input devices. It is
the collection of letters, numbers, images etc.
Process: Process is the operation of data as per given instruction. It is totally internal process of
the computer system.
Output: Output is the processed data given by computer after data processing. Output is also
called as Result. We can save these results in the storage devices for the future use. Computer
System All of the components of a computer system can be summarized with the simple
equations.
• Hardware = Internal Devices + Peripheral Devices All physical parts of the computer (or
everything that we can touch) are known as Hardware.
• Software = Programs Software gives "intelligence" to the computer.
• USER = Person, who operates computer.
3 |S C S 2 1 0 4
Software
Software, simply are the computer programs. The instructions given to the computer in the
form of a program is called Software. Software is the set of programs, which are used for
different purposes. All the programs used in computer to perform specific task is called
Software.
Types of software
i) System software:
a) Operating System Software DOS, Windows XP, Windows Vista, Unix/Linux, MAC/OS X
etc.
b) Utility Software Windows Explorer (File/Folder Management), Windows Media Player,
Antivirus Utilities, Disk Defragmentation, Disk Clean, Backup, WinZip, WinRAR etc…
2. Computer Language:
An artificial language used to write programs that can be translated into machine language
and then executed by a computer. As we know that computer understands only machine
language. It does not understand the English language or any other what we normally use. So to
perform tasks from computer we use programming language to write programs. These programs tell
the computer what to do? Each natural language has a method of using symbols of that language.
In English, the method is given by the rules of the grammar. These rules tell us which word to use
when and how to use it. Similarly, the rules of a programming language must also be used. These
rules are known as “Syntax Rules”. In case of natural language people can use poor and incorrect
language, but in case of programming language we can‟t use. Each language has strict syntax
rules and these rules cannot be ignored. Each program has its own syntax and this is further
converted to machine language. Now after the conversion, machine is able to understand the task.
This conversion is done by compiler or interpreted. A compiler or interpreter is tool that converts
the program into machine language. Each programming has its own compiler or interpreter.
Programming language can be classified into three broad categories: 1) Machine Language 2)
Assembly Language and 3) High Level Language.
i) Machine Language:
It is the language of the computer machine itself. A machine can understand this language
directly without any translator. It is also known as Binary language. It is only two digits language
i.e. 0s and 1s. It is first generation of the programming languages. Machine language was used when
the computer was of a huge size; approximately it covered one room.
4 |S C S 2 1 0 4
Only the developers could work with the computer. Because it was not easy as it is today. Input was
firstly converted into the Binary language of zeros and ones. Then fed to computer, computer
processed it and output is generated. This output is also in the form of machine language. Again it
was converted to human understandable language English. Thus it was a headache giver task.
Machine language is the fundamental language of the machines. Each machine we see today works
on the machine language. We give input in English and machine works on the machine code. Some
interfaces are there that converts our language into machine language. The circuitry of a machine
is wired in such a way that it immediately recognizes the machine language and operates the
machine
Machine language is not very easy language to learn. It is difficult to read and understand. The
most important advantage of machine language is that programs written in machine language are
executed very fast by the computer. This is mainly because machine language is directly understood
by the CPU and no translation of the program is required. However writing a program in machine
language has several disadvantages; Machine Dependent, Difficult to program and Difficult to
modify. Machine dependent means the machine code of one machine will not work for other
machine.
Machine Language is the toughest language of all the generations. Only developers of this
language and experienced scientists can use this language. New learner or normal users can’t even
understand it because of its complexity.
ii) Assembly Language:
In machine language we write the programs in binary code i.e. 0s and 1s. That is headache
giver task. But this headache is reduced by the Assembly Language. In Assembly Language,
programs can be easily written in alphanumeric symbols instead of 0s and 1s. For good and
effective programming, meaningful and easily remember able symbols are selected. For
example: ADD for addition, SUB for subtraction, CMP for comparison etc. Such symbols are
known as Mnemonics. A language which uses these mnemonics symbols is known as
Assembly Language. A program written in assembly language is known as assembly language
program.
The advantage of assembly language is that the execution time of an assembly language
program is less. An assembly language program runs faster to produce results.
The most disadvantage of assembly language is that programming in this language is difficult
and time consuming. Assembly language is machine dependent. The programmer must have
detailed knowledge of the structure of the computer. He must have the knowledge of registry of
the computer. The program written in assembly language for one computer cannot be used in any
other computer. It means that the assembly language program is not portable. Each processor has
its own instruction sets and hence its own assemble language.
5 |S C S 2 1 0 4
English and mathematics as compared to mnemonics in assembly languages. Example of high
level languages are BASIC, PASCAL, FORTRAN, COBOL, ADA, C, C++, C# and JAVA etc.
High level languages are independent of computer architecture. A programmer does not need
knowledge of architecture of the computer. The programming is easier. The same program can run
on any other computer which has a compiler of that language. The compiler is machine dependent
but not the language. Thus language is machine independent.
High level languages are very similar to English like language. These are easy to learn and use.
The programmer needs not to learn anything about the computer. He need not to worry about how
to store the code in the computer, where to store them, what to do with them etc. All this was in the
previous languages.
Writing programs in high level languages requires less time and effort. Programs written in high
level languages are easier to maintain than assembly language or machine language programs. This
is because these are easier to understand, easier to correct and modify. Insertion or removal of
instructions from a program is also possible.
Disadvantage of high level language is that it takes more time to run and requires more
computers‟ main memory.
3. Translators
i). Assembler:
A computer will not understand any program written in a language, other than its machine
language. The programs written in other languages must be translated into the machine language.
Such translation is performed with the help of software. A program which translates an assembly
language program into a machine language program is called an assembler. If an assembler which
runs on a computer and produces the machine codes for the same computer then it is called self
assembler or resident assembler. If an assembler that runs on a computer and produces the machine
codes for other computer then it is called Cross Assembler.
Assemblers are further divided into two types: One Pass Assembler and Two Pass Assembler. One
pass assembler is the assembler which assigns the memory addresses to the variables and translates
the source code into machine code in the first pass simultaneously. A Two Pass Assembler is
the assembler which reads the source code twice. In the first pass, it reads all the variables and
assigns them memory addresses. In the second pass, it reads the source code and translates the code
into object code.
6 |S C S 2 1 0 4
ii). Compiler:
It is a program which translates a high level language program into a machine language program. A
compiler is more intelligent than an assembler. It checks all kinds of limits, ranges, errors etc. But
its program run time is more and occupies a larger part of the memory. It has slow speed. Because
a compiler goes through the entire program and then translates the entire program into
machine codes. If a compiler runs on a computer and produces the machine codes for the same
computer then it is known as a self compiler or resident compiler. On the other hand, if a
compiler runs on a computer and produces the machine codes for other computer then it is known
as a cross compiler.
iii). Interpreter:
An interpreter is a program which translates statements of a program into machine code. It
translates only one statement of the program at a time. It reads only one statement of program,
translates it and executes it. Then it reads the next statement of the program again translates it
and executes it. In this way it proceeds further till all the statements are translated and executed.
On the other hand, a compiler goes through the entire program and then translates the entire program
into machine codes. A compiler is 5 to 25 times faster than an interpreter.
By the compiler, the machine codes are saved permanently for future reference. On the other
hand, the machine codes produced by interpreter are not saved. An interpreter is a small program
as compared to compiler. It occupies less memory space, so it can be used in a smaller system
which has limited memory space.
iv). Linker:
In high level languages, some built in header files or libraries are stored. These libraries are
predefined and these contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If linker does not find a library of
a function then it informs to compiler and then compiler generates an error. The compiler
automatically invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a
longer program is divided into smaller subprograms called modules. And these modules must
be combined to execute the program. The process of combining the modules is done by the linker.
v). Loader:
Loader is a program that loads machine codes of a program into the system memory. In
Computing, a loader is the part of an Operating System that is responsible for loading
programs. It is one of the essential stages in the process of starting a program. Because it places
programs into memory and prepares them for execution. Loading a program involves reading the
contents of executable file into memory. Once loading is complete, the operating system starts
the program by passing control to the loaded program code. All operating systems that support
program loading have loaders. In many operating systems the loader is permanently resident in
memory.
7 |S C S 2 1 0 4
4. Program Development Steps:
i). Algorithm:
It is a sequence of instructions (or set of instructions) to make a program more readable. It is a
process used to answer a question. In simple words an algorithm is a step-by-step procedure
for solving a problem. Algorithms can be expressed in any language, from natural languages like
English to programming languages like C. We use algorithms every day. For example, a recipe
for baking a cake is an algorithm. Most programs consist of algorithms. Making algorithm is
one of the principal challenges in programming [Link] algorithm must always terminate after
a finite number of steps. Simple example of algorithm to add two numbers:
An algorithm must have one starting point and one or more ending point. Its starting point can
be labeled as START and its ending point can be labeled as STOP. Here is example of one starting
point and one ending point.
Example of finding bigger number between two numbers with one START and two STOP:
Step 1: START.
Step 2: Take two variables named num1, num2.
Step 3: Read num1 and num2.
Step 4: if num1>num2 then
Step 5: print num1.
Step 6: STOP.
Step 7: else
Step 8: print num2.
Step 9: STOP.
8 |S C S 2 1 0 4
5. Introduction to C Language:
i). Introduction (History):
C language was designed by Dennis Ritchie at Bell Laboratories between 1969 and 1972. There
were many developments of C language between 1969 and 1972. And final language came into
existence in 1972. Like other languages C language was undergone a number of versions. In every
new version many new features were added to make it more powerful and more useful. It was not
written as a teaching help, but as an implementation language. It was developed for developing
operating systems, utility programs and compilers. C is a powerful structured and module
programming. Like most high level languages, C is a modular programming language. In which
each task can be developed as a module. It was written when computers were big and they capital
equipments.
C language is mainly influenced by the language B, which was further influenced by the BCPL
language. C language was also influenced by the languages such as CPL, Assembly, FORTRAN
and ALGOL. This C language further influenced some languages such as C++, C--, C sharp, Java,
JavaScript and Perl etc.
C language is known as middle level language because it consist the features of low level language
and high level language. Low level features are used for low level programming and High level
features are used for high level programming and mostly the high level programming is developed.
The first major use of C language was to write an operating system called UNIX. The success of
UNIX operating system and its features brought the consequent popularity for the C language. It
was standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C.
ii). Features:
C language is known as a middle level language, because it contains the features of both low
level language and high level language. Its features are as below:
Clarity: C language is quite close to English language. So its syntax is clearer and more
understandable. Its variables, names etc are written in simple English.
Portability: C language is a portable and can be run on any machine. It is independent of the
type of CPU and machine.
Built in: Various built in functions are available in C to perform required operations. Modular: C
language is a modular programming language which makes a “Divide and Conquer” approach.
In this approach we can module the programs and they are now easy to manage and understand.
Quicker Compiler: The speed of executing the C programs is very fast. A program in C,
created on one computer can be compiled and run on any other machine that has a similar C
compiler.
Simplicity: C language is easy to learn and easy to debug (Debug means to make a
program error free). Because of its easiness it is widely used from micro computers to mainframe
computers.
9 |S C S 2 1 0 4
Detect ability: It is a User Friendly language. C compiler detects the errors easily and
displays along with the program. It means C compiler tells us that where the errors are. It tells us
the type and number of the line in which the error is present.
Location of Data: It supports to the Pointer concept which tells us that where variables are
stored in the computer memory.
C language is case sensitive language. It means lower case and upper case letters are
considered as different.
6. Simple C program:
A C program consists of one or more functions or code modules. These are essentially groups of
instructions that are to be executed as a unit in a given order and that can be referenced by a
unique name. Each C program must contain a main() function. This is the first function called
when the program starts to run. Note that while "main" is not a C keyword and hence not reserved
it should be used only in this context.
A C program is traditionally arranged in the following order but not strictly as a rule.
STR UCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.
#include
The part of the compiler which actually gets your program from the source file is
called the preprocessor.
#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead
it is an instruction to the compiler to make it do something. It tells the C compiler to include
the contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special
place, by the fact that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all STanDard Input and
Output functions.
Your program will almost certainly want to send information to the screen and read
things from the keyboard, and stdio.h is the name of the file in which the functions that we
want to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in
later by the linker.
The ".h" portion of the filename is the language extension, which denotes an include
file. void
This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.
main
In this particular example, the only function in the program is called main.
11 |S C S 2 1 0 4
A C program is typically made up of large number of functions. Each of these is given
a name by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the
program execution starts from main.
(void)
This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Br ace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two
- for every open brace there must be a matching close one.
Braces allow us to group pieces of program together, often called a block.
A block can contain the declaration of variable used within it, followed by a sequence
of program statements.
In this case the braces enclose the working parts of the function main.
; (semicolon)
The semicolon marks the end of the list of variable names, and also the end of that
declaration statement.
All statements in C programs are separated by ";" (semicolon) characters.
The ";" character is actually very important. It tells the compiler where a given
statement ends.
If the compiler does not find one of these characters where it expects to see one, then
it will produce an error.
scanf
In other programming languages, the printing and reading functions are a part of the
language.
In C this is not the case; instead they are defined as standard functions which are part
of the language specification, but are not a part of the language itself.
The standard input/output library contains a number of functions for formatted data
transfer; the two we are going to use are scanf (scan formatted) and printf (print formatted).
printf
12 |S C S 2 1 0 4
Just like scanf, it is common to all versions of C and just like scanf, it is described in
the system file stdio.h.
The first parameter to a printf is the format string, which contains text, value
descriptions and formatting instructions.
Source File- This file contains the source code of the program. The file extension of
any c file is .c. The file contains C source code that defines the main function & maybe
other functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o,
meaning relocatable format machine code that is usually not directly executable. Object
files are produced by an assembler, compiler, or other language translator, and used as input
to the linker, which in turn typically generates an executable or library by combining parts
of object files.
Executable File- The binary executable file is generated by the linker. The linker
links the various object files to produce a binary file that can be directly executed.
Consider first a simple C program which simply prints a line of text to the computer screen.
This is traditionally the first C program you will see and is commonly called the “Hello World”
program for obvious reasons.
#include <stdio.h>
void main()
{
/* This is how comments are implemented in C
to comment out a block of text */
// or like this for a single line comment
As you can see this program consists of just one function the mandatory main function. The
parentheses, ( ), after the word main indicate a function while the curly braces, { }, are used to
denote a block of code -- in this case the sequence of instructions that make up the function.
13 |S C S 2 1 0 4
Comments are contained within a /* ... */ pair in the case of a block comment or a double
forward slash, //, may be used to comment out the remains of a single line of test.
The line
printf("Hello World\n " ) ;
is the only C statement in the program and must be terminated by a semi-colon.
The statement calls a function called printf which causes its argument, the string of text within
the quotation marks, to be printed to the screen. The characters \n are not printed as these
characters are interpreted as special characters by the printf function in this case printing out a
newline on the screen. These characters are called escape sequences in C and cause special
actions to occur and are preceded always by the backslash character, \ .
All C compiler include a library of standard C functions such as printf which allow the
programmer to carry out routine tasks such as I/O, maths operations, etc. but which are not part
of the C language, the compiled C code merely being provided with the compiler in a standard
form.
Header files must be included which contain prototypes for the standard library functions and
declarations for the various variables or constants needed. These are normally denoted by a
.h extension and are processed automatically by a program called the Preprocessor prior to the
actual compilation of the C program.
The line
#include <stdio.h>
Instructs the preprocessor to include the file stdio.h into the program before compilation so that
the definitions for the standard input/output functions including printf will be present for the
compiler. The angle braces denote that the compiler should look in the default “INCLUDE”
directory for this file. A pair of double quotes indicates that the compiler should search in the
specified path e.g.
#include “d:\myfile.h”
Note : C is case sensitive i.e. printf() and Printf() would be regarded as two different functions.
14 |S C S 2 1 0 4
8. Basic Data Types
There are five basic data types char, int, float, double, and void. All other data types in C are based
on these. Note that the size of an int depends on the standard size of an integer on a particular
operating system.
The signed and unsigned modifiers may be applied to types char and int and will simply change
the range of possible values. For example an unsigned char has a range of 0 to 255, all positive, as
opposed to a signed char which has a range of -128 to 127. An unsigned integer on a
16-bit system has a range of 0 to 65535 as opposed to a signed int which has a range of -32768 to
32767. Note however that the default for type int or char is signed so that the type signed char is
always equivalent to type char and the type signed int is always equivalent to int.
The long modifier may be applied to type int and double only. A long int will require 4 bytes of
storage no matter what operating system is in use and has a range of -2,147,483,648 to
2,147,483,647. A long double will require 10 bytes of storage and will be able to maintain up to
19 digits of precision. The short modifier may be applied only to type int and will give a 2 byte
integer independent of the operating system in use.
15 |S C S 2 1 0 4
Note: Note that the keyword int may be omitted without error so that the type unsigned is the
same as type unsigned int, the type long is equivalent to the type long int, and the type short is
equivalent to the type short int.
9. Variables:
A variable is a named piece of memory which is used to hold a value which may be modified by
the program. A variable thus has three attributes that are of interest to us : its type, its value and
its address.
The variable‟s type informs us what type and range of values it can represent and how much
memory is used to store that value. The variable‟s address informs us where in memory the
variable is located (which will become increasingly important when we discuss pointers later
on).
All C variables must be declared as follows:-
type variable-list ;
For Example :- int i ;
char a, b, ch ;
Variables are declared in three general areas in a C program. When declared inside functions
as follows they are termed local variables and are visible (or accessible) within the function (
or code block ) only.
void main()
{
int i, j ;
...
}
A local variable is created i.e. allocated memory for storage upon entry into the code block in
which it is declared and is destroyed i.e. its memory is released on exit. This means that
values cannot be stored in these variables for use in any subsequent calls to the function .
When declared outside functions they are termed global variables and are visible throughout the
file or have file scope. These variables are created at program start-up and can be used for the
lifetime of the program.
int i ;
void main()
{
...
}
When declared within the braces of a function they are termed the formal parameters of the
function as we will see later on.
int func1( int a, char b ) ;
16 |S C S 2 1 0 4
i) Variable Names:
Names of variables and functions in C are called identifiers and are case sensitive. The first
character of an identifier must be either a letter or an underscore while the remaining characters
may be letters, numbers, or underscores. Identifiers in C can be up to 31 characters in length.
An identifier‟s storage duration is the period during which that identifier exists in memory. Some
identifiers exist for a short time only, some are repeatedly created and destroyed and some exist
for the entire duration of the program. An identifier‟s scope specifies what sections of code it is
accessible from.
The auto storage class is implicitly the default storage class used and simply specifies a normal
local variable which is visible within its own code block only and which is created and destroyed
automatically upon entry and exit respectively from the code block.
The register storage class also specifies a normal local variable but it also requests that the
compiler store a variable so that it may be accessed as quickly as possible, possibly from a CPU
register.
The static storage class causes a local variable to become permanent within its own code block
i.e. it retains its memory space and hence its value between function calls.
When applied to global variables the static modifier causes them to be visible only within the
physical source file that contains them i.e. to have file scope. Whereas the extern modifier
17 |S C S 2 1 0 4
which is the implicit default for global variables enables them to be accessed in more than one
source file.
1. auto
Scope: Local to the block where it's declared (function or loop).
Lifetime: Exists only while the block is executing.
Example:
#include <stdio.h>
void myFunc() {
auto int x = 10; // 'auto' is optional, default for local variables
printf("x inside function: %d\n", x);
}
int main() {
myFunc();
// x is no longer accessible here
return 0;
}
2. register
Scope: Local to the block where it's declared.
Lifetime: Exists only while the block is executing.
Purpose: Suggests to the compiler to store the variable in a CPU register for faster
access. However, modern compilers often handle this optimization automatically, so it's
often not necessary to explicitly use register.
Example:
#include <stdio.h>
void myFunc() {
register int counter = 0;
// Operations on counter
printf("Counter: %d\n", counter);
}
int main() {
myFunc();
return 0;
}
3. static
Scope: Local to the block where it's declared (if declared inside a function or block) or
global (if declared outside any function).
Lifetime: Retains its value between function calls, initialized only once when the program
starts.
Example:
C
18 |S C S 2 1 0 4
#include <stdio.h>
void counterFunc() {
static int count = 0; // Static variable
count++;
printf("Count: %d\n", count);
}
int main() {
counterFunc(); // Output: Count: 1
counterFunc(); // Output: Count: 2
return 0;
}
4. extern
Scope: Global, accessible from any file where it's declared or linked.
Lifetime: Persists for the entire duration of the program.
Purpose: Used to declare variables that are defined in another source file.
Example
#include <stdio.h>
extern int myGlobalVar; // Declaration, not definition
int main() {
printf("Global variable from another file: %d\n", myGlobalVar);
return 0;
}
Example2
IV). CONSTANTS
Constants are fixed values that cannot be altered by the program and can be numbers,
characters or strings.
Some Examples :-
char : 'a', '$', '7'
int : 10, 100, -100 unsigned : 0,
255
float : 12.23456, -1.573765e10, 1.347654E-13
double : 1433.34534545454, 1.35456456456456E-200
long : 65536, 2222222
string : “Hello World\n”
Character constants are normally represented between single quotes, e.g. 'a', 'b', etc. However
they may also be represented using their ASCII (or decimal) values e.g. 97 is the ASCII value for
the letter 'a', and so the following two statements are equivalent. (See Appendix A for a listing of
the first 128 ASCII codes.)
char ch = 97 ;
19 |S C S 2 1 0 4
char ch = 'a' ;
There are also a number of special character constants sometimes called Escape
Sequences, which are preceded by the backslash character '\', and have special meanings in C.
\n newline
\t tab
\b backspace
\0 null character
Symbolic names are constants and not variables and thus do not appear in the declaration section. The
rules that apply to the #define statement which defines a symbolic constants are;
Symbolic names have the same form as variable names. Symbolic names are usually written in
CAPITAL letters to visually distinguish them from the normal variable names.
No black space between the # and word define is permitted
„#‟ must be the first character in the line
A black space is required between #define and symbolic name and between the symbolic name
and the constant.
#define statement must not end with a semicolon.
After definition, the symbolic name should not be assigned any other value within the program
using an assignment statement. Example MAX = 200; this is illegal
20 |S C S 2 1 0 4
Symbolic names are NOT declared for data type. Its data type depends on the type of constant.
#define statements may appear anywhere in the program but before it is referenced in the
program, Usual practice is to place the #define statements at the beginning of the program.
Program Example: Program to calculate the Average of 10 number entered through the
keyboard
#include<stdio.h>
#include<conio.h>
#define N10
main()
{
int count;
float sum, average, number;
sum = 0;
count= 0;
while(count< N)
{
printf("Enter any number ");
scanf("%f", &number);
count = count + 1;
}
average = sum/N;
printf(" N = %d Sum = %f", N, sum);
printf("Average = %f", average); getch();
}
C EXPRESSIONS
What is an expression?
In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the C programming language, an expression is defined as follows.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as follows...
21 |S C S 2 1 0 4
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Operand1 Operator Operand2
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Operand1 Operand2 Operator
i) Printf():
The printf() function is used for formatted output and uses a control string which is made up of a
series of format specifiers to govern how it prints out the values of the variables or constants
required. The more common format specifiers are given below
For Example :-
int i ;
printf( "%d", i ) ;
The printf() function takes a variable number of arguments. In the above example two
arguments are required, the format string and the variable i. The value of i is substituted for the
format specifier %d which simply specifies how the value is to be displayed, in this case as a
signed integer.
int i = 10, j = 20 ;
22 |S C S 2 1 0 4
char ch = 'a' ;
double f = 23421.2345 ;
printf( "%d + %d", i, j ) ; /* values are substituted from the variable list in order as required */
printf( "%c", ch ) ;
printf( "%s", "Hello World\n" ) ;
printf( "The value of f is : %lf", f ) ;/*Output as : 23421.2345 */
printf( "f in exponential form : %e", f ) ; /* Output as : 2.34212345e+4
Field width specifiers are used in the control string to format the numbers or characters
output appropriately .
For Example:-
int i = 15 ;
float f = 13.3576 ;
printf( "%3d", i ) ; /* prints "_15 " where _ indicates a space character */
printf( "%6.2f", f ) ; /* prints "_13.36" which has a total width of 6 and displays 2 decimal
places */
printf( “%*.*f”, 6,2,f ) ; /* prints "_13.36" as above. Here * is used as replacement character for
field widths */
There are also a number of flags that can be used in conjunction with field width specifiers to
modify the output format. These are placed directly after the % sign.
A - (minus sign) causes the output to be left-justified within the specified field,
a + (plus sign) displays a plus sign preceding positive values and
a minus preceding negative values, and
a 0 (zero) causes a field to be padded using zeros rather than space characters.
ii). scanf()
This function is similar to the printf function except that it is used for formatted input.
The format specifiers have the same meaning as for printf() and the space character or the
newline character are normally used as delimiters between different inputs.
For Example :-
int i, d ;
char c ;
float f ;
scanf( "%d", &i ) ;
scanf( "%d %c %f", &d, &c, &f ) ; /* e.g. type "10_x_1.234RET" */
scanf( "%d:%c", &i, &c ) ; /* e.g. type "10:x RET" */
The & character is the address of operator in C, it returns the address in memory of the
23 |S C S 2 1 0 4
variable it acts on. (Aside: This is because C functions are nominally call--by--value. Thus in
order to change the value of a calling parameter we must tell the function exactly where the
variable resides in memory and so allow the function to alter it directly rather than to uselessly
alter a copy of it. )
Note that while the space and newline characters are normally used as delimiters between
input fields the actual delimiters specified in the format string of the scanf statement must be
reproduced at the keyboard faithfully as in the case of the last sample call. If this is not done the
program can produce somewhat erratic results! „
The scanf function has a return value which represents the number of fields it was able to
convert successfully.
For Example :-
num = scanf( “%c %d”, &ch, &i );
This scanf call requires two fields, a character and an integer, to be read in so the value
placed in num after the call should be 2 if this was successful. However if the input was “a bc”
then the first character field will be read correctly as „a‟ but the integer field will not be
converted correctly as the function cannot reconcile “bc” as an integer. Thus the function will
return 1 indicating that one field was successfully converted. Thus to be safe the return value of
the scanf function should be checked always and some appropriate action taken if the value is
incorrect.
Example
char ch1, ch2;
printf( "Enter two characters : " ) ;
ch1 = getchar() ;
ch2 = getchar() ;
printf( "\n The characters are %c and %c\n", ch1, ch2 ) ;
In the above code segment if the input is "abcdefRET" the first two characters are read
into the variables all the others being discarded, but control does not return to the program until
the RET is hit and the buffer flushed. If the input was "aRET" then a would be placed in ch1 and
RET in ch2.
For example :-
char ch ;
ch = getch() ;
11. OPERATORS:
One of the most important features of C is that it has a very rich set of built in operators
including arithmetic, relational, logical, and bitwise operators.
i) Assignment Operators:
int x ;
x = 20 ;
Some common notation :- lvalue -- left hand side of an assignment operation
rvalue -- right hand side of an assignment operation
Type Conversions :- the value of the right hand side of an assignment is converted to
the type of the lvalue. This may sometimes yield compiler warnings if information is lost in the
conversion.
int x ;
char ch ;
float f ;
ch = x ; /* ch is assigned lower 8 bits of x, the remaining bits are discarded so we
..have a possible information loss */
x = f; /* x is assigned non fractional part of f only within int range,
information loss possible */
f = x; /* value of x is converted to floating point */
Multiple assignments are possible to any degree in C, the assignment operator has right to
left associativity which means that the rightmost expression is evaluated first.
For Example:-
x = y = z = 100;
In this case the expression z = 100 is carried out first. This causes the value 100 to be
placed in z with the value of the whole expression being 100 also. This expression value is then
taken and assigned by the next assignment operator on the left i.e. x = y = (z = 100);
+ - * / --- same rules as mathematics with * and / being evaluated before + and -.
25 |S C S 2 1 0 4
% -- modulus / remainder operator
For Example:-
int a = 5, b = 2, x ;
float c = 5.0, d = 2.0, f ;
x = a / b; // integer division, x = 2.
f = c / d; // floating point division, f = 2.5.
x = 5 % 2; // remainder operator, x = 1.
x = 7 + 3 * 6 / 2 - 1 ;// x=15,* and / evaluated ahead of + and -.
Note that parentheses may be used to clarify or modify the evaluation of expressions of
any type in C in the same way as in normal arithmetic.
x=7+(3*6/2)-1; // clarifies order of evaluation without penalty
x = ( 7 + 3 ) * 6 / ( 2 - 1 ) ; // changes order of evaluation, x = 60 now.
Program example: Program to illustrate the use of variables in expressions and their evaluation
#include<string.h>
#include<stdio.h>
#include<conio.h>
#define N 100
#define A 2
main()
{
int a, b, c, d, x, y, z;
a=9;
b = 12;
c = 3;
x = a-b/3 +c*2 -1;
y = a-b/ (3+c) * (2-1);
z = a- (b /(3+c) * 2) -1);
printf("x = %f\n", x);
printf("y = %f\n", y);
printf("z = %f\n", z);
getch();
}
OutPu
t
x
=10.000000
y = 7.000000
z =
4.000000
26 |S C S 2 1 0 4
iii). Increment and Decrement Operators:
There are two special unary operators in C, Increment ++, and Decrement - - , which
cause the variable they act on to be incremented or decremented by 1 respectively.
For Example:-
x++; /* equivalent to x=x+1; */
++ and -- can be used in prefix or postfix notation. In prefix notation the value of the variable is
either incremented or decremented and is then read while in postfix notation the value of the
variable is read first and is then incremented or decremented.
For Example :-
int i, j = 2 ;
i = ++ j ; /* prefix :- i has value 3, j has value 3 */
i = j++ ; /* postfix :- i has value 3, j has value 4 */
Many C operators can be combined with the assignment operator as shorthand notation
For Example :-
x = x + 10 ;
can be replaced by
x += 10 ;
These shorthand operators improve the speed of execution as they require the expression,
the variable x in the above example, to be evaluated once rather than twice.
Comma Operator
Used to link the related expressions together. A comma linked list of expressions is
evaluated left to right and the value of right-most expression is the value of the combined
expression
Value = (x =10, y =5, x+y);
Example
int x;
x = (5 + 3, 10 + 2); // x will be assigned 12
First, 5 + 3 is evaluated → result 8 (but discarded).
Then, 10 + 2 is evaluated → result 12 (used).
So, x = 12.
27 |S C S 2 1 0 4
Assignment operators
Assignment operators are used to assign the results of an expression to a variable. The
usual assignment operator is “=”. C has a set of „shorthand‟ assignment operators of the form
vop = exp;
a = a-1 a -+1
/* documentation section*/
#include<string.h>
#include<stdio.h>
#include<conio.h>
#define N 100
#define A 2 main()
{
int a;
a=A;
while (a < N)
Out Put
28 |S C S 2 1 0 4
2
16
Conditional Operators
A ternary operator pair “?” is used in C to construct conditional expressions. The format for using
the conditional operator is;
exp1 ? exp2 : exp3
where exp1, exp2 and exp3 are expressions. If exp1 is evaluated and found to be nonzero(true)
then expression exp2 is evaluated and becomes the value of the expression. If Exp1 is
found to be nonzero (false) the Exp3 is evaluated.
If exp=true then exp2 else exp3
example a= 10
b = 15;
x = (a>b)? a:b;
For Example :-
if ( x >= 0 && x < 10 )
printf( “ x is greater than or equal to zero and less than ten.\n” ) ;
Note: There is no Boolean type in C so TRUE and FALSE are deemed to have the following
meanings.
FALSE -- value zero
TRUE -- any non-zero value but 1 in the case of in-built relational operations
For Example:-
2>1 -- TRUE so expression has value 1
29 |S C S 2 1 0 4
2>3 -- FALSE so expression has value 0
i=2>1 ; -- relation is TRUE -- has value 1, i is assigned value 1
Note : Every C expression has a value. Typically we regard expressions like 2 + 3 as the only
expressions with actual numeric values. However the relation 2 > 1 is an expression which
evaluates to TRUE so it has a value 1 in C. Likewise if we have an expression x = 10 this has a
value which in this case is 10 the value actually assigned.
Note : Beware of the following common source of error. If we want to test if a variable has a
particular value we would write for example
if ( x == 10 ) …
if ( x = 10 ) …
this will give no compilation error to warn us but will compile and assign a value 10 to x
when the condition is tested. As this value is non-zero the if condition is deemed true no matter
what value x had originally. Obviously this is possibly a serious logical flaw in a program.
These are special operators that act on char or int arguments only. They allow the
programmer to get closer to the machine level by operating at bit-level in their arguments.
Recall that type char is one byte in size. This means it is made up of 8 distinct bits or
binary digits normally designated as illustrated below with Bit 0 being the Least Significant Bit
(LSB) and Bit 7 being the Most Significant Bit (MSB). The value represented below is 13 in
decimal.
RULE : If any two bits in the same bit position are set then the resultant bit in that position is set
otherwise it is zero.
30 |S C S 2 1 0 4
For Example :-
1011 0010 (178)
& 0011 1111 (63)
= 0011 0010 (50)
Bitwise OR, |
RULE : If either bit in corresponding positions are set the resultant bit in that position is set.
For Example :-
Bitwise XOR, ^
RULE : If the bits in corresponding positions are different then the resultant bit is set.
For Example :-
RULE : These move all bits in the operand left or right by a specified number of places.
For Example :-
2 << 2 = 8
Example:
31 |S C S 2 1 0 4
#include <stdio.h>
int main() {
unsigned int num = 5; // Binary: 0000...0101
unsigned int result = num << 2; // Shifts bits of 5 by 2
positions to the left
return 0;
}
The right shift operator >> shifts the bits of the left operand to the right by the number of
positions specified by the right operand.
For unsigned integers:
Vacated bit positions on the left are filled with zeros (logical right shift). This is equivalent to
dividing the number by 2 raised to the power of the shift amount.
For signed integers:
The behavior of filling vacated bits on the left is implementation-defined. It can be filled with
zeros (logical right shift) or with the sign bit (arithmetic right shift), preserving the sign of the
number. It is generally recommended to use unsigned integers for bitwise operations to ensure
predictable behavior.
Example:
#include <stdio.h>
int main() {
unsigned int num = 20; // Binary: 0000...010100
unsigned int result = num >> 2; // Shifts bits of 20 by 2
positions to the right
32 |S C S 2 1 0 4
return 0;
}
Important Considerations:
Shifting by a negative value or by a value greater than or equal to the width of the
data type results in undefined behavior.
Right-shifting signed negative values is implementation-defined; using unsigned
types for bitwise operations is safer for consistent behavior.
Ones Complement
Example:-
Note: With all of the above bitwise operators we must work with decimal, octal, or hexadecimal
values as binary is not supported directly in C.
The bitwise operators are most commonly used in system level programming where
individual bits of an integer will represent certain real life entities which are either on or off, one
or zero. The programmer will need to be able to manipulate individual bits directly in these
situations.
A mask variable which allows us to ignore certain bit positions and concentrate the
operation only on those of specific interest to us is almost always used in these situations. The
value given to the mask variable depends on the operator being used and the result required.
33 |S C S 2 1 0 4
The sizeof operator gives the amount of storage, in bytes, associated with a variable or a
type (including aggregate types as we will see later on).The expression is either an identifier or a
type-cast expression (a type specifier enclosed in parentheses).
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
= += -= *= /= %= &= ^= |= <<= >>= right to left
Lowest , left to right
34 |S C S 2 1 0 4
Operators at the top of the table have highest precedence and when combined with other
operators at the same expression level will be evaluated first.
For example take the expression
2 + 10 * 5;
Here * and + are being applied at the same level in the expression but which comes first ?
The answer lies in the precedence table where the * is at a higher level than the + and so will be
applied first.
When two operators with the same precedence level are applied at the same expression
level the associativity of the operators comes into play.
For example in the expression
2 + 3 - 4;
the + and - operators are at the same precedence level but associate from left to right and
so the addition will be performed first. However in the expression
x=y=2;
as we have noted already the assignment operator associates from right to left and so the
rightmost assignment is first performed.
Note : As we have seen already parentheses can be used to supersede the precedence rules and
force evaluation along the lines we require. For example to force the addition in 2 + 10 * 5 ; to
be carried out first we would write it as (2 + 10) * 5;
long double
double
float
unsigned
long
long
unsigned int
35 |S C S 2 1 0 4
signed int
For Example :-
int i ;
float f1, f2 ;
f1 = f2 + i ;
Since f2 is a floating point variable the value contained in the integer variable is
temporarily converted or cast to a floating point variable also to standardise the addition
operation in this case. However it is important to realise that no permanent modification is made
to the integer variable.
Explicit casting coerces the expression to be of specific type and is carried out by means of the
cast operator which has the following syntax.
which essentially does the same thing but the former is more obvious and descriptive of what is
happening.
Note: It should be noted that all of these casting operations, both implicit and explicit, require
processor time. Therefore for optimum efficiency the number of conversions should be kept to a
minimum.
// Driver Code
int main()
{
// Given a & b
int a = 15, b = 2;
float div;
// Division of a and b
div = a / b;
36 |S C S 2 1 0 4
printf("The result is %f\n", div);
return 0;
}
Output:
The result is 7.000000
Explanation: Here, the actual output needed is 7.500000, but the result is 7.000000. So to get
the correct output one way is to change the data type of a given variable. But correct output can
also be done by typecasting. This consists of putting a pair of parentheses around the name of
the data type like division = (float) a/b.
// Driver Code
int main()
{
// Given a & b
int a = 15, b = 2;
char x = 'a';
double div;
return 0;
}
37 |S C S 2 1 0 4