Problem Solving in C Notes
Problem Solving in C Notes
Study Material
D.N.R COLLEGE
UNIT-I
GENERAL FUNDAMENTALS
Introduction to Computer:Computer is an electronic device which can process data transformed into
information. That is useful to people.
Block Diagram of a Computer:The computer has mainly three parts.
1. Input Unit
2. C.P.U (Central Processing Unit)
3. Output Unit
1. Input Unit : The standard input device is keyboard some of the input devices are mouse, scanner,
touch screen, OMR(Optical Mark Recognition), OBR(Optical Barcode Recognition).
II. Arithmetic and Logical Unit (A. L. U): It performs the actual arithmetic and logical unit processing.
The result can be stored in the memory or it can be retained in arithmetic logical unit for further calculations.
III. Control Unit: It controls all other units in the system its main functions are
To control transfer of information between various units in the system.
To initiate appropriate functions by arithmetic logical unit.
3.Output Unit: It communicates the results of processing to the users in various forms. The standard output
unit is monitor, V. D. U (Visual Display Unit).
[1]
Characteristics of a Computer: A computer is equipped with number of Characteristics that helps it to
handle the different problems more efficiently
Accuracy
Speed
Large Storage Capacity
Versatility(Multi-Tasking)
Reliability
Diligence
Automatic
Source of Entertainment
Accuracy: The Computer system always performs accurate result with valid data and instructions.
Speed: A computer performs operation with very high speed millions of instructions in fraction of seconds
Large Storage Capacity: A computer has storage capacity it can store large volume of data. We can store
any kind of data in computer storage system. This data can Text, images, sounds, videos etc.
Versatility: A computer Is a versatile machine. It can perform a number of jobs depending upon the
instructions.
Like a computer can be used to write a letter to a friend in a word processor and at the same
time listen to various songs through a media player.
This property of computer is called versatility.
Reliability: Computer storage on data is called much more reliable that the manual storage we can store the
data in computer storage for a long period of time, accept until and the any kind of system failure occurs.
Diligence: Unlike human beings the computer can work continuously without getting tired.
Automatic: A machine that works itself without any human involvement is said to be an automatic machine.
Source of Entertainment: Today computer has become a great source of entertainment .We can play video
games, enjoy music and watching movies or various satellite channels through computer.
Limitations of Computers:-
[2]
Types of Software’s:
1. System Software
2. Application Software
3. Commercial Software
4. Open Source Software
5. Public Domain Software
6. Freeware Software
1. System Software: This is a collection of programs to control and operate the operations of computer
hardware. This software’s are written in low level language. System software interface between user and
system hardware.
E g: - Opening System (OS), Compilers.
Features:-
1. Close to system
2. Difficult to design and to understand
3. Fast in speed.
4. Written in low level language.
5. Less interactive.
2.Application Software: Application software protects are designed to satisfy a particular need of particular
environment. Application software is to perform various applications on the computer app.
Features:-
1. Close to user
2. Slow in speed
3. Easy to understand
4. Written in high level language
5. Easy to design
6. More interactive
3. Commercial Software: Commercial software is any software or program that is designed and developed
for licensing or sale to end users.
Commercial software is easy to use and easier information into existing system. These are mainly
used in business because update services are available.
E.g.:- ATM, Customer services.
Features:-
1. Easy to use and easy to implement.
4.Open Source Software: Open source software is computer software. The source code is available with a
license. The copy right holder provides the rights to study change and distribute the software to any one for
any purpose
E.g.:- Firefox. Open office.
5. Domain Software: Public domain software that has been placed in public domain. There is ownership
such as copy right patent.
E.g.:-Flash, Video game player.
6. Freeware Software: Freeware software is domain downloadable and free of charge. It is a free for
personal use. It is freeware does not contain any license.
E.g.:-Adobe reader, Skype.
[3]
Types of Computers: The computer can classified into four types
1. Main Frame Computers: The main frame computers are used in large organizations were many peoples
are frequently used same data. Main frame computers are large storage capacity and high processing speed
are known as main frame computers.
It is very expensive. It occupies large room and need A.C.
E.g.: IBM z Series, System z9 and System z10 servers.
2. Mini Computers: Mini computers first released in 1960.mini computers are also known as mid-range
computers because it is small size. And compare to pc it is very expensive. it is quality used in business
education, hospitals etc.
It is a multi-user system; it supports hundreds of users at a time. Mini computers storage capacity is
also high.
E.g.: Personal Laptop, PC etc.
3. Super Computers: Super computers are fastest, most powerful and more expensive computers. It is used
to process large amount of data and to solve complex scientific problems.
It can support thousands of users at the same time. Super computers are mainly used for weather
forecasting, online banking and research centers.
They have great speed and large storage capacity. It is filled up in entire room because these computers
are large size
4. Micro Computers: Micro computers are small size and it’s based on microprocessor technology. It is
specially designed for individual users. So it is known as personal computers. It includes a microprocessor,
memory, and minimal I/O circuitry mounted on a single printed circuit board. They actually formed the
foundation for present day microcomputers and smart gadgets that we use in day to day life.
E.g.: Tablets, Smart watches.
Generations of Computer:-
Generations in computer task are a step in technology. It provides a frame work. The growth of the computer
industry.
First Generation(1942-1955)
Second Generation(1955-1964)
Third Generation(1964-1975)
Fourth Generation(1975-1989)
Fifth Generation(1989-Present)
First Generation:-The first generation computers are made of “vacuum tubes” and hence the first
generation computers was extremely large in size and required more space. To enter data into computers
punched cards were used. Punched card was sheet of thick paper, in which holes were punched according to
a coding scheme.
[4]
Characteristics of First Generation Computers:-
Second Generation:-With invention of “junction transistors” the vacuum tubes were replaced by transistors.
Transistors were more tubes reliable, small size and require low power when compared with the vacuum
tubes.
1. Use of high level programming like Cobol, Fortran and Algal(Algorithmic language).
2. Use of transistors instead of vacuum tubes.
3. Increase in magnetic storage capacity.
4. Input or output operations made fast.
Third Generation:-In third generation computer were made up of I.C’S (Integrated Circuits).In an I.C.
hundreds of transistors were in corporate on a single silicon chip.
These occupy less space and required no air conditioning. these are user friendly and very easy to operator
1. These computers are used the large scale and very large scale integrated circuit.
2. These have increased high storage capacity and high speed.
3. Mini computers, micro computers are extremely used microprocessors.
4. These can be used for different applications.
Fifth Generation:-Super computers are fifth generation computers. It is also called expert system it works
with artificial intelligent
They are used to develop powerful machines and designing the computers. Fifth generation computers are
think like human being. It includes Robotics, networking and playing games.
[5]
Uses of Computers (or)Applications of Computers: Computers are used in various technical fields.
1. Education
2. Business
3. Banking
4. Engineering
5. Insurance
6. Hospitals
7. Government Organizations
8. Advertisements
9. Communication Technology
10. Security
Engineering:-Computers can also use in engineering applications ,following software’s are used in
engineering.
Hospitals:- Computer are used to store the information of all clients (or) customers and medicines it is also
performing surgeries of operations
[6]
Introduction to Algorithms and Programming Language
Algorithm:-
Properties of Algorithm:-
Step-1: Start
Step-5: Stop
Step-1: Start
Step-2: Read the three numbers to be compared, as A, B and C.
Step-3: Check if A is greater than B.
Step-4: If true, then check if A is greater than C.
Step-5: If true, print 'A' as the biggest number.
Step-6: If false, print 'C' as the biggest number.
Step-7: If false, then check if B is greater than C.
Step-8:If true, print 'B' as the biggest number.
Step-9:If false, print 'C' as the biggest number.
Step-10: End
[7]
Benefits of Algorithm:-
Flow chart:-
The program in which different types of instructions are drawn in the form of different shapes of boxes
and the logical flow is indicated by interconnecting arrows. The main objective of creating flowchart is to
help the programmer in understanding the logic of programmer and to trap any kind of logical errors present
in algorithm.
Flow chart use different symbols to represent different operations to the program. A flow chart is
drawn according to define rules using standard flowchart symbols prescribed by “ANSI”-(American
National Standard Institute). The standard symbols that are frequently used in flow chart are
[8]
Flow Chart Symbols:-
Flow lines are represented by arrow lines. That are used to connect symbols these lines indicate the
sequence of steps and the flow of operations.
Terminator:- Terminator is used to represent by rectangle with rounded ends. These symbol is used to
indicate the beginning (start), the termination (end/stop) in the program logic.
Input (or) Output:- Input/output is represented by the parallelogram these symbol is represents an input
taken from the user (or) the output that is displayed to user.
Processing:- The processing is represented by rectangle this symbol is used for representing arithmetic and
data movement instructions. It denotes the logical process of moving data from one memory location to
another location.
Decision:- This symbol is represented by diamond. It denotes a decision to be made. This symbol has one
entry and exist paths. The path chosen depends on whether the answer to a question is yes (or) no.
Connector:- This symbol is represented by circle. It is used to join different flow lines.
[9]
Guidelines for Creating A Flow Chart:-
The following guide line should be used for creating a flow chart
Makes Logic Clear: It is easy follow a graphical representation of the task. The symbols are connected in
such a way. That they make the system visible.
Communication: Since the flow chart is a graphical representation of a problem solving logic. It is
enhanced meaning of communicating the logic of a system.
Effective Analysis: A flow chart helps the problem analysis in an effective way.
Proper Testing and Debugging: Flow chart helps to identify and correct the errors in the program. It also
helps in testing process.
Appropriate Document: Flow chart acts as a high quality program documentation tool.
Disadvantages of Flowchart:-
Complex: For very large programming consisting of thousands of statements. The flow chart consists of
many papers (or) pages making them different to flow.
Costly: Flow charts are feasible for sort and straight forward problem solving logic flow chart because a
costly flow chart, in huge application.
Difficult to Modify: Any modification to flow chart needs to redraw the flowchart. Considering the entire
logic again due to its symbolic nature redrawing complex flow chart is a difficult task.
No Update: Programs are generally updated regularly but the corresponding flow charts are not updated
regularly.
[10]
Examples:-
Draw a flow chart to find sum of two numbers
[11]
Generations of Programming Language:-
Program : Program is a set of instructions to solve a particular problem.
Programming:-
Process of creating programs.
A programming language is a computer language used to write instructions for computer in the well-
defined format.
The set of instructions is called a program and the process of creating programs is called
programming.
Types of Programming Language: Programming languages are classified into major languages.
[12]
Translates like compilers & interpreters are used to translate programs written in high level
languages into machine languages and reverse also
High level languages are machine independent
High level languages are easy to learn because they use common English words as, they (or) their
keyword
It is easy to modify and maintain the programs certain in high level language.
4. Very High Level Language:-
Fourth generation languages are the easiest programming languages available today. They are very
easy to learn because these syntax and grammar is very easy to learn.
Programming in this languages does not require any programming experience in other language.
Fourth generation languages are machine independent.
Fourth generation languages are also known as very high level languages.
Most fourth generation languages are used to occur data bases
SQL(Structured Query Language) is the best example fourth generation language. It is used to create
and modify information in DBMS (Database Management System).
5. Fifth Generation Language:-
Fifth generation programming language design a make a computer solve a given problem without
the programmer (user).
The fifth generation programming language is also known as natural language.
Fifth generation programming is based on solving problems using constraints given to the program.
Prolog &mercury are the best known fifth generation language.
Pseudo Code:-
if condition then
Sequence 1
else
Sequence 2
end if
Here, the else keywords & sequence 2 are optional if, the condition is true sequence 1 is performed
otherwise sequence 2 is performed.
[13]
Example:-if age>=18 then
display eligible to vote
else
1. The goal of structured programs is to write correct programs that are easy to understand & modify.
2. Structured programs takes less time to write then other programs
3. A structured program is easy to debug because each procedure in its specialized to perform just one
task.
4. Individual procedures are easy to change as well as to understand.
1. To create a program to manage the names & addresses of a list of students for these you would need to
breakdown the program in the following modules.
Enter new name and address
Modify existing entries
Sort entries
Print the list
2. Now, each of the proceeding modules can befatherly breakdown into small modules. For example, the
first module can be
Prompt the user to enter new data
Read the existing list from the disk
Add the name & address to the existing list
Save the updated list to the disk.
3. Simply modify existing entries can be further divided into modules such as
Read the existing list from the disk
Modify one or more entries
Save the updated list to the disk.
[14]
UNIT-II
INTRODUCTION
History of C:
Features of C-Language: C-Language is very powerful and popular because of its features.
The Main features are:
Portability: C-Language programs are highly portable. Portability means a c-program written in one
environment can be executed in another environment. For example you write a program in DOS
environment you can run in windows environment.
Extendibility: C-language has an important facility called extendibility. It means you can write your own
file or functions and include in another programs in other words a user can write No. of functions, sub-
programs according to the requirement.
Reliability: A ‘C’ compiler gives and accurate results it has a facility of warning which guides for better and
efficient programming.
Middle Level Language: ‘C’ language is also called middle level language. Because it has both types of
features i.e. high-level languages as well as low-level languages.
Powerful : C is provides variety of data types, functions, conditional statements and looping statements.
Uses of C Language:
‘C’ is very simple language i.e., used by software professionals
The uses of ‘c’ language are:-
C-language is mainly used for system programming.
It is widely accepted by professionals
For portability and convenience is sometimes used as an intermediate language for implementing
other languages.
‘C’ language is widely used to implement user applications.
For creating compiles of different languages. Compiler is converts into source code to machine code.
Unix kernel is completely developed in C- language.
[15]
Structure of the ‘C’ Program.
The ‘C’ Program structure contains the following sections.
Documentation Section.
Header File Section
Definition Section
Global Declaration Section
main () Function
{
Local Declaration Part
Execution Part
}
User Defined Section
Documentation Section: In the documentation section we can give the comments. here comment statements
are non-executable statements. Comment can be divided into two types there are
1. Single line comments are represented by “//”.
2. Multi line comments are represented by “/*………….
…………...*/.
Header File Section: This section provides instructions to the compiler to link functions from the Library
each header file by default contains with the extension of ‘h’ the file should be included by using # include.
E.g.: # include <stdio.h>
The <stdio.h> is a file it is included all the definitions of input, output functions.
Definition Section: We can define a variable with its value in the definition section.
Syntax: #define variable name value;
E.g. 1. #define a 10;
2. # define name “ “;
Global Declaration Section: Some variables are used in more than one function such variables are called
global variables and that variables are declared in the global declaration section that is outside of the main ()
function.
Main()Function: Every ‘C’ program must contain main ( ) with empty parenthesis after main is necessary.
The function main is the starting point of every ‘C’ program. The program execution starts with the opening
braces ({ ) and ends with the closing braces (}) between these braces the programmer should give the
program statements. The main has two parts. They are
Declaration Part: The declaration part declared the entire variables that are used in executable part the
initialization of variables are also done in this part.
Execution Part: This part has reading, writing and processing statements having input or output functions,
formulas, conditional statements, looping statement and function calling statements.
User Defined Section: In this section function definitions are defined by the user. These functions are
generally defined after the main function or before the main function. This section is optional.
[16]
E.g.:- Write the First ‘C’ Program
#include<stdio.h>
void main()
{
clrscr();
printf(“My First Program in C”);
return 0;
getch();
}
Output:- My First Program in C
#include<stdio.h>
It is the first statement in our code. All pre-process commands starts with #symbol(hash).
The # include statements tells the compiler to include the standard library (input/output) or header
file <stdio.h>in the program.
main() function
The main() function after all the statements in the program have been written. The last statements in
the program have been written. The last statements in the program return will an integral value to the
operating system.
The two {} curly braces are used to group of all the related statements of main() function.
printf(“My First Program in C”);
The printf() function is defined in stdio.h file and is used to print text on the screen. The message to be
displayed on the screen to the enclosed with in double quotes (“ “) and put inside brackets (or) parenthesis.
The backslash is an escape sequence and represents a new line character.
Example:-
Sequence Meaning
\n New Line
\t Tab Space
\b Back Space
\v Vertical Tab
// Back Slash
return 0:
This is a return command that is used to write the value “0” to the operating system give an indication.
That there are no errors during the execution of program.
[17]
Source File: The source code file contains a source of the programs. The file extension of any c source code
that defines the main functions’ and other functions. The main function is the starting point of execution
when you successfully compile and run the program in the files of c program the source file is always file
extension is”.c”.
Header File: Header files provide instructions to the compiler to link functions from the library. Each
header file by default contains ‘.h’extension and its name can use only leters,digits,dashes and underscores
some standard header files are automatically available to ‘c’ programmers
Binary Executable File: The binary executable file is generated by linker the linker links various object
files to produce a binary file that can be directly executed (.exe).
Compiling and Executing C-Program: C is a compiler language every c program must be run through a
‘C’ compiler that’s creates an executable file to be run by the computer.
The programming process starts with creating a source file. That consists of a program written in
‘C’langauge.
Source File: The source file usually contains ASCII characters and can be produced with a text editor the
source file is produced by a special program called compiler.
Compiler: The compiler translates the source code into a object code the object code contains machine
instructions for the CPU.
Object file: The object file is processed with another special program called linker.
[18]
Keywords: C-languages have some reserved words which cannot be used as variables the reserved words
are called keywords. There are mainly 40 keywords among which 32 keywords are used by many ‘C’
compilers these keywords are called standard keywords whereas the remaining keywords are called optional
keywords.
Optional Keywords :
[19]
Basic Data Types in “C”: A Data type is a set of values along with a set of rules for allowed operations. ‘C’
supports several data types of data each of which is stored differently in the computer’s memory mainly data
types are divided into three types.
1.Primitive Data Type: ‘C’ supports mainly four primitive data types.
Character Data Type
Integer Data Type
Float Data Type
Double Data Type.
Character Data Type: The character data type accepts single character only. Characters are either signed
or unsigned. But mostly characters are used an unsigned type. The size of the character data type is 1 byte
in the memory. The range of unsigned character is 0to 255. The range of signed are character is –128 to
+127. char is the keyword of the character data type.
Syntax: char list of variables;
E.g. char ch1, ch2, ch3;
Integer Data Type: An integer type accepts integer values only. It does not contains any real or float
values. The range of an integer variable is -32, 768 to +327,67. int is the keyword for integer data type.
In generally 2 bytes of memory is required to store an integer value.
Syntax: int list of variables;
E. g: int a, b, c;
Float Data Type: The float data type accepts real values it can contains any floating point values. The
range of the floating variable is 3.4E – 38 to 3.4E + 38. float is the keyword for
In generally 4 bytes of memory is required to store an float value with 6 digits of precision.
Syntax: float list of variable;
Eg: float f1, f2, f3;
Double Data Type :The double data type accepts large floating value. The range of the double variable is
1.7E –308 to 1.7E + 308. Double is the key word for double data type. In generally 8 bytes of memory is
required to store double value.
Syntax: double list of variables;
E.g. double d, e, f;
[20]
Void Datatype: void is an empty data type that has no value. . The void keyword specifies that the function
does not return a value.
2.DerivedData Types: Derived data types are derived from the primary data types. The derived data types
may be used for representing a single or multiple values. These are called secondary data type. The derived
data types are arrays, pointers, functions, etc.
3.UserDefined Data Types: The data types are defined by the user is called user defined data types. The
user defined data types are structures ,unions etc.
Enumerated Data Types: It allows the user to define a variable or an identifier, which is used for
representation of existing data types. In other words, it provides us a way to define our own data
type and also can define the value for a variable or an identifier stores into the main memory.
Syntax :enum identifier { v1,v2,v3…….,vn};
Here enum is the reserve word and v1,v2,v3…,vn all are the values which is also called enumeration
constants.
Eg :enum month{jan,feb,mar,….,dec};
Typedef: This is used to represent the existing data type .i.e. by using this the new type can be used
in place of the old type anywhere in a C program. Also we can create the typedef variables for
improving the readability of the program.
Syntax :typedef data-type identifier;
Here data-type may be int, float ,double and char. Identifier gives us the information of new
name given to the data type. Note that typedef cannot create a new type.
Eg: typedef int pay;
C – Language Data Type Table Form:
[21]
Variables :Variable is an identifier .It is used for storing value .The variable can be changed during
the execution of the program .Variable refers to an address of memory where the data is stored..’C’
supports two basic kinds of variables
Numeric Variables.
Character Variables.
Numeric Variables:
1. Numeric variables can be used to store either integer values (or)floating point values.
2. Numeric variables may be also associated with modifier such as short,long,signed and unsigned.
3. Thedifference between signed and unsigned variables is can only be positive.
Character Variable :
1. Character variables can include any letter from the alphabet or from the ASCII code.
2. Char and numbers 0 to 9that are given with in single quotes.
Declaring Variables :
1. Each variable used in the program must be declared. To declare a variable specify the data type of
The variable followed by its name type of the variable followed by its name.
2. The data type indicates the kind of data that the variable will store.
3. Variable names should always be meaningful and must reflect the purpose of they are used in the
Program
4. The n-variable declaration always ends with a semi column(;).
For Examples:
Syntax:datatype variable1,variable2,variable3……variable-n;
int a;
inta,b,c,d;
intemp-num,regno;
char grade;
double balance-amount;
float salary,fee;
Initializing Variables:
While declaring the variables we can also initialize them with some values.
Examples: int a=10;
int temp-num=7;
char grade=’A’;
double balance-amount=100000;
float salary=5000;
[22]
Constants: The value was not changed during the execution of the program is called constants. Mainly they
are two types of constants.
They are
1. Numeric constants
2. Character constants.
1) Numeric Constants: These have numeric data with or without decimal points having positive or negative
sign. These are further sub divided into two categories. There are
Integer Constant
Real or Float Constant
Integer Constant: Integer constant has integer data without any decimal points are with any positive or
negative sign. These are further sub divided into three types. Those are
E.g.: 8, 7, 6, 5, 4…etc.,
ii) Octal - Integer Constant: These consist of combination of numbers from 0to7 with positive or negative
sign. It has leading with ‘O’ (Upper case or lower case). ‘O’ means octal
iii)Hexa- Decimal Integer Constant: These have Hexa decimal data leading with OX or X or H (capital or
small). These have combination of 0to9 and AtoF (capital or small). These letters represents the numbers 10
to15.
E.g.:23A,OXB2.
[23]
2) Real or Float Constant: Some constants which have decimal point value with in it is having any
positive or negative sign.
Eg: 22.34, 2.4 E 38 that means 2.4 X 1038.
Real constants are further divided into two categories.
I.) With Exponent Part
Ii.) Without Exponent Part.
i.) Without Exponent Part: Without exponent ‘E’ and having a decimal part mantissa.
E.g.: 30.6, -30.6
ii.)With Exponent Part: It is also called a scientific representation. Here ‘C’ has base value of 10 It
computes the power.
E.g.: 3.5 X 105 = 3.5 e5.
3) Character Constants: Character constants have either a single character or a group of characters or a
character with back slash (\) used for special purpose. These are further divided into three types.
a)Single Character Constant: These have a single character with in single quotes. So, These are called
single character constant.
E.g. : “DNRCOLLEGE”,”JOHN”,…etc.,
c)Back Slash: These are used for special purpose in ‘C’ language. These are used in output statement like
print (). Puts (), another name of Back slash character constant is escaping sequences.
Constant Meaning
\b Back space
\n Newline
\t Tab space
\v Vertical tab
\f Move one page to next
\o Null character
\r returns
[24]
Operators: Operators are used for compute a formula or compare two variable values or create logical
relationship between two operands or low-level programming we can say operators are used for processing.
Operators are divided into:
1. Arithmetic Operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Conditional Operators.
6. Bit Wise Operators.
7. Increment / Decrement Operators.
8. Comma Operator.
9. Equality Operators.
10. sizeof Operators.
1.Arithmetic Operators: ‘C’ provides all the basic Arithmetic operators in an Arithmetic expression like
x + y x and y are the operands. ‘+’ is the operator. ‘C’ used the precedence rules to decide which operator
is used first these are listed in the following table.
5. Conditional Operators: In ‘c’ Conditional operator ‘? :’ Constructs conditional expression of the form
Example : (A>B)?(A+B):(A-B);
Where Exp1, Exp2, Exp3 are expression. The operator ‘?:’ works as follows Exp1 is evaluated first. If it is
true then the expression Exp2 is evaluated. If the Exp1, is false Exp3 is evaluated.
6. Bitwise Operators : A special type of operators known as bitwise operators for manipulation of data in
Bit level. These operators are used for testing the Bits are shifting them right or left.
[26]
Increment Operators: In ‘C’ the operator ‘+ +’ is used as Increment operator it adds 1 to the variable we
can add 1 to the variable in one of the two types.
1. Pre Incrementing
2. Post Incrementing.
1).Pre-Incrementing: This operator first increments the value of the variable and then execution
proceeding.
Syntax: ‘++’ variable name;
E.g.: ‘++’a;‘++’ a is equivalent to a=1+a;
2).Post-Incrementing: This operator continuous with the execution before adding 1 to the variable and then
increments the variable by 1
Decrement Operator: In ‘C’ the operator ‘- -‘ is used as decrement operator. It subtracts one from the
variable we can subtract one from the variable in one of two ways.
1. Pre – Decrementing
2. Post – Decrementing
1).Pre–Decrementing: This operator first decreases the value of the variable and then execution proceeds.
Syntax : ‘- -‘ variable name;
Ex : ‘- -‘ a;‘- -‘ a is equivalent to a= -1+a.
2).Post–Decrementing: This operator continuous with the execution before subtracting one from the
variable and then decrements the variable by 1.
Syntax : Variable name ‘- -‘ ;
Ex : a’- -‘; a ‘- -‘ is equivalent to a=a-1.
8.CommaOperator: The comma operator is used to separate more than one variable in variable declaration.
The comma operator is also used to separate two or more expressions.
Ex.:int a, b, c; Ex.: int x=2,y=5;
9.Equality Operators: C language supports two kinds of equality operators to compare their operands for
equality or inequality. They are ‘==’equal to x==y, ‘!=’ not equal x!=y.
10.Sizeof Operators:The size of operator is a unary operator used to calculate the size of data type this
operator can be applied to all data types this operator is used to determine the amount of memory space that
the variable/expression/data type will take
Ex: int a =10;
unsigned int result;
result=sizeof (a);
result= 2
which is the space required to store the variable ‘a’ in memory.
[27]
Input / Output Functions: The Input / Output functions are used for reading the data from the keyboard
and displaying the result on the screen are the two main tasks of any program to perform these tasks ‘C’ has
no. of Inputs & Output functions. When a program is needs data it takes data through the input functions
and send the result through the output function.
Input Functions: Input functions are
1. scanf( ) function
2. getch( ) function
3. getchar( ) function
4. getche( ) function
5. gets( ) function
1).scanf () :Thescanf function is used to read the data from the keyboard. You can store the given value into
the variable through the scanf ( );
Syntax: scanf (“Control string”, &v1,&v2,&v3,---- &vn”);
Here v1, v2, ----vn are the variables and “&” is used to store the given value into the variables. The control
string has some format strings.
Some Format Strings are :
2).getchar ( ): This function is used for reading a single character from the keyboard. The getchar ( ) can be
assigned a character into the character type variable.
Syntax: ch=getchar( ); Where ‘ch’ is the variable of character type.
3).getch( ) :The getch( ) is used to get a single character from the keyboard it will not display the character
on the screen and it will store the given character on the buffer it is used at the end of the program to
terminate the output screen.
Syntax: getch ();
4).getche( ):The getche ( ) is used to get a single character from the keyboard it will display the character on
the screen and the character will be stored on buffer it is used at the end of the program to terminate the
output screen.
Syntax: getche ();
5).gets ( ):The purpose of the gets function is to read the string it can read a string until you press enter key
from the keyboard it will mark null character (‘\0’) at the end of the string.
Syntax: gets (ch);Where ‘ch’ is the string variable.
[28]
Output Functions: Output functions are:
1. printf()
2. putchar ()
3. puts ( )
1.printf ( ) : The printf( ) is used to display a text message or a value stored in the variable. It requires
conversion symbol and the variable name to print the data.
Syntax: Printf (“control strings”, v1,v2,------vn”);
(OR)
Printf (“Message line or text line”);
Where v1,v2,-------vn are the variable.
The Control Strings uses some Printf ( ) Format Strings some Format Strings are:
Type Conversion and Type Casting: The type conversion is done when the expression has various of
different data types the data type is promoted from lower to higher level. Type conversion is automatically
done when assign an integer value to a floating point variable consider the following code
floatx;
int y=3;
x=y;
Now x=3.0 as the integer value is automatically converted into float value.
Type Casting:Type casting is also known as forced conversion it tells the compiler to represent the value of
expression in certain way.it is done when the value of higher data type is converted into the value of lower
data type. Consider the following code
float salary=10000.00,
x=y
intsal;
sal=(int)salary;
When floating point numbers are converted into integers the digits after the decimal are truncated.
[29]
Decision Control and Looping Statements: Supports two types of decision control statements that can
after the flow of sequence of instructions.
They are 1) Conditional Branching Statements.
2) Unconditional Branching Statements.
1) Conditional Branching Statements: The Conditional branching helps to jump one part of the program to
another depending on weather a particular condition is satisfy or not. the control statement includes
a) if statement
b) if- else statement
c) nested if-else statement
d) if-else-if statement
e) switch case statement
a) if statement: Only one statement occurs in “if”. It is having only one block.
Syntax:- if (condition)
{
True Statement
}
Statement x;
First the condition will be checked. If the condition is true than the true statement block will be
executed and after execution of this block, statement x will be executed. If the condition is false then only
statement X will be executed.
[30]
b) if-else statement: This statements also has a single condition with two different blocks (i) is true block
and other one is false block.
Syntax:-if (condition)
{
True statement;
}
else
{
False statement;
}
Statement x;
First the condition will be checked. If the condition is true then true statement block will be executed.
Then control goes to statement x. If the condition is false then the false statement block will be executed
then control goes to statement x.
c) nested if-else statement: When an if statement occurs within another if statement is called nested if else
statement.
Syntax:-if(condition)
{
if(condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Statement x;
Condition one will be checked if it is true condition two will be checked. If condition 2 is true then the
statement one will be executed. If condition 2 is false the statement two will be executed.
[31]
d) else-if ladder statement: No. of conditions arise in a sequence, then we can use ladder if statement to
solve the problem in the simple manner.
Syntax:- if(condition)
{
Statement 1;
}
elseif(condition 2)
{
Statement 2;
}
elseif(condition 3)
{
Statement 3;
}
---------------
---------------
elseif(condition)
{
Statement n;
}
else
{
default statement;
}
Statement x;
In this statement 1st condition will be checked, if it is true the statement 1 will be executed, if the condition 1
is false the condition 2 will be checked. If it is true statement 2 will be executed. Otherwise further next
condition will be checked and this process will be continue till the end of the condition.
e) switch case statement: The switch case statement is a multi-way branch statement. The tests whether
expression matches one of the constant values. This switch case statement requires only one arguments
which is checked with numbers of cases options.
Syntax:-switch (expression)
{
case value 1: Statement 1;
break;
case value 2: Statement 2;
break;
------
------
case value n: Statement n;
break;
default: statement;
}
[32]
Write a program to find a day of week.
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
clrscr();
printf(“\n Enter day number:”);
scanf(“%d”,&day);
switch(day)
{
case 1:printf(“\n sunday”);
break;
case 2:printf(“\n monday”);
break;
case 3:printf(“\n tuesday”);
break;
case 4:printf(“\n wednesday”);
break;
case 5:printf(“\n thursday”);
break;
case 6:printf(“\n friday”);
break;
case 7:printf(“\n saturday”);
break;
default:printf(“invalid day number”);
}
getch();
}
[33]
Iterative Statements(Looping Statements): Iterative statements are used to repeat their execution of list of
statements depends on the value of integer expression.
(or)
A single statement (or) group of statements will be executed again and again in a program such type of
processing is called loop.
“C” supports three types of iterative statements also known as looping statements. They are
while-loop
do-while loop
for loop
while loop: In while loop one (or) more statements are repeatedly executed. Until a particular condition is
true. while loop is an entry control loop.
Syntax:-while(condition)
{
Block of statements;
}
In the while loop first the condition is tested. If the condition is true. Then only the body of statement
will be executed. It will be executed again and again till condition becomes false. Otherwise if the condition
is false. The control will be jump to false statement.
[34]
do-while loop: The do-while loop is similar to while loop. The only one difference in a do-while loop .The
test condition is tested at the end of the loop. That means it is clear the body of loop gets executed atleast
once. do-while loop is an exit control loop.
Syntax:-do
{
Block of statements;
}
while(condition);
for-loop: It is a looping statement which repeat again and again till it satisfy the defined condition.
It is on e step loop which initialize (or) initialization, check the condition and increment (or) decrement
Step in the loop in a single statement.
[35]
The execution for the “for loop” is as follows
1) Initialization of variable is done first
2) The value of variable is tested is tested is using test condition. If the condition is true the body
of the loop is executed if the condition is false the loop is terminated.
3) When the body of loop is executed the control transfers back to the 1 st statement for the last
expression. That is increment/decrement.
4) After increment/decrement the value of the control again goes to the test condition. If the
condition is true, the body of the loop is again executed. The process continuous until the test
condition is false.
E.g: Write a C program to print 1 to N number using for loop.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i, n;
clrscr();
printf (“Enter n value”);
scanf (“%d”, &n);
printf (“\n 1 to n numbers are:”);
for (i=1; i<=n; i++)
{
printf (“\n%d”, i);
}
getch();
}
[36]
Nested for- loop: One for statement with in another for statement is called nested for loop.
Syntax:-for (initialization; test condition; increment/decrement)
{
for (initialization; test condition; increment/decrement)
{
Statement 1;
Statement 2;
-------
--------
Statement n;
}
Statement 1;
Statement 2;
---------
---------
Statement n;
}
Unconditional Branching is when the programmer forces the execution of a program to jump to another
part of the program. ... The goto, break, continue, return statements are used for unconditional branching.
break statement: break is a keyword in “c” statement is used to terminate the loop i.e., the control comes
out from the current loop. When over the break keyword is encountered. It is also called as loop terminator.
The break statement is widely used with for loop, while loop & do-while loop.
Syntax: break;
continue statement: The continuous statement is opposite to break statement. It appears in the body of the
loop. Whenever a continuous statement appears the rest of the statements in the loop are skipped. And it
continuous with the next iteration of current loop.
(or)
The continuous statement is exactly opposite to break statement. The continuous statement is used for
continuing next iteration of next statement, when it occurs in the loop it doesn’t terminate, but it skips the
statements after this statement. It is useful when you want to continue the program without executing any
part of the program.
Syntax: continue;
goto statement: It doesn’t require any condition goto is a keyword in ‘c’ this statement process control any
where in the program. i.e., control is transferred to another part of program without testing any condition.
The user has to define goto statement as follows.
Syntax: goto label;
return statement: It is a keyword in ‘c’ it is commonly used in user defined functions (or) sub functions to
return a value, the program control transfers from sub function to main function.
Note:-‘C’ language supports 4 statements to perform unconditional control transfers.
They are
1) return
2) goto
3) break
4) continue
These 4 statements are also called “jumping statements”.
[37]
Example Programs:
1) Example program for Integer data type.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
int b=7;
int c;
clrscr();
c=a+b;
printf(“ Integer Addition value is:%d”,c);
getch();
}
Output: Integer Addition value is: 12
2) Example program for Float data type.
#include<stdio.h>
#include<conio.h>
void main()
{
float a=5.0;
float b=7.0;
float c;
clrscr();
c=a+b;
printf(“Float Addition value is:%f”,c);
getch();
}
Output: Float Addition value is :12.0
3) Display the ASCII Values of characters &using char datatype.
#include<stdio.h>
#include<conio.h>
void main()
{
charch;
clarscr();
printf(“Enter any character:”);
scanf(“%c”,&ch);
printf(“\n ASCII value of character %c is:%d”,ch,ch);
getch();
}
Output: Enter any character: A
ASCII value of character A is: 65
Enter any character: b
ASCII value of character b is: 98
[38]
4) Example program for enum (Enumerated) data type
#include<stdio.h>
#include<conio.h>
void main()
{
enum week{sun,mon,tues,wed,thu,fri,sat};
clrscr();
printf(“Sun=%d”,sun);
printf(“\n Mon=%d”,mon);
printf(“\n Tues=%d”,tues);
printf(“\n Wed=%d”,wed);
printf(“\n Thu=%d”,thu);
printf(“\n Fri=%d”,fri);
printf(“\n Sat=%d”,sat);
getch();
}
Output: Sun=1
Mon=2
Tues=3
Wed=4
Thu=5
Fri=6
Sat=7
5) Write a program for addition of Three Numbers with using scanf() function.
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,c,d;
clrscr();
printf(“Enter a,b,c values:”);
scanf(“%d%d%d”,&a,&b,&c);
d=a+b+c;
printf(“ \n Integer Addition value is:%d”,d);
getch();
}
Output: Enter a,b,c values: 10 20 30
Integer Addition value is: 60
[39]
6) Write a program to implement all Arithmetic Operations
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,c,d,e,f;
clrscr();
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
c=a+b
printf(“ \n Addition value is:%d”,c);
d=a-b
printf(“\n Subtraction value is:%d”,d);
e=a*b
printf(“\n Multiplication value is:%d”,e);
f=a/b
printf(“\n Division value is:%d”,f);
getch();
}
Output: Enter a,b values: 10 2
Addition value is: 12
Subtraction value is: 8
Multiplication value is: 20
Division value is: 5
[40]
8) Write a Swapping program & read the values from keyboard.
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,temp;
clrscr();
printf(“Enter a values:”);
scanf(“%d”,&a);
printf(“\n Enter b values:”);
scanf(“%d”,&b);
printf(“\n Before Swapping values a=%d,b=%d”,a,b);
temp=a;
a=b;
b=temp;
printf(“\n After Swapping values a=%d,b=%d”,a,b);
}
Output: Enter a values: 10
Enter b values: 20
Before Swapping values a=10,b=20
After Swapping values a=20,b=10
9) Write a program to find the bigger of two numbers without false statement.
(if- statement example program)
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b;
clrscr();
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“ \n a is big”);
getch();
}
Output: Enter a,b values: 20 5
a is big
[41]
10) Write a program to find the biggest of two numbers with false statement.
(if- else statement example program)
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b;
clrscr();
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“ \n a is big”);
}
else
{
printf(“ \n b is big”);
}
getch();
}
Output:1 Enter a,b values: 20 5
a is big
Output:2 Enter a,b values: 20 50
b is big
[43]
13) Example program for do- while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n,i=1;
floatavg;
printf(“\n Enter the value of n”);
scanf(“%d”,&n);
do
{
sum=sum+i;
i=i+1;
}
while(i<=n);
printf(“\n Sum is :%d’, sum);
avg=(float)sum/n;
printf(“\n Average is: %f”,avg);
getch();
}
Output:
[44]
15) Example program for nested for-loop.
#include<stdio.h>
#include<conio.h>
void main ()
{
int n=2,m=3,i,j;
clrscr();
printf(“\n Nested for-loop output is :”);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
printf(“\n hello!”);
}
printf(“@ok@”);
}
getch();
}
Output:
16) Write a ‘C’ Program to find the Given Number is Even or Odd.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter the n value:”);
scanf(“%d”,&n);
if(n/2==0)
{
printf(“\n The given number is Even”);
}
else
{
printf(“\n The given number is Odd”);
}
}
Output: 1) Enter the n value: 10
The given number is Even
2) Enter the n value: 7
The given number is Odd
[45]
UNIT-III
ARRAYS
Definition: Array is a collection of collection of similar data items (or) elements. These data elements have
same data type. The elements of array are stored in sequence memory location and referred by index.
Arrays are used to reduce confused and length of the program. Each element of an array can be
accessed with the array name followed by a subscript which includes in square brackets .The
subscript provided from zero(0) for the first element ,increased by one to the next element.
Declaration of an Array: An array must be declared before its use. Declaring an array means we need to
specify.
Syntax:- Data type Array name [size] ;
Example: int a[5];
float c[10];
Datatype: What kind of data value it can store .E.g.: integer, float, char, double….etc.,
Array Name : To identify an array name.
Size: Minimum number of values that an array can store.
Initialization of Arrays: An elements of array can be initialized at the time of declaration. When an array is
initialized we need to provide a value for every element in the array.
Syntax: Data type Array-name [size]={list of values};
Example: int a[5]={1,2,3,4,5};
Types of Arrays: There are three types of arrays.
1. One – Dimensional Array
2. Two – Dimensional Array
3. Multi – Dimensional Array
1) One – Dimensional Array: A list of items can be given one variable name using only one
subscript and such variable is called a single subscripted variable (or) one dimensional array .
Declaration of One Dimensional Array:
Like any other variable, array must be declared before they are used .
Syntax: Data type array name [size] ;
Example: int a[5];
float c[10];
Initialization of One Dimensional Array:
The array can be initialized at the time of declaration .
Syntax: Data type array name [size] = {list of values};
Example: inta[5]={1,2,4,8,16};
#include<stdio.h>
#include<conio.h>
void main()
{
inta[10],n,i;
clrscr();
printf(“\n enter the size of an array:”);
scanf(“%d”,&n);
printf(“\n enter the elements in to an array”);
for(i=0;i<n-1;i++)
{
scanf(“%d”&a[i]);
}
printf(“\n the array elements are:”);
for(i=0;i<n-1;i++)
{
printf(“%3d”,a[i]);
}
getch();
}
2)Two-Dimensional Array: A two dimensional array is specified using two subscripts. Where one subscript
is denotes rows and other subscript is denotes column. It is also known as double dimensional array (or) two
dimensional array.
Declaration of Two-Dimensional Array:
Syntax: Data type array name [rows][column];
E.g.:intarr[2][3];
Initialization of Two-Dimensional Array: The two dimensional array can be initialized at the time of
declaration.
Syntax: Data type array name[row size][column size] = {list of values};
Example: intarr[2][3]={5,7,10,2,1,3};
Here the value assigned to the array is as follows.
arr[0][0]=5 arr[1][0]=2
arr[0][1]=7 arr[1][1]=1
arr[0][2]=10 arr[1][2]=3
[47]
E.g. Write a C program to read and print on two dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
inta[5][5],i,j,r,c;
clrscr();
printf(“\n Enter the order of matrix:”);
scanf(“%d%d”,&r,&c);
printf(“\n Enter the elements in to the array:”);
for(i=0;i<=r-1;i++)
{
for(j=0;j<=c-1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“\n The elements of the matrix are \n\n”);
for(i=0;i<r-1;i++)
{
for(j=0;j<=c-1;j++)
{
printf(“%d3d”,a[i][j]);
}
printf(“\n\n”);
}
getch();
}
Output:
[48]
4.Substraction (or) deference: Two matrixes can be subtracted from each other by storing the result in
third matrix two matrixes are said to be compared, when they have same number of rows and columns
elements of matrixes can be subtracted as follows
Cij=Aij-Bij
3)Multi – Dimensional Array: A multi-dimensional array is an array of arrays. It is specified to use
NX N indexes a multi-dimensional array.
A particular element is specified in using subscripts as A[I1][I2][I3]------[In]
STRING
Definition: A string is a group of characters. A string in ‘C’ defined as any group of characters
enclosed between double quotes(“ “) marks. The string can be of any length, the end of the string is
marked with the single character(‘\0’) the null character.
The strings are actually one dimensional array of characters terminated by null character. The character
arrays are declared in c in a similar manner of numeric array.
Declaration:
Syntax: char string name[size];
Strings can be initialized at the time of declaration at the same time initializations at the time
of declaration the string can be initialized in any one of the following manner.
E.g: char name[10] = “Krishna”;
char name[10] = {‘k’,’r’,’i’,’s’,’h’,’n’,’a,};
“C” library supports a large number of string handling functions. Following are the most commonly
used String Handling Functions.
String Handling Functions: The ‘C’ library supports a large number of string handling functions that can be
used to manipulate the string in many ways you must include the string header file in your program.
String handling functions are:
1. strcat()concatenation
2. strcpy()copy
3. strlen()length
4. strcmp()compare
5. strrev()reverse
6. strupr()upper case
7. strlwr()lower case
1) strcat( ) : The strcat( ) function is used to joins two strings.
Syntax: strcat(str1,str2);
str1 andstr2 are two strings. When the function strcat() is executed str2 is appended to str1.
2) strcpy( ) : This function is used to copy one string into another string it accepts two strings as
arguments.
Syntax: strcpy(target,source);
If first argument is generally an identifier, that represents the strings. The second argument can be a
string constant. The function copies the string of source to target.
3) strlen( ) : This function counts and returns the number of characters in a string.
Syntax: variable= strlen(string);
Where variable is an integer variable, which receives the value of the length of the string the
argument is a string constant.
[49]
4) strcmp( ) : This function compares two strings and returns a integer value.
Syntax: strcmp(str1,str2);
It returns zero if the strings are equal, greater than zero if string 1 is bigger than string 2 and less
than zero if string1 is less than string2.
5) Strrev(): The purpose of this function is two reverse a string this function takes string variable as a single
argument here the first character becomes last and the last character becomes first in the string.
Syntax: strrev(string);
E.g: char str1[10]=”degree”;
Printf(“reverse string of str1=%s”,strrev(s1));
O/P:- reverse string of str1=eerged
6) Strupr(): The purpose of this function is to convert into upper case this function converts all the character
of a string from lower case to upper case.
Syntax:-strupr(string);
E.g: char str1[10]=”degree”;
Printf(“str1 is converted into upper case :%s”,strupr(str1));
O/P:- str1 is converted into upper case :DEGREE
7) Strlwr(): The purpose of this function is to convert string into lower case this function converts all the
character of a string from upper case to lower case.
Syntax:-strlwr(string);
E.g: char str1[10]=”DEGREE”;
Printf(“str1 is converted into lower case :%s”,strupr(str1));
O/P:- str1 is converted into lower case :degree
E.g: Write a ‘C’ Program to perform various String Operations.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s1[20]="govt";
char s2[20]="college";
char s3[20]="ORGANIZATION";
clrscr( );
printf("\n Length of string s1 is:%d",strlen(s1));
strcat(s1,s2);
printf("\n Join two strings s1 and s2:%s",s1);
printf("\n String s2 convert to uppercase:%s",strupr(s2));
printf("\n String s3 convert to lowercase:%s",strlwr(s3));
strrev(s1);
printf("/n Reverse of string s1 is:%s",s1);
strcpy(s1,s2);
printf("\n Copy of string is:%s",s1);
getch( );
}
Out put: Length of string s1 is:4
Join two strings s1 and s2:govtcollege
String s2 convert to uppercase: COLLEGE
String s3 convert to lowercase: organization
Reverse of string s1 is :tvog
Copy of string is : college
[50]
Operations of String: The different operations that are performed on strings. They are
*String length: The number of characters in the string constitutes the length of the string.
Eg:-strlen(“c programming is fun”);
Will return “c” programme to “20” (including blank spaces)
*Comparing two strings: To compare two strings each and every character is compared from both the
strings if all the character are same then the two strings are equal.
Eg:-S1-hello
S2-hello
strcmp(s1,s2);
strings are equal
*Reverse a string: If s1=”hello” the reverse of s1=”olleh”. To reverse a string we need to swap the first
character with the last, second character with the last second character and so on----.
Eg:-how r u
strrev(s1);
U r who
[51]
Example program for string reverse.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s1[20]="govt";
clrscr( );
strrev(s1);
printf("/n Reverse of string s1 is:%s",s1);
getch( );
}
OUTPUT: Reverse of string s1 is :tvog
[52]
UNIT – IV
FUNCTIONS
Function: A function is a group of statements that together perform specific tasks. A large program can be
split into smaller segments. So that it can be efficiently solved.
The function are categorized into two types
Pre-defined functions (or) Library functions.
User-defined functions
The major difference between the user defined functions and pre-defined functions are not required to
be written by user. While writing a program. Many program required to a particular group of unstructured
accessed repeatedly. From the different place with in the program. This repeated instructions can be placed in
a single function and can be accessed whenever necessary.
Function is a group of statements that carries out to specific task. Every c program starts with atleast
one function. Which is main(). The main() calls another to share the work.
Library functions are pre-defined se of functions they task is limited.
Eg:-printf(), scanf(), sqrt()….etc.
These functions cannot modify.
User defined functions are define by user. According to our requirement are called user defined functions.
Advantages of function:
1. It provides reusability. Because function calls many times.
2. Generally large programs can be divided into smaller programs.
3. It is too easy to modify.
4. It is easy to debug and find out the errors.
How function work:
Function can be define and called it takes some data from the calling function. And return a value to
the called function. Whenever function is called control passes to the called function. And working of
the calling function is complete control returns back the calling function and executes the next
statement.
The value of actual arguments passed by the calling function are received by the formal arguments of
the called function.
The function operates on formal arguments and sends back the result to the calling function.
The return function performs the task. Every function consists of three parts.
Function declaration.
Function definition.
Function call (or) Calling function.
Function declaration:
Function declaration consists of three components such as return type, function name and aruguments
being passed. The function declaration must be ends with a semi column (;).
Syntax:-
return type, function name (arg1, arg2 ……arg n);
int sum(int, int);
float multi();
Function definition: The function definition consists of two components. The first line and the body of the
function. The function definition is same as function declaration except that is does not end with a semi
column(;)
[53]
Syntax:-
return type function name (arg 1,arg 2…..arg n)
{
function body;
return(expression);
}
The body of the function may contain local variables, statements, expressions and also a return type.
Function cal (or) Calling function: The function call statement invokes the function. When a function is
invoked the compiler jumps to the called function to execute the statements that are a part of function. Once
the called function is executed, the program control passes back to the calling function.
Syntax:
function name(variable 1, variable 2….);
Example:
main()
{
…..
…..
abc (x,y,z); // Call Function;
……
……
}
abc(i,j,k) // Called Function;
{
……
……
return();
}
Example Program: Find addition of two numbers by using functions.
#include<stdio.h>
#include<conio.h>
int add(int,int); //Define function;
void main()
{
int a,b,c;
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
c=add(a,b); //Call Function;
printf(“The sum value is:%d”, c);
getch();
}
int add(int p,int q) //Called Function;
{
int m;
m=p+q;
return(m);
}
OUTPUT:
[54]
Types of Functions:
Depending upon the arguments return value sends back to the calling functions based on this the
functions are divided into four types.
1. A function without arguments and without return a value.
2. A function with arguments and with return value.
3. A function with arguments and without return value.
4. A function without arguments and with return value.
1. A function without arguments and without return value:
In this function neither the data is passed through the calling function not the data sent back from
the called function.
There is no data transfer between calling & the called function. The function is only executed &
nothing is return (or) obtain.
These functions are independent. They read data values& print results in the same block.
Such functions may be useful to print same messages, draw a line or split the lines etc.
Syntax:-
Calling function Analysis Called function
void fname(); No arguments are passed void fname()
statements; {
{ Statements;
f name(); }
statements(); No values are passed
}
Example:-
#include<stdio.h>
void main()
{
void msg(); /* calling function*/
msg();
}
void msg() /* called function */
{
Printf(“welcome”);
}
2.A function with arguments and with return value:
In such functions the copy of actual arguments is passed to formal arguments.
The return value is sent back to the called function.
In such functions the data is transferred between calling and the called function i.e., communication
between is made.
Syntax:-
Calling function Analysis Called function
void main() Arguments are passed. int f name(formal arguments list)
{ {
int f name (actual arguments list); Statements;
f name(actual arguments list); return value;
} }
Values are sent back
[55]
Example:- /* addition of two numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int);
int a,b,c;
clrscr();
printf(“Enter two values”);
scanf(“%d%d”, &a,&b);
c=add(a,b);
printf(“sum=%d”,c);
getch();
}
int add(int x,int y)
{
int z;
z=x+y;
return z;
}
3.A function with arguments and without return value:
In such functions the arguments are passed through the calling function.
The calling function operates the values but no result is sent back.
Such functions are dependent on the calling function there is no gain to the main() function.
Syntax:-
Calling function Analysis Called function
void main() Arguments are passed void f name(formal arglist)
{ {
void f name(actual arg datatype list1); Statements;
statements; }
f nam(actual arg list 1);
statements;
} No values are sent back
Example:-
/* write a program to given number is even or odd*/
#include<stdio.h>
#include<conio.h>
void main()
{
void evenodd(int);
int a;
clrscr();
printf(“Enter one value:”);
[56]
scanf(“%d”,&a);
evenodd(a);
getch();
}
void evenodd(int n)
{
if(n%2==0)
printf(“Given number is even:”);
else
printf(“Given number is odd”);
}
Output:-
Enter one value:-4
Given number is even
4.A function without arguments and with return value:
In such type of function no arguments are passed through the main function but the called function
returns the value
The called function is independent. It reads the value input from the keyboard or generates from the
initialization and returns the value
Here both the calling & called function are communicated with each other.
Syntax:-
Calling function Analysis Called function
No arguments are passed int f name()
void main() {
{ Statements;
int f name(); return value;
statements; }
f name;
statements;
} Values are sent back
[58]
2) Call by reference :
Call by reference in which address of variable passed by the calling function to called function.
Example:-
/* Swapping of two numbers in Call by reference*/
#include<stdio.h>
#include<conio.h>
void swap(int *,int*);
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values :”);
scanf(“%d%d”,&a,&b);
printf(“\nBefore swapping in main a=%d\t b=%d\t”,a,b);
swap(&a,&b);
printf(“\nAfter swapping in main a=%d\t b=%d\t”,a,b);
getch();
}
void swap(int *p,int *q)
{
int *temp;
*temp=*p;
*p=*q;
*q=*temp;
printf(“\n After swapping in function p=%d\t,q=%d\t”,*p,*q);
}
Output :
Enter a,b values : 2 3
Before swapping in main a=2 b=3
After swapping in function p=3,q=2
After swapping in main a=3,b=2
Recursion:
‘C’ language supports recursive features i.e., function is called repeatedly by itself. The recursion can
be directly (or) indirectly.
The direct recursion function called itself. In indirect recursion function call another function. Then
the called function calls calling function.
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
[59]
int fact(int);
clrscr();
printf(“Enter n value”);
scanf(“%d”, &n);
f=fact(n);
printf(“\n The factorial of %d is %d”, n, f);
getch();
}
int fact(int n)
{
int f;
if(n==0)
{
return n;
else
f=n*fact(n-1);
return f;
}
Output:-
Enter n value:2
The factorial of 2 is 2
Storage Classes
The storage class determine the part of memory when the variable would be stored.
Each variable has a storage class which decides scope, visibility and life time of that variable.
A variable declared inside of the main function is called “local variables”.
A variable declared outside of any function is called “global variable”.
There are 4 types of storage classes in ‘c’
1. Automatic storage class 3. Static storage class
2. External storage class 4. Register storage class
1. Automatic storage class: Automatic variables are defined inside a function. A variable declared inside the
function without use storage class, name by default is an automatic variable. Automatic variables is also
called as local variable. It is declared to use “auto “keyword.
[61]
STRUCTURE
Definition: A Structure is a collection of one or more variables of different data types grouped together
under a single name.
A Structure is similar to a record it stores related information about variable. Structure is a basically
user defined data type that can store related information.
The major difference between a structure and array is that an array contains related information of
some data type, but structure is a collection of variables with different data types.
Structure Declaration: A Structure is declared as a “struct” keyword followed by structure name all the
variables of the structure are declared with in the structure.
Syntax:
struct structure_name
{
data type var-name1;
data type var-name2;
-------------------
-------------------
};
For example; To declare a structure for a student with related information roll no, name, fee section --,is
declared as exactly in the example.
Ex:- struct student
{
int rollno;
char name[20];
float fees;
};
Initialization of structure: A structure can be initialized in some way as other data types are initialized
initializing a structure means assigning some constants to the member of structure.
The initializes are enclosed in braces {} and are separated by commas(,).
[62]
Accessing the members of a structure: Each member of a structure can be used just like a normal variable.
A structure member variable is generally accessed to using a “.” dot operator.
Syntax:- struct-var.member-name
the dot(.)operator is used to select a particular member of the structure.
Eg:- std1.rno=01;
std1.name=”rahul”;
std1.course=”bsc”;
std1.fees=4500;
Eg:-Write a c program to read and display student information using structures
#include<stdio.h>
#include<conio.h>
int main()
{
struct student
{
int roll-no;
char name[30];
float fees;
char dob[30];
};
struct student std1;
clrscr();
printf(“\n enter roll-no:”);
scanf(“%d”,&std1.roll-no);
printf(“\n enter name:”);
scanf(“%d”,&std1.name);
printf(“\n enter fees:”);
scanf(“%f”,&std1.fees);
printf(“\n enter date of birth:”);
scanf(“%d”,&std1.dob);
printf(“\n*********student details*********”);
printf(“\n rollno=%d”,std1.rollno);
printf(“\n name=%s”,std1.name);
printf(“\n fees=%f,std1.fees);
printf(“\n dob=%d,std1.dob);
getch();
return 0;
}
Output:
enter roll-no:1
enter name: ravi
enter fees:4500
enter dob:17-11-1998
******student details*********
roll-no=1
name=ravi
[63]
fees=4500
dob=17-11-1998
Nested structure: A structure can be placed with in another structure. A structure that contains another
structure as its member is called nested structure
The easier and clear way is to declare a nested structure separately and then group them in a high level
structure (from lower level to higher level) the nesting must be done from inside out.
Eg:-Write a c program to read and display student information using structure with in a structure
#include<stdio.h>
#include<conio.h>
int main()
{
struct dob
{
int day;
int month;
int year;
};
struct student
{
int roll-no;
char name[30];
float fees;
struct dob date;
};
struct student std1;
clrscr();
printf(“\n enter roll-no:”);
scanf(“%d”,&std1.roll-no);
printf(“\n enter name:”);
scanf(“%d”,&std1.name);
printf(“\n enter fees:”);
scanf(“%f”,&std1.fees);
printf(“\n enter date of birth:”);
scanf(“%d%d%d”,&std1.date.day,&std1.date.month,&stud1.date.year);
printf(“\n*********student details*********”);
printf(“\n rollno=%d”,std1.rollno);
printf(“\n name=%s”,std1.name);
printf(“\n fees=%f,std1.fees);
printf(“\n dob=%d-%d-%d”, std1.date.day,std1.date.month,stud1.date.year);
getch();
return 0;
}
Output:
enter roll-no:2
enter name:”Victor”
[64]
enter fees:5000
enter dob:1-12-1998
******student details*********
roll-no=2
name=Victor
fees=5000
dob=1-12-1998
Self referential structure: The self referential structures are includes at least one member as a pointer to the
same structure is known as self referential structure it can be linked together to form useful data structures
such as lists, queues, stacks and trees. It is terminated with a null pointer(0)
Syntax: struct struct-name
{
type member;type2 member2;
-------------------
-----------------
struct struct-name*next;
};
E.g.:- struct node
{
int data;
struct node*next;
};
UNIONS
Union: A union is a special data type available in C. It is a collection of variables of different data types in
the same memory location. In structure each member has own storage location. Unions provide an efficient
way of using the same memory location for multiple purposes. a union is declared using” union” keyword.
Declaring a union: The syntax for declaring a union is same as that of declaring a structure using the
keyboard struct and the union is used union keyword
Syntax: union union-name
{
data type var-name;
data type var-name;
----------------------
----------------------
};
Ex:-write a c program to read and display student information using unions
#include<stdio.h>
#include<conio.h>
int main()
{
union student
{
int roll-no;
[65]
char name[30];
float fees;
char dob[30];
};
union student std1;
clrscr();
printf(“\n enter roll-no:”);
scanf(“%d”,&std1.roll-no);
printf (“\n enter name:”);
scanf (“%d”,&std1.name);
printf (“\n enter fees:”);
scanf (“%f”,&std1.fees);
printf (“\n enter date of birth :”);
scanf (“%d”,&std1.dob);
printf(“\n*********student details*********”);
printf(“\n rollno=%d”,std1.rollno);
printf(“\n name=%s”,std1.name);
printf(“\n fees=%f,std1.fees);
printf(“\n dob=%d,std1.dob);
getch();
return 0;
}
Output:
enter roll-no:1
enter name: raju
enter fees:4500
enter dob: 17-11-1998
******student details*********
roll-no=1
name=raju
fees=4500
dob=17-11-1998
[66]
UNIT-V
POINTER
A pointer is a variable, which contains the address of another variable. A pointer provides an indirect way of
accessing the value of a data item.
Declaring a pointer variable: Declaration of pointer variable is similar to the declaration of a common
variable. A pointer is a variable should be declared before they are used. The general syntax used forthe
declaration of pointer is as.
Syntax: Data-type *pointer-variable;
Where data type may be integer (int), real(float),character(char) or double. Also here (asteric sign) means it is
pointer operator and pointer variable is any variable linked with’*’ sign.
it is pointer operator and pointer variable is any variable linked with '*' sign.
Advantages:
1. Pointers increase the execution speed of the C-Program and are more efficient.
2. Pointer access the memory elements very easily.
3. Pointer reduces the length and complexity of the program.
4. By using pointer, we can declare lesser number of variables in memory.
5. Pointers access the memory elements very easily.
6. We can pass arguments to functions by reference.
Disadvantages:
1. Pointers are slower than normal variables
2. If used incorrectly pointer leads to bugs(errors)
3. An erroneous input leads to erroneous output
[67]
Passing arguments to functions using pointers:
Using call-by value method it is impossible to modify the actual parameters in the call when you pass
then to a function
Pointers provide a mechanism to modify data declared in one function using the code written in another
function we must pass the address of variables, we want to change
To use pointers for passing arguments to a function we must do the following.
1. Declare the function variables as pointers
2. Use the de-reference pointer in the function body
3. Pass the address as the actual arguments when the function is called
Ex:- swapping of two numbers by using Call-by reference (Or) Call by pointers.
/* Swapping of two numbers in Call by reference*/
#include<stdio.h>
#include<conio.h>
void swap(int *,int*);
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values :”);
scanf(“%d%d”,&a,&b);
printf(“\nBefore swapping in main a=%d\t b=%d\t”,a,b);
swap(&a,&b);
printf(“\nAfter swapping in main a=%d\t b=%d\t”,a,b);
getch();
}
void swap(int *p,int *q)
{
int *temp;
*temp=*p;
*p=*q;
*q=*temp;
printf(“\n After swapping in function p=%d\t,q=%d\t”,*p,*q);
}
Output :
Enter a,b values : 2 3
Before swapping in main a=2 b=3
After swapping in function p=3,q=2
After swapping in main a=3,b=2
[68]
Array of pointers: An array of pointers can be declared as int*ptr[10];
The above statement can be declared have an array of 10 pointers to an integer variable. for example int
p=1,q=2,r=3,s=4,t=5
ptr[0]=&p;
ptr[1]=&q;
ptr[2]=&r;
ptr[3]=&s;
ptr[4]=&t;
Eg:- #include<stdio.h>
#include<conio.h>
void main()
{
int *p,i=0;
int a[5]={1,2,3,4,5};
clrscr();
p=&a[0];
printf(“pointer of array elements are”);
while(i<5)
{
printf(“%d”,&p);
p++;
i++;
}
getch();
}
Output: pointer of array elements are 1,2,3,4,5;
Function pointers: Every function has an address function pointers are pointer variables that point to the
address of a point function pointers can be declare assign values and used to access the functions.
In order to declare a pointer to a function the name of function must be enclosed between parenthesis and
an asteric (*) symbol is inserted before the name.
Syntax:- the syntax of declaring a function pointer is
retune type(*function pointer name)(arg list);
Ex:-int (*func)(int a,float b);
Address Operator (&): The address of the memory variable can be accused by using address operator (&).
Now suppose q is a variable having value 280 and this variable is stored in the memory address at 6000.
Then to represent address of the memory, we apply a variable p, which is pointer or memory variable. We
can store address of q variable in p pointer variable as by using & operator.
Eg :write a program to print address and value of variable
# include<stdio.h>
#include<conio.h>
void main()
{
int x,*p;
clrscr();
printf(“enter x values:”);
[69]
scanf(“%d”,&x);
p=&x;
printf(“\n address of x=%u”,&x);
printf(“\n value of x=%d”,x);
printf(“\n address of x=%d,*p);
getch();
}
Output: enter x value=6
address of x=65500
value of x=6
address of x=65500
void pointer: void pointer (or) generic pointer is a special type of pointer that can be pointed to object to any
data type it is declared like a normal pointer using void keyword.
Null pointer: Null pointer are used in situations where one of the pointer in the program points to different
location at different types.
Wild pointer: A pointer which is not initialized with any address is called wild pointer.
1. malloc()
2. calloc()
3. Realloc()
4. free()
[70]
1. malloc():
Malloc allocates requested size of bytes and return void pointer to the first byte of the allocated space
Malloc() allocates single block of requested memory
Syntax:- declare a pointer
Pointer name=(cast type*)malloc(byte size);
2. calloc():
Calloc () allocates multiple blocks of requested memory. Each of the same size and returns starting
address of the memory to the pointer variable. This is widely used in array.
Syntax:-declare a pointer
Ptr=(int*)calloc(n,2);
3.realloc():
This Realloc() is used to make changes in the memory location(i.e.)increase or decrease is already
allocated by malloc()or calloc()
This realloc reallocates the memory
Syntax:-declare a pointer
Pointer variable=(cast type*)realloc(pointer name, new size);
4.free():
It is essential to clean up memory at the end of the program
In the memory location filled with the garbage values so it is very much required to clean up
Syntax:-void tree(void*back);
FILES
Definition:
A file is a collection of data stored on a secondary storage device such as hard disk.
Files are mega data structure in information processing.
By using files, we need to perform some input and output operations i.e., how data is read from a file
or write be a file.
Reading data from files:
C provides the following set of functions to read a data from a file
1. fscanf()
2. fgets()
3. fgetc()
4. fread()
1. fscanf(): The fscanf() is used to read formatted data from a stream.
Syntax:
int fscanf(file *stream, const char *format….);
The fscanf() function is used to read data from the stream and store them. According to the parameter format
into the locations pointed by additional arguments.
2. fgets(): This function stands for ‘file gets strings”. This function used to get a string from a stream.
Syntax:
char *fgets(char *str, int size, file *stream);
This function reads at most the number of characters specified by size from the given stream and stores them
in string(str).
3. fgetc(): This function return the next character from the string and End of the File(EOF). If the end of the
file reached or if there is an error.
[71]
Syntax:
int fgetc(file *stream);
fgetc() function reads a single character from the current position of a file.
4. fread(): This function is used to read data from a file.
Syntax:
int fread(void *str,size-t, size, size-t num, file *stream);
This functions reads number of objects are placed them in to the array pointed by the string (str).
Example program for create a file and write operation.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen(“e://file.txt”,”w”);
fprintf(fp,”Hello”);
fclose(fp);
getch();
}
Output: Hello
[72]
Write a C program to read operation.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[200];
fp=fopen(“e:/file.txt”,”r”);
while(fscanf(fp,”%s”,text)!=EOF)
{
printf(“%s”,text);
}
fclose(fp);
getch();
}
Types of files:
Files are basically classified into three types:
1. Sequential files (Text files)
2. Random files (direct files)
3. Binary files (indirect level files)
1. Sequential File (Text files):
In this organization, the records will be arranged one after another.
It consists of alphabets and digits. So, it is called as text files.
For example if you want a record from a sequential file then, we will search from beginning to end. It
is the time consuming process. Generally it is used to store small amount of data.
Sequential Operations:
1. Defining and naming a file
2. Opening a file
3. Reading a file
4. Writing a file
5. Closing a file
2. Random Files (Direct Files):
It consists of fixed length of records. Each record can be identified by a unique number.
It is an efficient method as compared to sequential files.
These files are also called as direct files.
Random File Operations:
1. Defining and naming a file
2. Opening a file
3. Reading a file
4. Writing a file
5. Closing a file
3. Binary Files (Indirect Files):
It may contain graphical (or) image (or) compiled codes(machine language).
This file can be accessed byte by byte. So, data will be stored under 0’s and 1’s(zero’s and one’s)
It is the fastest and efficient method for accessing data.
[73]
Binary File Operations:
1. Defining and naming a file
2. Opening a file
3. Reading a file
4. Writing a file
5. Closing a file
Basic File Operations :
The following operations perform on files, they are
1. Naming file
2. Defining a file
3. Opening a file
4. Reading a file
5. Writing a file
6. Closing a file
1). Naming a file: A file name consists of two parts namely
a). Primary name
b). Secondary name
Primary name is mandatory or conform. Secondary name is optional.
Example :
Student.txt →Secondary name
↓
Primary name
2). Defining a file: While working with files we must create a file pointer to the file.The file pointer provides
communication between program and operating system.
Example :
FILE *fp;
Where “FILE” is a new data type,” fp” is file pointer to the file to file data type.It creates a link
between program and operating system.
3). Opening a file: While working with files,the file must be open,the combined fopen() creates a new file or
opening and existing file, it is represented by as follows.
Example :
Variable_name = fopen(“file name”,”file mode”);
FILE *fp;
fp=fopen(“student.txt”,”w”);
Here w is used for writing mode.
4). Reading a file:
To read data from a file, we use input statements such as fscanf(), fgets(), fgetc(), fread()
5). Writing a file:
To write data from a file, we use output statements such as fprintf(),fputs(),fputc(),fwrite()
6). Closing a file:
Once the file processing finished or completed close all the files that have being opened,fclose() is used
to close file.
[74]
How to open a file:
If you want to storee data in the secondary memory,we must specify certain things about the file to the
file,they include:
1. File name
2. Data structure
3. Purpose
1). File name: It is a string of characters that makes a valid file name for the operating system,it contains
primary name,secondary name.
Example:
Student.c
Simple.txt
2). Data structure: Data structure of a file is defined as “FILE” in library of standard input, output function
definitions. FILE is defined as data type
Example
a). FILE *fp;
b). fp=fopen(“file name”, “file mode”);
3). Purpose: It specifies the purpose of opening this file.
*******************
[75]