IP_RG23
IP_RG23
INTRODUCTION TO PROGRAMMING
Introduction to Computer :-
In the modern era, computers are an essential part of our everyday existence. That means computers are
present in almost every field, making our day-to-day tasks easier and faster. Now-a-days, computers can be
seen in banks, shops, schools, hospitals, railways, and many more places, including our home. As they are
such an essential part of our lives.
What is a Computer?
The straightforward meaning of a computer is a machine that can calculate. However, modern computers are
not just a calculating device anymore. They can perform a variety of tasks. In simple terms, a computer is a
programmable electronic machine used to store, retrieve, and process data.
According to the definition, "A computer is a programmable electronic device that takes data, perform
instructed arithmetic and logical operations, and gives the output."
2
Whatever is given to the computer as input is called 'data', while the output received after processing is called
'information'.
The term 'Computer' was first introduced in 1640 and referred to as 'one who calculates'. It was derived from
the Latin word 'computare', which meant 'to calculate'. In 1897, it was known as the 'calculating machine'.
Later in 1945, the term 'computer' was introduced as 'programmable digital electronic computer, which is now
called a 'computer'.
When the computers were introduced, they were large and could fill an entire room. Some computers were
operated using large-sized vacuum tubes. In 1833, Charles Babbage (known as the father of the computer)
invented an early calculator, which was named as the 'difference engine'. Later in 1837, he introduced the
first mechanical, general-purpose computer 'Analytical Engine'. Over time, computers became powerful in
performance and small in size.
Generations of Computer :-
There are five generations of the computer, which can be classified as below:
First Generation (1946 - 1959): During the first generation, computers were based on electronic valves
(Vacuum Tubes). Some popular computers of first-generation are ENIAC, EDVAC, UNIVAC, etc.
Second Generation (1959 - 1965): During the second generation, computers were based on Transistors.
Some popular computers of second-generation are IBM 1400, IBM 1620, IBM 7000 series, etc.
Third Generation (1965 - 1971): During the third generation, computers were based on Integrated Circuits
(ICs). Some popular computers of the third generation are IBM 360, IBM 370, PDP, etc.
Fourth Generation (1971 - 1980): During the fourth generation, computers were based on very large scale
integrated (VLSI) circuits. Some popular computers of fourth-generation are STAR 1000, CRAY-1, CRAY-
X-MP, DEC 10, etc.
Fifth Generation (1980 - Present): The fifth generation is still ongoing. The computers are based on multiple
technologies, such as ultra large scale integration (ULSI), artificial intelligence (AI), and parallel
processing hardware. The fifth generation of computers includes Desktop, Laptop, NoteBook, etc.
The basic organization of a computer contains many components. The essential components of the computer
can be defined as follows:
Input Unit:- Input Units or devices are used to input the data or instructions into the computers. Some most
common input devices are mouse and keyword.
Output Unit:- Output Units or devices are used to provide output to the user in the desired format. The most
popular examples of output devices are the monitor and the printer.
Control Unit:- As its name states, this unit is primarily used to control all the computer functions and
functionalities. All the components or devices attached to a computer interact with each other through the
control unit. In short, the control unit is referred to as 'CU'.
3
Arithmetic & Logic Unit:- The arithmetic & logic unit helps perform all the computer system's arithmetic
and logical operations. In short, the arithmetic logic unit is referred to as 'ALU'.
Memory Unit:- Memory unit is used to store all the input data, instructions, and output data. Memory usually
has two types: Primary Memory and Secondary Memory. The memory found inside the CPU is called the
primary memory, whereas the memory that is not the integral part of the CPU is called secondary memory.
Control Unit, arithmetic & logic unit, and the memory simultaneously form the central processing unit
(called CPU in short).
The block diagram of any computer system is as shown below:
C.P.U
Arithmetic &
Input Unit Logic Unit Output Unit
Control Unit
Memory Unit
program counter :- A program counter (PC) is a CPU register in the computer processor which has the
address of the next instruction to be executed from memory. It is a digital counter needed for faster execution of
tasks as well as for tracking the current execution point.
Characteristics of a Computer :-
Speed:- Computers are high-speed electronic machines. They can carry around 3-4 million
instructions per second. Even advanced computers can handle trillions of instructions per second.
Accuracy:- Computers are also known for their accurate performance. They can complete the given
jobs at almost 100% accuracy. Although errors may occur in computers, they are usually caused by
incorrect input, incorrect instructions, or bugs in chips. All of these are human errors.
Storage Capacity:- Computers can easily store a massive size of data. Modern computers come
inbuilt with high storage features compared to older days. Additional data can be stored on secondary
devices like external hard disks, or flash memory, etc.
Reliability:- Computers are reliable and consistent; they can process the same tasks any number of
times without throwing any error. Computers don't get tired like humans, so they are superior to
perform rule-based, repetitive tasks.
Versatility:- The variety of tasks that a computer can perform are almost infinite. That means
computers can perform different tasks without making errors. For one moment, a computer can be
used to perform data entry tasks or ticket booking, and the very next moment, it can be used for
complex mathematical calculations or continuous astronomical observations, etc.
Types of Computers :-
According to physical size, computers are classified into the following types:
4
Super Computer:- Super computers are the fastest and the most expensive type of computers. They
are large and require more space for installation. These types of computers are mainly designed to
perform massive data-based and complex tasks. Super computers are capable enough to handle
trillions of instructions at the same time.
Mainframe Computer:- Mainframe computers are comparatively smaller in size as compared to
super computers. However, they are not much small. These types of computers are designed to
perform hundreds or thousands of jobs at a time simultaneously. These computers can handle heavy
tasks, including complex calculations and can store vast amounts of data. They are best suited for big
organizations such as banking, telecom, and educational sectors.
Micro Computer:- Microcomputers are cheap in price and support multi-user platform. These are the
general-purpose computers designed to handle all the necessary tasks of individual needs. Since they
are comparatively slower than mainframe computers, thereby are suitable for small organizations.
They are best suited for internet café, schools, universities, offices, etc. A microcomputer is also
referred to as the 'Personal Computer (PC)' in general life. Laptop and desktop are examples of micro
computers.
Mini Computer:- Mini computers are also referred to as Mini frame computers. These are the midsize
multiprocessing computer designed purposely for easy carry. These types of computers are light-
weight and can fit in a small space. They are suitable for billing, accounting, education, and business
purposes. Since these minicomputers are easy to carry, they are the best option for those who need a
computer while traveling. Tablet PC, Notebooks, and cell phones are examples of mini computers.
Workstation: Workstation is a powerful, single-user computer. A workstation is a personal computer
with a faster microprocessor, a massive amount of RAM, higher-quality monitors, high graphic
memory, etc. This is best suited for performing any specific type of task professionally. According to
the type of tasks, a workstation can be referred to as a music workstation, graphic workstation, or
engineering design workstation. Most businesses and professionals use workstations for performing
tasks like animation, music creation, video editing, poster designs, data analysis and more.
Computers cannot work on their own. They need instructions from humans to complete tasks.
Moreover, computers follow the given instructions blindly without thinking about the outcomes.
Computers need a power supply to work. Without a power supply, they are just useless.
Working on a computer continuously for a long period can cause several health issues.
Wastage of computers and their parts leave a negative impact on the environment.
Computers are taking human jobs in many sectors. They are replacing human work and thus
increasing unemployment.
Applications of Computers :-
5
Low-level language is machine-dependent (0s and 1s) programming language. The processor runs low-
level programs directly without the need of a compiler or interpreter, so the programs written in low-level
language can be run very fast. Low-level language is further divided into two parts :
i. Machine Language -: Machine language is a type of low-level programming language. It is also called as
machine code or object code. Machine language is easier to read because it is normally displayed in binary
or hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to execute the programs faster than the
high-level programming language.
ii. Assembly Language -: Assembly language is also a type of low-level programming language that is
designed for specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine language.
6
The advantage of assembly language is that it requires less memory and less execution time to execute a
program.
High-level programming language (HLL) is designed for developing user-friendly software programs and
websites. This programming language requires a compiler or interpreter to translate the program into machine
language (execute the program).
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective C, Cobol,
Perl, Pascal, LISP, FORTRAN, and Swift programming language.
Procedural Oriented programming language is used by a software programmer to create a program that can be
accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual Studio.
The advantage of POP language is that it helps programmers to easily track the program flow and code can be
reused in different parts of the program.
The advantage of POP language is that it helps programmers to easily track the program flow and
code can be reused in different parts of the program.
The main advantage of object-oriented programming is that OOP is faster and easier to execute, maintain,
modify, as well as debug.
iii. Natural language -: Natural language is a part of human languages such as English, Russian, German,
and Japanese. It is used by machines to understand, manipulate, and interpret human's language. It is used by
developers to perform tasks such as translation, automatic summarization, Named Entity Recognition
(NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any subject and directly
respond within seconds.
7
Middle-level programming language lies between the low-level programming language and high-level
programming language. It is also known as the intermediate programming language and pseudo-language.
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human language.
An algorithm is a finite set of instructions which are being carried in a specific order to perform the specific
task. It is not the complete program or code; it is just a solution (logic) of a problem, which can be represented
either as an informal description using a Flowchart or Pseudo code.
Characteristics of an Algorithm:-
Input: An algorithm has some input values. We can pass 0 or some input value to an algorithm.
Output: We will get 1 or more output at the end of an algorithm.
Unambiguity: An algorithm should be unambiguous which means that the instructions in an
algorithm should be clear and simple.
Definiteness: Algorithms must specify every step and the order the steps must be taken in the process.
Definiteness means specifying the sequence of operations for turning input into output.
Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm should
contain a limited number of instructions, i.e., the instructions should be countable.
Effectiveness: An algorithm should be effective as each instruction in an algorithm affects the overall
process.
Language independent: An algorithm must be language-independent so that the instructions in an
algorithm can be implemented in any of the languages with the same output.
Problem Definition
Problem Analysis
Algorithm Design
Flowchart
Implementation
Testing
Documentation
8
Problem Definition
We have to clearly define the problem that the algorithm needs to solve. We have to clearly understand the
problem statement so that a proper algorithm can be designed. This stage includes understanding the input data,
desired output, and constraints or requirements.
Problem Analysis
Analyze the problem to gain insights into its characteristics, complexity, and potential solutions. This may
involve studying the data, identifying patterns, understanding the relationships between different variables, and
considering different approaches.
Algorithm Design
Based on the problem analysis, design an algorithm that outlines the step-by-step process for solving the
problem. This may involve selecting appropriate data structures, choosing suitable problem-solving techniques,
and designing tools for defining the logic or flow of the algorithm.
Flowchart Development
A flowchart is a visual representation of the algorithm for non-technical people so that they can easily
understand the algorithm. Create a high-level representation of the algorithm using flowcharts. Flowcharts use
graphical symbols to represent the steps and flow of the algorithm.
Implementation
Translate the algorithm design into a specific computer programming language. Write the code to implement the
algorithm, taking into consideration the syntax, data types, and control structures of the programming language.
Testing
Test the algorithm by giving the test data and see if the desired output is generated. Testing with various inputs
to verify the correctness and effectiveness of the algorithm. Identify and fix any bugs or errors that may arise
during testing. Testing may involve different types of inputs to ensure the algorithm performs correctly in
different scenarios.
Documentation
Document the algorithm, including its design, implementation details, and any assumptions or limitations. This
documentation helps others understand and use the algorithm effectively.
Complex algorithm design may involve multiple iterations to redefine the development process. These stages
are:
Evaluation
Iteration
Optimization
Evaluation
Evaluate the algorithm’s performance against specific criteria, such as accuracy, speed, memory usage, and
scalability. Compare it with other existing algorithms or benchmarks to determine its effectiveness in solving
the problem.
9
Iteration
Based on the evaluation results, refine and iterate the algorithm to further improve its performance or address
any shortcomings. This may involve revisiting the problem analysis, design, or implementation stages to fine-
tune the algorithm.
Optimization
Optimize the algorithm to improve its performance, efficiency, or scalability. This may involve analyzing the
time and space complexity of the algorithm, identifying bottlenecks, and making necessary adjustments or
optimizations to enhance its performance.
Advantages of Algorithms:-
Efficiency: Algorithms streamline processes, leading to faster and more optimized solutions.
Reproducibility: They yield consistent results when provided with the same inputs.
Problem-solving: Algorithms offer systematic approaches to handle complex problems effectively.
Scalability: Many algorithms can handle larger datasets and scale with increasing input sizes.
Automation: They enable automation of tasks, reducing the need for manual intervention.
Disadvantages of Algorithms:-
The problem is complex and needs to be broken down into smaller, manageable parts.
There is a need to understand the big picture before diving into details.
A clear understanding of the end goal is required before starting the project.
The solution can be divided into smaller subproblems that can be solved independently.
The problem has multiple potential solutions, and a top-down approach can help prioritize and evaluate
them.
10
Advantages:
Easy to understand and implement.
Provides clear objectives and expectations.
Supports effective allocation of resources.
Disadvantages:
Inflexible to change
Limited to pre-determined solutions.
Can lead to missed opportunities or inefficiencies.
Can result in lower motivation and participation from lower-level employees.
Bottom-Up Approach
A bottom-up approach, on the other hand, is an investment strategy that depends on the selection of
individual stocks.
It observes the performance and management of companies and not general economic trends.
The bottom-up approach analyzes individual risk in the process by using mathematical models and is
thus data-intensive.
This method does not rely on historical data.
It is a forward-looking approach unlike the top-down model, which is backward-looking.
Advantages:
Flexibility: Bottom-up approach allows for changes to be made at any stage of the process.
Empowerment: It gives individuals and smaller groups the power to make decisions.
Robustness: This approach can result in more robust solutions, as each component can be thoroughly
tested and debugged.
Disadvantages:
Slow Progress: The bottom-up approach can be slow, as each component must be completed before
moving on to the next.
Lack of coherence: The final solution may lack coherence, as it is assembled from individual parts.
Difficulty in managing complex projects: This approach can be difficult to manage for complex
projects with many components.
Step4 : c=A+B
Step5 : Print c
Step6 : Stop
In the above example “step-1” indicates the starting point of an algorithm “step-2” and “step-3” are used to
assign values to the variables A and B. “Step-4” calculates the addition operation. “Step-5” prints the result of
“C” and finally “step-6” stops the process and ends the execution.
We may write one more algorithm for the above task like the following. Here we read values for the
variables. This technique helps us to read different value to different variables.
Step1 : Start
Step2 : Read A
Step 3 : Read B
Step 4: C←A+B
Step 5: Print C
Step 6: Stop
Flow charts :-
A flow chart is a pictorial (or) graphical representation of an algorithm. It represents the logic flow in which
the different types of instructions are drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting the arrows. The boxes represent operations, while the arrows represent the sequence
of the operations. The following table shows the flow charts symbols and their use (processing).
Input / Output
Processing
Decision
Connector
Flow line:- Flow line is represented by an arrow which is used to connect symbols.
Terminals: - The terminal symbol is used to indicate the beginning (start), the termination (end) or
halt (pause) in the program logic.
Input output:-The symbol represents an input taken from the user or output is displayed to the user
Processing:- The process symbol is used to process the data like performing calculations, moving
data from memory to other devices.
Decision:-The decision symbol is used to construct conditions and then execute a path of statements
based on the given condition. If the condition is TRUE, one path of process will be executed otherwise
(FALSE) another will execute.
Connector:- This symbol is used to join different flow lines.
Pseudocode :-
12
Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology
that allows the programmer to represent the implementation of an algorithm. It is simply an implementation
of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like
any of the programming language and thus can’t be compiled or interpreted by the computer.
1. Arrange the sequence of tasks and write the pseudo code accordingly.
2. Start with the statement of a pseudo code which establishes the main goal or the aim.
Example:
3. The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it
helps to comprehend the decision control and execution mechanism. They also improve the readability
to a great extent.
Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
4. Use appropriate naming conventions. The human tendency follows the approach to follow what we
see. If a programmer goes through a pseudo code, his/her approach will be the same as per it, so the
naming must be simple and distinct.
5. Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower
case for variables.
6. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
7. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
8. Check whether all the sections of a pseudo code is complete, finite and clear to understand.
9. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.
13
Performance analysis of an algorithm depends upon two factors i.e. amount of memory used and amount of
computing time consumed on any CPU. Formally they are notified as complexities in terms of:
Space Complexity.
Time Complexity.
Space Complexity of an algorithm is the amount of memory it needs to run to completion i.e. from start of
execution to its termination. Space needed by any algorithm is the sum of following components:
1. Fixed Component:- This is independent of the characteristics of the inputs and outputs. This part
includes: Instruction Space, Space of simple variables, fixed size component variables, and constants
variables.
2. Variable Component:- This consist of the space needed by component variables whose size is
dependent on the particular problems instances(Inputs/Outputs) being solved, the space needed by
referenced variables and the recursion stack space is one of the most prominent components. Also this
included the data structure components like Linked list, heap, trees, graphs etc.
Therefore the total space requirement of any algorithm 'A' can be provided as:
Time Complexity of an algorithm is the amount of computer time it needs to run to completion. The time taken
by a program is the sum of the compile time and the run/execution time . The compile time is independent of the
instance (problem specific) characteristics. Following factors affect the time complexity:
Therefore the again the time complexity consist of two components fixed(factor 1 only) and
variable/instance(factor 2,3 & 4), so for any algorithm 'A' it is provided as:
‘C’-LANGUAGE
Introduction & History:-
C language is one of the structured programming languages. It was developed by Dennis
Ritchie at Bell laboratories, U.S.A in 1972. It is derived from the language BCPL (Basic Combined
Programming Language).
‘C’ language is called middle level language because ‘C’ supports both features of low-level
language and high-level language. Through low-level features, C language is used for memory
management, bit manipulations and direct memory access using pointers. The high-level language
features are conditional statements, functions and files that are used for general purpose.
Features of C language:-
1. General Programming Language: ‘C’ was originally developed for system programming. But it
is also used for writing commercial as well as scientific applications.
2. Maintainability: It is reliable, simple and easy to use.
3. System Programming: C language is used to develop compilers, operating systems and other
utility programs for system software.
4. Portability: C language is highly portable language i.e. a C program written on one computer can
be compiled and executed on a different computer with less or no modifications in the program.
5. Structured Programming Language: It supports many control structures such as “if, switch,
while, do…while, for” etc. to develop well defined and easy to maintain programs.
6. Modularity: Through modularization, we can break down program code into small functional
units called functions and then integrate them to make a complete application.
7. Limited Keywords: It has only 32 keywords and hence several standard functions are available
with ‘C’ are used for developing error free programs.
Documentation Section
Link Section
Definition Section
Global Variables Declaration Section
main( )
{
Local variables declaration part Executable
statements part
}
Sub-program Section
Function 1
Function 2
: (User-defined functions)
:
:
Documentation Section:-
It is an optional section that consists of a set of comment lines that are enclosed within /*
and */ and giving the details of the program. The comment lines are not executed in a program.
Link Section:-
It is also an optional section that provides instructions to the compiler to link functions from
the other files.
Example: #include <stdio.h>
#include “sample.c”
Definition Section:-
It is also an optional section that defines the symbolic constants (macros) that are used in the
program.
Examples: #define CITY “DELHI”
#define cube(n) n*n*n
The executable part may contain one or more statements to display, read and controlling
programming elements. But this part must contain at least one executable statement.
The declaration part and execution part must be enclosed within curly braces.
Sub-program Section:-
This section contains the definitions of all the user-defined functions. The user-defined
functions can be defined before or after the main( ) function section. This section is also optional
section.
Each and every user-defined function can also be divided into two parts namely declaration
part and executable part.
Example:
/* This program finds area of circle */
#include <stdio.h>
#define PI 3.141
extern int r = 0;
main( )
{
float areaofcircle( );
float area;
clrscr( );
printf(“Enter radius of circle “);
scanf(“%d”,&r);
area = areaofcircle( );
printf(“%f”, area);
}
float areaofcircle( )
{
float a;
a = PI * r * r;
return (a);
}
To get a result form C program, we should compile and execute the C program.
Compiling a c program:- Compiler is a translator, which is used to convert a source program into machine
code which is run on computer. Here C compiler helps us to make sure that the program is free from syntax
errors. To compile the program - select Compile menu command and execute Compile command like the
following.
17
After compiling, we will see as dialog box as shown below. If the compilation is success – we will see a
Success message. Otherwise, we will see the error message with number of errors. These are shown in the
following diagrams.
The screen shot of a Successful compilation:
Executing a C program:- To execute the C program – we select Run menu command and execute
Run command like the following:
18
Now we will see the output on the screen like the screen like the following:
C- Language elements
The C -Character Set :-
Identifiers
Data Types
The data type specifies what type of data is stored and manipulated in the computer
system. It also specifies the memory usage by a memory variable.
In ‘C’ language, the data types are classified as shown below:
Data Types
Primary
Datatypes
Integer Family:-
The keyword ‘int’ is used to declare integer type variables. We can use sign qualifiers (signed
or unsigned) and size qualifiers (short or long) in the declaration of integer type variables. The
qualifiers ‘short’ and ‘signed’ are the default qualifiers and hence they are optional in the declaration.
The following table shows integer data types and their range of values:
Memory
Data type Range Format Character
Reserved
int (or) short int (or) -32768 to +32767
2 bytes %d or %i
short signed int (-215 to +215-1)
unsigned int (or) 0 to 65535
2 bytes %u or %ud
short unsigned int (0 to +216-1)
long int (or ) -2147483648 to +2147483647
4 bytes %𝑙d
long signed int (-231 to +231-1)
0 to 4294967295
long unsigned int 4 bytes %𝑙u
(0 to +232-1)
Float Family:-
The keywords ‘float’ and ‘double’ are used to declare float type variables. We can also use
qualifiers to declare float type variables. The following table shows float data types and their range of
values:
Memory
Data type Range Format Character
Reserved
3.4e-4932 to
long double 10 bytes %Lf or %Le
1.1e+4932
Character Family:-
The keyword ‘char’ is used to declare character data type variables. It contains any alphabet,
digit (or) special character. The following table shows character data types and their range of values:
21
Memory
Data type Range Format Character
Reserved
char (or) -128 to +127
1 byte %c
signed char (-27 to +27-1)
0 to 255
unsigned char 1 byte %c
(0 to +28-1)
Variables
A variable is a name which is given to a memory location where the data is stored
temporarily. It is an identifier whose value is changed during the execution of a program.
The user is allowed to access the data from the memory location through the variable name.
A variable can hold only one value in its location.
1. A variable name must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of a variable should not exceed 8 characters. But some compilers allow upto 31
characters.
4. Commas are not allowed
5. Blank spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as variable names.
8. A variable name must not be repeated (declaration) in the declaration
Examples:
Valid Variables: a salary sum stud_name c123 etc.
Invalid Variables: a+b ( Special Character present)
2abc ( First letter is not an alphabet)
float ( it is a keyword)
Declaration of Variables:-
A variable must be declared before it is used in the program. The declaration of variables tells
the compiler to reserve memory space with specified variable names depending on the specified data
type.
The general format of variable declaration is as follows:
Syntax:-
datatype
In the above syntax, var1, var2, …. refers
the ‘datatype’ ; to any valid data type. Var1, var2, …. are the
variable names associated to the data type.
22
Ex:
int a, b, sum ;
float avg, f ;
char ch ;
double xyz ;
Initialization of Variables:-
Assigning a value to a variable while declaration is called initialization of variables. If a
variable is not initialized it contains garbage value.
Syntax:-
Constants
A constant is a fixed value. It doesn’t change its value during the execution of the program.
The following are the different types of constants used in C language.
• Integer Constants
• Floating Point Constants Number Type
• Symbolic Constants
23
Integer constants:-
Any number without fractional part is called an integer constant. The integer numbers can
be represented using decimal numbers (0…9) or Octal numbers (0…7) or Hexa-decimal numbers
(0…9 A B C D E F). Octal number must be preceded with ‘0’ and hexa-decimal number must be
preceded with ‘0x’ (or) 0X. An integer constant must not contain commas and spaces.
Character Constants:-
A character constant contains only one character enclosed within single quotes. A character
constant may contain any alphabet, digit or special symbol. It can be used for arithmetic operations.
However, its ASCII value is used in arithmetic operation.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.
String Constants:-
A string constant is a sequence of one or more characters enclosed within double quotes. It
can contain alphabets, digits or special symbols.
Ex: “A” “ABCDE” “%d” “Result = %d” etc.
Symbolic Constants:-
A symbolic constant is a name substituted for sequence of characters. It can be used to
represent a numeric constant or a character constant or a string constant.
Syntax: #define scname sctext
Where ‘scname’ is the name of symbolic constant and ‘sctext’ is the text of a symbolic
constant.
Ex:
#define PI 3.1419
#define name “abcde”
#define max_value 400.75
24
Input-Output Statements
In 'C' language , the input and output statements (or) functions are used to receive data from
the input device and to send data to the output device. These functions are standard built-in
functions which are available in “stdio.h” header file.
The input-output (I/O) functions are classified into 2 categories as shown below:
I / O Statements
Formatted Unformatted
The functions that accept numbers, characters and strings as arguments to read and display
using format characters (like %d, %f etc.) are called formatted input-output functions. Using these
functions the values can be formatted (arranged) according to the user requirements. The ‘scanf( )’
and ‘printf( )’ functions are used as formatted I/O functions.
Scanf( ) Function:-
It is a formatted input function which is used to accept data from the user (keyboard) at run
time. The given data is transferred to the memory and is stored in the specified variables.
Syntax:
Inscanf(format-string
the above syntax, the, &var1, &var2, ……
‘format-string’ ) ; to a string constant that contains format
refers
characters according to the type and number of variables. Other characters are not allowed.
var1, var2, …… are the variables to hold the given values. All the variables except string
variables must be preceded by the address (&) operator.
The values that are supplied through keyboard must be separated by either space(s), tab(s),
or newline(s).
Example:- Let a and b are integer type, c is float type, x and y are character type variables. Then
this can be used as follows:
1. scanf(“%d”, &a);
2. scanf(“%d %f”,&a, &c);
25
Syntax-1: printf(string) ;
In the above syntax, the ‘values-list’ can be variables, constants, or expressions separated by
commas. Syntax-2: printf(string, values-list) ;
The ‘string’ is a string constant that contains the following:
i. Any character in the ‘C’ character set.
ii. Format characters that begin with ‘%’ symbol
iii. Escape sequence characters that begin with ‘\’ symbol
Examples:-
1. printf(“Hello. What is your name?”);
2. printf(“%d”, 70*45);
3. printf(“Sum of 2 numbers = %d”, sum);
4. printf(“Total = %d \n Average = %f”, total, avg);
getch() putchar()
getche() putc()
getchar() puts()
getc()
gets()
getch():-
This function is used to accept a character from the console and stores it in a variable, if
specified. It will not echo the character on the screen. It continues program execution whenever we
press any key.
Syntax:- variable = getch();
26
getche():-
This function is used to accept a character from the console and stores it in a variable, if
specified. It will echo the character on the screen. It continues program execution whenever we
press any key.
syntax:- variable = getche();
getchar():-
This function is used to accept a character from the keyboard and stores it in a variable, if specified. It
continues program execution whenever we press ENTER key.
Syntax:- variable = getchar();
getc():-
This function is used to read a character from the file and stores it in a variable, if specified.
Syntax:- variable = getc(filepointer);
gets():-
This function is used to accept a string from the keyboard and stores it in a array variable. It
reads a sequence of characters until ENTER key is pressed. It stores a null character ‘\0’ at the end
of the string.
Syntax:- gets(variable);
putchar():-
This function is used to print a character on the standard output device i.e. monitor.
Syntax: putchar(arg);
putc():-
This function is used to store a character in the file.
Syntax: putc(variable, filepointer);
Here, variable represents any character variable and the file pointer is the file variable which
represents the file in which character is stored.
puts():-
This function is used to print a string on the monitor.
Syntax:- puts(string);
1. Arithmetic operators:-
Arithmetic operators are used to perform arithmetic calculations. The following are the
various arithmetic operators.
Operator Meaning
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulo division (Remainder)
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical AND (&&) Operator-: This operator gives true if all the conditions are true otherwise it
gives false.
Ex:- A && B
Logical OR ( ¦¦ ) Operator-: This operator gives true if any or all the conditions are true otherwise
it gives false.
Ex:- X ¦¦ Y
Logical NOT (!) Operator-: This operator negates the result of a condition. It means if the
condition is true then it gives false. If the condition is false then it returns true.
Ex:- !N
4. Assignment Operators:-
The assignment operators are used to assign (store) a value to a variable. An assignment
operator always consists of a variable on left hand side and a valid expression / constant / variable
on right hand side.
Syntax:-
Expression/
Variable =
Constant/
Variable
Eg: 1) x = 35; y = a + b * c; z = y; a = b = 50;
2) x+=80; y-+30; z*=20; a/=5;
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
>> Right shift
<< Left shift
Ex: A<<2, B>>3, x ^ y
8.Special Operators:-
Type Conversion:- ‘C’ language automatically converts lower type to higher type or
same type. For example, Converting int type to long type because int is lower type than
long or float type to long type because both allocates the same size of memory. The result
of the above is higher type.
Ex: int
a=90;
long b;
b=a;
Type Casting:- Sometimes, we may convert higher type to lower type. In such situation,
we must cast the value into one type to a specific type. So that, the process of converting
one type to another is called type-casting. The general form of type casting is as follows.
Syntax:- dataType variable1= (type) variable2;
In the above syntax, the type which is placed in between parenthesis is the
primary data-type which is converted variable2 to variable1.
Ex:- int a;
long
b=80;
a = (int)
b;
In the above example, the long variable ‘b’ is converted to int variable ‘a’.
Example:-
main()
{
int n;
long
a,b;
a=
10;
b = 20;
n = (int) a + b;
printf(“ %d \n“,n);
Expressions in C-Language :-
An expression is a collection of operands joined together by certain operators that represent a value. There
are two types of expressions. They are :
1. Arithmetic or Numeric Expression (it uses arithmetic operators).
2. Relational or Boolean Expression (it uses relational or logical operators).
In the C programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to their
precedence and associativity.
#include<stdio.h> main()
{
float a,b,c,x,y,z; a=9;
b=12; c=3;
x= a-b/3+c*2-1;
y= a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("x = %f\n",x);
printf("y = %f\n",y);
printf("z = %f\n",z);
}
Output:-
x = 10.000000
y = 7.000000
z = 4.000000
C supports some character constants having a backslash in front of it. The lists of backslash characters have
a specific meaning which is known to the compiler. They are also termed as "Escape Sequence Characters".
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Unit-II : Control Structures (or) Control Statements
Control Structures are the statements used to specify the order in which the instruction is executed in
the program. These are used in the following situations:
To execute statements based on a condition
To execute a set of statements repeatedly until a condition is satisfied
To branch the execution sequence from one statement to another statement.
In ‘C’ language, the control statements are classified into 3 types. They are as follows:
Control Statements
1).if statement
The ‘if’ statement is a conditional execution statement that executes the specified set of
instructions based on the condition. The Syntax and flowchart are as follows:
if (condition) Flowchart
{
statement-block ;
T
} condition T
F Statement-block
F
In the above syntax, the condition is a relational/logical/Boolean expression that must be enclosed within
parenthesis. If the condition is true then the statements in the statement-block are executed, otherwise they
are not executed. To specify more than one statement in a statement-block, they must be enclosed within a
pair of flower braces ({}).
Example:-
1. if (avg >= 75)
printf(“grade is distinction”);
2. if (a < 0)
a++;
2) if…else statement
It is also conditional execution statement that executes the statements based on the
condition. If the condition is true then it executes one group of instructions otherwise it executes
another group of statements. The Syntax and flowchart are as follows:
if (condition)
{ Flowchart
statement-block1 ;
}
T
else FF ccsscondition T
{
statement-block2 ; Statement-block2 Statement-block1
statement-block1 ;
else
statement-block2 ;
}
else
{
if (condition3)
statement-block3 ;
else
statement-block4 ;
}
Cond-1
case V1 : statement-block1;
[break;]
case V2 : statement-block2;
[break;]
: :
: :
case Vn : statement-block-n;
[break;]
default : statement-block-d;
}
In the above syntax, ‘op’ is either a constant, variable (or) expression that results an integer value. The switch
statement uses the value of ‘op’ to execute the statement-blocks.
V1, V2, …, Vn are the values that represent the value of ‘op’. These are the constants either integer or
character type. These values must be unique.
When statement-block contains many statements then they must be enclosed within a pair of braces ({}).
Working: The switch statement searches for a match of switch variable (op) and case constants (V1, V2, …,
Vn). If a value matches to the ‘op’, the switch statement executes all the statements in that case-block. If there
is ‘break’ statement in that block then it terminates the execution of switch statement. If ‘break’ is not present
then all the statements of remaining blocks are executed.
If any value doesn’t match to the ‘op’ then the ‘default’ block is executed, if it is specified in the switch
statement.
Example: main( )
{
int a;
clrscr( );
printf(“Enter a single digit
number”); scanf(“%d”,&a);
switch (a)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“Monday”);
break;
case 3: printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:printf(“Saturday”);
break;
default:printf(“Wrong digit”);
}
Iterative / Looping / Repetitive Control Statements
The iterative statements are used to execute a single statement or a group of statements
repeatedly or continuously as long as the given condition has been satisfied. The iterative
statements are also called Repetitive (or) Looping control statements.
In 'C' language, there are 3 types of repetitive control structures. They are
1. while
2. do…while
3. for
Syntax:-
while (condition)
statement-block;
}
In the above syntax,
1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.
2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed with in braces ({}).
Working:- The ‘while’ statement executes all the statements in the statement-block as long as the
given condition true. When the condition false then the loop is terminated and the control is
transferred to the statement after the statement-block.
do…while Statement
This statement is used to execute one or more statements repeatedly as long as the specified
condition is satisfied. It is an exit control loop structure. The do…while structure executes at least
one time even initially the condition is false.
Syntax:-
do
{
statement-block;
} while (condition);
In the above syntax,
1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.
2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in braces ({}).
Working:-The ‘do…while’ statement executes all the statements in the statement-block first and
then tests the condition. When the condition true (non-zero) then the loop is repeated otherwise the
loop is terminated.
Example: A program to print first ‘n’ natural
numbers. #include<stdio.h>
main( )
{
int a=1, n;
clrscr( );
printf(“Enter n
value”);
scanf(“%d”,&n);
do
{
printf(“%d \t”, a);
a++;
} while (a<=n);
}
for Statement
This statement is used to execute a set of statements repeatedly as long as the specified
condition is satisfied.
Syntax:-
for(initialization ; condition ; increment/decrement)
{
statement-block;
}
Here,
Flowchart:-
initialization
F
condition
co
Increment /
T decrement
Statement-block
Example:-
A program to find and print the sum of first ‘n’ natural numbers.
#include<stdio.h>
void main( )
{
int a, n, sum=0;
clrscr( );
printf(“Enter n
value”);
scanf(“%d”,&n);
for (a=1; a<=n; a++)
{
printf(“%d \t”, a);
sum+=a;
}
printf(“Result = %d”,sum);
}
goto Statement
The ‘goto’ statement is an unconditional branching statement used to transfer the program
control from one place to another place within a program.
Syntax:-
goto label ;
Here, the label is an identifier used to name the target location to which the control is
transferred. The target statement must be named with label name followed by a colon as follows:
label : statement ;
The label names must be unique within a program.
Working:- While program execution, when ‘goto’ statement is reached then it branches the
execution control to the specified label in the program and it continues execution from that point.
break Statement
Normally the break statement is used in switch statement. But it is also used to terminate the
execution of a loop unconditionally.
Syntax:-
break ;
Example:
void main( )
{
for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
if (num<0)
break;
sum=sum+num;
}
printf(“Result=%d”,sum);
}
continue Statement
The continue statement must be used in loops only. When the continue statement is reached
within a loop, it continues the execution from the first statement of the loop.
Syntax:-
continue;
Example:-
void main( )
{
int i, n, sum, num;
printf(“How many values?”);
scanf(“%d”,&n);
i=0;
while (i<=n)
{
i++;
scanf(“%d”,&num);
if (num<0)
continue;
}
}
UNIT–III : Arrays & Strings
Arrays
Definition: An array is a collection of elements of same type that share a common name.
The elements of an array are stored in contiguous memory locations.
In ‘C language, arrays are classified into two types. They are
1. One Dimensional Arrays
2. Multi Dimensional Arrays
0 1 2 3 4
Syntax:-
datatype arrayname[size] = {V0, V1, …, Vsize-1} ;
Here, V0, V1, …, Vsize-1 are the initial values of the specified array. If we omit the values
then an array contains garbage values. The number of values must be less than or equal to the size
of the array. When there are few values then the remaining elements are assigned with zeros.
Ex:
a[0] a[1] a[2] a[3] a[4]
int a[5] = {78, 34, 98, 90, 124};
78 34 98 90 124
Reading the arrays elements: To read the array elements thru keyboard, we write and execute the
following example
for(i=0;i<n;i++)
scanf(“%d”,&num[i]);
Accessing elements of the Array :-
Once we store the elements of an array, we may access the elements of the array. To access
the array elements, we use the index numbers of the array. The index numbers are used to identify a
particular location of the array. The following example is used to accessing the elements of an array
and prints them on the screen.
main()
{
int a[]={ 5, 6, 9, 7, 3};
int i;
clrscr();
Two-Dimensional Arrays
When an array uses only two subscripts then it is called “two-dimensional array”. A two-
dimensional array is useful for matrix operations.
Declaration of Two-Dimensional Array:-
The general format of declaring a two dimensional array is as follows:
Syntax:-
datatype arrayname[rowsize][columnsize] ;
In the above syntax,
The datatype is any valid data type of ‘C’ language. An array can hold all the values based
on the specified data type.
The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements
will share this variable name.
The ‘rowsize’ indicates maximum number of rows and ‘columnsize’ indicates number of
columns in a row.
Example: int a[4][3];
Here, it reserves 12 (4 rows x 3 columns) integer type memory locations for the array ‘a’.
The conceptual view for the above declaration is as shown below:
a[4][3]
0 1 2
0
1
2
3
Initialization of Two Dimensional Array:-
While declaring an array, we can initialize it with some values. The general format to
initialize two dimensional array is as follows:
Syntax:-
datatype arrayname[rowsize][columnsize] = {{row1 values}, {row2 values}, …, } ;
Here, If we omit the values then an array contains garbage values. The number of values
must be less than or equal to the size of the array. When there are few values then the remaining
elements are assigned with zeros.
Example-1:
int a[2][3] = { {4, 6, 8}, {1, 3, 5}};
This example initializes the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 6 8
1 1 3 5
Example-1:
int a[2][3] = { {4, 8}, {5}};
This example initialises the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 8 0
1 5 0 0
Calculating the length of the array:- To find the length of the array, we use the sizeof() function.
In ‘C’ language, once we declare the array variable, the variable allocates maximum size of the
array which we given the size of the array. The following example is used to find out the size of the
array.
int a[50];
int n = sizeof(a);
Strings
Definition:- A string is a sequence of one or more characters. Any group of characters enclosed
within double quotes is a string constant. In ‘C’ language, strings are manipulated using arrays and
pointers.
Ex: “Hello” “Computer Science” etc.
A string is a one dimensional array of characters terminated by a null (\0) character. The null
character is stored at the end of array of characters to mark the end of the string. If an array is used
to store the strings then that array is often called “string variable”. A string that is not terminated by
‘\0’ is not really a string, but it is only a collection of characters.
Operations on strings:-
The common operations performed on strings are:
i. Reading and writing strings
ii. Combining strings together (concatenation)
iii. Copying one string to another
iv. Comparing strings for equality
v. Finding the number of characters in a string (length)
2. char city[6] =
“DELHI”; (OR)
char city[] = “DELHI”;
In the above examples, the ‘ C’ compiler automatically inserts ‘\0’ character at the end. So, the
conceptual view for the above examples is as shown below:
D E L H I \0
2. A string can be initialized using pointers as follows:
Ex: char *city = “DELHI”;
Here, it stores the string “DELHI” into memory and assigns the starting location address to
the pointer variable ‘city’. The conceptual view for the above example is as shown below:
City[0] D E L H I \0
City[1] B A N G A L O R E \0
City[2] C H E N N A I \0
Example:
#include<stdio.h>
#include<string.h>
main( )
{
int n;
char name[10] = “ABCDE”;
n = strlen(name);
printf(“length = %d”, n);
}
Output : 5
2. strrev( ) Function:-
This function is used to reverse all the characters in the given string except null character.
Where ‘string’ is constant or array variable.
Syntax:- strrev(string);
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] =
“ABCDE”; strrev(name);
puts(name);
}
Output : EDCBA
3. strlwr( ) Function:-
This function converts all the uppercase letters in the given string into lowercase.
Where ‘string’ is constant or array variable.
Syntax:- strlwr(string);
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strlwr(name);
puts(name);
}
Output : abcde
4. strupr( ) Function:-
This function converts all the lowercase letters in the given string into uppercase.
Where ‘string’ is constant or array variable.
Syntax:- strupr(string);
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strlwr(name);
puts(name);
}
Output : ABCDE
5. strcpy( ) Function:-
This function copies the contents of one string (source) to another string (destination). The
contents of the source string are unchanged. Where ‘string1’ is destination string and ‘string2’ is
source string. The contents of string2 are copied to string1.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[10] = “ABCDE”;
char b[10];
strcpy(b, a);
puts(b);
}
The above example copies the contents of ‘a’ to ‘b’. Hence the output is ABCDE.
6. strcat( ) Function:-
This function appends the contents of one string (source) to another string (destination).
This is called concatenation of two strings. The contents of the source string are unchanged.
Where ‘string1’ is destination string and ‘string2’ is source string. The contents of string2 are
appended to string1.
syntax:- strcat(string1, string2);
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30] = “ABC”;
char b[30] = “DEF”;
strcat(b, a);
puts(b);
}
The above example append the contents of ‘a’ to ‘b’. Hence the output is DEFABC
7. strcmp( ) Function:-
This function is used to compare two strings.
Syntax:- strcmp(string1, string2)
Here,
1. If string1 is equal to string2 then it returns value 0
2. If string1 is less than string2 then it returns a negative (less than 0) value.
3. If string1 is greater than string2 then it returns positive (greater than 0) value.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30], b[30];
int c;
printf(“Enter First String”);
gets(a);
printf(“Enter Second String”);
gets(b);
c = strcmp(a, b);
if (c = = 0)
printf(“String1 and string2 are equal”);
else
if (c < 0)
printf(“String1 is less than string2”);
else
if (c > 0)
printf(“String1 is greater than string2”);
}
UNIT-IV : Pointers & User Defined Functions
Pointers
Definition:- A pointer is a variable that holds the memory address of a data item such as a variable,
an array element, etc.
The organization of memory is designed in such a way that it contains continuous locations
called memory cells to store data. The size of memory location that is assigned to each data value
depending on the type of data declared. A unique numeric address is allotted to each of these
memory locations for easy accessing of data. It is possible for the programmer to access this
memory address using a special variable called pointer.
For instance, let ‘P’ is a pointer variable that contains the address of another variable ‘Q’. then
‘P’ is said to be pointing to ‘Q’. If the address of ‘Q’ is 1625 then the value of ‘P’ would be 1625.
Using this address we can manipulate the value of ‘Q’. It can be as shown below:
Value of P 1625 50
Value of Q
Address of P 2956 1625 Address of Q
Pointer Operators:-
‘C’ language provides two special operators to manipulate the data items directly from
memory location using pointer variables.
1. Address Operator (&):-
The address operator is used to get and assign the address of a variable to a pointer variable.
Ex: pv = &v;
Where ‘pv’ is a pointer variable which holds the address of the variable ‘v’. So ‘pv’ is a
pointer to ‘v’ that points to the location of ‘v’ as shown below:
Points
Address of v Value of v
to
pv v
The above diagram shows the relationship between ‘pv’ and ‘v’. Hence pv=&v and v=*pv.
Example: :
main( )
{
int a=50;
int *p;
p = &a;
printf(“Value of a = %d “,a);
printf(“Address of a = %u “,&a);
printf(“Value of p = %u”,p);
printf(“Address of p = %u”,&p);
printf(“Address of a = Value of p = %u”,p);
printf(“Value of a = *p = %d”,*p);
}
Output:
Value of a =
Address of a =
Value of p =
Address of p =
Address of a = Value of p =
Value of a = *p =
Pointer Assignment:-
Like simple variables, a pointer variable can also be assigned to another pointer variable.
Example:
main( ) 1468p a
50
{ 2565
int a=50; int *p, *m; p=&a;
1468
m = p;
printf(“Value of p = %u”,p); 1468 m
printf(“Value of m = %u”,m); 3789
}
Pointer Expressions and Pointer Arithmetic
Like other variables, pointer variables can be used in expressions and also construct the pointer arithmetic.
For example: if P1 and P2 are declared and initialized as pointer variables. Then construct the arithmetic
expression like the following.
X = *p1 * *p2;
Sum = *p1 + *p2;
In the above example, the values of pointer variables P1 and P2 are evaluated and
assigned the result to the variables.
Example:
main()
{
int *p1, *p2,x,sum,a,b;
a=20;
b=30;
p1=&a;
p2=&b;
x= *p1 * *p2;
}
Pointers and arrays :-
There is a close relationship between pointers and arrays. The elements of an array can be
efficiently accessed by using pointers. ‘C’ Language provides two methods of accessing array
elements. They are pointer arithmetic method and array indexing method. However, pointer
arithmetic will be faster.
To access array elements, the address of first element (base address) of an array can be
assigned to the pointer variable and using this address we can access the remaining elements of that
array.
For example,
int a[10], *p;
p = &a;
Assigns the base address of the array variable ‘a’ to the pointer variable ‘p’. Now to access 5th
element of ‘a’, we can write either a[4] or *(p+4).
Example:
main( )
{
int a[20],i , n,
*p; clrscr( );
printf(“How many values
“); scanf(“%d”,&n);
p = a; /* assigns beginning address of ‘a’ to ‘p’
*/ for(i=0;i<n;i++)
scanf(“%d”,(p+i)); /* inputs value to array thru pointer */
for(i=0;i<n;i++)
printf(“%3d”,*(p+i)); /* displays value of array thru pointer */
}
Array of Pointers:-
A pointer can also be declared as an array. As a pointer variable always contains an address,
an array of pointers contains a collection of addresses. Like an array, the elements of an array of
pointers are also stored in the memory in contiguous memory locations.
The general form to declare an array of pointers is as follows:
Syntax:
datatype *arrayname[size];
Here ‘dataype’ is the base type of pointer array and the size indicates the number of
elements in the pointer array.
Example:
main( )
{
int a[5]={10,20,30,40,50}, i;
int *p[5];
for(i=0;i<5;i++)
p[i] = &a[i];
for(i=0;i<5;i++)
printf(“%u “,p[i]);
}
In the above example, the pointer variable ‘p’ holds the address of the elements of array
variable ‘a’. This can be as shown below:
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
Pointer to Pointers:-
We can use a pointer to point another pointer that points to the target value. This is called
multiple indirection or pointer to pointer.
The value of pointer is the address of a variable that contains the desired value. In the case
of a pointer to pointer, the first pointer contains the address of a variable and the second pointer
contains the address of first pointer which points to the object that contains desired value.
Here the datatype is the base type of the variable to which the pointer is pointing. The
variable represents the name of the pointer variable.
Example:
int a=50, *p,
**m; p = &a;
m = &p;
The above example can be represented as shown below:
m p a
2002 1001 50
1.malloc( ) Function:-
Using this function, we can allocate memory space to a variable. The space must be
specified in the form of bytes. This function returns NULL if the allocation of memory fails. It
means, if the memory is not sufficient to allocate then it returns NULL.
The general format of malloc( ) function is as follows:
Syntax:
pv = (type *) malloc(size);
Here ‘pv’ is pointer variable and ‘type’ is the data type of the variable. The size is a numeric
constant or expression that indicates the number of bytes allocated to the variable.
Example-1:
int *p;
p = (int *) malloc(4);
Here, it allocates 4 bytes of memory to the variable ‘p’. Hence we can use the variable ‘p’ as two
elements of ‘int’ type.
Example-2:
float *p;
p = (float *) malloc(sizeof(float));
Here, it allocates 4 bytes of memory to the variable ‘p’, because the size of float is 4
bytes. Example-3:
int *p, n=5;
p = (int *) malloc(n*sizeof(int));
This example allocates memory for 5 integers of two bytes each i.e. 10 bytes.
2.calloc( ) Function:-
This function is also used to allocate space to a variable. But it initializes all the elements
with zero. Normally this function is used to allocate space for arrays and structures.
Syntax:
pv = (type *) calloc(n, size);
Here ‘pv’ is pointer variable and ‘type’ is the data type of the variable. The ‘n’ is number of
elements and the size specifies the number of bytes for each element.
Example-1:
int *p;
p = (int *) calloc(1, 2);
This example creates only one memory location and allocates two bytes to that
element. Example-2:
int *p, n=5;
p = (int *) calloc(n, sizeof(int));
This example creates n elements of 2 bytes each i.e. 5x2 = 10 bytes.
3.free( ) Function:-
This function is used to remove (free) the allocated space of a variable. Once memory is
released, we must allocate memory space to that variable later.
Syntax:
free(pv);
A structure is a collection of data items of different data types or same data type that
are referenced under one name.
The structure concept provides a convenient way of keeping related information together.
The data items that form the structure are called members (Also called elements or fields). The
individual elements can be accessed and processed separately. We can define our own data type by
using structures.
Declaring a Structure:-
The keyword ‘struct’ is used to define a structure. The structure definition is as follows:
Syntax:
Struct tag
{
datatype member1;
datatype member2;
:
:
datatype member-n;
In the above examples, for each variable i.e. st1 or st2, the conceptual view of memory
representation is as shown below:
Structurevariable . membername
For example, to access the members of ‘st’ variable declared in the above example are as follows:
Example:
Struct temp
{
int a,b;
};
main( )
{
struct temp m,n;
printf(“Enter 2 values “);
scanf(“%d %d”,&m.a, &m.b);
n = m; /* structure assignment */
printf(“a=%d , b=%d “,n.a, n.b);
}
Array of structures :-
Like any other type, we can also declare an array of structures. To declare an array of
structures, we must first define a structure and then declare an array of that type.
Syntax:
Struct tag arrayname[size];
Example:
Struct student
{
int htno;
char name[20];
float avg;
} st[20];
The above example creates 20 elements of type ‘student’. The conceptual view of the above
declaration is as shown below:
struct Node
{
int item;
struct Node *link;
};
The diagrammatic representation of the above structure is as follows.
Node
item link
Here the data is stored in the item field and the link is pointer to the next node.
Example:
struct Linked_List
{
int item;
struct Linked_List *link;
}Node;
main()
{
Node *head;
head = (Node *) malloc (sizeof(Node));
head item = 35;
headlink(Node *) malloc (sizeof(Node));
headlinkitem=55; headlinklink=NULL;
printf(“ % d \n”,headitem); printf(“
% d \n”,headlinkitem);
}
Differences between Structures and Arrays:-
Arrays Structures
1. An array is a group of elements of same type 1. A structure is a collection of data items may
that share a common name of different types referenced under one name
2. An array type variable can be defined using 2. A structure can be defined by using the
square brackets. keyword ‘struct’
Example: int a[20]; Example:
Struct stud
{
int htno;
char nm[5];
float avg;
} st;
3. The individual elements are accessed by 3. The individual members of the structure are
writing a value in square brackets after array accessed through the use of dot operator.
name. Example:
Example: st.htno refers to htno of
A[0] represents first element st st.nm refers to nm of st
th
A[3] represents 4 element
4. The conceptual view of the above array in 4. The conceptual view for the above structure
the memory is is
5. Arrays can be initialised while they are 5. The structure members are initialised as
declaring as follows follows
int a[5]={1,3,5,6,2}; Struct stud st={1,”ABC”,75.25};
6. The direct assignment is not possible 6. Variables of same type structures can
between two array variables assigned directly
int a[5]={1,2,3,4,5}, b[5]; Struct stud st1={1,”ABC”,75}, st2;
b = a; is invalid assignment st2 = st1; is valid assignment
7. If we access the name of the array, it returns 7. If we access name of the structure, it returns
base address of the array the value of first element in the structure
User Defined Data Types : Unions
A union is a collection of data items of different data types or same data type that are
referenced under one name.
All the members of a union share the same storage area within the computer’s memory.
Unions are useful for the applications involving multiple members where values need not be
assigned to all of the members at one time.
When a union is declared, the compiler automatically allocates memory location to hold
largest data type of members in the union.
Declaring a Union:-
The keyword ‘union’ is used to define a union. The union definition is as follows:
Syntax:
union tag
{
datatype member1;
datatype member2;
:
:
datatype member-n;
Example:-
union temp
{
int a;
float b;
char c;
} m,
n;
The above example defines a union called ‘temp’ and declares variables ‘m’ and ‘n’ of that
type.
Union variables can also be declared separately as follows:
union temp m, n;
In the above examples, the union variables occupy 4 bytes of memory. Because the largest member
in the above example is ‘b’ of float data type.
m.a
m.b
m.c
In the above example, all the members i.e. a, b and c share same storage area i.e. 4 bytes of
memory.
Structures Unions
1. Structure is a collection of data item 1. Union is also collection of data item may of
may of different data types referenced different data types referenced under one name
under one name
3. In a structure, memory is reserved for all 3. In a union, memory is reserved only for the
members of that structure largest member of that union
4. All members of structure cannot share 4. All members of structure can share the same
the same storage area storage area
5. All members of structure can be 5. All members of union cannot be accessed at a
accessed at a time time
6. We can store data for all members in the 6. We can store data for only one member of an
structure union
7. The structure variables can be initialized 7. The union variables cannot be initialized. But if
and can give values for all members we want to initialize, we can give value to the
Example: first member only
Struct temp m={10, 50.25, ‘M’}; Example:
Union temp m={10};
An enumeration data type is a derived (user-defined) data type which is similar to structures
and unions. Its members are constants. These constants represent values and they can be assigned to
corresponding enumerated variables.
Enumeration types are user-defined types that allows programmer to name a finite set of
elements which are called enumerators or enumeration constants or enumeration members.
Here, ‘tag’ is the name of enumeration type and id1, id2, id3, ……., id-n are identifiers
which represent enumeration constants. By default, ‘c’ compiler assigns integer values starting from
zero to each identifier automatically. But we can change these values.
Ex-1: enum grade {distinction, first, second, third} ;
In this example, ‘grade’ is the name of enumeration tag, and ‘distinction, first, second, third’
are the enumeration constants which assigns values 0, 1, 2, 3 respectively.
Ex-2:-
enum grade {distinction=10, first=20, second=30, third=40} ;
In this example, enumeration constants are assigned with values 10, 20, 30 and 40
respectively.
Note:
1. An enumeration constant cannot be read from the keyboard.
2. An enumeration constant can be assigned to any integer variable.
3. An enumeration constant can also be printed.
Sample program:-
main( )
{
enum colour {red, blue, green, yellow};
enum colour c;
c = red; /* assigns ‘red’ i.e. the value 0 to the variable ‘c’
*/ if (c = = yellow)
printf(“yellow”);
else if (c = = red)
c=
blue; else if (c
= = 2)
} printf(“green”);
UNIT-V : Functions & Files
Definition:- A function is a self-contained program block that performs some specific task.
Every ‘C’ program consists of one or more functions. One of these functions must be called main( ).
In C, Functions are divided into two types. They are:
1. Standard or built-in functions 2. User-defined functions.
The use of user-defined functions allows a large program to be broken down into a number of
smaller functions (modules).
Uses of functions:-
There are several advantages to this modular approach, they are
The use of function avoids the need for redundant (repeated) programming of the same
instructions.
The functions can be accessed many times within a program by passing different values as
parameters.
Functions improve the logical clarity of a program. That means such programs are easier to
write and debug.
The use of functions also enables a programmer to develop a user-defined library of frequently
used modules. This library file can be included in any program.
Defining a Function:-
A user-defined function must be defined within a program before using it. If a program
contains multiple functions, their definitions may appear in any order, and they must be
independent of one another. One function definition cannot be included within another.
The definition of a function has 2 parts. They are (i) Function header and (ii) Function body.
The general form for defining a function is as
follows: Syntax:
returntype functionname(datatype arg1, datatype arg2, …, datatype arg-n)
{
function-body ;
[return(value);]
}
Here,
1. The ‘returntype’ represents the type of value of the item that is returned by the function to
its calling point. The default return type is ‘int’.
2. The ‘function name’ is an identifier that represents the name of user-defined function
3. Arg1, arg2, …, arg-n are the variables (arguments) that represent formal parameters of the
function. These are receiving values from the calling point. However, a function can be
defined without arguments.
4. The data types represent the type of arguments.
5. The function body may contain one or more statements. These statements can be
input/output, assignment and control statements etc.
6. The ‘return’ statement returns a value to the function’s calling point, if it is
used.
Example:-
float adding(int a, float b)
{
float c;
c = a + b;
return(c);
}
Where, ‘function name’ is name of user-defined function that must be available in the program.
Arg1, arg2, …, arg-n are the values that are send to the function. These are referred as actual
arguments.
While accessing a function, the following points must be remembered:
i. The number and order of actual parameters and formal parameters must be same.
ii. When a function returns a value to its calling point then the returned value must be assigned
to a variable or it must be used in the output function.
Note:- If a function does not return anything, or it does not have any arguments to declare, then the
function can be declared using void as follows
Ex: void reading( void );
return statement:-
The return statement is used to return a value from a user-defined function to its calling
point. This statement can be used in the following ways:
Syntax-1: return ;
Syntax-2: return (value) ;
When a return statement is executed, the control returns back to the calling point. If a value
is given along with return statement, it replaces the value at the calling point. The value can be
constant, variable or expression. The value may or may not be enclosed within the parenthesis.
The return statement can return only one value to its calling point. The return statement can
occur anywhere and many times in the body of the function.
Examples:
1. return ;
2. return (25);
3. return 25;
4. return (x+y);
5. return x+y;
Passing parameters :-
Parameters are used for exchanging the information between the calling point and called
function. There are two types of parameters. They are (i) Actual Parameters and (ii) Formal
Parameters.
Actual Parameters:- The parameters that are included in function calling point are called “actual
parameters”. These are used to send values to the called function.
Formal Parameters:- The parameters that are included in function definition are called “formal
parameters”. These are used to receive values from the calling point.
While using actual and formal parameters the following rules must be followed:
1. The number of actual parameters must be equal to the number of formal parameters.
2. The data types of actual parameters must be same to their corresponding formal parameters.
3. The actual and formal parameters may or may not be having same names
Example:
-main( )
{
float adding(int , float);
int a = 15;
float b = 25.75, c;
clrscr( );
c = adding ( a, b);
Actual Parameters
printf(“Result = %f”,c);
}
float adding(int m, float n)
{ Formal Parameters
return (m+n);
}
The place of declaration of variables specifies the scope and lifetime of variables. Based on
place of declaration, the variables are classified into two types. They are
1. Local (Internal or Private) variables
2. Global (External or Public) variables
Local Variables:-
The variables that are declared inside a function are called local variables. The local
variables are created when the function is called and destroyed (deleted) when function is finished
its execution.
The local variables are referred (accessed or used) only within the function in which they
are declared i.e. these variables’ lifetime is only within function in which they are declared.
Global Variables:-
The variables that are declared outside a function are called global variables. The global
variables are created at the beginning of the program and destroyed (deleted) when program is
completed. These variables’ lifetime is entire program.
The global variables are accessed in all functions within the program that follows the
declaration of these variables.
#include <stdio.h>
int x=10, y=30; /* Global to all functions
*/ main( )
{
void sample1(
); void
sample2( );
int a=10, b=10; /* Local to function main( ) */
a = a + x;
sample1( )
;
sample2( )
; b = b + y;
printf(“%d %d”,a,b);
}
int n=20; /* Global to the functions sample1 and sample2*/
void sample1( )
{
int m=30; /* Local to the function sample1( ) */
printf(“%d %d”,m, n);
}
void sample2( )
{
int k=20; /* Local to the function sample2( )
*/ printf(“%d %d”,k, n);
}
Storage classes
A storage class is used to declare variables. It tells the compiler the following points.
The location of the variable i.e. where the variable would be created i.e. either in memory or
in CPU registers.
The default initial value of the variable
The scope of variable i.e. in which function the value of a variable would be available
The life of the variable i.e. how long a variable exists
The following are various storage classes are used to declare variables in ‘C’ language.
1. Automatic Storage class (auto)
2. Register storage class (register)
3. Static storage class (static)
4. External storage class (extern)
The general format for declaring variables using storage class is as follows:
Example:
main( )
{
auto int x, y;
}
sample( )
{
auto float x, y;
Example:
main( )
{
register int x, y;
register char
ch;
}
sample( )
{
auto float x, y;
}
Example:
extern int a=1,
b=2; main( )
{
void sample( );
printf(“a=%d, b=%d \n”,a,
b); sample( );
printf(“a=%d, b=%d \n”,a, b);
}
void sample( )
{
a = a + 10;
b = b+20;
}
Output:
a=1, b=2
a=11, b=22
Recursion
Recursion is a process by which a function calls itself repeatedly. In the recursion process, a
function is repeated endlessly or until some specified condition has been satisfied. Recursion is
used for repetitive computations in which each action is started in terms of a previous result.
For Example, to find factorial of 5, it can be recursively computed as
follows: 5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1
In the same way, the factorial of n is recursively defined
as, N! = N * (N-1)! if N > 1
= 1 if N <=1
Definition :-
A file is a collection of bytes that contains some information permanently. A file is created
in secondary storage devices.
Use of Files :-
Normally, a program inputs and outputs values as handled through the variables, which are
created in primary memory. So the values given by a user are stored temporarily. Once program
execution is completed, the values are also automatically removed.
Hence to store data permanently in the memory, we can use files concept. A file is created
in the secondary memory device such as disk or tape. When a file is created, we can modify or
delete data present in the file as and when needed.
Terminology :-
In ‘c’ language, the information is stored in a file in the form of fields and records.
Field:- It is an elementary data item (int, float or char) that is used to store a single unit of data.
For example, EMPNO is a field name that represents employee number.
Record:- A set of fields is called a record. For example, a group of empno, empname,and salary
is a record.
File:- A file is collection of related records. For example, employee file contains employee records.
FILE datatype:-
To manipulate files in ‘c’ language, we must use FILE data type. It is a structure
datatype that is used to create file buffer area. The general format is as follows:
Here, FILE is the name of data type and ‘fp’ is file pointer which will contain all the
information about the file.
Mode Meaning
“r” Opens text file for reading
“w” Opens text file for writing
“a” Opens text file in append mode
“rb” Opens binary file for reading
“wb” Opens binary file for writing
“ab” Opens binary file for append
“r+” Opens text file for reading and writing
“w+” Opens text file for writing and reading
The opened file must be closed at the end of all input and output operations done on it. The
fclose( ) function is used to close an opened file. Once a file is closed, we cannot perform any
operation on that file until it is opened again.
Syntax: fclose(fp);
fgetc() function:-
This function is used to read a single character from the file and stores it in a variable.
fgets() function :-
This function is used to read the specified number of characters from the file and stores it in
a variable.
fscanf() function:-
This function is used to read data items from the file and stores them into variables. It reads
values based on formatting characters specified. This function returns an integer if it is success
otherwise it returns zero. The general format is as follows:
Here, ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The ‘variable-
list’ contains one or more variables.
fputc() function:-
This function is used to store a single character into file. The general format is as follows:
fputs() function:-
This function is used to store a string into the file.
Syntax:- fputs(string, fp);
fprintf() function:-
This function is used to store data items into the file. It writes values based on formatting
characters specified. The general format is as follows:
Here, ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The ‘variable-
list’ contains one or more variables separated by commas.
Ex: fprintf(fp, “%d %s %f”,rno, snm, avg);
feof() function:-
This function checks whether end of file has been reached or not. It returns non-zero when
end of file is reached otherwise it returns zero.
Syntax:- feof(fp); where ‘fp’ is file pointer