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

Unit-I Naresh IT

The document outlines the principles of the C programming language, emphasizing the importance of clear problem definition and methodical problem-solving steps. It discusses various computer languages, the role of operating systems, and the significance of algorithms and flowcharts in programming. Additionally, it highlights the features, history, and importance of C, noting its efficiency, portability, and modular programming capabilities.

Uploaded by

lavion609
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Unit-I Naresh IT

The document outlines the principles of the C programming language, emphasizing the importance of clear problem definition and methodical problem-solving steps. It discusses various computer languages, the role of operating systems, and the significance of algorithms and flowcharts in programming. Additionally, it highlights the features, history, and importance of C, noting its efficiency, portability, and modular programming capabilities.

Uploaded by

lavion609
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Principles of C programming language

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.1 Procedure (Steps Involved in Problem Analysis)


A computer cannot solve a problem on its own. One has to
provide step by step solutions of the problem to the computer. In
fact, the task of problem solving is not that of the computer. It is
the programmer who has to write down the solution to the
problem in terms of simple operations which the computer can
understand and execute.
In order to solve a problem by the computer, one has to pass
though certain stages or steps. They are
1. Understanding the problem.
2. Analyzing the problem.
3. Developing the solution.
4. Coding and implementation.
1. Understanding the problem: Here we try to understand the
problem to be solved in totally. Before with the next stage or
step, we should be absolutely sure about the objectives of the
given problem.
2. Analyzing the problem: After understanding thoroughly the
problem to be solved, we look different ways of solving the
problem and evaluate each of these methods. The idea here is to
41
Principles of C programming language
search an appropriate solution to the problem under
consideration. The end result of this stage is a broad overview of
the sequence of operations that are to be carries out to solve the
given problem.
3. Developing the solution: Here the overview of the sequence
of operations that was the result of analysis stage is expanded to
form a detailed step by step solution to the problem under
consideration.
4. Coding and implementation: The last stage of the problem
solving is the conversion of the detailed sequence of operations
in to a language that the computer can understand. Here each
step is converted to its equivalent instruction or instructions in
the computer language that has been chosen for the implantation.

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.

Steps involved in algorithm development


41
Principles of C programming language
An algorithm can be defined as “a complete,
unambiguous, finite number of logical steps for solving a
specific problem “

Step1. Identification of input: For an algorithm, there are


quantities to be supplied called input and these are fed
externally. The input is to be identified first for any specified
problem.
Step2: Identification of output: From an algorithm, at least one
quantity is produced, called for any specified problem.
Step3: Identification the processing operations: All the
calculations to be performed in order to lead to output from the
input are to be identified in an orderly manner.
Step4: Processing Definiteness: The instructions composing the
algorithm must be clear and there should not be any ambiguity in
them.
Step5: Processing Finiteness: If we go through the algorithm,
then for all cases, the algorithm should terminate after a finite
number of steps.
Step6: Possessing Effectiveness: The instructions in the
algorithm must be sufficiently basic and in practice they can be
carries out easily.
An algorithm must possess the following properties
1. Finiteness: An algorithm must terminate in a finite number of
steps
2. Definiteness: Each step of the algorithm must be precisely
and unambiguously stated

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.

b.Input and output indicators: Parallelograms are used to


represent input and output operations. Statements like
INPUT, READ and PRINT are represented in these
Parallelograms.

c. Process Indicators: - Rectangle is used to indicate any set


of processing operation such as for storing arithmetic
operations.

d.Decision Makers: The diamond is used for indicating the


step of decision making and therefore known as decision
box. Decision boxes are used to test the conditions or ask
41
Principles of C programming language
questions and depending upon the answers, the appropriate
actions are taken by the computer. The decision box symbol
is

e. Flow Lines: Flow lines indicate the direction being


followed in the flowchart. In a Flowchart, every line must
have an arrow on it to indicate the direction. The arrows
may be in any direction

f. On- Page connectors: Circles are used to join the different


parts of a flowchart and these circles are called on-page
connectors. The uses of these connectors give a neat shape to
the flowcharts. In a complicated problems, a flowchart may
run in to several pages. The parts of the flowchart on different
pages are to be joined with each other. The parts to be joined
are indicated by the circle.

g. Off-page connectors: This connector represents a break in


the path of flowchart which is too large to fit on a single
page. It is similar to on-page connector. The connector

41
Principles of C programming language
symbol marks where the algorithm ends on the first page
and where it continues on the second.

Consider a problem of multiplying two numbers


Algorithm
Step1: Input numbers as a and b.
Step2: Find the product of a and b.
Step3: Print the result.

1.4 C – Language History:


 C is a general-purpose language which has been closely

associated with the UNIX operating system for which it was


developed - since the system and most of the programs that
run it are written in C.

41
Principles of C programming language

 The C programming language is a structure oriented


programming language, developed at Bell Laboratories in
1972 by Dennis Ritchie.
 C programming language features were derived from an
earlier language called “B” (Basic Combined Programming
Language – BCPL).
 C language was invented for implementing UNIX operating
system.
 In 1978, Dennis Ritchie and Brian Kernighan published the
first edition “The C Programming Language” and
commonly known as K&R C.
 In 1983, the American National Standards Institute (ANSI)
established a committee to provide a modern,
comprehensive definition of C. The resulting definition, the
ANSI standard, or “ANSI C”, was completed late 1988.

1.5 Features of C Language: C is the widely used language.


Below are some of the Features of C Programming
1. Low Level Features:
 C Programming provides low level features that are
generally provided by the Lower level languages. C is
Closely Related to Lower Level Language such as
“Assembly Language “.
 It is easier to write assembly language codes in C
programming.

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

 Provides Wide verity of ‘Functions’


 Provides useful Control & Loop Control Statements
4. Bit Manipulation :
 C Programs can be manipulated using bits. We can perform
different operations at bit level. We can manage memory
representation at bit level. [Eg. We can use Structure to
manage Memory at Bit Level]
 It provides wide verity of bit manipulation Operators. We
have bitwise operators to manage Data at bit level.
5. High Level Features :
 It is more User friendly as compare to previous languages.
Previous languages such as BCPL, Pascal and other
programming languages never provide such great features to
manage data.
 Previous languages have their pros and cons but C
Programming collected all useful features of previous
languages thus C become more effective language.
6. Modular programming is a software design technique that
increases the extent to which software is composed of separate
parts, called modules
 C Program Consist of Different Modules that are integrated
together to form complete program

7. Efficient Use of Pointers :


 Pointers has direct access to memory.
 C Supports efficient use of pointer.

41
Principles of C programming language

 It is a robust language with rich set of built-in functions and


operators that can be used to write any complex program.
 The C compiler combines the capabilities of an assembly
language with features of a high-level language.
 Programs Written in C are efficient and fast. This is due to its
variety of data type and powerful operators.
 It is many times faster than BASIC.
 Another important feature of C program is its ability to extend
itself.
 A C program is basically a collection of functions that are
supported by C library. We can also create our own function
and add it to C library.
 C language is the most widely used language in operating
systems and embedded system development today.

1.6 Importance of ‘C’ language:


C language is a famous programming language due to its
qualities. Some qualities are:
1. It is robust language whose rich setup of built in functions and
operator can be used to write any complex program.
2. Program written in C are efficient due to several variety of
data types and powerful operators.

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.

C program structure follows:


1. Documentation section //Comments
2. Linking section - #include<stdio.h>
41
Principles of C programming language
3. Definition section #define Z 8.14748
4. Global declaration section int a = 5;

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.

1.8 Escape Sequence in C


An escape sequence in C language is a sequence of characters
that doesn't represent itself when used inside string literal or
character.
It is composed of two or more characters starting with backslash
\. For example: \n represents new line.

List of Escape Sequences in C


Escape Meaning
41
Principles of C programming language
Sequence
\a Alarm or Beep
\b Backspace
\f Form Feed - A page-
breaking ASCII control
character
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\0 Null

Escape Sequence Example


#include <stdio.h>
#include <conio.h>
main()
{
int number=50;
clrscr();
printf("You\nare\nlearning\n\'C\' language\n\"Do you know C la
nguage\"");
41
Principles of C programming language
getch();
}
Output:
You
are
learning
'C' language
"Do you know C language"

1.9 What are the various Data Types used in C?


C Language is rich in its data types. Data types vary according
to their use. Actually variable type depends on the data type.
Data types give a clear description of nature of data either in
numeric forms (integer or real) or in character form. There are
mainly five types of data types used in the Turbo-C. They are
1. Scalar or Primary data types
2. Secondary or Derived data types
3. User defined data types
4. Empty data types
5. Pointer data types

1. Scalar or Primary data types


The primary data type means fundamental data types. They are
sub divided into four categories:
(a) Integer data type
(b) Float data type
(c) Double precision real or Double or Long float data type
(d) Character data type

Integer: These are of integral type without decimal point. These


are signed or unsigned. These data types are short int, int, long

41
Principles of C programming language
int. The Integer variables have a limited value. They range from
–32768 to 32767

Syntax: int variable1, variable2…….variable n;


“%d “ is a format specification for integer
variables.
Long int: In order to provide some control over the range of
numbers and storage space, C has three classes of integer
storage, namely short int, int and long int, in both signed and
unsigned forms. We declare long and unsigned integers to
increase the range of values.

Floating point types: Floating point numbers are stored in 32


bits with 6 digits of precision. Floating point numbers are
defined in ‘C’ by keyword float. When the accuracy provided by
a float number is not sufficient, the type double can be used to
define the number. A double data type number uses 64 bits
giving a precision of 14 digits. These are known as double
precision numbers. Remember that double type represents the
same data type that float represents, but with a greater precision.
To extend the precision further, we may use long double which
uses 80 bits.

Character types: A single character can be defined as a


character (char) type data. Characters are usually stored in 8 bits
of internal storage.

Type Size (bits) Range


Signed Char 8 -128 to 127
Unsigned Char 8 0 to 255
Int or short int 16 -32,768 to 32,767
Int or Long int 32 -2,147,483,648 to
2,147,483,647
41
Principles of C programming language
Float 32 3.4E-38 to 3.4E+38
Double 64 1.7E-308 to 1.7E+308
Long Double 80 3.4E-4932 to 1.1E+4932

2. Structured Data Type or Derived data type:


They are derived from the primary data type by adding some
additional relationship with the various elements of the primary
or scalar data types. These data types have different structure
depending on the C-coding. These are further divided into three
types.

 Arrays and Strings


 Structures
 Unions
3. Enumerated Data Type or User defined data type:
It provides a way to define our own data type and also define the
value of a variable or an identifier stores into the main memory.
These are two types they are

 Enumerated data type


 User defined data type

4. Void or Empty Data type:


Void or empty data type is used in the user-defined function or
user-defined sub programs. These are used when the function
returns nothing.

5. Pointer data type:


Pointer data types are used to handle the data at their memory
addresses.

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.

Example of variable names:

Salary Delhi Emp_name distance sum1

Any variable declared in a program should confirm to the


following rules:
1. Variable must always begin with a letter, although some
systems permit underscore as the first character.
2. The length of a variable must not be more than 8 characters.
3. White space is not allowed
4. A variable should not be a Keyword
5. It should not contain any special characters.
6. Uppercase and lowercase are significant. That is, the variable
Total is not the same as total or TOTAL.
Examples of Invalid Variable names are
123 (area) 6th abc%

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.

The general format of any declaration


Syntax: datatype v1, v2, v3, ……….. vn;
Where v1, v2, v3 are variable names. Variables are separated by
commas.
Example: int sum;
int number, salary;
double average, mean;

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)

 hexadecimal constant(base 16)

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.

1.12 Input and Output statements used in C:


C support many input and output statements. It also supports
formatted input and output.
Basic Character Input & Output Statements:

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

will print : 100 144 64

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

This directive tells the CPP to replace instances of


MAX_ARRAY_LENGTH with 20. Use #define for constants to
increase readability.

#include<stdio.h>
#include"myheader.h"

41
Principles of C programming language

Operators & Expressions

 The C programming language provides a rich set of built-in


operators, that we can use in manipulating data.
 An Operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations. Operators are
used in programs to manipulate data and variables.
 An expression is a sequence of operands and operators that
reduces to a single value.

Example:10+15 is an expression whose value is 25.


The value can be any type other then void.

‘C’ Operators can be classified into a number of categories. They


include:

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

Example: a-b a+b a*b a/b a%b


Here a and b are variables and are known as operands.

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.

Example: a=14, b=4


a -b=10; a+b=18; a*b = 56; a/b= 3; a%b = 2;

Example Program: #include<stdio.h>


void main()
{
int months, days;
printf(“Enter days \n”);
scanf(“%d”, &days);
months = days / 30;
41
Principles of C programming language
days = days % 30;
printf(“Months = %d Days = %d”, months,
days);
}

b). Real Arithmetic:


An arithmetic operation involving only real operands is
called real arithmetic. A real operand may assume values either
in decimal or exponential notation. Since floating point values
are rounded to the number of significant digits permissible, the
final value is an approximation of the correct result.

Example: X = 6.0/7.0 = 0.857143


Y = 1.0/3.0 = 0.333333

c). Mixed Mode Arithmetic:


When one of the operands is real and the other is integer, the
expression is called a mixed-mode arithmetic expression. If
either operand is of the real type, then only the real operation is
performed and the result is always a real number.

Example: 15 / 10.0 = 1.5

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.

A simple relational expression contains only one relational


operator and takes the following form.
exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple


constants, variables or combination of them.

Given below is a list of examples of relational expressions


and evaluated values.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE

Relational expressions are used in decision making


statements of C language such as if, while and for
statements to decide the course of action of a running
program.

3. Logical Operators: C has the following logical operators;


they compare or evaluate logical and relational expressions.

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.

Example: a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10


the whole expression is true only if both expressions are true i.e.,
if a is greater than b and x is equal to 10.
b). Logical OR (||)
The logical OR is used to combine 2 expressions or the condition
evaluates to true if any one of the 2 expressions is true.

Example: a < m || a < n

The expression evaluates to true if any one of them is true or if


both of them are true. It evaluates to true if a is less than either m
or n and when a is less than both m and n.
c). Logical NOT (!)
The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the
expression is true. In other words it just reverses the value of the
expression.
41
Principles of C programming language

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.

In addition, C has a set of shorthand assignment operators of the


form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a C
binary arithmetic operator. The operator oper is known as
“shorthand assignment operator”.

Example
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as
follows
41
Principles of C programming language

Shorthand assignment operators


Statement with
Statement with
simple
shorthand
assignment
operator
operator
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
5. Increment and Decrement Operators
The increment and decrement operators are one of the unary
operators which are very useful in C language. They are
extensively used in for and while loops. The syntax of the
operators is given below
++ variable name
variable name++
– –variable name
variable name– –

The increment operator ++ adds the value 1 to the current


value of operand and the decrement operator – – subtracts the
value 1 from the current value of operand. ++variable name
and variable name++ mean the same thing when they form
statements independently, they behave differently when they
are used in expression on the right hand side of an assignment
statement.

Consider the following :


m = 5;

41
Principles of C programming language
y = ++m; (prefix)

In this case the value of y and m would be 6


Suppose if we rewrite the above statement as

m = 5;
y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6.


A prefix operator first adds 1 to the operand and then the result is
assigned to the variable on the left. On the other hand, a postfix
operator first assigns the value to the variable on the left and then
increments the operand.
6. Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question mark
(?) and the colon (:)
The syntax for a ternary operator is as follows

exp1 ? exp2 : exp3

The ternary operator works as follows

exp1 is evaluated first. If the expression is true then exp2 is


evaluated & its value becomes the value of the expression. If
exp1 is false, exp3 is evaluated and its value becomes the value
of the expression. Note that only one of the expression is
evaluated.

For example

a = 10;
b = 15;
x = (a > b) ? a : b
41
Principles of C programming language

Here x will be assigned to the value of b. The condition follows


that the expression is false therefore b is assigned to x.
./* Example : to find the maximum value using
conditional operator)
#include<stdio.h>
void main()
{
int i, j, larger;
printf (“Input 2 integers : ”);
scanf(“%d %d”, &i, &j);
larger = i > j ? i : j;
printf(“The largest of two numbers is %d \n”, larger);
}

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);

First assigns 10 to x and 5 to y and finally assigns 15 to value.


Since comma has the lowest precedence in operators the
parenthesis is necessary. Some examples of comma operator are
 In for loops:
for (n=1, m=10, n <=m; n++,m++)
 In while loops
While (c=getchar(), c != ‘10’)
 Exchanging values
t = x, x = y, y = t;

b). The “sizeof” Operator:


The operator size of gives the size of the data type or
variable in terms of bytes occupied in the memory. The operand
may be a variable, a constant or a data type qualifier.

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.

The operators are the higher level of precedence is evaluated


first. The operators of the same precedence are evaluated either
from left-to-right or from right-to-left, depending on the level.
This is known as the associativity property of an operator.

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:

 Less code has to be written.


 A single procedure can be developed for reuse, eliminating the
need to retype the code many times.
 Programs can be designed more easily because a small team
deals with only a small part of the entire code.
 Modular programming allows many programmers to
collaborate on the same application.
 The code is stored across multiple files.
 Code is short, simple and easy to understand.
 Errors can easily be identified, as they are localized to a
subroutine or function.
 The same code can be used in many applications.
 The scoping of variables can easily be controlled.
Difference between Structured programming and Modular
programming
Modular programming means separating your programs into
separate functional units (modules). Each module does a well-
defined task and the modules are called by one-another as
needed. Typically, the state of each module is encapsulated and
only supposed to be altered by the functions from that module.
On the other hand, structured programming is a technique
where you use subprograms (functions) and control-structures
(like if-statements or loops) to structure the control-flow of your
programs instead of doing so by liberal use of go to. If you learn
programming today, you won't ever have learned how to write
unstructured programs.

41

You might also like