Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Complete Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Unit I

Introduction to Components of Computer System


A computer is a programmable machine that receives input, stores and manipulates data, and provides
output in a useful format.
Computers are used just about everywhere in our society:
● Communications: internet, e-mail, cell phones
● Word Processing: typing/printing documents
● Business Applications: accounting, spreadsheets
● Entertainment, Database Management
● Engineering Applications: scientific analysis, simulations
● Manufacturing: CAD/CAM, robotics, assembly and many more.
The two major components of computer system are
● Hardware Component
● Software Component
Hardware Component: This refers to the machinery part of the computer system. The part you can
break or touch. Examples are mouse, monitor, CPU, etc.
Software Component: Suit of programs written to control the activities of the computer system e.g.
operating system, program translators.
COMPUTER SOFTWARE
Software is a suite of programs written to achieve a target goal. Software is designed to exploit and
provide the potential capabilities of the hardware to the user. Computer software is divided in to two
broad categories:
1. System software
a. Operating System
b. System Support
c. System Development
2. Application software.
a. General Purpose
b. Application Specific
System software manages the computer resources .It provides the interface between the hardware and
the users. Application software, on the other hand is directly responsible for helping users solve their
problems.

System Software: System software consists of programs that manage the hardware resources of a
computer and perform required information processing tasks. It is essential for the day today activities
of the computer. Examples of systems software are: Operating system, translators, utilities,
housekeeping routines etc.These programs are divided into three classes: the operating system, system
support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this software
is to keep the system operating in an efficient manner while allowing the users access to the system.
System support software provides system utilities and other operating services. Examples of system
utilities are sort programs and disk format programs. Operating services consists of programs that
provide performance statistics for the operational staff and security monitors to protect the system and
data.
The last system software category, system development software, includes the language translators
that convert programs into machine language for execution, debugging tools to ensure that the
programs are error free and computer –assisted software engineering (CASE) systems.

Application software Application software is broken in to two classes: general-purpose software


and application – specific software.
General purpose software is purchased from a software developer and can be used for more than one
application. Examples of general purpose software include word processors,database management
systems ,and computer aided design systems. They are labeled general purpose because they can solve
a variety of user computing problems.
Application –specific software can be used only for its intended purpose. A general ledger system
used by accountants and a material requirements planning system used by a manufacturing
organization are examples of application-specific software. They can be used only for the task for
which they were designed they cannot be used for other generalized tasks.
The relationship between system and application software is shown in fig-2.In this figure, each circle
represents an interface point .The inner core is hard ware. The user is represented by the out layer. To
work with the system,the typical user uses some form of application software. The application
software in turn interacts with the operating system ,which is apart of the system software layer. The
system software provides the direct interaction with the hard ware. The opening at the bottom of the
figure is the path followed by the user who interacts directly with the operating system when
necessary.

Fig.1.1 Categories of computer software


TRANSLATORS: These are special software designed to translate a program written in high level or
low level language to machine language which is the only language computer understands. Machine
language uses binary codes to represents data, instruction and information.
TYPES OF TRANSLATORS: The three types of translators are: Assembler, interpreter and
compiler.
● Compiler: It translates high level language (source code) to the machine language (object code). It
translates the whole of the high level language such as FORTRAN, COBOL called source code
into the equivalent program in m
● achine language called the object program or object code at once.
● Interpreter: Interpreter like compiler translates a program written in high level language to a
machine language. While compiler translates the whole program once, interpreter translates one
instruction at a time and executing each instruction one after the other until the whole area is
completely translated and executed. It is slower than compiler.
● Assemblers: Assemblers translate the low level language (Assembly language) to the machine
language.

CENTRAL PROCESSING UNIT (C P U)


Is the brain or the heart of a computer. Is also known as processor and consist of three units
namely –
● Control Unit ( C U)
● Arithmetic logic Unit ( A L U)
● Main Memory unit ( M M U)

Fig.1.2 Components of Computer System


The system unit is the core of a computer system. Usually it's a rectangular box placed on or
underneath your desk. Inside this box are many electronic components that process data. The most
important of these components is the central processing unit (CPU), or microprocessor, which acts
as the "brain" of your computer. Another component is random access memory (RAM), which
temporarily stores information that the CPU uses while the computer is on. The information stored
in RAM is erased when the computer is turned off.
Almost every other part of your computer connects to the system unit using cables. The cables
plug into specific ports (openings), typically on the back of the system unit. Hardware that is not
part of the system unit is sometimes called a peripheral device. Peripheral devices can be external
such as a mouse, keyboard, printer, monitor, external Zip drive or scanner or internal, such as a
CD-ROM drive, CD-R drive or internal modem. Internal peripheral devices are often referred to as
integrated peripherals. There are two types according to shape: tower and desktop.
A motherboard (mainboard, system board, planar board or logic board) is the main printed circuit
board found in computers and other expandable systems. It holds many of the crucial electronic
components of the system, such as the central processing unit (CPU) and memory, and provides
connectors for other peripherals.
TYPES OF PROCESSORS
i) Complex Instruction Set Computers (CISC)
ii) Reduced Instruction Set Computers (RISC)
FUNCTIONS OF CENTRAL PROCESSING UNIT
- Process data.
- Control sequence of operations within the computers.
- It gives command to all parts of a computer.
- It control the use of the main memory in storing of data and instructions.
- It provides temporary storage (RAM) and permanent storage (ROM) of data.
MEMORY AND STORAGE UNIT
This unit can store instructions, data, and intermediate results. This unit supplies information to
other units of the computer when needed. It is also known as internal storage unit or the main
memory or the primary storage or Random Access Memory (RAM).
Its size affects speed, power, and capability. Primary memory and secondary memory are two types
of memories in the computer. Functions of the memory unit are −
● It stores all the data and the instructions required for processing.
● It stores intermediate results of processing.
● It stores the final results of processing before these results are released to an output device.
● All inputs and outputs are transmitted through the main memory.

CONTROL UNIT
Is the centre of operations for the computer system, it directs the activities of the computer
system.This unit controls the operations of all parts of the computer but does not carry out any
actual data processing operations.
Functions of this unit are −
● It is responsible for controlling the transfer of data and instructions among other units of a
computer.
● It manages and coordinates all the units of the computer.
● It obtains the instructions from the memory, interprets them, and directs the operation of
the computer.
● It communicates with Input/Output devices for transfer of data or results from storage.
● It does not process or store data.
ALU (Arithmetic Logic Unit)
This unit consists of two subsections namely,

● Arithmetic Section
● Logic Section
Arithmetic Section
Function of arithmetic section is to perform arithmetic operations like addition, subtraction,
multiplication, and division. All complex operations are done by making repetitive use of the
above operations.
Logic Section
Function of logic section is to perform logic operations such as comparing, selecting, matching,
and merging of data.

OPERATING SYSTEM
The Operating System is a program with the following features −
● An operating system is a program that acts as an interface between the software and the
computer hardware.
● It is an integrated set of specialized programs used to manage overall resources and operations
of the computer.
● It is a specialized software that controls and monitors the execution of all other programs that
reside in the computer, including application programs and other system software.

Fig.1.3 Operating System as an interface


\Objectives of Operating System
The objectives of the operating system are −
● To make the computer system convenient to use in an efficient manner.
● To hide the details of the hardware resources from the users.
● To provide users a convenient interface to use the computer system.
● To act as an intermediary between the hardware and its users, making it easier for the users to
access and use other resources.
● To manage the resources of a computer system.
● To keep track of who is using which resource, granting resource requests, and mediating
conflicting requests from different programs and users.
● To provide efficient and fair sharing of resources among users and programs.

Characteristics of Operating System


Here is a list of some of the most prominent characteristic features of Operating Systems −
● Memory Management − Keeps track of the primary memory, i.e. what part of it is in use by
whom, what part is not in use, etc. and allocates the memory when a process or program
requests it.
● Processor Management − Allocates the processor (CPU) to a process and de-allocates the
processor when it is no longer required.
● Device Management − Keeps track of all the devices. This is also called I/O controller that
decides which process gets the device, when, and for how much time.
● File Management − Allocates and de-allocates the resources and decides who gets the
resources.
● Security − Prevents unauthorized access to programs and data by means of passwords and
other similar techniques.
● Job Accounting − Keeps track of time and resources used by various jobs and/or users.
● Control Over System Performance − Records delays between the request for a service and
from the system.
● Interaction with the Operators − Interaction may take place via the console of the computer
in the form of instructions. The Operating System acknowledges the same, does the
corresponding action, and informs the operation by a display screen.
● Error-detecting Aids − Production of dumps, traces, error messages, and other debugging
and error-detecting methods.
● Coordination between Other Software and Users − Coordination and assignment of
compilers, interpreters, assemblers, and other software to the various users of the computer
systems.

COMPUTER LANGUAGES
To write a program for a computer, we must use a computer language. Over the years, computer
languages have evolved from machine languages to natural languages.
● 1940’s Machine level Languages
● 1950’s Symbolic Languages
● 1960’s High-Level Languages
Machine Languages:
In the earliest days of computers, the only programming languages available were machine languages.
Each computer has its own machine language, which is made of streams of 0’s and 1’s.
Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits of a
computer are made of switches transistors and other electronic devices that can be in one of two states:
off or on. The off state is represented by 0, the on state is represented by 1.
The only language understood by computer hardware is machine language.
Symbolic Languages:
In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the concept of a
special computer program that would convert programs into machine language.
The early programming languages simply mirror to the machine languages using symbols of
mnemonics to represent the various machine language instructions because they used symbols, these
languages were known as symbolic languages.
Computer does not understand symbolic language it must be translated to the machine language. A
special program called assembler translates symbolic code into machine language. Because symbolic
languages had to be assembled into machine language they soon became known as assembly
languages.
Symbolic language uses symbols or mnemonics to represent the various ,machine language
instructions.
High Level Languages:
Symbolic languages greatly improved programming effificiency; they still required programmersto
concentrate on the hardware that they were using. Working with symbolic languages wasalso very
tedious because each machine instruction has to be individually coded. The desire toimprove
programmer efficiency and to change the focus from the computer to the problembeing solved led to
the development of high-level language.
High level languages are portable to many different computers, allowing the programmer
toconcentrate on the application problem at hand rather than the intricacies of the computer.High-level
languages are designed to relieve the programmer from the details of the assemblylanguage. High
level languages share one thing with symbolic languages, They must beconverted into machine
language. The process of converting them is known as compilation.The first widely used high-level
languages, FORTRAN (FORmulaTRANslation)was created byJohn Backus and an IBM team in
1957;it is still widely used today in scientific and engineeringapplications. After FORTRAN was
COBOL(Common Business-Oriented Language). AdmiralHopper was played a key role in the
development of the COBOL Business language.C is a high-level language used for system software
and new application code.

C PROGRAMMING BASICS TO WRITE A PROGRAM


Below are few commands and syntax used in C programming to write a simple C program. Let’s see
all the sections of a simple C program line by line.
C Basic commands Explanation

This is a preprocessor command that includes standard input


#include <stdio.h> output header file(stdio.h) from the C library before compiling a C
program

This is the main function from where execution of any C program


int main()
begins.

{ This indicates the beginning of the main function.

/*_some_comments_* whatever is given inside the command “/* */” in any C program,
/ won’t be considered for compilation and execution.

printf(“Hello_World!
printf command prints the output onto the screen.
“);

getch(); This command waits for any character input from keyboard.
This command terminates C program (main function) and returns
return 0;
0.

} This indicates the end of the main function.

A SIMPLE C PROGRAM
Below C program is a very simple and basic program in C programming language. This C program
displays “Hello World!” in the output window. And, all syntax and commands in C programming are
case sensitive. Also, each statement should be ended with semicolon (;) which is a statement
terminator.

#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! ");
getch();
return 0;
}
OUTPUT:
Hello World!

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT


Below are the steps to be followed for any C program to create and get the output. This is common to
all C program and there is no exception whether its a very small C program or very large C program.

1. Create
2. Compile
3. Execute or Run
4. Get the Output
CREATION, COMPILATION AND EXECUTION OF A C PROGRAM
Prerequisite:
● If you want to create, compile and execute C programs by your own, you have to install C
compiler (IDE tool and GCC compiler) in your machine. Then, you can start to execute your own
C programs in your machine.

BASIC STRUCTURE OF A C PROGRAM


Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program. All C programs are having sections/parts which are mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS
/*
Documentation section
C programming basics & structure of C programs
*/

#include <stdio.h> /* Link section */


int total = 0; /* Global declaration, definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf ("This is a C basic program \n");
total = sum (1, 1);
printf ("Sum of two numbers : %d \n", total);
return 0;
}

int sum (int a, int b) /* User defined function */


{
return a + b; /* definition section */
}
OUTPUT:
This is a C basic program
Sum of two numbers : 2

DESCRIPTION FOR EACH SECTION OF THE C PROGRAM:


● Let us see about each section of a C basic program in detail below.
● Please note that a C program mayn’t have all below mentioned sections except main function and
link sections.
● Also, a C program structure mayn’t be in below mentioned order.

Sections Description

We can give comments about the program, creation or modified date,


author name etc in this section. The characters or words or anything
which are given between “/*” and “*/”, won’t be considered by C
compiler for compilation process.These will be ignored by C
Documentation compiler during compilation.
section Example : /* comment line1 comment line2 comment 3 */

Header files that are required to execute a C program are included in


Link Section this section

In this section, variables are defined and values are set to these
Definition Section variables.

Global declaration Global variables are defined in this section. When a variable is to be
section used throughout the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like
declaration section return type, parameter names used inside the function.

Every C program is started from main function and this function


contains two major sections called declaration section and executable
Main function section.

User defined User can define their own functions in this section which perform
function section particular task as per the user requirement.

KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS:


1. C programming is a case sensitive programming language.
2. Each C programming statement is ended with semicolon (;) which are referred as statement
terminator.
3. printf() command is used to print the output onto the screen.
4. C programs are compiled using C compilers and displays output when executed.

Printf() and scanf() in C


● printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default. These functions are declared and related macros are defined in
“stdio.h” which is a header file in C language.
● We have to include “stdio.h” file as shown in below C program to make use of these printf() and
scanf() library functions in C language.

printf() Function In C Language:


● In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
● We use printf() function with %d format specifier to display the value of an integer variable.
● Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
● To generate a newline,we use “\n” in C printf() statement.
Note:
C language is case sensitive. For example, printf() and scanf() are different from Printf() and
Scanf(). All characters in printf() and scanf() functions must be in lower case.
You can see the output with the same data which are placed within the double quotes of printf
statement in the program except
● %d got replaced by value of an integer variable (no),
● %c got replaced by value of a character variable (ch),
● %f got replaced by value of a float variable (flt),
● %lf got replaced by value of a double variable (dbl),
● %s got replaced by value of a string variable (str),
● %o got replaced by a octal value corresponding to integer variable (no),
● %x got replaced by a hexadecimal value corresponding to integer variable
● \n got replaced by a newline.
Example:
#include <stdio.h>
int main()
{
charch = 'A';
charstr[20] = "fresh2refresh.com";
floatflt = 10.234;
int no = 150;
doubledbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}

scanf() Function In C Language:


● In C programming language, scanf() function is used to read character, string, numeric data
from keyboard
● Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
● Then, user enters a string and this value is assigned to the variable “str” and then displayed.
● The format specifier %d is used in scanf() statement. So that, the value entered is received as
an integer and %s for string.
● Ampersand is used before variable name “ch” in scanf() statement as &ch.
● It is just like in a pointer which is used to point to the variable. For more information about
how pointer works, please click here.
Example:
#include <stdio.h>
int main()
{
charch;
charstr[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

KEY POINTS TO REMEMBER IN C printf() AND scanf():


1. printf() is used to display the output and scanf() is used to read the inputs.
2. printf() and scanf() functions are declared in “stdio.h” header file in C library.
3. All syntax in C language including printf() and scanf() functions are case sensitive.

C PREPROCESSOR DIRECTIVES:
● Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
● Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Below is the list of preprocessor directives that C programming language offers.

Preprocessor Syntax/Description

Syntax: #define
This macro defines constant value and can be any of the basic data
Macro types.

Syntax: #include <file_name>


Header file The source code of the file “file_name” is included in the main
inclusion program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional Set of commands are included or excluded in source program before
compilation compilation with respect to the condition.

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:


● #define – This macro defines constant value and can be any of the basic data types.
● #include <file_name> – The source code of the file “file_name” is included in the main C
program where “#include <file_name>” is mentioned.

#include <stdio.h>

#define height 100


#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'

void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
EXAMPLE PROGRAM FOR CONDITIONAL COMPILATIONDIRECTIVES:

EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:


● “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause
statements are included in source file.
● Otherwise, “else” clause statements are included in source file for compilation and execution.

#include <stdio.h>
#define RAJU 100

int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
OUTPUT:
RAJU is defined. So, this line will be added in this C file

EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:


● #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause
statements are included in source file.
● Otherwise, else clause statements are included in source file for compilation and execution.
Example:
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);

#endif
return 0;
}
OUTPUT:
SELVA is not defined. So, now we are going to define here
EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:
● “If” clause statement is included in source file if given condition is true.
● Otherwise, else clause statement is included in source file for compilation and execution.

#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100

EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE:


This directive undefines existing macro in the program.
#include <stdio.h>

#define height 100


void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}
OUTPUT:
First defined value for height : 100
value of height after undef& redefine : 600

Comments
It is useful to place a comment in place to indicate what you are doing. It is added into the program for
making the program easier to understand and these are not compiled by the compiler or interpreter. It
is useful if you want someone else to be able to ever read your code.

There are two ways to use comment in C which are as follows:

● Single Line comment


● Multi Line comment
Single Line comment – It is used to apply the comment on a single line. To apply single line
comment // is used.
e.g.
printf(“hello World"); // It will print the string hello World

Multi Line comment – It is used to apply the comment on multiple lines. To apply multi line use
/*comment */.
e.g.
printf("hello World"); /*It will print the

string hello World*/


Data types in CLanguage
Data types specify how we enter data into our programs and what type of data we enter. C language has
some predefined set of data types to handle various kinds of data that we can use in our program. These
data types have different storage capacities.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer (int), floating point(float), character(char)
and “void”.
2. Derived data types:
Derived data types are nothing but primary data types but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can
hold only integer values. Every variable which is used in the program must be declared as what data-type it
is.

Fig.1.4 Categorization of data types.


Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255


long int or signed long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Floating point type


Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

void type
“void” type means no value. This is usually used to specify the type of functions which returns nothing.
Unlike other primitive data types in c, void data type does not create any variable but returns an empty
set of values. Thus, we can say that it stores null.
The void type specifies that no value is available. It is used in three kinds of situations –
Sr.No. Types & Description

1 Function returns as void


There are various functions in C which do not return any value or you can say
they return void. A function with no return value has the return type as void. For
example, void exit (int status);

2 Function arguments as void


There are various functions in C which do not accept any parameter. A function
with no parameter can accept a void. For example, int rand(void);

3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc(size_t size ); returns a
pointer to void which can be casted to any data type.

Algorithm in Programming
In programming, algorithm is a set of well-defined instructions in sequence to solve the problem.
Qualities of a good algorithm
1. Input and output should be defined precisely.
2. Each steps in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in such a
way that, it can be used in similar programming languages.

Examples of Algorithms in Programming


Write an algorithm to add two numbers entered by user.

Step 1:
Start
Step 2:
Declare variables num1, num2 and sum.
Step 3:
Read values num1 and num2.
Step 4:
Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Write an algorithm to find the largest among three different numbers entered by user.

Step 1:
Start
Step 2:
Declare variables a,b and c.
Step 3:
Read variables a,b and c.
Step 4:
If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Introduction to flowcharts
A flowchart is a graphical representation of an algorithm. These flowcharts play a vital role in the
programming of a problem and are quite helpful in understanding the logic of complicated and lengthy
problems. Once the flowchart is drawn, it becomes easy to write the program in any high level
language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is
correct to say that a flowchart is a must for the better documentation of a complex program.Flowcharts
are usually drawn using some standard symbols;
Basic Symbols used in Flowchart Designs
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A
pause/halt is generally used in a program logic under some error conditions. Terminal is the first
and last symbols in the flowchart.

2. Input/Output: A parallelogram denotes any function of input/output type. Program instructions


that take input from input devices and display output on output devices are indicated with
parallelogram in a flowchart.

3. Processing: A box represents arithmetic instructions. All arithmetic processes such as adding,
subtracting, multiplication and division are indicated by action or process symbol.

4. Decision Diamond symbol represents a decision point. Decision based operations such as yes/no
question or true/false are indicated by diamond in flowchart.

5. Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is
useful to use connectors to avoid any confusions. It is represented by a circle.

6. Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of flowchart.
Example of a flowchart:
Problem: Write an algorithm and draw the flowchart for finding the average of two numbers
Algorithm:
Input: two numbers x and y
Output: the average of x and y
Steps:
1. input x
2. input y
3. sum = x + y
4. average = sum /2
5. output average
START

END

Fig.1.5 Flowchart to find average of two numbers

Errors in C Programming
Error is an illegal operation performed by the user which results in abnormal working of the
program.Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors should be
removed before compiling and executing.
Syntax errors
Syntax: All languages have a set of rules for how words and sentences should be structured. These
rules are collectively known as the language syntax. In computer programming, syntax serves the
same purpose, defining how declarations, functions, commands, and other statements should be
arranged.
A syntax error is an error in the source code of a program. Since computer programs must follow strict
syntax to compile correctly, any aspects of the code that do not conform to the syntax of the
programming language will produce a syntax error. Syntax errors are small grammatical mistakes,
sometimes limited to a single character. For example, a missing semicolon at the end of a line or an
extra bracket at the end of a function may produce a syntax error.
Common syntax errors are:
● Spelling mistakes.
● Missing out quotes.
● Missing out brackets.
● Using upper case characters in key words e.g. IF instead of if.
● Missing out a colon or semicolon at end of a statement.
● Using tokens in the wrong order.
Errors that occur when you violate the rules of writing C syntax are known as syntax errors. This
compiler error indicates something that must be fixed before the code can be compiled. All these
errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
● Missing Parenthesis (})
● Printing the value of variable without declaring it
● Missing semicolon like this:
Example:
// C program to illustrate
// syntax error
#include<stdio.h>
voidmain()
{
intx = 10;
inty = 15;

printf("%d", (x, y)) // semicolon missed


}
Error:
error: expected ';' before '}' token
Example:Syntax of a basic construct is written wrong. E.g.: while loop
// C program to illustrate
// syntax error
#include<stdio.h>
intmain(void)
{
// while() cannot contain "." as an argument.
while(.)
{
printf("hello");
}
return0;
}
Error:
error: expected expression before '.' token
while(.)
In the given example, the syntax of while loop is incorrect. This causes a syntax error.
Logical Errors
A logic error (or logical error) is a ‘bug’ or mistake in a program’s source code that results in incorrect
or unexpected behaviour. It is a type of runtime error that may simply produce the wrong output or
may cause a program to crash while running. Many different types of programming mistakes can
cause logic errors. For example, assigning a value to the wrong variable may cause a series of
unexpected program errors. Multiplying two numbers instead of adding them together may also
produce unwanted results.
Logic errors occur when there is a design flaw in your program. Common examples are:
● Multiplying when you should be dividing
● Adding when you should be subtracting
● Opening and using data from the wrong file
● Displaying the wrong message

On compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are called
logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
Example:
// C program to illustrate
// logical error
intmain()
{
inti = 0;

// logical error : a semicolon after loop


for(i = 0; i< 3; i++);
{
printf("loop ");
continue;
}
getchar();
return0;
}
No output

References:
● https://nptel.ac.in/courses/106105171/2
● https://www.tutorialspoint.com/computer_fundamentals/computer_operating_system.htm
● Kernighan 78 – B. W. Kernighan and D. M. Ritchie, The C Programming Language,
Prentice-Hall: Englewood Cliffs, NJ, 1978. Second edition, 1988.
● Thinking 90 – C* Programming Guide, Thinking Machines Corp. Cambridge Mass., 1990
● https://www.geeksforgeeks.org/an-introduction-to-flowcharts/
● https://www.programiz.com/article/flowchart-programming
● https://www.programiz.com/article/algorithm-programming
Unit II
Operators and Operands
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to
perform a certain mathematical or logical manipulation. Operators are used in programs to manipulate data
and variables.
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition. And those variables are termed as operands.
C operators can be classified into following types:
● Arithmetic operators
● Relational operators
● Logical operators
● Bitwise operators
● Assignment operators
● Conditional operators
● Special operators

Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one
Relational operators
The following table shows all relation operators supported by C.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to “float” or “double”
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift

Now lets see truth table for bitwise “&”, | and “^”
a b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and the
right operand specifies the number of positions that the bits in the value have to be shifted. Both operands
have the same precedence.
Example :
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010

Assignment Operators
Assignment operators supported by C language are as follows.
Operato Description Example
r
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
-= subtracts right operand from the left operand and assign the result to left a-=b is same as a=a-b
operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left operand a%=b is same as
a=a%b
Conditional operator
The conditional operators in C language are known by two more names

1. Ternary Operator
2. ? : Operator
It is actually the “if” condition that we use in C language decision making, but using conditional operator,
we turn the “if” condition statement into a short and simple operator.
The syntax of a conditional operator is :
expression1 ? expression2: expression 3
Explanation:

● The question mark "?" in the syntax represents the if part.


● The first expression (expression 1) generally returns either true or false, based on which it is decided
whether (expression 2) will be executed or (expression 3)
● If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is executed.
● If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3) is
executed.
Special operator
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
* Pointer to a variable *x ; will be pointer to a variable x

Operators Precedencein C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* &sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision Making
In programming, decision making is used to specify the order in which statements are executed.

if statement
The syntax of if statement is:

if (testExpression)
{
// statement(s)
}

How if statement works?


The if statement evaluates the test expression inside the parenthesis.
● If the test expression is evaluated to true (nonzero), statement(s) inside the body of “if” is
executed.
● If the test expression is evaluated to false (0), statement(s) inside the body of “if” is skipped
from execution.

if...else statement
The if statement may have an optional else block. The syntax of if..else statement is:

if (testExpression) {
// statement(s) inside the body of if
}
else {
// statement(s) inside the body of else
}

How if...else statement works?


If test expression is evaluated to true,
● statement(s) inside the body of if statement is executed
● statement(s) inside the body of else statement is skipped from execution.
If test expression is evaluated to false,
● statement(s) inside the body of else statement is executed
● statement(s) inside the body of if statement is skipped.

if...else Ladder (if...else if....else Statement)


The if...else statement executes two different codes depending upon whether the test expression is
true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check for multiple test expressions and execute different
statement(s).
Syntax of nested if...else statement

if (testExpression1)
{
// statement(s)
}
else if(testExpression2)
{
// statement(s)
}
else if (testExpression 3)
{
// statement(s)
}
else
{
// statement(s)
}
Nested if...else
It is possible to include if...else statement(s) inside the body of another if...elsestatement.
This program below relates two integers using either <, > and = similar like in if...elseladder
example. However, we will use nested if...else statement to solve this problem.

Example 4: Nested if...else


#include<stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d",&number1,&number2);

if(number1 >= number2)


{
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else
{
printf("Result: %d > %d", number1, number2);
}
}
else
{
printf("Result: %d < %d",number1, number2);
}
return0;
}

Switch Statement:The switch case statement is used when we have multiple options and we need
to perform a different task for each option. Switch case statements are a substitute for long if
statements that compare a variable to several integral values
● The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
● Switch is a control statement that allows a value to change control of execution.

C – Switch Case Statement


Syntax:
switch (variable or an integer expression)
{
case constant:
//C Statements
;
case constant:
//C Statements
;
default:
//C Statements
;
}
Example of Switch Case in C
#include <stdio.h>
int main()
{
intnum=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Default: value is: 2
Important Points about Switch Case Statements:
1. The expression provided in the switch should result in a constant value otherwise it would not
be valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions for switch:
// Variable expression not allowed
switch(ab+cd)
switch(a+b+c)
2. Duplicate case values are not allowed.
3. The default statement is optional. Even if the switch case statement do not have a default
statement,
it would run without any problem.
4. The break statement is used inside the switch to terminate a statement sequence. When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement.
5. The break statement is optional. If omitted, execution will continue on into the next case. The
flow of control will fall through to subsequent cases until a break is reached.
6. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.
Example of Switch Case with break
I’m taking the same above that we have seen above but this time we are using break.
#include <stdio.h>
int main()
{
inti=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
Difference between switch and if
● if statements can evaluate float conditions. switch statements cannot evaluate floatconditions.
● if statement can evaluate relational operators. switch statement cannot evaluate relational operators
i.e they are not allowed in switch statement.

Loops in C Program
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition
is reached.
● An operation is done, such as getting an item of data and changing it, and then some condition is
checked such as whether a counter has reached a prescribed number.
● Counter not reached: If the counter has not reached the desired number, the next instruction in
the sequence returns to the first instruction in the sequence and repeat it.
● Counter reached: If the condition has been reached, the next instruction “falls through” to the
next sequential instruction or branches outside the loop.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end
of loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. do – while loop is exit controlled loop.
for Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a specific
number of times. The loop enables us to perform n number of steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value,
then check whether this variable is less than or greater than counter value. If statement is true, then
loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
● Initialization Expression: In this expression we have to initialize the loop counter to some
value. for example: inti=1;
● Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i<= 10;
● Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: i++;

Example: for loop

// Program to calculate the sum of first n natural numbers


// Positive integers 1,2,3...n are known as natural numbers

#include<stdio.h>
int main()
{
intnum, count, sum =0;

printf("Enter a positive integer: ");


scanf("%d",&num);

// for loop terminates when n is less than count


for(count =1; count <=num;++count)
{
sum+= count;
}

printf("Sum = %d", sum);

return0;
}

Output

Enter a positive integer: 10


Sum = 55

While Loop
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loops are used in
situations where we do not know the exact number of iterations of loop beforehand. The loop
execution is terminated on the basis of test condition.
Syntax:
We have already stated that a loop is mainly consisted of three statements – initialization expression,
test expression, update expression. The syntax of the three loops – For, while and do while mainly
differs on the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements

update_expression;
}

Example : while loop


// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n

#include<stdio.h>
int main()
{
int number;
longlong factorial;

printf("Enter an integer: ");


scanf("%d",&number);

factorial=1;

// loop terminates when number is less than or equal to 0


while(number >0)
{
factorial*= number;// factorial = factorial*number;
--number;
}

printf("Factorial= %lld", factorial);

return0;
}

Output

Enter an integer: 5
Factorial = 120

Do while loop
In do while loops also the loop execution is terminated on the basis of test condition. The main
difference between do while loop and while loop is in do while loop the condition is tested at the end
of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled
loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.
Important Points:
● Use for loop when number of iterations is known beforehand, i.e. the number of times the loop
body is needed to be executed is known.
● Use while loops where exact number of iterations is not known but the loop termination
condition is known.
● Use do while loop if the code needs to be executed at least once like in Menu driven programs

Example: do...while loop


// Program to add numbers until user enters zero

#include<stdio.h>
int main()
{
double number, sum =0;

// body of loop is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf",&number);
sum+= number;
}
while(number !=0.0);

printf("Sum = %.2lf",sum);

return0;
}
Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

JUMP STATEMENTS IN C – BREAK, CONTINUE, GOTO, RETURN


Jump Statement makes the control jump to another section of the program unconditionally when
encountered. It is usually used to terminate the loop or switch-case instantly. It is also used to escape
the execution of a section of the program.
there are 4 jump statements offered by C Programming Language:

▪ Break
▪ Continue
▪ Goto
▪ Return

BREAK

A break statement is used to terminate the execution of the rest of the block where it is present and
takes the control out of the block to the next statement. It is mostly used in loops and switch-case to
bypass the rest of the statement and take the control to the end of the loop. The use of break in
switch-case has been explained in the previous tutorial Switch – Control Statement.
Another point to be taken into consideration is that break statement when used in nested loops only
terminates the inner loop where it is used and not any of the outer loops. Let’s have a look at this
simple program to better understand how break works:
#include <stdio.h>
intmain()
{
inti;
for(i=1;i<=15;i++)
{
printf("%d\n",i);
if(i==10)
break;
}
return0;
}
Output:-
1
2
3
4
5
6
7
8
9
10
In this program, we see that as soon as the condition if(i==10) becomes true the control flows out of
the loop and the program ends.

CONTINUE

The Continue statement like any other jump statements interrupts or changes the flow of control
during the execution of a program. Continueis mostly used in loops. Rather than terminating the loop
it stops the execution of the statements underneath and takes the control to the next iteration. Similar
to a break statement, in case of nested loop, the continue passes the control to the next iteration of the
inner loop where it is present and not to any of the outer loops.Let’s have a look at the following
example:
#include <stdio.h>
int main()
{
inti,j;
for(i=1;i<3;i++)
{
for(j=1;j<5;j++)
{
if(j==2)
continue;
printf("%d\n",j);
}
}
return0;
}
Output:-
1
3
4
1
3
4
In this program, we see that the printf() instruction for the condition j=2 is skipped each time during
the execution because of continue. We also see that only the condition j=2 gets affected by
the continue. The outer loop runs without any disruption in its iteration.

GOTO

This jump statement is used to transfer the flow of control to any part of the program desired. The
programmer needs to specify a label or identifier with the goto statement in the following manner:
goto label;
This label indicates the location in the program where the control jumps to. Have a look at this simple
program to understand how goto works:
#include <stdio.h>
intmain()
{
inti,j;
for(i=1;i<5;i++)
{
if(i==2)
gotothere;
printf("%d\n",i);
}
there:
printf("Two");
return0;
}
Output:-
1
Two
In this program, we see that when the control goes to the goto there; statement when i becomes equal
to 2 then the control next goes out of the loop to the label(there: ) and prints Two.

RETURN

This jump statement is usually used at the end of a function to end or terminate it with or without a
value. It takes the control from the calling function back to the main function(main function itself can
also have a return).
An important point to be taken into consideration is that return can only be used in functions that is
declared with a return type such as int,float, double, char, etc. The functions declared with void type
does not return any value. Also, the function returns the value that belongs to the same data type as it
is declared. Here is a simple example to show you how return statement works.
#include <stdio.h>
charfunc(intascii)
{
return((char)ascii);
}
intmain()
{
intascii;
charch;
printf("Enter any ascii value in decimal: \n");
scanf("%d",&ascii);
ch=func(ascii);
printf("The character is : %c",ch);
return0;
}
Output:-
Enter any ascii value in decimal:
110
The character is : n
In this program we have two functions that have a return type but only one function is returning a
value[func()] and the other is just used to terminate the function[main()]. The function func() is
returning the character value of the given number(here 110). We also see that return type of func() is
char because it is returning a character value.
The return in main() function returns zero because it is necessary to have a return value here because
main has been given the return type int.
References:
1. https://nptel.ac.in/courses/106104128/18
2. https://www.codingeek.com/tutorials/c-programming/jump-statements-in-c-break-continue-got
o-return/
3. https://www.tutorialcup.com/cprogramming/break-continue-goto.htm
4. https://www.programiz.com/c-programming/c-break-continue-statement
5. https://www.geeksforgeeks.org/loops-in-c-and-cpp/
6. https://www.programiz.com/c-programming/c-for-loop
7. https://nptel.ac.in/courses/106104128/6
8. https://www.studytonight.com/c/switch-statement-in-c.php
9. https://www.programiz.com/c-programming/c-switch-case-statement
10. https://www.geeksforgeeks.org/switch-statement-cc/
11. https://beginnersbook.com/2014/01/switch-case-statements-in-c/
Unit III
ARRAYS
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students are represented using an array name students. A particular value is
indicated by writing a number called index number or subscript in brackets after array name. The
complete set of value is referred to as an array, the individual values are called elements.
ONE – DIMENSIONAL ARRAYS :
A list of items can be given one variable index is called single subscripted variable or a
one-dimensional array. The subscript value starts from 0.
If we want 5 elements the declaration will be-- intnumber[5];
The elements will be number[0], number[1], number[2], number[3], number[4]
There will not be number[5]
Declaration of One - Dimensional Arrays :
Type variable – name [sizes];
Type – data type of all elements Ex: int, float etc.,
Variable – name – is an identifier
Size – is the maximum no of elements that can be stored.
Ex:- float avg[50]
This array is of type float. Its name is avg. and it can contains 50 elements only. The range starting
from 0 – 49 elements.
Initialization of Arrays :
Initialization of elements of arrays can be done in same way as ordinary variables are done when they
are declared.
Type array name[size] = {List of Value};
Ex:-int number[3]={0,0,0};
If the number of values in the list is less than number of elements then only that elements will be
initialized. The remaining elements will be set to zero automatically.
Ex:- float total[5]= {0.0,15.75,-10};
The size may be omitted
Example:
main()
{
inti;
float x[10],value,total;
printf(“Enter 10 real numbers\n”);
for(i=0;i<10;i++)
{
scanf(“%f”,&value);
x[i]=value;
}
total=0;
for(i=0;i<10;i++)
total=total+x[i]
for(i=0;i<10;i++)
printf(“x*%2d+=%5.2f\n”,I+1,x*I+);
printf(“total=%0.2f”,total);
}
TWO – DIMENSIONAL ARRAYS:
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
type array name [row-size][col-size];
Example:
/* Write a program Showing 2-DIMENSIONAL ARRAY */
/* SHOWING MULTIPLICATION TABLE */
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
{
introw,cols,prod[ROWS][COLS];
inti,j;
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
{
row = i+1;
printf(“%2d|”,row);
for(j=1;j < = COLS;j++)
{
COLS=j;
prod[i][j]= row * cols;
printf(“%4d”,prod*i+*j+);
}
}
}
INITIALIZING TWO DIMENSIONAL ARRAYS:
They can be initialized by following their declaration with a list of initial values enclosed in braces.
Ex:-int table[2][3] = {0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to one. The initialization is done by row by
row. The above statement can be written as
int table[2][3] = {{0,0,0},{1,1,1}};
When all elements are to be initialized to zero, following short-cut method may be used.
int m[3][5] = {{0},{0},{0}};
STRINGS (CHARACTER ARRAYS) :
A String is an array of characters. Any group of characters (except double quote sign)defined between
double quotes is a constant string.
Ex: “C is a great programming language”.
If we want to include double quotes.
Ex: “\”C is great \” is norm of programmers “.
Declaring and initializing strings :-
A string variable is any valid C variable name and is always declared as an array.
char string name [size];
Here, size determines number of characters in the string name. When the compiler assigns a character
string to a character array, it automatically supplies a null character (‘\0’) at end of String. Therefore,
size should be equal to maximum number of character in String plus one. String can be initialized
when declared as
1. char city*10+= “NEW YORK’;
2. char city[10]= ,‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’/0’-;
3.C also permits us to initializing a String without specifying size.
Ex:- char Strings* += ,‘G’,’O’,’O’,’D’,’\0’-;
READING STRINGS FROM USER:
%s format with scanf can be used for reading String.
char address[15];
scanf(“%s”,address);
The problem with scanf function is that it terminates its input on first white space it finds. Soscanf
works fine as long as there are no spaces in between the text.
Reading a line of text :
If we are required to read a line of text we use getchar(). which reads a single characters. Repeatedly
to read successive single characters from input and place in character array.
Example:
/* Program to read String using scanf&getchar */
#include<stdio.h>
main()
{
char line[80],ano_line[80],character;
int c;
c=0;
printf(“Enter String using scanf to read \n”);
scanf(“%s”, line);
printf(“Using getchar enter new line\n”);
do
{
character = getchar();
ano_line[c] = character;
c++;
- while(character !=’\n’);
c=c-1;
ano_line*c+=’\0’;
}
STRING INPUT/OUTPUT FUNCTIONS:
C provides two basic ways to read and write strings.First we can read and write strings with the
formatted input/output functions,scanf/fscanf and prinf/fprinf.Second we can use a special set of strin
only functions ,get string(gets/fgets)and put string(puts/fputs).
Formatted string Input/Output:
Formatted String Input:scanf/fscanf:
Declarations:
intfscanf(FILE *stream, const char *format, ...);
intscanf(const char *format, ...);
The scanf functions provide a means to input formatted information from a stream fscanf reads
formatted input from a stream scanf reads formatted input from stdin.
These functions take input in a manner that is specified by the format argument and store eachinput
field into the following arguments in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which specifies howthe
input is to be stored in the appropriate variable. Other characters in the format stringspecify characters
that must be matched from the input, but are not stored in any of the following arguments. If the input
does not match then the function stops scanning and returns.
A whitespace character may match with any whitespace character (space, tab, carriage return,new line,
vertical tab, or formfeed) or the next incompatible character.
Formatted String Output:printf/fprintf:
Declarations:
intfprintf(FILE *stream, const char *format, ...);
intprintf(const char *format, ...);
The ..printf functions provide a means to output formatted information to a stream.
fprintf sends formatted output to a stream
printf sends formatted output to stdout
These functions take the format string specified by the format argument and apply each following
argument to the format specifiers in the string in a left to right fashion. Each character in the format
string is copied to the stream except for conversion characters which specify a format specifier.
String Input/Output
In addition to the Formatted string functions,C has two sets of string functions that read and write
strings without reformatting any data.These functions convert text file lines to strings and strings to
text file lines.
gets():
Declaration:
char *gets(char *str);
Reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline
character is read or when the end-of-file is reached, whichever comes first. The newline character is
not copied to the string. A null character is appended to the end of the string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file
occurs before any characters have been read, the string remains unchanged.
puts:
Declaration:
int puts(const char *str);
Writes a string to stdout up to but not including the null character. A newline character is appended to
the output.
On success a nonnegative value is returned. On error EOF is returned.
STRING HANDLING/MANIPULATION FUNCTIONS:
strcat( ) Concatenates two Strings
strcmp( ) Compares two Strings
strcpy( ) Copies one String Over another
strlen( ) Finds length of String
strcat() function:
This function adds two strings together.
Syntax: char *strcat(const char *string1, char *string2);
strcat(string1,string2);
string1 = VERY
string2 = FOOLISH
strcat(string1,string2);
string1=VERY FOOLISH
string2 = FOOLISH
Strncat: Append n characters from string2 to stringl.
char *strncat(const char *string1, char *string2, size_t n);
strcmp() function :
This function compares two strings identified by arguments and has a value 0 if they are equal. If they
are not, it has the numeric difference between the first non-matching characters in the Strings.
Syntax:intstrcmp (const char *string1,const char *string2);
strcmp(string1,string2);
Ex:-strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“ROM”,”Ram”);
Strncmp: Compare first n characters of two strings.
intstrncmp(const char *string1, char *string2, size_t n);
strcpy() function :
It works almost as a string assignment operators. It takes the form
Syntax: char *strcpy(const char *string1,const char *string2);
strcpy(string1,string2);
string2 can be array or a constant.
Strncpy: Copy first n characters of string2 to stringl .
char *strncpy(const char *string1,const char *string2, size_t n);
strlen() function :
Counts and returns the number of characters in a string.
Syntax:intstrlen(const char *string);
n= strlen(string);
n🡪integer variable which receives the value of length of string.
EXAMPLE:
/* Illustration of string-handling */
#include<stdio.h>
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int X,L1,L2,L3;
printf(“Enter two string constants\n”);
scanf(“%s %s”,s1,s2);
X=strcmp(s1,s2);
if (X!=0)
{
printf(“Strings are not equal\n”);
strcat(s1,s2);
}
else
printf(“Strings are equal \n”);
strcpy(s3,s1);
L1=strlen(s1);
L2=strlen(s2);
L3=strlen(s3);
printf(“s1=%s\t length=%d chars \n”,s1,L1);
printf(“s2=%s\t length=%d chars \n”,s2,L2);
printf(“s3=%s\t length=%d chars \n”,s3,L3);
}
References:
1. https://www.cs.uic.edu/~jbell/CourseNotes/C_Programming/Arrays.html
2. https://www.studytonight.com/c/arrays-in-c.php
3. https://www.studytonight.com/c/arrays-in-c.php
4. https://www.programiz.com/c-programming/c-arrays
5. https://www.tutorialspoint.com/cprogramming/c_arrays.htm
Unit IV
Application of Algorithms

Binary Search
Binary Search is applied on the sorted array or list of large size. It's time complexity
of O(logn) makes it very fast as compared to other sorting algorithms. The only
limitation is that the array or list of elements must be sorted for the binary search
algorithm to work on it.

Algorithm:
BinarySearch(A, x):

where ‘A’ defines the array and ‘x’ is the element to be searched.

1. n = len(A)
2. beg = 0
3. end = n - 1
4. result = 0
5. while (beg <= end)
a. mid = (beg + end) / 2
b. if (A[mid] <= x)
i. beg = mid + 1
ii. result = mid
c. else
i. end = mid - 1
6. return result
Bubble Sorting:

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based


algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets as its
2
average and worst case complexity are of O(n ) where n is the number of items.

Bubble Sort Working Concept:


2
We take an unsorted array for our example. Bubble sort takes Ο(n ) time so we're
keeping it short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is
greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.
The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
To be precise, we are now showing how an array should look like after each iteration.
After the second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that an array is completely sorted.
Algorithm:
We assume list is an array of n elements. We further assume that swap function swaps
the values of the given array elements.

beginBubbleSort(list)

for all elements of list


if list[i] > list[i+1]

swap(list[i], list[i+1])
end if
end for

return list

endBubbleSort
Insertion Sort:
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained
which is always sorted. For example, the lower part of an array is maintained to be
sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
2
its average and worst case complexity are of Ο(n ), where n is the number of items.

Insertion Sort Working:


We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted
sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.


It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see
that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the
sorted sub-list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

9
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list.

Algorithm
Now we have a bigger picture of how this sorting technique works, so we can
derive simple steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Selection sort:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place
comparison-based algorithm in which the list is divided into two parts, the sorted part at
the left end and the unsorted part at the right end. Initially, the sorted part is empty and
the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundary by one element to the right.

This algorithm is not suitable for large data sets as its average and worst case
2
complexities are of O(n ), where n is the number of items.

Selection Sort Working:


Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.

So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner.

We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.

14
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −

15
Algorithm
Step 1 −Set MIN to location 0
Step 2 −Search the minimum element in the list
Step 3 −Swap with value at location MIN
Step 4 −Increment MIN to point to next element
Step 5 −Repeat until list is sorted

Algorithmic Complexity
Algorithmic complexity is concerned about how fast or slow particular algorithm
performs. A given algorithm will take different amounts of time on the same inputs
depending on such factors as: processor speed; instruction set, disk speed, brand of
compiler and etc. The way around is to estimate efficiency of each
algorithm asymptotically. We will measure time as the number of elementary "steps"
(defined in any way), provided each such step takes constant time.

Sometimes, there are more than one way to solve a problem. We need to learn how to
compare the performance different algorithms and choose the best one to solve a
particular problem. While analyzing an algorithm, we mostly consider time complexity
and space complexity. Time complexity of an algorithm quantifies the amount of time
taken by an algorithm to run as a function of the length of the input. Similarly, Space
complexity of an algorithm quantifies the amount of space or memory taken by an
algorithm to run as a function of the length of the input.

Example
Constant Time: O(1)
An algorithm is said to run in constant time if it requires the same amount of time
regardless of the input size. Examples:
● array: accessing any element
● fixed-size stack: push and pop methods
● fixed-size queue: enqueue and dequeue methods
Linear Time: O(n)
An algorithm is said to run in linear time if its time execution is directly proportional to
the input size, i.e. time grows linearly as input size increases. Examples:
● array: linear search, traversing, find minimum
● ArrayList: contains method
● queue: contains method

Problem:To find roots of Quardratic Equation


ALGORITHM to find the roots of Quardratic Equation:
Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp←b/2a
ip←√(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

Program: Find roots of quardratic equation


#include<stdio.h>
#include<math.h>
voidmain()
{
inta,b,c,d;
float x1,x2;
printf("Input the value of a,b& c : ");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
{
printf("Both roots are equal.\n");
x1=-b/(2.0*a);
x2=x1;
printf("First Root Root1= %f\n",x1);
printf("Second Root Root2= %f\n",x2);
}
elseif(d>0)
{
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("First Root Root1= %f\n",x1);
printf("Second Root root2= %f\n",x2);
}
else
printf("Root are imeainary;\nNo Solution. \n");
}
OUTPUT:
Input the value of a,b& c : 1 5 7
Root are imaginary;
No Solution.
Unit V&VI
FUNCTIONS:
A function is a self-contained program segment that carries out some specific well defined
tasks.
Every program must have a main function to indicate where the program has to begin its
execution. While it is possible to code any program utilizing only main function, it leads to a
number of problems. The program may become too large and complex and as a result task of
debugging, testing and maintaining becomes difficult. If a program is divided into functional
parts, then each part may be independently coded and later combined into a single unit, these
subprograms called “functions” are much easier to understand debug and test.
There are times when some types of operation for calculation is repeated many times at many
points throughout a program. For instance, we might use the factorial of a number at several
points in the program. In such situations, we may repeat the program statements whenever
they are needed. Another approach is to design a function that can be called and used
whenever required.
The advantages of using functions are
1. It facilitates top-down modular programming.
2. The length of a source program can be reduced by using functions at appropriate
places.
3. It is easy to locate and isolate a faculty function for further investigations.
4. A function may be used by many other programs.
The form of the C functions.

Types of Functions:
1. User-defined Functions
C allow programmers to define functions. Such functions created by the user are
called user-defined functions.
Syntax:
Function-type function-name ( argument list )
{
local variable declarations;
executable statement 1;
executabie statement 2;
----------
----------
----------
return (expression) ;
}
The return statement is the mechanism for returning a value to the calling function.
All functions by default returns int type data. we can force a function to return a
particular type of data by using a type specifier in the header.

A function can be called by simply using the function name in the statement.
Example:

#include <stdio.h>
voidfunctionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}

2. Standard Library Functions


The standard library functions are built-in functions in C programming to handle tasks
such as mathematical computations, I/O processing, string handling etc.These
functions are defined in the header file. When you include the header file, these
functions are available for use.
For example:
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in "stdio.h" header file.There
are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all
these functions are available for use.

ANSI C Standard Library Functions:

The C language is accompanied by a number of library functions that perform various


tasks.The ANSI committee has standardized header files which contain these
functions.

Some of the Header files are:

<ctype.h> character testing and conversion functions.


<math.h> Mathematical functions
<stdio.h> standard I/O library functions
<stdlib.h> Utility functions such as string conversion routines memory
allocation routines , random number generator,etc.
<string.h> string Manipulation functions
<time.h> Time Manipulation functions

Function Definition :
typefunc_name( parameter list )
{
//declarations;
//statements;
}
Function Header :

Function Calls :
When a function is called, expressions in the parameter list are evaluated (in no particular
order!) and results are transformed to the required type. Parameters are copied to local
variables for the function and function body is executed when return is encountered, the
function is terminated and the result (specified in the return statement) is passed to the calling
function (for example main).
Ex:
int fact (int n)
{
inti, product = 1;
for (i = 2; i<= n; ++i)
product *= i;
return product;
}
int main (void)
{
inti = 12;
printf(“%d”,fact(i));
return 0;
}
Parameter Passing Techniques:
Parameter passing mechanism in „C‟ is of two types.
1. Call by Value
2. Call by Reference.
The process of passing the actual value of variables is known as Call by Value.
The process of calling a function using pointers to pass the addresses of variables is known as
Call by Reference. The function which is called by reference can change the value of the variable
used in the call.

Example of Call by Value:


#include <stdio.h>
void swap(int,int);
main()
{
inta,b;
printf(“Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“Before Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
swap(a,b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

Example of Call by Reference:


#include<stdio.h>
main()
{
inta,b;
a = 10;
b = 20;
swap (&a, &b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

RECURSION:
Recursion is a repetitive process in which a function calls itself (or) a function is called
recursive if it calls itself either directly or indirectly. In C, all functions can be used
recursively.
In programming languages, if a program allows you to call a function inside the same
function, then it is called a recursive call of the function.
Example:
void recursion(){
recursion();/* function calls itself */
}
int main(){
recursion();
}

Examples on Recursion:
FACTORIAL
The following example calculates the factorial of a given number using a recursive function-

#include<stdio.h>

unsignedlonglongint factorial(unsignedinti){

if(i<=1){

return1;

returni* factorial(i-1);

int main(){

inti=12;

printf("Factorial of %d is %d\n",i, factorial(i));

return0;

When the above code is compiled and executed, it produces the following result −

Factorial of 12 is 479001600

FIBONACCI SERIES
The following example generates the Fibonacci series for a given number using a recursive
function −

#include<stdio.h>

intfibonacci(inti){

if(i==0){

return0;

if(i==1){

return1;

returnfibonacci(i-1)+fibonacci(i-2);

int main(){

inti;

for(i=0;i<10;i++){

printf("%d\t\n",fibonacci(i));

return0;

When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34

Ackermann Function:
The Ackerman function is a well-known recursive function defined for m>= 0, n >= 0 as
follows:
A(m,n) = n+1, if m==0
A(m,n) = A(m-1,1), if m>0 and n==0
A(m-1,A(m,n-1)), if m>0 and
A(m,n) =
n>0

Find A(m,n) for the given m and n. The Ackerman function should be defined using
recursion only (hence use of arrays is not allowed). Also print the number of recursive calls
made to the function.

Input Format: The input contains the indices m and n separated by space.

Output Format: Output the following two values, separated by a space:

1. the value of A(m,n)


2. the number of recursive calls to Ackerman function, A.

Example:

//implementation of the recursive ackermann function


intack(intm, intn)
{
if(m == 0){
returnn+1;
}
elseif(m > 0){
ack(m-1, 1);
}
elseif((m > 0) && (n > 0)){
ack(m-1, ack(m, n-1));
}
}//end ack

Merge Sort
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used
for merging two halves. The merge(a[], l, m, h) is key process that assumes that a[l..m]
andarr[m+1..h] are sorted and merges the two sorted sub-arrays into one.Merge sort required
splitting and then merging of a pair of sorted arrays.
Merging steps involves:
1. Take two elements one from each array A and B.
2. Compare them and place smaller of two (say from A) in sorted list.
3. Take next element from A and compare with element in hand (from B).
4. Repeat until one of the array is exhausted.
5. Now place all remaining elements of non-empty array one by one.
C programming code:
Merging:
Merge sort

Main function:

UNIT –VII & VIII


STRUCTURES
A Structure is a collection of elements of dissimilar data types. Structures provide the ability
to create user defined data types and also to represent real world data.
Suppose if we want to store the information about a book, we need to store its name (String),
its price (float) and number of pages in it(int). We have to store the above three items as a
group then we can use a structure variable which collectively store the information as a book.
Structures can be used to store the real world data like employee, student, person etc.
Declaration :
The declaration of the Structure starts with a Key Word called Struct and ends with ; . The
Structure elements can be any built in types.
struct<Structure name>
{
Structure element 1;
Structure element 2;
-
-
-
Structure element n;
};
Then the Structure Variables are declared as
struct< Structure name ><Var1,Var2>;
Example:-
structemp
{
intempno.
charename[20];
floatsal;
};
structemp e1,e2,e3;
The above Structure can also be declared as :
structemp
{
intempno;
charename[20];
floatsal;
}e1,e2,e3;
Initialization :
Structure Variables can also be initialised where they are declared.
structemp
{
intempno;
charename[20];
floatsal;
};
structemp e1 = { 123,”Kumar”,5000.00};
● To access the Structure elements we use the .(dot) operator.
● To refer empno we should use e1.empno
● To refer sal we whould use e1.sal
Structure elements are stored in contiguous memory locations as shown below. The above
Structure occupies totally 26 bytes.

ARRAY OF STRUCTURES :
To store more number of Structures, we can use array of Structures. In array of Structures all
elements of the array are stored in adjacent memory location.
/* Program to illustrate the usage of Array of Structures.

Void main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];
inti;
for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”);
scanf(“%s%f%d”, b[i].name,&b[i].price,&b[i].pages);
}
for (ii=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}

POINTERS:
One of the powerful features of C is ability to access the memory variables by their memory
address. This can be done by using Pointers. The real power of C lies in the proper use of
Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a
pointer points to a variable that is stored at that address. A pointer itself usually occupies 4
bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
Eg:-
int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
A pointer is a variable that contains an address which is a location of another variable in
memory.
Consider the Statement
p=&i;
Here “&‟ is called address of a variable.
“p‟ contains the address of a variable i.
The operator & returns the memory address of variable on which it is operated, this is called
Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to
display the contents of the Pointer Variable.
Consider the following Statements :
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following printf
statements is :
Printf() statement Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5

Representing Linked List using Pointers:


Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not
stored at contiguous location; the elements are linked using pointers.

Representation:
A linked list is represented by a pointer to the first node of the linked list. The first node is
called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:

1) Data
2) Pointer (Or Reference) to the next node

In C, we can represent a node using structures. Below is an example of a linked list node with
an integer data.

Example:

// A linked list node


struct Node
{
int data;
struct Node *next;
};

UNIT –IX
File Handling in C Language

A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. It is a readymade structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are
the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning point
Opening a File or Creating a File
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of
opening the file. Mode can be of following types,
*fpis the FILE pointer (FILE *fp), which will hold the reference to the opened (or
created)file.
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
intfclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are simplest functions used to read and write
individual characters to a file.
#include<stdio.h>
#include<conio.h>

main()
{
FILE *fp;
charch;
fp = fopen("one.txt", "w");

printf("Enter data");

while( (ch = getchar()) !=


EOF) { putc(ch,fp);

}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc()) != EOF)

printf("%c",ch);
fclose(fp);
}
Reading and Writing from File using fprintf() and fscanf()
#include<stdio.h>
#include<conio.h>

structemp
{
char name[10];
int age;

};

void main()

{
structemp e;
FILE *p,*q;

p = fopen("one.txt", "a"); q
= fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name,
e.age);fclose(p);

do
{

fscanf(q,"%s %d", e.name,


e.age);printf("%s %d", e.name,
e.age);

while( !feof(q)
); getch();

}
In this program, we have create two FILE pointers and both are refering to the same file but
in different modes. fprintf() function directly writes into the file, while fscanf() reads from
the file, which can then be printed on console usinf standard printf() function.

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will
not happen. Append mode is used to append or add data to the existing data of file(if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the
present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The
Opening modes are mentioned in the table for opening modes above.

fread() andfwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-written, size_of_elements,
number_of_elements,
pointer-to-file);

fread() is also used in the same way, with the same arguments like fwrite() function.
Belowmentioned is a simple example of writing into a binary file

const char *mytext = "The quick brown fox jumps over the
lazy dog";

FILE *bfp= fopen("test.txt",


"wb"); if (bfp) {

fwrite(mytext,sizeof(char),strlen(mytext),bfp)
;fclose(bfp) ;

}
fseek(), ftell() and rewind() functions

• fseek() - It is used to move the reading control to different positions using fseek
function.
• ftell() - It tells the byte location of current position of cursor in file pointer.
• rewind() - It moves the control to beginning of the file.

You might also like