Unit-I Naresh IT
Unit-I Naresh IT
Principles of C Programming
1. Introduction
A computer is a very powerful and versatile machine
capable of performing a multitude of different tasks, yet it has no
intelligence or thinking power. Note a computer performs many
tasks exactly in the same manner as it is told to do. This places
responsibility on the user to instruct the computer in a correct
and precise manner, so that the machine is able to perform the
required job in a proper way. A wrong or ambiguous instruction
may sometimes prove disastrous.
In order to instruct a computer correctly, the user must have
clear understanding of the problem to be solved. A part from this
he should be able to develop a method, in the form of series of
sequential steps, to solve it. Once the problem is well-defined
and a method of solving it is developed, then instructing the
computer to solve the problem becomes relatively easier task.
Thus, before attempt to write a computer program to solve a
given problem. It is necessary to formulate or define the problem
in a precise manner. Once the problem is defined, the steps
required to solve it, must be stated clearly in the required order.
ASCII Codes
American Standard Code for Information Interchange.
These are binary codes for alpha numeric data and are used for
printers and terminals that are connected to computer systems for
alphabetizing and sorting.
Operating Systems
41
Principles of C programming language
The set of instructions which resides in the computer and
governs the system are called operating systems, without which
the machine will never function. They are the medium of
communication between a computer and the user. DOS,
Windows, Linux, UNIX etc are Operating Systems.
Application Programs
These programs are written by users for specific purposes.
Computer Languages
They are of three types –
Machine language (Low level language)
Assembly language
User Oriented language (Higher level
language)
Machine language depends on the hard ware and comprises of
0 and 1 .This is tough to write as one must know the internal
structure of the computer. At the same time assembly language
makes use of English like words and symbols. With the help of
special programs called Assembler, assembly language is
converted to machine oriented language. Here also a
programmer faces practical difficulties. To overcome this
hurdles user depends on higher level languages, which are far
easier to learn and use. To write programs in higher level
language, programmer need not know the characteristics of a
computer. Here he uses English alphabets, numerals and some
special characters.
Some of the higher level languages are FORTRAN, BASIC,
COBOL, PASCAL, C, C++, ADA etc. We use C to write
41
Principles of C programming language
programs. Note that higher level languages cannot directly be
followed by a computer. It requires the help of certain softwares
to convert it into machine coded instructions. These softwares
are called Compiler, Interpreter, and Assembler. The major
difference between a compiler and an interpreter is that compiler
compiles the user’s program into machine coded by reading the
whole program at a stretch where as Interpreter translates the
program by reading it line by line.
1.2 Algorithm
Definition: A set of sequential steps usually written in Ordinary
Language to solve a given problem is called Algorithm.
It may be possible to solve to problem in more than one
ways, resulting in more than one algorithm. The choice of
various algorithms depends on the factors like reliability,
accuracy and easy to modify. The most important factor in the
choice of algorithm is the time requirement to execute it, after
writing code in High-level language with the help of a computer.
The algorithm which will need the least time when executed is
considered the best.
41
Principles of C programming language
3. Effectiveness: Each step must be effective, in the sense that it
should be primitive easily convert able into program statement)
can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it
can be used to solve problems of a specific type for any input
data.
5. Input/output: Each algorithm must take zero, one or more
quantities as input data produce one or more output values. An
algorithm can be written in English like sentences or in any
standard representation sometimes, algorithm written in English
like languages are called Pseudo Code
Example
1. Suppose we want to find the average of three numbers, the
algorithm is as follows
Step 1:Read the numbers a, b, c
Step 2:Compute the sum of a, b and c
Step 3:Divide the sum by 3
Step 4:Store the result in variable d
Step 5:Print the value of d
Step 6:End of the program
2. Write an algorithm to calculate the simple interest using the
formula Simple interest = P*N* R/100.
Where P is principle Amount, N is the number of years and R is
the rate of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2: Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.
41
Principles of C programming language
1.3 Flowchart
A flow chart is a step by step diagrammatic representation of
the logic paths to solve a given problem or A flowchart is visual
or graphical representation of an algorithm. The flowcharts are
pictorial representation of the methods to b used to solve a given
problem and help a great deal to analyze the problem and plan its
solution in a systematic and orderly manner. A flowchart when
translated in to a proper computer language, results in a complete
program.
Advantages of Flowcharts
1. The flowchart shows the logic of a problem displayed in
pictorial fashion which felicitates easier checking of an
algorithm.
2. The Flowchart is good means of communication to other
users. It is also a compact means of recording an algorithm
solution to a problem.
3. The flowchart allows the problem solver to break the problem
into parts. These parts can be connected to make master chart.
4. The flowchart is a permanent record of the solution which can
be consulted at a later time.
Differences between Algorithm and Flowchart
Algorithm Flowchart
1. A method of representing the 1. Flowchart is diagrammatic
step-by-step logical procedure representation of an algorithm.
for solving a problem. It is constructed using different
2. It contains step-by-step types of boxes and symbols.
English descriptions, each step 2. The flowchart employs a
representing a particular series of blocks and arrows,
operation leading to solution of each of which represents a
problem. particular step in an algorithm.
41
Principles of C programming language
3. These are particularly useful 3. These are useful for detailed
for small problems. representations of complicated
4. For complex programs, programs.
algorithms prove to be 4. For complex programs,
Inadequate. Flowcharts prove to be
adequate
Symbols used in Flow-Charts:
The symbols that we make use while drawing flowcharts as
given below are as per conventions followed by International
Standard Organization (ISO).
a. Oval: Rectangle with rounded sides is used to indicate either
START/STOP of the program.
41
Principles of C programming language
symbol marks where the algorithm ends on the first page
and where it continues on the second.
41
Principles of C programming language
2. Portability:
C Programs are portable i.e they can be run on any Compiler
with Little or no Modification
Compiler and Preprocessor make it Possible for C Program
to run it on Different PC
3. Powerful
Provides Wide verity of ‘Data Types‘
41
Principles of C programming language
41
Principles of C programming language
41
Principles of C programming language
3. The C compiler combines the capabilities of an assembly
language with the feature of high level language. Therefore, it
is well suited for writing both system software and business
package.
4. There are only 32 keywords; several standard functions are
available which can be used for developing program.
5. C is portable language; this means that C programs written for
one computer system can be run on another system, with little
or no modification.
6. C language is well suited for structured programming, this
requires user to think of a problems in terms of function or
modules or block. A collection of these modules make a
program debugging and testing easier.
7. C language has its ability to extend itself. A c program is
basically a collection of functions that are supported by the C
library. We can continuously add our own functions to the
library with the availability ofthe large number of functions.
8. In India and abroad mostly people use C programming
language because it is easy to learn and understand.
1.7 Basic Structure of a C program:
C program can be viewed as a group of building blocks
called functions. A function is a subroutine that may include one
or more statements designed to perform a specific task.
void main( )
{
Declaration part;
int b = 10; //Local Variable
a+b;
a+b+c;
Executable part;
}
Subprogram section ()
{
int c = 45; //Local var
a+c;
c+b; Error
return c;
Body of the subprogram;
}
1. The documentation section consists of a set of comment lines
giving the name the program.
2. The link section provides instructions to the compiler to link
functions from the system library.
3. The definition section defines all symbolic constants.
4. There are some variables that are used in more than one
function. Such variables are called global variables and are
declared in the global declaration section that is outside of all the
functions.
41
Principles of C programming language
Every C program must have one main() function section.
This section contains two parts declaration part and executable
part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable
part. These two parts must appear between the opening and the
closing braces. The program execution begins at the opening
brace and ends at the closing brace.
The subprogram section contains all the user-defined
functions that are called in the main function.
41
Principles of C programming language
int. The Integer variables have a limited value. They range from
–32768 to 32767
41
Principles of C programming language
1.10 VARIABLES
A variable is a data name that may be used to store a data
value.
A variable value that can change any time during the
execution.
It is a memory location used to store a data value.
A variable name should be carefully chosen by the
programmer so that its use is reflected in a useful way in the
entire program. Variable names are case sensitive.
Declaration of Variables:
Every variable used in the program should be declared to the
compiler. The declaration does two things.
41
Principles of C programming language
1. It tells the computer what the variables name is.
2. Specifies what type of data the variable will hold.
Initialization of Variable
C variables declared can be initialized with the help of
assignment operator ‘=’.
Syntax: data_type variable_name=constant/literal/expression;
or
variable_name=constant/literal/expression;
Example
int a=10;
1
a = a+2;
2
int a=b+c;
3
a=10;
4
a=b+c;
Multiple variables can be initialized in a single statement by
single value, for example, a=b=c=d=e=10;
NOTE: C variables must be declared before they are used in the
c program. Also, since c is a case sensitive programming
language, therefore the c variables, abc, Abc and ABC are all
different.
41
Principles of C programming language
1.11 Constant :
A constant is a value or an identifier whose value cannot be
altered in a program. For example: 1, 2.5, "C programming is
easy", etc.
As mentioned, an identifier also can be defined as a constant.
const double PI=3.14;
Here, PI is a constant. Basically what it means is
that, PI and 3.14 is same for this program.
Below are the different types of constants you can use in C.
1. Integer constants
An integer constant is a numeric constant (associated with
number) without any fractional or exponential part. There are
three types of integer constants in C programming:
decimal constant(base 10)
octal constant(base 8)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and
hexadecimal constant starts with a 0x.
2. Floating-point constants
A floating point constant is a numeric constant that has
either a fractional form or an exponent form.
For example: -2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5
3. Character constants
A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'
41
Principles of C programming language
4. Escape Sequences
Sometimes, it is necessary to use characters which cannot be
typed or has special meaning in C programming. For example:
newline(enter), tab, question mark etc. In order to use these
characters, escape sequence is used.
For Example: “\n” is used for New line. The backslash ( \
) causes "escape" from the normal way
5. String constants
String constants are the constants which are enclosed in a
pair of double-quote marks. For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline
6. Enumeration constants
Keyword enum is used to define enumeration types. For
example:
enum color {yellow, green, black = 0, white};
Here, color is a variable
and yellow, green, black and white are the enumeration
constants having value 0, 1, 2 and 3 respectively.
41
Principles of C programming language
getchar() function: It reads one character from the standard
input. If there is no more characters available, the special value
EOF will be return.
Example: char c;
………
………
c=getchar();
putchar() function: It writes one character to the standard
output (Monitor).
Example: char c;
c=”A”;
putchar(c);
Formatted Input:
Input data can be entered into the computer from a standard
input device by means of the standard C library function scanf().
This function can be used to enter any combination of numerical
values, single character and strings. The function returns the
number of data items that have been entered successfully.
Syntax: scanf( "control string", arg1, arg2,….argn)
The control string consists of control characters, whitespace
characters and nor-whitespace characters. The control characters
are preceded by a % sign and are listed below.
Control
Character Explanation
%c A single character
%d A decimal integer
%i An integer
%e, %f, %g A floating-point number
41
Principles of C programming language
%o An octal number
%s A string
%x A hexadecimal number
%p A pointer
An integer equal to the number of characters read
%n
so far
%u An unsigned integer
%[ ] A set of characters
%% A percent sign
Example: int i;
float f;
char c;
char str[10];
scanf(“%d %f %c %s”,&i,&f,&c,&str);
Formatted Output:
Output data can be written from the computer onto a
standard output device using the library function printf(). This
function can be used to output any combination of numerical
values, single characters and strings. It similar to the input
function scanf(), except that its purpose is to display data rather
than enter into the computer.
Syntax: printf(control string, arg1, arg2, ….argn)
The control string characters are listed above (same as input
control string)
Example:
printf(“%d %o %x\n”, 100,100,100);
41
Principles of C programming language
printf(“%c %d %f %e %s
%d%%\n”,’3’,4,3.24,66000000,”nine”,8);
will print : 3 4 3.240000 6.600000e+7 nine 8%
C Preprocessor:
The C Preprocessor is not a part of the compiler, but is a
separate step in the compilation process. In simple terms, a C
Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It
must be the first nonblank character, and for readability, a
preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor
directives –
Directive Description
#define Substitutes a preprocessor macro.
#include Inserts a particular header from another file.
#undef Undefines a preprocessor macro.
#ifdef Returns true if this macro is defined.
#ifndef Returns true if this macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative for #if.
#endif Ends preprocessor conditional.
#error Prints error message on stderr.
Preprocessors Examples
41
Principles of C programming language
Analyze the following examples to understand various
directives.
#define MAX_ARRAY_LENGTH 20
#include<stdio.h>
#include"myheader.h"
41
Principles of C programming language
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators (=)
5. Increment & Decrement Operators
6. Conditional Operator ( a1 ? a2 : a3 )
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators:
41
Principles of C programming language
C provides all the basic arithmetic operators. These can operate
on any built-in data type allowed in C.
Symbol Meaning
* multiplication
/ division
% modulo
+ addition
- subtraction
a).Integer Arithmetic:
When both the operands in a single arithmetic expression
such as a+b are integers, the expression is called as an integer
expression, and the operation is called Integer Arithmetic.
Integer arithmetic always yields an integer value.
2. Relational Operators:
Often it is required to compare the relationship between
operands and bring out a decision and program accordingly. This
is when the relational operator comes into picture. These C
supports the following relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
41
Principles of C programming language
>= is greater than or equal to
== is equal to
!= is not equal to
Example:
It is required to compare the marks of 2 students, salary of 2
persons; we can compare those using relational operators.
Operator Meaning
&& Logical
41
Principles of C programming language
AND
|| Logical
OR
! Logical
NOT
a). Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with
relational operators simultaneously. If both the expressions to the
left and to the right of the logical operator is true then the whole
compound expression is true.
For example
! (x >= y) the NOT expression evaluates to true only if the value
of x is neither greater than or equal to y
Truth Table
Value of the
expression
Op-1 Op-2
Op-1 && Op-1 ||
Op-2 Op-2
1 1 1 1
1 0 0 1
0 1 0 1
0 0 0 0
4. Assignment Operators
The Assignment Operator evaluates an expression on the right
of the expression and substitutes it to the value or variable on the
left of the expression.
Example
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as
follows
41
Principles of C programming language
41
Principles of C programming language
y = ++m; (prefix)
m = 5;
y = m++; (post fix)
For example
a = 10;
b = 15;
x = (a > b) ? a : b
41
Principles of C programming language
7. Bitwise Operators
C has a distinction of supporting special operators known as
bitwise operators for manipulation data at bit level. A bitwise
operator operates on each bit of data. Those operators are used
for testing, complementing or shifting bits to the right on left.
Bitwise operators may not be applied to a float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left Shift
>> Shift right Shift
41
Principles of C programming language
8. Special Operators
C supports some special operators of interest such as comma
operator, size of operator, pointer operators(& and *) and
member selection operators (. and ->).
a). The Comma Operator:
The comma operator can be used to link related expressions
together. A comma-linked list of expressions are evaluated left to
right and value of right most expression is the value of the
combined expression.
For example the statement: Value = (x = 10, y = 5, x + y);
Example
m = sizeof (sum);
41
Principles of C programming language
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of
arrays and structures when their sizes are not known to the
programmer. It is also used to allocate memory space
dynamically to variables during the execution of the program.
Arithmetic Expressions:
An arithmetic expression is a combination of variables,
constants, and operators arranged as per the syntax of the
language.
Note: C does not have an operator for exponentiation.
Algebraic C Expression
Expression
axb-c a* b - c
(x+y) (m+n) (x+y) *(m+n)
(ab/c) a*b/c
a/bc a/b*c
Evaluation of Expressions:
Expressions are evaluated using an assignment statement of the
form:
Variable = expression;
Where variable is any valid C variable name. When the
statement is encountered, the expression is evaluated first and the
result then replaced the previous value of the variable on the left-
41
Principles of C programming language
hand side. All variables used in the expression must be assigned
values before evaluation is attempted.
Examples:
X = a * b – c;
Y = b / c * a;
Z = a – b / c + d;
Program:
void main()
{
float a, b, c, 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);
}
Precedence of Arithmetic Operators:
An arithmetic expression without parenthesis will be
evaluated from left to right using the rules of precedence of
operators. There are two distinct priority levels of arithmetic
operators in C
High priority * / %
Low priority + -
The basic evaluation procedure includes ‘two’ left-to-right
passes through the expression.
During the first pass, the high priority operators (if any) are
applied as they encountered.
41
Principles of C programming language
During the second pass, the low priority operators (if any)
are applied as they encountered.
Whenever parentheses are used, the expressions within
parenthesis assume the highest priority.
Example:
Consider the following evaluation statement,
x=a–b/3+c*2–1
Where a = 9, b=12, c= 3 then the statement becomes
x = 9 – 12 / 3 + 3 * 2 – 1
and is evaluated as follows:
First pass:
Step 1 : x = 9 – 4 + 3 * 2 – 1
Step 2 : x = 9 – 4 + 6 – 1
Second Pass:
Step 3 : x = 5 + 6 – 1
Step 4 : x = 11 – 1
Step 5 : x = 10
Operator Precedence and Associativity:
Each operator in C has a precedence associated with it. This
precedence is used to determine how an expression involving
more than one operator is evaluated. There are distinct levels of
precedence and a operator may belong to one of these levels.
Structured programming:
41
Principles of C programming language
Structured programming is a subset of procedural
programming that enforces a logical structure on the program
being written to make it more efficient and easier to understand
and modify. Certain languages such as Ada, Pascal, and dBASE
are designed with features that encourage or enforce a logical
program structure.
Structured programming frequently employs a top-down
design model, in which developers map out the overall program
structure into separate subsections. A defined function or set of
similar functions is coded in a separate module or submodule,
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."
Structured programming was first suggested by Corrado Bohm
and Guiseppe Jacopini. The two mathematicians demonstrated
that any computer program can be written with just three
structures: decisions, sequences, and loops. In this model (which
is often considered to be synonymous with structured
programming, although other models exist) the developer
separates programs into subsections that each have only one
point of access and one point of exit.
Almost any language can use structured programming
techniques to avoid common pitfalls of unstructured languages.
Unstructured programming must rely upon the discipline of the
developer to avoid structural problems, and as a consequence
may result in poorly organized programs. Most modern
procedural languages include features that encourage structured
programming. Object-oriented programming (OOP) can be
thought of as a type of structured programming, uses structured
41
Principles of C programming language
programming techniques for program flow, and adds more
structure for data to the model.
Modular Programming:
Modular programming is the process of subdividing a
computer program into separate sub-programs (Modules).A
module is a separate software component. It can often be used in
a variety of applications and functions with other components of
the system. Similar functions are grouped in the same unit of
programming code and separate functions are developed as
separate units of code so that the code can be reused by other
applications.
Modules in modular programming enforce logical boundaries
between components and improve maintainability. They are
incorporated through interfaces. They are designed in such a way
as to minimize dependencies between different modules. Teams
can develop modules separately and do not require knowledge of
all modules in the system.
Each and every modular application has a version number
associated with it. This provides developers flexibility in module
maintenance. If any changes have to be applied to a module,
only the affected subroutines have to be changed. This makes the
program easier to read and understand.
Modular programming has a main module and many
auxiliary modules. The main module is compiled as an
executable (EXE), which calls the auxiliary module functions.
Auxiliary modules exist as separate executable files, which load
when the main EXE runs. Each module has a unique name
assigned in the PROGRAM statement. Function names across
modules should be unique for easy access if functions used by
the main module must be exported.
Languages that support the module concept are IBM
41
Principles of C programming language
Assembler, COBOL, RPG, FORTRAN, Morpho,Zonnon and
Erlang, among others.
The benefits of using modular programming include:
41