C Notes Full
C Notes Full
C Notes Full
DONBOSCO COLLEGE
Kottiyam,Kollam,Kerala
(Affiliated to the University of Kerala)
Name : ……………………………………………………………………………………………
SYLLABUS
Module I: Introduction to programming: Algorithm & Flow charts: Definitions,
Symbols used to draw flowcharts, Program Writing – Structure of the Program, top
down design, Source code, Object code, Executable file, Variables and Constants,
Rules for naming the Variables/Identifiers; Basic data types of C, int, char, float,
double; storage capacity – range of all the data types;
Module II: Basic Elements: Operators and Expressions: Expression Evaluation
(Precedence of Operators); simple I/O statements, Control structures, if, if else,
switch-case, for, while, do-while, break, continue. Arrays: Defining simple arrays,
Multi-dimensional arrays, declaration, initialization and processing.
Module III: Functions & Pointers: concept of modular programming, Library, User
defined functions, declaration, definition & scope, recursion, Pointers: The & and *
Operators, pointer declaration, assignment and arithmetic, visualizing pointers,
call by value; call by reference, dynamic memory allocation. Storage classes.
Module IV: Advanced features: Array & pointer relationship, pointer to arrays,
array of pointers. Strings: String handling functions; Structures and unions; File
handling: text and binary files, file operations, Functions for file handling, Modes
of files
Module I
Introduction to programming: Algorithm & Flow charts: Definitions, Symbols used
to draw flowcharts, Program Writing – Structure of the Program, top down design,
Source code, Object code, Executable file, Variables and Constants, Rules for
naming the Variables/Identifiers; Basic data types of C, int, char, float, double;
storage capacity – range of all the data types;
Input Device: Input device is used to accept the data and instructions in to the
computer. Through the input device, i.e. keyboard, instructions and data are
stored in a computer’s memory. Stored instructions are further read by the
computer from its memory and thus a computer manipulates the data according to
the instructions. The various input devices that can be used in a computer
are keyboards, mouse, light pen, track ball, optical character reader and scanner.
Central Processor Unit: CPU is the abbreviation for central processor unit. It is
the heart of the computer system. It is a hardware device in the computer and
quite often it called as microprocessor chip. Since it is a tiny chip hence called as
microprocessor chip. This chip is produced from silicon vapor over which millions
of transistors are mounted with modern fabrication techniques.
The brain of the computer is CPU. This chip is responsible to interpret and execute
the instructions. It comprises arithmetic and logical unit, registers and control
unit. The arithmetic and logical unit performs various arithmetic and logical
operations on the data based upon the instructions. The control unit generates the
timing and control signals for carrying out operations within the processor.
Registers are used for holding the instructions and storing the results temporarily.
Instructions are stored in the memory and they are fetched one by one and
executed by the processor.
Output Device: The output device is used to display the results on the screen or
to send the data to an output device. The processed data is ultimately sent to the
output device by the computer. The output device can be a monitor, a printer, and
so on.
Memory: Memory is used to store the program. There are two types of semi-
conductor memories. They are as follows:
semi-conductor memory is used for storing the instructions and data in the form
of ones and zeros. The memory can be called user’s memory or read–write memory.
Processor first reads the instructions and data from the primary memory (semi-
conductor memory). Then, it executes the instructions.
One more memory device used by a computer is called read only memory (ROM).
This contains a fixed software program for providing certain operations. This is
non-volatile memory. Its contents cannot be eliminated when power supply goes
off. The basic input–output system (BIOS) is a software used to control various
peripheral devices such as a keyboard, a monitor, a printer, a mouse, ports
including serial and parallel ports. In fact, this is an operating system. It is
possible to access the users’ written programs, i.e. by loading a file, saving it and
doing modifications to it in the later stage. As soon as a personal computer is
switched on, the software gets booted from ROM. Thus, various functions are
assigned to all supporting peripherals of a central processing unit (CPU) and easy
interactions are provided to the user by BIOS while booting the system.
INTRODUCTION TO C
The C language is closely associated with the UNIX operating system. The source
code for the UNIX operating system is in C. The C programs are efficient, fast and
highly portable, i.e. C programs written on one computer can be run on another
with mere or almost no modification.
C is not a strongly typed language. But typed statements are checked thoroughly
by C compilers. The compiler will issue errors and warning messages when syntax
rules are violated. There is no automatic conversion of incompatible data types. A
programmer has to perform explicit type conversion.
terms of 1s and 0s. Hence, writing a program with a machine language is very
difficult. Moreover, speed of writing, testing and debugging is very slow in machine
language. Chances of making careless errors are bound to be there in this
language. The machine language is defined by the hardware design of that
hardware platform. Machine languages are tedious and time consuming.
Assembly Language
The programs written in other than the machine language need to be converted to
the machine language. Translators are needed for conversion from one language to
another. Assemblers are used to convert assembly language program to machine
language. Every processor has its own assembly language. For example, 8085 CPU
has its own assembly language. CPUs such as 8086, 80186, 80286 have their own
assembly languages.
1. It is time consuming for an assembler to write and then test the program.
2. Assembly language programs are not portable.
3. It is necessary to remember the registers of CPU and mnemonic
instructions by the programmer.
4. Several mnemonic instructions are needed to write in assembly language than a
single line in high-level language. Thus, assembly language programs are longer
than the high language programs.
High-Level Language
1. Assembler
2. Compiler
3. Interpreter
Assembler
Compiler: Compilers are the translators, which translate all the instructions of the
program into machine codes, which can be used again and again . The program,
which is to be translated, is called the source program and after translation the
object code is generated. The source program is input to the compiler. The object
code is output for the secondary storage device. The entire program will be read by
the compiler first and generates the object code. However, in interpreter each line
is executed and object code is provided.
Interpreter: Interpreters also come in the group of translators. It helps the user to
execute the source program with a few differences as compared to compilers. The
source program is just like English statements in both interpreters and compilers.
The interpreter generates object codes for the source program. Interpreter reads
the program line by line, whereas in compiler the entire program is read by the
compiler, which then generates the object codes. Interpreter directly executes the
program from its source code. Due to this, every time the source code should be
inputted to the interpreter. In other words, each line is converted into the object
codes. It takes very less time for execution because no intermediate object code is
generated.
STRUCTURE OF A C PROGRAM
Include Header File Section: C program depends upon some header files for
function definition that are used in the program. Each header file has extension
‘.h’. The header files are included at the beginning of the program in the C
language. These files should be included using # include directive as given below.
Example:
# include <stdio.h> or
# include “stdio.h”
1. In this example, <stdio.h> file is included, i.e. all the definitions and prototypes
of function defined in this file are available in the current program. This file is
also compiled with the original program.
2. Global Declaration:This section declares some variables that are used in more
than one function. These variables are known as global variables. This section
must be declared outside of all the functions.
3. Function main():Every program written in C must contain main() and its
execution starts at the beginning of this function. In ASCII C standard, first line
of C program from where program execution begins is written as follows.
int main(void)
This is the function definition for main(). Parenthesis followed to main is to tell the
user again that main() is a function. The int main(void) is a function that takes no
arguments and returns a value of type int. Here in this line, int and void are
keywords and they have special meanings assigned by the compiler. In case int is
not mentioned in the above statement, by default the function returns an integer.
Alternately, one can also write the first line of C program from where program
execution begins is as follows.
void main(void)
Here, this function takes no arguments and returns nothing. Alternately, one can
also write the same function as follows.
The programmer can either write the function main with int main(void) or void
main(). Only in the formal case, return statement should be used before the end of
function for terminating the execution of the main function.
The program contains statements that are enclosed within the braces. The opening
brace ({) and closing brace (}) are used in C. Between these two braces, the program
should declare declaration and executable part. The opening curly brace specifies
the start of the definition of the main function. The closing curly brace specifies
the end of the code for the main function.
4. Declaration Part:The declaration part declares the entire local variables that are
used in executable part. Local variable scope is limited to that function where the
local variables are declared. The initializations of variables can also be done in
this section. The initialization means providing initial value to the variables.
5. Executable Part:This part contains the statements following the declaration of
the variables. This part contains a set of statements or a single statement.
6. Function Call:From the main() a user defined function can be invoked by the
user as per need/application.
7. User-defined Function:The functions defined by the user are called user-defined
functions. These functions are defined outside the main() function.
8. Body of the Function: The statements enclosed within the body of the function
(between opening and closing brace) are called body of the function.
9. Comments:Comments are not necessary in a program. However, to understand
the flow of programs a programmer can insert comments in the program.
Comments are to be inserted by the programmer. It is useful for documentation.
The clarity of the program can be followed if it is properly documented.
Comments are statements that give us information about the program which are to
be placed between the delimiters /* and */. The programmers in the programs for
enhancing the lucidity frequently use comments. The compiler does not execute
comments.
Example:
/* This is single comment */
/* This is an example of /* nested comments */*/
/* This is an example of
of comments in
multiple lines */ /* It can be nested */
PROGRAMMING RULES
the declaration part. The user can also write one or more statements in one line
separating them with a semi-colon (;). Hence, it is often called a free-form
language. The following statements are valid:
a=b+c;
d=b*c;
or
a=b+c; d=b*c;
7. The opening and closing braces should be balanced, i.e. if opening braces are four;
closing braces should also be four.
Linking is also an essential process. It puts together all other program files and
functions that are required by the program. For example, if the programmer is
using pow() function, then the object code of this function should be brought
from math.h library of the system and linked to the main() program. After linking,
the program is stored on the disc.
4. Executing the Program:After the compilation the executable object code will be
loaded in the computer’s main memory and the program is executed. The loader
performs this function. All the above steps/phases of C program can be performed
using menu options of the editor.
same is displayed. The user is again forced to go to edit window. After removing an
error, the compiler compiles the program. Here, at this stage object code is
generated. During the program execution, if user makes mistakes in inputting
data, the result would not be appropriate. Therefore, the user again has to enter
the data. The output is generated when a program is error free.
ADVANTAGES OF C
1. It contains a powerful data definition. The data type supported are characters,
alphanumeric, integers, long integer, floats and double. It also supports string
manipulation in the form of character array.
7. The C language has 32 keywords and about 145 library functions and near about
30 header files.
8. C works closely with machines and matches assembly language in many ways.
HEADER FILES
stdio.h: Standard input and output files. All formatted and unformatted functions
include file operation functions defined in this file. The most useful
formatted printf() and scanf() are defined in this file. This file must be included at
the top of the program. Most useful functions from this header files are printf(),
scanf(), getchar(), gets(), putc() and putchar().
conio.h: Console input and output. This file contains input and output functions
along with a few graphic-supporting functions. The getch(),
getche() and clrscr() functions are defined in this file.
math.h: This file contains all mathematical and other useful functions. The
commonly useful functions from this files are floor(), abs(), ceil(), pow(), sin(),
cos() and tan().
There are different ways of representing the logical steps for finding a solution of a
given problem. They are as follows:
1. Algorithm
2. Flowchart
3. Pseudo-code
In the algorithm, a description of the steps for solving a given problem is provided.
Here, stress is given on the text. Flowchart represents the solution of a given
problem graphically. Pictorial representation of the logical steps is a flowchart.
Another way to express the solution of a given problem is by means of a pseudo-
code.
ALGORITHM
The algorithm is defined as ‘the finite set of steps, which provide a chain of actions
for solving a problem’. Each step in the algorithm should be well defined.
STEP 1: Start.
STEP 6: Exit.
CLASSIFICATION OF ALGORITHMS
On the basis of repetitive steps, an algorithm can further be classified into two
types.
ii. In the above statement, it is predicted that the loop will iterate 10
times.
2. Indirect Algorithm: In this type of algorithm, repetitively steps are executed.
Exactly how many repetitions are to be made is unknown.
for (j=1;j<=n;j++)
Based on the control transfer, the algorithms are categorized in the following three
types.
Example:
Testing whether a number is even or odd. Testing whether a number is
positive or negative.
2. Non-deterministic:In this type of algorithm to reach to the solution, we
have one of the multiple paths.
Example:
To find a day of a week.
3. Random algorithm:After executing a few steps, the control of the program
transfers to another step randomly, which is known as a random algorithm.
A random search
Example:
To find shortest paths from a given source to all destinations in the network.
FLOWCHARTS
Start and end: The start and end symbols indicate both the beginning and the end
of the flowchart. This symbol looks like a flat oval shaped. Usually this symbol is
used twice in a flowchart, that is, at the beginning and at the end.
Decision or test symbol: The decision symbol is diamond shaped. This symbol is
used to take one of the decisions. Depending on the condition the decision block
selects one of the alternatives. While solving a problem, one can take a single, two
or multiple alternatives depending upon the situation. In case the condition is
satisfied /TRUE a set of statement(s) will be executed otherwise for false the
control transfers to exit.
Single alternative decision: Here more than one flow line can be used depending
upon the condition. It is usually in the form of a ‘yes’ or ‘no’ question, with
branching flow line depending upon the answer. With a single alternative, the flow
diagram will be as
Multiple alternative decisions: Every decision block has two branches. In case
the condition is satisfied, execution of statements of appropriate blocks take place,
otherwise next condition will be verified. If condition 1 is satisfied then block 1
statements are executed. In the same way, other decision blocks are executed.
parts in a flowchart. Quite often, two parts of the flowcharts may be on two
separate pages. In such a case, connector can be used for joining the two parts.
Only one flow line is shown with the symbol. Only connector names are written
inside the symbol, that is, alphabets or numbers.
valid C character set which are as follows: (i) Letters (ii)Digits (iii) White Spaces &
Escape Sequences and (iv) Special Characters. As C character set consists of
escape sequences so each escape sequence begins with back slash (\) and it
represents a single character. Any character can be represented as character
constant using escape sequence.
Character set
Lowercase
Horizontal tab \t
a to z
Vertical tab \v
New line \n
Form feed \f
Backslash \\
Alert bell \a
Carriage return \r
Question mark \?
Single quote \’
Double quote \”
The C characters are assigned unique codes. There are many character codes used
in the computer system. The widely and standard codes used in computer are
ASCII and EBCDIC (Extended Binary Coded Decimal Interchange Code).
DELIMITERS
The language pattern of C uses special kind of symbols, which are called
delimiters.
Delimiters
TYPES OF TOKENS
1. Keywords: Key words are reserved by the compiler. There are 32 keywords
(ANSI Standard).
2. Variables: These are user defined. Any number of variables can be defined.
3. Constants: Constants are assigned to variables.
4. Operators: Operators are of different types and are used in expressions.
5. Special Characters: These characters are used in different declarations in
C.
6. Srings: A sequence of characters.
THE C KEYWORDS
The C keywords are reserved words by the compiler. All the C keywords have been
assigned fixed meanings and they cannot be used as variable names.
C keywords
IDENTIFIERS
Identifiers
Identifiers are user-defined names. They are generally defined in lowercase letters.
However, the uppercase letters are also permitted. The underscore (_) symbol can
be used as an identifier. In general, an underscore is used by a programmer as a
link between two words for the long identifiers.
Example:
1. #define N 10
2. #define a 15
CONSTANTS
The constants in C are applicable to the values, which do not change during the
execution of a program. There are several types of constants in C. They are
classified into following groups
Numerical Constants
2. Real Constants: Real constants are often known as floating point constants.
Real constants can be represented in exponential or fractional form. Integer
constants are unfit to represent many quantities. Many parameters or
quantities are defined not only in integers but also in real numbers. For
example, length, height, price, distance, etc. are also measured in real
numbers.
The part that precedes e is called mantissa and the part that follows it is an
exponent. In this example, 2.4561 is the mantissa and +3 is the exponent.
Character Constant
Example:
‘a’, ‘8’, ‘−’
Length of a character, at the most, is one character.
Character constants have integer values known as ASCII values. For example the
statement printf (“%c %d”, 65, ‘B’) will display character ‘A’ and 66.
2. String Constants: String constants are a sequence of characters enclosed
within double quote marks. The string may be a combination of all kinds of
symbols.
Example:
“Hello”, “India”, “444”, “a”.
VARIABLES
A variable is used to store values. It has memory location and can store single
value at a time. When a program is executed, many operations are carried out on
the data. The data types are integers, real or character constants. The data is
stored in the memory, and at the time of execution it is fetched for carrying out
different operations on it.
A variable is a data name used for storing a data value. Its value may be changed
during the program execution. The variable value keeps on changing during the
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 26
lOMoARcPSD|27682773
DATA TYPES
The basic data types are char, int, float and double.
The C supports a number of qualifiers that can be applied to these basic data type.
The short and long qualifiers provide different length to int. The short is always 16
bits and long is 32 bits, i.e. int is either 16 or 32 bits.
Eg: int a;
p = &a;
void sum();
void main()
{
sum();
void sum()
Statements;
The above sample program has two functions sum() and main(). Where
sum()is a user defined function.
int a[10]; the variable a can store values upto 10. The variable start from
a[0],a[1],....a[9].
i. Structure: To declare all the variables for the program under a common name. It
uses separate memory location for the variables.
ii. Union: same as structure. It uses same memory location for the variables.
Here jan will be assigned a constant value 0, feb as 1 and so on. The identifiers are
not to be enclosed in quotation mark. Integer constants are not permitted.
iv.Typedef:
String name; //creates a string variable name of size 50Derived data types are
pointers, functions and arrays.
C DATA TYPES
All C compilers offer different integer data types. They are short and long. Short
integer requires half the space in memory than the long. The short integer requires
2 bytes and long integers 4 bytes
Occupies 4
Occupies 2 bytes in memory bytes
in memory
Range:
Range: −32,768 to 32,767 −2147483648
to 2147483647
Program runs
Program runs faster
slower
Format
Format specifier is %d or %i
specifer is %ld
Example: Example:
long
int a=2;
b=123456;
long
short int b=2;
int c=1234567;
Occupies 2 bytes in
Occupies 2 bytes in memory
memory
Range: −32,768 to
Range: 0 to 65535
32,767
Format specifier
Format specifier is %u
is %d or %i
By default signed
By default unsigned int is
int is short signed
short unsigned int
int
Example: 4294967295
Unsigned
Signed Character
Character
Occupies 1
Occupies 1 bytes in memory
bytes in memory
Format
Format specifier: %c
specifier: %c
Unsigned
Signed Character
Character
When printed
When printed using %d format using %d format
specifier, prints ASCII character. specifier, prints
ASCII character
unsigned char
char ch=‘b’;
=‘b’;
Occupies 4
bytes in Occupies 8 bytes in memory
memory
Range:
3.4e−38 to Range: 1.7 e−308 to +1.7e+308
+3.4e+38
Format
Format string: %lf
string: %f
Example: Example:
float a; double y;
Example:
long double k;
DECLARING VARIABLES
The declaration of variables should be done in declaration part of the program. The
variable must be declared before they are used in the program. Declaration
ensures the following two things: (i) compiler obtains the variable name and (ii) it
tells to the compiler data type of the variable being declared and helps in allocating
the memory. The variable can also be declared before main() such variables are
called external variables. The syntax of declaring a variable is as follows.
Syntax:
Data_type variable_name;
Example:
int age;
char m;
float s;
double k;
int a,b,c;
The int, char, float and double are keywords to represent data types. Commas
separate the variables, in case variables are more than one.
Character char
Integer int
INITIALIZING VARIABLES
Variables declared can be assigned or initialized using assignment operator ‘=’. The
declaration and initialization can also be done in the same line.
Syntax:
variable_name = constant;
or
Example:
x=5; where x is an integer variable.
Example:
int y=4;
Example:
The third example as cited above for declaration of variables is also a valid
statement.
Value assignment
Multiple assignment
In Figure , the variable z is assigned a value 1, and z then assigns its value
to y and again y to x. Thus, initialization in chain system is done. However, note
that following declarations are invalid:
DYNAMIC INITIALIZATION
TYPE MODIFIERS
The keywords signed, unsigned, short and long are type modifiers. A type modifier
changes the meaning of basic data type and produces a new data type. Each of
these type modifiers is applicable to the basic data type int. The modifiers signed
and unsigned are also applicable to the type char. The long type modifier can be
applicable to double type.
Example:
TYPE CONVERSION
In C, it is possible to convert one data type to another. This process can be done
either explicitly or implicitly. The following section describes explicit type
conversion.
Similarly, in case an expression contains one of the operands as long int and the
other unsigned int operands, the latter operand is converted to long int.
the following table describes automatic data type conversion from one data type to
another while evaluating an expression.
WRAPPING AROUND
When the value of variable goes beyond its limit, the compiler would not flag any
error message. It just wraps around the value of a variable. For example, the range
of unsigned integer is 0 to 65535. In this type, negative values and values greater
than 65535 are compatible.
The value assigned is greater by 1 than the range. Here, the compiler starts again
from beginning after reaching the end of the range.
Constant Variable
If we want the value of a certain variable to remain the same or unchanged during
the program execution, it can be done by declaring the variable as a constant. The
keyword const is then prefixed before the declaration. It tells the compiler that the
variable is a constant. Thus, constant declared variables are protected from
modification.
Example:
The compiler protects the value of ‘m’ from modification. The user cannot assign
any value to ‘m’, but using pointer the value can be changed. When user attempts
to modify the value of constant variable, the message ‘cannot modify the constant
object’ will be displayed.
Volatile Variable
The volatile variables are those variables that can be changed at any time by other
external program or the same program. The syntax is as
follows:
volatile int d;
Types of operators
Symbolic Representatio
Type of Operator
n
Comma operator ,
Conditional operators ?:
OPERATOR PRECEDENCE
ASSOCIATIVITY
1. Left to right: In this type, expression, evaluation starts from left to right
direction.
Example:
12 * 4 / 8 % 2
In the above expression, all operators are having the same precedence, and so
associativity rule is followed (i.e. direction of execution is from left to right).
= 48 / 8 % 2
=6%2
= 0 (The above modulus operation provides remainder 0)
2. Right to left: In this type, expression, evaluation starts from right to left
direction.
Example:
a=b=c
In the above example, assignment operators are used. The value of c is assigned to
b and then to a. Thus, evaluation, is from right to left.
1. Comma Operator (,): The comma operator is used to separate two or more
expressions. The comma operator has the lowest priority among all the operators.
It is not essential to enclose the expressions with comma operators within the
parentheses. For example, the following statements are valid.
Example:
a. a=2,b=4,c=a+b;
b. (a=2,b=4,c=a+b;)
2. Conditional Operator (?): The conditional operator contains condition followed
by two statements or values. The condition operator is also called the ternary
operator. If the condition is true, the first statement is executed, otherwise the
second statement is executed.
Conditional operators (?) and (:) are sometimes called ternary operators because
they take three arguments. The syntax of the conditional operator is as follows:
Syntax:
Condition ? (expression1) : (expression2);
Two expressions are separated by a colon. If the condition is true expression 1 gets
evaluated, otherwise expression 2 gets evaluated. The condition is always written
before the ? mark.
ARITHMETIC OPERATORS
There are three types of arithmetic operators. These are (i) binary operator and (ii)
unary operator and (iii) ternary operator
1.
Binary Operator: These operators are commonly used in most of the computer
languages. These arithmetic operators are used for numerical calculations between
the two constant values. They are also called Binary Arithmetic Operators. Binary
operators are those operators which require two operands. C evaluates arithmetic
operations as follows.
Arithmetic operators
+ Addition 2+2=4
− Subtraction 5−3=2
* Multiplication 2*5=10
/ Division 10/2=5
2.
Unary Operators: The operators which require only one operand are called unary
operators. Unary operators are increment operator (++), decrement (−−) and minus
(−).
− Minus
++ Increment
−− Decrement
1.
Minus (−): Unary minus is used for indicating or changing the algebraic sign of a
value.
Example:
int x=−50;
int y=−x;
assign the value of −50 to x and the value of −50 to y through x. The minus (−) sign
used in this way is called the unary operator because it takes just one operand.
There is no unary plus (+) in C. Even though, a value assigned with plus sign is
valid, for example int x=+50, here, + is valid, but in practice this sign should not
be attached in C.
2.
Increment (++) and Decrement (−−) Operators: The C compilers produce very
fast and efficient object codes for increment and decrement operations. This code
is better than generated by using the equivalent assignment statement. So,
increment and decrement operators should be used whenever possible.
The operator ++ adds one to its operand, whereas the operator −− subtracts one
from its operand. For justification, x=x+1 can be written as x++; and x=x−1; can be
written as x−−;. Both these operators may either follow or precede the operand.
That is x=x+1; can be represented as x++; or ++x;
If ‘++’ or ‘−−’ are used as a suffix to the variable name, then post-
increment/decrement operations take place. Consider an example for
understanding the ‘++’ operator as a suffix to the variable.
x=20;
y=10;
z=x*y++;
In the above equation, the current value of y is used for the product. The result is
200, which is assigned to ‘z’. After multiplication the value of y is incremented by
one.
If ‘++’ or ‘−−’ are used as a prefix to the variable name, then pre
increment/decrement operations take place. Consider an example for
understanding ‘++’ operator as a prefix to the variable.
x=20;
y=10;
z=x*++y;
z=x*y++;
a=x*y;
printf(“\n%d %d”,z,a);
RELATIONAL OPERATORS
These operators are used to distinguish between two values depending on their
relations. These operators provide the relationship between two expressions. If the
relation is true then it returns a value 1 otherwise 0 for false. The relational
operators together with their descriptions,
Assignment operators
Consider the following example: k=k+3; in this expression, the variable on the left
side of = is repeated on the right. The same can be written as follows:
k+=3;
The operators = and += are called assignment operators. The binary operators
which need two operands to their either side are surely have a corresponding
assignment operator operand = to the left side.
LOGICAL OPERATORS
The logical relationship between the two expressions is tested with logical
operators. Using these operators, two expressions can be joined. After checking the
conditions, it provides logical true (1) or false (0) status. The operands could be
constants, variables and expressions the three logical operators
1. The logical AND (&&) operator provides true result when both expressions are
true, otherwise 0.
2. The logical OR (||) operator provides true result when one of the expressions is
true, otherwise 0.
3. The logical NOT operator (!) provides 0 if the condition is true, otherwise 1.
BITWISE OPERATORS
C supports six bit operators. These operators can operate only on integer
operands such as int, char, short, long.
Bitwise operators
Operators Meaning
˜ One’s complement
| Bitwise OR
Shifting two bits right means the inputted number is to be divided by 2s where s is
the number of shifts i.e. in short y=n/2s, where n = number and s = the number of
position to be shift.
There are a number of I/O functions in C, based on the data types. The
input/output functions are classified in two types:
1. Formatted functions
2. Unformatted functions
With formatted functions, the input or output is formatted as per our requirement.
The readability in easy way is possible with formatted functions. For example, with
formatted functions one can decide how the result should appear or display on the
screen.
1.
scanf(“control string”, argu1, argu2,. . .);
Precisely, if we write scanf() as scanf(“%d”,&x); where %d is a control string which
is nothing but conversion specification and it is to be placed within double
quote. The other part is the argument and a sign & (ampersand) must precede it.
Arguments are the identifiers.
For displaying the result, prinf() formatted function is used.
2. Unformatted Functions: The unformatted input/output functions work only with
character data type. They do not require format conversion symbol for formatting
of data types because they work only with character data type. There is no need to
convert data. In case, values of other data types are passed to these functions,
they are treated as character data.
FORMATTED FUNCTIONS
1. The printf() statement: The formatted output as per the programmers requirement
is displayed on the screen with printf(). The list of variables can be indicated in
the printf().The syntax of printf() statement is as follows:
The control string specifies the field format such as %d, %s, %f, and variables as
taken by the programmer.
Flags: Flags are used for output justification, numeric signs, decimal points,
trailing zeros. The flag (−) left justifies the result. If it is not given, the default is
right justification. The plus (+) signed conversion result always starts with a plus
(+) or a minus (−) sign.
Width specifier : It sets the minimum field width for an output value. Width can be
specified through a decimal point or using an asterisk ‘*’.
2. The scanf() statement: The scanf() statement reads all types of data values. It is
used for runtime assignment of variables. The scanf() statement also requires
conversion symbol to identify the data to be read during the execution of the
program. The scanf() statement stops functioning when some input entered does
not match with format string. The syntax of the scanf() statement is the same
as printf() except they work exactly opposite of each other.
Syntax:
The syntax of the input function for inputting the data is scanf().
Example:
The control string has to be enclosed within double quotes. It specifies the format
specifier, such as %d for integer, %f for float, %c for character, etc. and the data
are to be invoked by arguments, such as address of variable1, address of variable
2, etc.
scanf(“%d”,&x);
Here, “ %d” is the format specifier in the control string, which is nothing but the
conversion specification and it is to be placed within double quotes. The other part
is the variable and & (ampersand) must precede it.
scanf(“%d %f %c”,&a,&b,&c);
The scanf() statement requires ‘&’ operator called address operator. The address
operator prints the memory location of the variable. Here, in the scanf() statement
the role of ‘&’ operator is to indicate the memory location of the variable, so that
the value read would be placed at that location.
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 47
lOMoARcPSD|27682773
The scanf() statement also returns values. The return value is exactly equal to the
number of values correctly read. In case of any mismatch, error will be thrown.
The prinf() and scanf() statements follow different data types It can be seen from
this table that format string is initialized with %sign as a special character, which
indicates the format of the data to be displayed on the screen.
Short integer %d or %i
Short unsigned %u
Unsigned hexadecimal %x
Unsigned octal %o
Floating %f or %g
Real
Double floating %lf
Signed character %c
String %s
Octal number %o
The printf() and scanf() statements follow the combination of characters called
escape sequences. In order to come out, computers from routine sequence escape
sequences are used. These are nothing but special characters starting with ‘\’.
\n New line 10
\b Backspace 8
\f Form feed 12
\’ Single quote 39
\\ Backslash 92
\o Null 0
\t Horizontal tab 9
\r Carriage return 13
\a Alert 7
\” Double quote 34
\v Vertical tab 11
\? Question mark 63
UNFORMATTED FUNCTIONS
1. Character I/O
2. String I/O
3. File I/O
4. Character I/O
1.getchar() -
This function reads a character-type data from standard input. It reads one
character at a time till the user presses the enter key. The syntax of
the getchar() is as follows:
Variable name=getchar();
Example:
char c;
c=getchar();
OUTPUT:
Enter a char :g
a=g
2.
putchar();
This function prints one character on the screen at a time, read by the standard
input.
putchar(variable name);
Example:
char c=‘C’;
putchar (c);
void main()
{
char c=‘C’;
clrscr();
putchar(c);
}
OUTPUT:
C
3.
These functions read any alphanumeric character from the standard input device.
The character entered is not displayed by the gectch() function.
Syntax of getche() is as follows:
getche();
The getche() accepts and displays the character whereas getch() accepts but does
not display the character.
4.
putch();
This function prints any alphanumeric character taken by the standard input
device.
1.
String I/O
1.
gets ();
This function is used for accepting any string through stdin (keyboard) until enter
key is pressed. The header file stdio.h is needed for implementing the above
function. Format of gets() is as follows:
void main()
char ch[30];
clrscr();
OUTPUT:
4.24 Write a program to print the accepted character using puts() function.
Explanation:
This program is the same as the previous one. Here, to display the
string puts() function is used.
void main()
char ch[30];
clrscr();
gets(ch);
puts(ch);
OUTPUT:
Entered String:
puts is in use.
3.
cgets();
This function reads string from the console. The syntax is as follows.
Syntax:
cgets(char *st);
4.
cputs() :
This function displays string on the console. The syntax is as follows.
Syntax:
cputs(char *st);
clrscr();
1.
clrscr();
This function is used to clear the screen. It clears previous output from the screen
and displays the output of the current program from the first line of the screen. It
is defined in conio.h header file. The syntax is as follows.
Syntax:
clrscr();
2.
exit();
This function terminates the program. It is defined in process.h header file. The
syntax is as follows.
Syntax:
exit();
3.
sleep();
This function pauses the execution of the program for a given number of seconds.
The number of seconds is to be enclosed between parentheses. It is defined in
dos.h header file. The syntax is as follows.
Syntax:
sleep(1);
void main()
clrscr();
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 54
lOMoARcPSD|27682773
gets(t);
sleep(5);
puts(t);
getche();
OUTPUT:
Explanation:
3.
system ();
Syntax:
system (“dir”);
The command should be enclosed within double quotation marks. After we run
this command using C, directory will be displayed. Programmer can verify this
command.
1. The if statement
2. The if–else statement
3. The if–else–if ladder statement
4. The switch case statement
5. The goto unconditional jump
6. The loop statement
Besides, the C also supports other control statements such as continue, break.
The decision-making statement checks the given condition and then executes its
sub-block. The decision statement decides which statement to execute after the
success or failure of a given condition.
The relational operators are useful for comparing the two values. They can be used
to check whether they are equal to each other, unequal or one is smaller/greater
than the other.
Sequential execution: The statements in the program are executed one after
another in a sequential manner. This is called the sequential execution.
THE IF STATEMENT
C uses the keyword if to execute a set of command lines or one command line
when the logical condition is true. It has only one option. The sets of command
lines are executed only when the logical condition is true .
The if statement
the if block statements execute only when the condition in if is true. When the
condition is false, program control executes the next statement which appears
after the if statement.
The if–else statement takes care of the true and false conditions. It has two blocks.
One block is for if and it is executed when the condition is true. The other block is
of else and it is executed when the condition is false. The else statement cannot be
used without if. No multiple else statements are allowed with one if
if ( expression is true)
statement1; /* if block */
statement2;
else
statement4;
5.
else
OR
if ( expression is true)
statement1; /* if block */
statement2;
else
statement4;
Write a program to calculate the square of those numbers only whose least
significant digit is 5.
void main()
int s,d;
clrscr();
scanf(“%d”,&s);
d=s%10;
if(d==5)
s=s/10;
else
OUTPUT:
Enter a Number : 25
Square = 625
Explanation:
TABLE
Basic=Rs. 3000.
Hra=20% of basic.
Da=110% of basic.
Conveyance=Rs.500.
Incentive=10% of sales.
Bonus=Rs. 500.
2. TABLE
Basic=Rs. 3000.
Hra=20% of basic.
Da=110% of basic.
Conveyance=Rs.500.
Incentive=5% of sales.
Bonus=Rs. 200.
void main()
float bs,hra,da,cv,incentive,bonus,sale,ts;
clrscr();
scanf(“%f”, &sale);
if(sale>=100000)
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incentive=sale*10/100;
bonus=500;
else
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incentive=sale*5/100;
bonus=200;
ts=bs+hra+da+cv+incentive+bonus;
printf(“\nHra : %.2f”,hra);
printf(“\nDa : %.2f”,da);
printf(“\nConveyance : %.2f”,cv);
printf(“\nIncentive : %.2f”,incentive);
printf(“\nBonus : %.2f”,bonus);
getch();
OUTPUT:
Hra: 600.00
Da: 3300.00
Conveyance: 500.00
Incentive: 10000.00
Bonus: 500.00
Explanation:
The if condition checks the given figure of sales. If sale is more than Rs. 1,00,000,
the first bock following the if statement is executed otherwise the else block is
executed. In both the blocks, simple arithmetic operations are performed to
calculate the allowances and total salary.
In this kind of statement, a number of logical conditions are checked for executing
various statements. Here, if any logical condition is true the compiler executes the
block followed by if condition, other wise it skips and executes the else block. In
the if–else statement, the else block is executed by default after failure of
condition. In order to execute the else block depending upon certain condition we
can add, repetitively, if statements in else block. This kind of nesting will be
unlimited. Figure 5.5 describes the nested if–else–if blocks.
if(condition)
{
/*Inside first if block*/
if(condition)
{
From the above block, following rules can be described for applying nested if-else-
if statements.
In this kind of statement, a number of logical conditions are checked for executing
various statements. Here, if the first logical condition is true the compiler executes
the block followed by first if condition, otherwise it skips that block and checks for
next logical condition followed by else-if, if the condition is true the block of
statements followed by that if condition is executed. The process is continued until
a true condition is occurred or an else block is occurred. If all if conditions become
false, it executes the else block. In the if-else-if ladder statement, the else block
may or may not have the else block.
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 66
lOMoARcPSD|27682773
if(condition)
statement 2;
else if(condition)
statement 4;
else if(condition)
statement 6;
else
statement 8;
From the above block, following rules can be described for applying nested if-else-
if statements:
Given below programs are described on the bases on nested if-else and if-else-
if ladder statements.
The keyword break allows the programmers to terminate the loop. The break skips
from the loop or block in which it is defined. The control then automatically goes to
the first statement after the loop or block. The break can be associated with all
conditional statements.
We can also use the break statements in the nested loops. If we use
the break statement in the innermost loop, then the control of the program is
terminated only from the innermost loop.
The difference between the break and exit() is provided in Table 5.1.
Sr.
break exit()
No
1. It is a keyword. It is a function.
break continue
Exits from current block or loop. Loop takes the next iteration.
goto label;
Here, the label is the position where the control is to be transferred. A few
examples are described for the sake of understanding.
switch(variable or expression)
case constant A :
statement;
break;
case constant B :
statement;
break;
default :
statement ;
The switch expression should not be terminated with a semi-colon and/or with
any other symbol. The entire case structure following switch should be enclosed
with curly braces. The keyword case is followed by a constant. Every constant
terminates with a colon. Each case statement must contain different constant
values. Any number of case statements can be provided. If the case structure
contains multiple statements, they need not be enclosed with curly braces. Here,
the keywords case and break perform the job of opening and closing curly braces,
respectively.
3. The switch execution
When one of the cases satisfies, the statements following it are executed. In case,
there is no match, the default case is executed. The default can be put anywhere
in the switch expression. The switch statement can also be written without
the default statement. The break statement used in switch causes the control to go
outside the switch block. By mistake, if no break statements are given all the
cases following it are executed
The C supports nested switch statements. The inner switch can be a part of an
outer switch. The inner and outer switch case constants may be the same. No
conflicts arise even if they are the same. A few examples are given below on the
basis of nested switch statements.
The distinction between the switch case and the nested ifs is narrated in Table 5.3.
Table 5.3 Distinction between the switch case and nested ifs
switch statement
Explanation:
In this program, a menu appears with five options and it requests the users to
enter their choice. The choice entered by the user is then passed
to switch statement. In the switch statement, the value is checked with all the case
constants. The matched case statement is executed in which the line is printed of
the user’s choice. If the user enters a non-listed value, then no match occurs
and default is executed. The default warns the user with a mes-sage ‘Invalid
Choice’.
What is a Loop?
Steps in Loop
Initialization: It is the first step in which starting and final values are assigned to
the loop variable. Each time the updated value is checked by the loop itself.
The C language supports three types of loop control statements and their syntaxes
are described in Table 6.1 (also see Figures 6.1 and 6.2).
Loops in C
The for loop statement comprises three actions. These actions are placed in
the for statement itself. The three actions are initialize counter, test
condition and Re-evaluation parameters, which are included in one statement. The
expressions are separated by semi-colons (;). This leads the programmer to
visualize the parameters easily. The for statement is equivalent to while and do-
while statements. The only difference between for and while is that in the latter
case logical condition is tested and then the body of the loop gets executed.
However, in the for statement, test is always performed at the beginning of the
loop. The body of the loop may not be executed at all times if the condition fails at
the beginning.
for (a=10;a<10;a−−)
printf(“%d”, a);
For example, in the above two-line program will never execute because the test
condition is not proper at the beginning, hence statement following to for loop does
not execute.
The do-while loop executes the body of the loop at least once regardless of the
logical condition.
The for loop allows to execute a set of instructions until a certain condition is
satisfied. Condition may be predefined or open-ended. The general syntax of
the for loop will be as given in Table 6.2 (see also Figures 6.3 and 6.4).
Explanation:
The for statement contains three expressions which are separated by semi-colons.
Following actions are to be performed in the three expressions.
1. The initialize counter sets to an initial value. This statement is executed only once.
2. The test condition is a relational expression, that determines the number of
iterations desired or determines when to exit from the loop. The ‘for’ loop continues
to execute as long as conditional test is satisfied. When the condition becomes
false the control of the program exits from the body of the ‘for’ loop and executes
next statement after the body of the loop.
3. The re-evaluation parameter decides how to make changes in the loop (increment
or decrement operations are to be used quite often). The body of the loop may
contain either a single statement or multiple statements. In case, there is only one
statement after the for loop, braces may not be necessary. In such a case, only one
statement is executed till the condition is satisfied. It is good practice to use braces
even for single statement following the for loop.
The syntax of the ‘for’ loop with only one statement is shown in the third row
of Table 6.3.
The for loop can be specified by different ways and it is as per Table 6.3.
Displays
for(a =10;a>=0;a−−) ‘a’ is decremented from 10
value from 10
printf(“%d”, a) to 0.
to 0
We can also use loop within loops. In nested for loops one or more for statements
are included in the body of the loop. In other words C allows multiple for loops in
nested forms. The numbers of iterations in this type of structure will be equal to
the number of iteration in the outer loop multiplied by the number of iterations in
the inner loop.
Another kind of loop structure in C is the while loop. The while loop is frequently
used in programs for the repeated execution of statement/s in a loop. Until a
certain condition is satisfied the loop statements are executed.
while(test condition)
The test condition is indicated at the top and it tests the value of the expression
before processing the body of the loop. The test condition may be any expression.
The loop statements will be executed till the condition is true, i.e. the test
condition is evaluated and if the condition is true, then the body of the loop is
executed. When the condition becomes false the execution will be out of the loop.
The execution of the loop can be followed by the following flow chart given
in Figure 6.5.
Here, the block of the loop may contain either a single statement or a number of
statements. The same block can be repeated.
The braces are needed only if, the body of the loop contains more than one
statement. However, it is good practice to use braces even if the body of the loop
contains only one statement.
do
statement/s;
while(condition);
The difference between the while and do-while loop is the place where the
condition is to be tested. In the while loops the condition is tested following
the while statement, and then the body gets executed, whereas in the do-while the
condition is checked at the end of the loop. The do-while loop will execute at least
one time even if the condition is false initially. The do-while loop executes until the
condition becomes false. The comparison between the while and do-while loop is
given in Table
Sr.
while Loop do-while Loop
No.
Condition is
Condition is mentioned at
1 specified at the
the bottom.
top.
Body statement/s
Body statement/s executes
is/are executed
2 even when the condition is
when condition is
false.
satisfied.
It is an entry- It is an exit-controlled
4
controlled loop. loop.
do-while(condition)
{
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 79
lOMoARcPSD|27682773
statement/s;
while(condition);
C continue statement
The continue statement in C language is used to bring the program control to the
beginning of the loop. The continue statement skips some lines of code inside the
loop and continues with the next iteration. It is mainly used for a condition so that
we can skip some code for a particular condition.
Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped
C break statement
The break is a keyword in C which is used to bring the program control out of the
loop. The break statement is used inside loops or switch statement. The break
statement breaks the loop one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. The break statement in C can
be used in the following two scenarios:
Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c
C break statement
The break is a keyword in C which is used to bring the program control out of the
loop. The break statement is used inside loops or switch statement. The break
statement breaks the loop one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. The break statement in C can
be used in the following two scenarios:
Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c
An array is a linear and homogeneous data structure. Similar type of elements are
stored continuously in memory and that too under one variable name.
Thus for example: int num[6]; This is the declaration of an integer array of
int num[6] = {2, 4, 6, 8, 10, 12}; The individual elements could be initialized:
Array Terminology
Size: The number of elements or the capacity to store elements in an array is called
its size. It is always written in brackets ‘[]’.
Type: Type refer to data type. It decides which type of element is stored in the
array. It instructs the compiler to reserve memory according to the data
type.
Base: The address of the first element (0th) is a base address. The array
Index: The array name is used to refer to the array element. For example, in
num[x], num is array name and x is the index. The value of x begins at 0
Range: Index of an array varies from lower bound to upper bound while
1) One-Dimensional Array
Array elements are stored in sequence one after another. The elements
elements.
Example: int num[5]; An array is initialized. The type of variable is integer. Its
variable name is num and the size of the array is 5. The elements of the
integer array num[5] are stored in contiguous memory locations. Each integer
element requires 2 bytes. Similarly, the elements of arrays of any data type are
stored in contiguous memory location. The only difference is that the number of
memory locations is different for different data types.
(‘\0’) is automatically added at the end. The NULL character acts as the end of the
string. Other type of arrays do not have the NULL character at the end.
After an array is declared, its elements must be initialized. Otherwise, they will
contain “garbage”. An array can be initialized at compile time or at run time.
We can initialize the elements of arrays in the same way as the ordinary
variables, when they are declared. The general form of initialization of arrays is:
The values in the list are separated by commas. For example, the statement
int num[3] = { 0, 0, 0 };
will declare the variable num as an array of size 3 and will assign zero to each
element. If the number of values in the list is less than the number of elements,
then only that many elements are initialized.
For example,
Int total[5] = {100,150, 75}; will initialize the first three elements to 100, 150, 75
The size may be omitted. In such cases, the compiler allocates enough space for all
initialized elements. For example,
int counter[] = {1, 1, 1, 1}; will declare the counter array to contain 4 elements
with initial values 1. This approach works fine as long as we initialize every
Thus, char name[ ] = {‘J’, ’o’, ‘h’, ‘n’,‘\0’}; declares the name to be an array of five
characters, initialized with the string “John” ending with the null character.
Alternatively, we can assign the string literal directly as: char name [ ] = “John”;
Compile time initialization may be partial. That is, the number of initializers may
be less than the declared size. In such cases, the remaining elements are
initialized to zero, if the array type is numeric and NULL if the type is char.
void main()
int i, num[10];
scanf(“%d”, &num[i]);
searching.
void main()
{ int i, n, num[12] = {11, 22, 33, 44, 22, 55, 66, 33, 22, 77, 88, 55};
printf(“%d, ”, num[i]);
scanf(“%d”, &n);
if(num[i]==n)
array.
void main()
scanf(“%d”, &n);
scanf(“%d”, &num[i]);
scanf(“%d”, &p);
p--;
if(i>=p)
num[i] = num[i+1];
if(num[i]!=0)
position in an array.
void main()
scanf(“%d”, &n);
scanf(“%d”, &num[i]);
p--;
num[i] = num[i-1];
num[i] = el;
3. Merging: The elements of two arrays can be merged into a single one.
One method of merging two arrays is to copy all elements of one array
into a third array. Then copy the elements of the second array into the
the second array. The elements of two arrays can also be merged in
alternate order.
void main()
int i, j = 0, k = 0;
int num3[10];
printf(“%d, ”, num1[i]);
printf(“%d, ”, num2[i]);
if(i%2 == 0)
num3[i] = num1[j++];
else
num3[i] = num2[k++];
printf(“%d, ”, num3[i]);
void main()
int i, *ptr, num[8] = {11, 22, 33, 44, 55, 66, 77, 88};
ptr = num;
void main()
scanf(“%d”, &n);
scanf(“%d”, &num[i]);
printf(“%5d”, num[i]);
/* Sorting */
temp = num[i];
num[i] = num[j];
num[j] = temp;
printf(“%5d”, num[i]);
elements with rows and columns. Consider the example, int x[3][3]; The two-
dimensional array can be arranged into rows and columns. This arrangement of
array elements is only for the sake of understanding. Actually the elements are
stored in the contigious memory locations. The two-dimensional array is a
collection of three one-dimensional arrays. The first argument in x[3][3] means the
number of rows, i.e. the number of one-dimensional array and the second
argument shows the number of elements. x[0][0] means the first element of the
first row and column. In one row, the row number remains the same and the
column numbers change. The number of rows and columns iscalled the range of
an array. The computer memory is linear and all types ofarrays, one, two or multi-
dimensional arrays are stored in the continuousmemory locations.
following their declaration with a list of initial values enclosed in braces .Theymay
also be initialized at run time.
void main()
int i, j, a[3][3] = {11, 22, 33, 44, 55, 66, 77, 88, 99};
printf(“\n\tRow%d ”, i);
void main()
int i, *p, num[3][3]={11, 22, 33, 44, 55, 66, 77, 88, 99);
p = &num[0][0];
argument shows the number of elements. x[0][0] means the first element of
the first row and column. In one row, the row number remains the same andthe
column numbers change. The number of rows and columns is called therange of
an array. The computer memory is linear and all types of arrays, one,two or multi-
dimensional arrays are stored in the continuous memorylocations.
following their declaration with a list of initial values enclosed in braces .They
void main()
int i, j, a[3][3] = {11, 22, 33, 44, 55, 66, 77, 88, 99};
printf(“\n\tRow%d ”, i);
void main()
int i, *p, num[3][3]={11, 22, 33, 44, 55, 66, 77, 88, 99);
p = &num[0][0];
1. Transpose of a Matrix:
The transpose of matrix interchanges rows and columns, i.e. the row elements
Program to read the elements of the matrix and transpose its elements.
void main ()
b[j][i] = a[i][j];
printf(“%4d”, b[i][j]);
printf(“\n\t”);
void main()
scanf(“%d ”, &a[i][j]) ;
scanf(“%d ”, &b[i][j]);
c[i][j] = a[i][j]+b[i][j]);
c[i][j] = a[i][j]-b[i][j]);
void main()
scanf(“%d ”, &a[i][j]) ;
scanf(“%d ”, &b[i][j]);
printf(“%5d”, c[i][j]);
printf (“\n\t”);
* Always remember that subscripts begin at 0 (not 1) and end at (size -1).
more scalable.
* Be aware of the difference between the “kth element” and the “element k”.
The kth element has a subscript k-1, whereas the element k has a
subscript of k itself.
“garbage”.
* When using expressions for subscripts, make sure that their results do not
* When using control structures for looping through an array, use proper
* Make sure that the subscript variables have been properly initialized before
STRINGS
A sequence of characters, digits, symbols enclosed within double quotation mark is
known as string. A string is always declared as character array. Every sting is
terminated with a null character ‘\0’.
Declaration
To declare a string the variable should be declared as character array.
char var name[size];
Eg:char name[20];
Initialization
The compiler automatically inserts the null character at the end of the string .so
initialization of null character is not essential.but an extra memory space should
be provided to include a null character at the end . If extra memory space is not
provided then the output will contain garbage value along with the string.
char str[]=”india”;
char str[]=”india \0”;
char name [8]={‘n’,’i’,’m’,’i’,’s’,’h’,’a’,’\0’};
To read and print strings use printf and scanf along with loop statements or else
use puts and gets functions.
2. Program to read a string through keyboard and determine the length of string and
find its equivalent ascii character
General syntax
int var = strlen(charvar);
2.strcpy()
The function is used to copy a string from a source to destination .the syntax is
strcpy(destination var,source var);
1.
Program to copy contents of one string to another by using strcpy
3.strncpy()
Syntax
stricmp(source var,destination var);
6.strcmp()
The function compare 2 strings upto a specified length.the syntax of the function
isstrcmp(source var,destination var,int var);
Pgm to compare 2 string upto a specified length.
7.strncmp()
The function can be used instead of strncmp().the only difference between
strncmp() and strnicmp() is strnicmp does not discriminate between small and
capital letters.
8.strlwr()
The function is used to convert string to lower case.
Syntax
strlwr(char var);
9.strupr()
The function converts lower case string to upper case strings.
Syntax
strupr(char var);
10.strdup()
The function is used for duplicating a given string at the allocated memory location
which is pointed by the pointer variable.
Syntax
ptr var=strdup(char var);
11.strchr();
The function returns the pointer position to the 1st occurrence of the character in
the gien string.
Syntax
ptr var=strchr(char array,char var);
12.strstr();
The function finds the second string in the 1st string .it returns the pointer location
from where the second string starts.
Syntax
strstr (char array,char array);
13.strcat();
The function is used to append the target string to the source string ie; the
function concatenate 2 strings.
Syntax
strcat(char array,char array);
Program to append the 2nd string at the end of 1st string
14.strncat()
The function concatenates 2 strings up to the specified length.
Syntax
strcat(car array1,char array2,length);
15.strrev()
The function reverses the given string
Syntax
str rev(char array);
16.strset()
The function replaces every character of the string with the given symbol.
strset(text,symbol);
17. strnset()
The function replaces every character of a string with the given symbol upto a
length.
strset(text,symbol, n);
18. strspn()
This function returns the position of the string from where the source array is not
matching the target one.
19.strpbrk()
The function searches for the 1st occurrence of the character in a given string and
then displays the string starting from th specified character.
Syntax
ptr var=strbrk(txt1,txt2[5]);
Functoins Description
Module III: Functions & Pointers: concept of modular programming, Library, User
defined functions, declaration, definition & scope, recursion, Pointers: The & and *
Operators, pointer declaration, assignment and arithmetic, visualizing pointers,
call by value; call by reference, dynamic memory allocation. Storage classes.
FUNCTIONS
1. Library functions
They are predefined set of functions .their task is limited.they cannot be changed
or modified by the user. Eg: pow(),sqrt(),clrscr()
It is the function name and follows the same rule for naming a variable.
Eg:int sum(int,int);
2. Function call
(a)if there is no arguments the n the function can be called by using only the
function name.
Eg:sum();
(b) If there is arguments then the function can be called by using the actual
arguments
Eg:sum(a,b);
3. Function definition
A function provides the actual body of the function. a function definition contains
return type of the function, function name ,parameter list(data type and formal
arguments)&the function body.
{
int add;
add=a+b;
printf(“%d”,add);
}
The arguments of the called function are called formal arguments.
4. return statement
It is used to return a value to the calling function. The return statement can be
used in a no: of ways.
1. return(); the statement returns 0 to the operating system if the value entered by
the user is 1 or –ve.
2.
return;it is used to exit from a function
return(exp);
3.
return (&var); it returns value of avariable using pointer.
5.
return (sqrt(var)); library functions can be used along with the return statement.
6.
return float(square(2.8));
TYPES OF FUNCTIONS
Depending on arguments and return value the functions are divided into 4 types
In this type data is neither passed through the calling function nor send to back to
called function. There no data transfer is there. The functions are used perform
any operation and act independently .they read data & print result in the same
block.
abc();
}
void abc()
{
//input statement
// processing
//output statement
}
eg:Program to add 2 no:s
In this type no arguments is passed through the main function, but the called
function returns values. The called fn is independent. It reads value from the
keyboard or the variables are initialized & return the value to the main function
In this type of functions arguments are passed to the calling function & the called
fn operates on the value but no result is send back .the result is utilized by the
called function.
In this type of function copy of the actual arguments is passed to the formal
arguments .here data is transferred to b/w calling and called functions. There
should be a return statement in the called function and is collected by a variable
in the main function.
1.call by value
In this type the value of actual arguments is passed to the formal arguments and
the operation is done on the formal arguments .any change in the formal argument
does not affect actual argument. The changes made in the actual arguments are
local to the block of called function (copy of actual arguments are passed to the
formal arguments
2. Call by reference
In this type the address of the values are passed. Functions operate on address
rather than values. The formal arguments are pointers to actual arguments. The
changes made in the arguments are permanent.
Recursion
A function calling repetitively by itself is called recursion. The recursion can be
directly or indirectly
Program to find factorial of no
Types of recursion
The major application of recursion is game programming
1.direct recursion
When a function calls itself it is know n as direct recursion. In this type only one
function is involved.
2. Indirect recursion
In this type of recursion a function calls to another function and then called
function calls to the calling function. Here more than 2 functions are involved.
Advantages
• Almost all the problem can be solved without recursion, but there may be some
situation where a programmer must use recursion.
• Eg:program to display all the file of a system.
• Recursion is very flexible in data structure.
• Length of program can be reduced.
Disadvantages
POINTERS
poi
nter is a special variable that stores the address of another variable .pointer can
have any name as like normal variables but is always denoted by an asterisk(*)
symbol
Features.
1. It is a fundamental tool in developing code in c.
2. Saves memory space.
3. Memory is accessed efficiently.
Pointers are used to allocate memory dynamically.
4. Pointers are used with data structures.
5. used for file handling.
6. Execution time with pointer is faster.
Pointer declaration
Genral syntax:
data type * variable name;
The data type specifies the type of variable the pointer variable holds.
The indirection operator is also called dereferencing operator (*). When a pointer is
dereferenced, the value at that address is retrieved. The indirection operator is
used for declaration of dereference & symbol is the address operator and
represents address of the variable .the operator immediately preceding the
variable will return the address of the variable
Eg: int *x;
float *y;
The statement int *x ; tells the compiler that it holds the address of an integer
value .
Dynamic memory allocation
The allocation of memory during a program runtime is called dynamic memory
allocation. It is essential for data structure.
Types of pointers
1.Void pointers
Pointers can also be declared as void. The void pointers cannot be dereferenced
because the compiler cannot determine the size of the object that the pointer
points to. Even though void pointer declaration is possible it is not allowed.
2.Wild pointers.
the pointers that are declared as constant cannot be modified .the variable ‘const’
is sed to declare a variable as pointer
Eg: int k=10;
int const * p=&k;
char * const str =”constant”;
Module IV: Advanced features: Array & pointer relationship, pointer to arrays,
array of pointers. Strings: String handling functions; Structures and unions; File
handling: text and binary files, file operations, Functions for file handling, Modes
of files
POINTERS & ARRAYS
Array name itself is an address or pointer .it points to the address of 1st element
.the elements of the array together with their address can be displayed by using
array name itself. Array elements are always stored in continuous memory
location.
q:Write a program to display array elements and their address using array name as
a pointer?
Points to remember
1.arr[5]={10,20,30,12,34},p;
arr[p];
*(arr+p),*(p+ar),p[arr] will give the value of the array
2.&arr[p],arr+p will give the address of the array.
Array of pointers
Structure
A structure is a collection of one or more variables of different data types of
grouped under common name. It is a derived data type to be arranged in a group
of related data items of different data types.
Declaration &initialization
The general syntax to declare a structure is
struct structure name
{
datatype1 var1;
datatype2 var2;
.
.
}obj name;
Here struct is a keyword and struct name is the structure type which is also
known as a tag. The different variables of different data type are enclosed within a
pair of curly braces .the closing brace is terminated with a semi colon.
Objects
After defining the structure the objects of the structure has to be created .it is
similar to declaring variables of any data type. The memory allocation takes place
only when the objects are declared.
Initialization
The variables of the structure can be initialized in the following ways.
1.struct book
{
char name[20];
float price;
}
struct book b1;
b1.bname=”pgmg in c”;
b1.price=350;
Or
struct book b1={“pgmg in c”,350}
q:Program to read the values and assign them to structure variables(the structure
should include book name,no of pages&price)
Array of structures
Array is a collection of similar datatype .we can define an array of structure where
the every element is of structure type .array of structure can be declared as
struct time
{
int sec;
int min;
int hr;
}t[3];
Here t[3]; is an array of 3 elements containing 3 objects of time structure .each
element of t[3] has 3 members sec ,min & hr.
q:Write a pgm to create an array of structure objects .the structure details can be
information about car no,start time and reaching time of 10 cars.
q:Write a pgm to display name rolllno grade of 5 students .declare the structure
student with variables name,rollno,garde.create an array of structure objects.
q:Wite a pgm to display name age and height of 3 students using array of structure.
Pointer to structure
Programmer can define pointer to structure .here starting address of the member
variable can be accessed .such pointers are called structure pointers.
struct stud
{
char name[20];
int rollno;
float avg;
}*ptr;
in
the eg: * ptr is pointer to structure stud (when the object is a pointer .create a
normal object and assign it to the pointer by symbol ‘&’.
The variables of the structure can be accessed using an -> operator along with
pointer variable.
Eg:
void main()
{
struct stud
{
char name[20];
int rollno;
}*s1;
struct stud n1;
printf(“enter values”);
gets(n1.name);
scanf(%d”,&n1.rollno);
s1=&n1;
printf(“the values are “);
printf(“%s%d”,s1->name,s1->rollno);
Q:write a pgm to declare the pointer to structure and display contents of structure
.the structure book contains variable name,author and pages.
char* name[20];
int*rollno;
}*s1;
char nm[20];
int rn;
printf(“enter name and rollno”);
gets(nm);
sacnf(“%d”,rn);
s1->name=&nm;
s1->rollno=&rn;
printf(“the name is%s”,*s1->name):
print(“rollnois%d”,*s1->rollno);
Type definition
Typedef
It is used to create a new datatype .
Syntax
typedef datatype variable name;
Eg: typedef int hours;
From the above stmt hours can be used to create integer variables instead of int.
hours hr;
The stmt declaes ‘hr’ as integer variable.
Write a pgm to create a user defined datatype hours on int datatype and use int in
the pgm.
The programmer can create heir own data type and define what values the
variables of these data types can hold.
Syntax: tag name{identifiers};
enum month {jan=1,feb,…dec};
The statement creates a user defined data type and keyword enum is followed by
the tagname month. The enumerators are jan,…dec.
The values of the identifiers are constant unsigned integers starting from 0.by
default the compiler assign values from 0 onwards. The programmer can initialize
their own constants to each identifier.
Q:write a pgm to create enumerated datatype for days in a week and display their
integer constants.
Q:wirite a program to create enumerated data for 12 months initialize the 1st
identifier with 1 and display integer constants of jan feb june and dec.
Q:write a program to declare enum datatype &display values(true means 1 ,false
means0).
UNION
Union is a variable similar to structure. In structure each member has its own
memory location. The union requires bytes that are equal to the number of bytes
required for the largest member.
Syntax:
union unionname
{
datatype 1 varname1;
datatype2 varname2;
.
DONBOSCO COLLEGE Downloaded by Mohit Nayak (mohitnayak.229548@gmail.com) 115
lOMoARcPSD|27682773
.
}object;
Here union is the keyword and union name is defined by the programmer. The
object along with dot(.)Operator is used to access the union variables.
q:write a program to define a union result with variables rollno,mark and grade;
FILES
A file is a accumulation of data stored on the disk created by the user ie;a file is a
collection of records. A record is a group of related data item. A file can be
collection of numbers, symbols and text. The library functions of file are available
in<stdio.h>
Types of files
Sequential file
In this type data are kept sequentially it takes more time for accessing the records
.eg:to access the 10th record, the first 9 records should be accessed.
Random access file
In this type data can be read and modified randomly. The access time is less
compared to the sequential file. The user can access the desired record without
accessing the other records.
Opening a file
The opening of a file creates a link between the operating system and the file
functions. This task is carried out by the file that is defined in <stdio.h>
Syntax:
file*fopen (“filename”,”mode”);
Eg:file*fp;
fp=fopen(“data.txt”, “r”);
Here fp is a pointer variable data.txt is the filename and r specifies that the file is
open in read mode.
Closing a file
The file that is open using fopen should be closed after the work is over. The
closing enables to washout all the contents from the ram buffer.
Syntax:
fclose(ptr var name);
Or
fcloseall();
TEXT MODES
text mode binary explanation
mode
w(write) wb this mode opens file for writing .if
the file is already exist then its
contents will be over written.if the
file is not found , a new file is
created
r(read) rb this mode opens file for reading .
if the file is not found then the
compiler returns ‘null’ to the file
pointer.
a(append) ab this mode opens pre existing file
for appending .if the file is not
found then ‘null’ is returned.
w+(write+read) r+b this mode opens file in read and
write mode
a+ this mode pens file in read mode
and records can be added at the
end of the file
r+(read+write) w+b this mode opens file in read and
write mode.
a+b this mode opens file in append
mode ie;data can be written at the
end of the file.
Q:write a program to enter name rollno and mark into the text file and read the
same.
3.fgetc and fputc
This function is similar to getc() function. It also reads a character and increments
the file pointer position.
Syntax:
var=fgetc(file ptr);
fputc()
This function writes a character to the file. It also incerements the file pointer.
Syntax:
fputc(var,filepointer);
4.fgets()
The function is used too read a string from a file. It also copies string to a memory
location referred by an array
Syntax;
fgets(var,num,fileptr);
variable is a string variable, number represent no: of characters and file pointer is
a variable created by using file.
5.fputs()
The function is used to write a string into the open file .
Syntax
fputs(var,fileptr);
1.file pointer
2.offset
it is the value for moving the file pointer forward from current
position or backward from current position.
3.position
2.ftell()
this function is used to find the current position of the file pointer. it returns the
pointer from the beginning of the file.
syntax
variable=ftell(fileptr);
write a pgm to print the current position of the file pointer if the file is not empty.
write a pgm to write to a file from the 10th position.
preprocessor directives
conditional compilation.
programmer can include conditional compilation directives which allow the
programmer to include the portions of code based on the conditions . the most
frequently used conditional compilation directives are: #ifdef, #else, #endif.
eg:
#define LINE1
void main()
{
int x=5;
#ifdef LINE
printf(“this line is no:1”) ;
#else
free
memory
global
variable
program
Space for local variables is allocated from stack .each time when the variable
comes into existence; the free memory is called the ‘heap’. The size of the heap
does not remain constant all the time for all programs. Its size keeps on changing
during the execution of the program. This is due to the creation and destruction of
variables that are local to the functions and blocks.
MEMEORY MODELS
1. Tiny:
All segment registers are initialized with identical value and the addressing is
accomplished 16 bits. The programs are executed quickly in this case.
2. Small:
All codes should fit in a single 64 kb segment and all data should fit in a 2nd 64 kb
bit segment. Execution speed is same as that of tiny model.
3. Medium:
All data should be fit in single 64 kb segment and the code is allowed to use
multiple segments fast access of data but slower program execution.
4. Compact:
All codes should fit in 64 kb but the data can use multiple segments. There is slow
access to data and quick code execution.
5. Large:
Both code and data are allowed to use multiple segments. There is slower code
execution.
6. Huge:
Both code and data are allowed to use multiple segments and there is slowest code
execution.
MEMORY ALLOCATION FUNCTIONS
1. malloc(): it is used to allocate the memory block with the function .ie; it is used
to allocate memory space to the variables of different data type.
2. calloc():
it is used for allocating multiple blocks of memory for the variables.
3. Free ()
It is used to release the memory if it is not required.
(Header file used for these three are <stdio.h>or<alloc.h>)
The analysis can also be made for logical accuracy, tracing the algorithm
implementing it and checking with some data and with mathematical techniques
to confirm its accuracy.
GRAPHIC FUNCTIONS
Aheader file graphics.h is used to include the graphic functions to the program. To
switch to the graphic mode, a function name init graph() is used.
FEW GRAPHIC FUNCTIONS
1. initgraph(): this function initializes the graphic system.
2. Close graph (): it is used to shut down the graphic system.
3. line (): it is used to draw a line between 2 specified points.
4. circle (): this is used to draw a circle at specified points of the given radius.