0% found this document useful (0 votes)
35 views81 pages

Notes All Units

Uploaded by

sanyamkumar75
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
35 views81 pages

Notes All Units

Uploaded by

sanyamkumar75
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 81

Unit I

Definition of a computer
Computer term is derived from the word compute. A computer is an electronic device that takes data
and instructions as an input from the user, processes data and provide useful information known as
output.
Or
A computer generally means a programmable machine. The two principal characteristics of a computer
are: it responds to a specific set of instructions in a well-defined manner and it can execute a
prerecorded list of instructions (a program).

Modern computers have more capabilities, like:


1) Perform complex and repetitive calculations, rapidly and accurately.
2) Store large amount of data and information for subsequent manipulations.
3) Hold a program of a model which can be explored in many different ways.
4) Compare items and make decisions.
5) Provide information to the user in many different ways.
6) Automatically correct or modify the parameters of a system under control.
7) Draw and print graphs.
8) Converse with users interactively and
9) Receive and display audio and video signals.

Characteristics of Computer

SPEED : In general, no human being can compete to solving the complex computation, faster than
computer.
ACCURACY : Since Computer is programmed, so what ever input we give it gives result with
accurately.
STORAGE : Computer can store mass storage of data with appropriate formate.
DILIGENCE : Computer can work for hours without any break and creating error.
VERSATILITY : We can use computer to perform completely different type of work at the same time.
POWER OF REMEMBERING : It can remember data for us.
NO IQ : Computer does not work without instruction.
NO FEELING : Computer does not have emotions, knowledge, experience, feeling.

Classification of computer by their Basic Operating Principle

Using this classification technique, computers can be divided into Analog, Digital and Hybrid systems.
They are explained as follows:
I Analog Computers:
Analog computers were well known in the 1940s although they are now uncommon. An analog
computer is a form of computer that uses the continuously changeable aspects of physical phenomena
such as electrical, mechanical, or hydraulic quantities to model the problem being solved. In contrast,
digital computers represent varying quantities symbolically, as their numerical values change, these
computers performs the computing operations of additions, subtraction, multiplication, division,
integration and function generation....
The computing units of analog computers respond immediately to the changes which they detect in the
input variables. Analog computers excel in solving differential equations and are faster than digital
computers.

II Digital Computers:
A digital computer is an electronic device that stores data in terms of digits (numbers). Digital
computers also proceed in discrete steps which involve binary digits from one state to the next. The
computer uses binary number system to perform its calculations as well as logical operations.

Most computers today are digital. Digital computers manipulate most data more easily than analog
computers. They are designed to process data in numerical form and their circuits perform directly the
mathematical operations of addition, subtraction, multiplication, and division. Because digital
information is discrete, it can be copied exactly but it is difficult to make exact copies of analog
information.

III Hybrid Computers:


A hybrid computer is a type of computer that is designed to provide the features and functions that are
found by both the digital and the analog computers. A hybrid computer system offers a much cost
effective method that is used to perform complex simulations.

Classifications of Digital Computers:

According to size:

1. Microcomputer - is the smallest, low cost digital computers. A MICROCOMPUTER or


PERSONAL COMPUTER, PC for short, is most widely used especially at home because of its
affordable price and manageability
- it consists of : CPU, Keyboard, Monitor, Printer, and the disks drives.
- can only be used by one person at a time.
Examples: (Personal Computers, Workstations, Portable Computers)

2. Minicomputer – medium sized, more powerful than a microcomputer designed specifically for
the multi-user environment.
- can allow several person using the machine at the time.
- serves as stand-alone computer.
- 40 to 100 employees or remote terminals.
- these perform multi-tasking and allow many terminals to be connected to their
services.

3. Mainframe Computer – larger, expensive computer system that can be used in multi-user
environment.
- can serve more than 100 remote terminals. Mainframe computer are large general
purpose computers. Mainframe computers generally require special attention and are
kept in a controlled atmosphere. They are multi-tasking and generally used in areas
where large database are maintained e.g. government departments and the airline
industry.
4. Supercomputers – most powerful, expensive, fastest computers ever invented. Operate at
speeds measured in nanoseconds and even in picoseconds.

Describe the basic functions ( operations) performed by a computer system, with the help of a
suitable diagram.
Or
Explain the basic components of a digital computer with its block diagram.
Or
Explain Functional components of digital computer.

Answer:

The basic components of a computer are:


 Input Unit
 Output Unit
 Memory / Storage Unit
 Arithmetic Logic Unit
 Control Unit
 Central Processing Unit
When a computer is asked to do a job, it handles the task in a very special way:
1) It accepts the information from the user. This is called input.
2).It stored the information until it is ready for use. The computer has memory chips, which are
designed to hold information until it is needed.
3).It processes the information. The computer has an electronic brain called the Central Processing
Unit, which is responsible for processing all data and instructions given to the computer.
4).It then returns the processed information to the user. This is called output.
Input Unit
Input Unit accepts the instructions and data from the outside world. Then it converts these instructions
and data in computer acceptable form, after that it supplies the converted instructions and data to the
computer system for further processing.
Ex. Keyboard, Mouse, Scanners, OMR, OCR etc

Output Unit
The output unit is just reverse of the input unit. it accepts the result produced by computer, which are in
coded form and can't be easily understood by us. Then it converts these coded result into human
readable form. After that it supplies the converted results to the outside world.
Ex. Monitor, Printer, Plotter etc.

Memory Unit
The Memory Unit is the part of the computer that holds data and instructions for processing. Although
it is closely associated with the CPU, in actual fact it is seperate from it. Memory associated with the
CPU is also called primary storage, primary memory, main storage, internal storage and main memory.
When we load software from a floppy disk, hard disk or CD-ROM, it is stored in the Main Memory.
There are two types of computer memory inside the computer:
 Primary Memory
 Secondary Memory
Primary Memory
Primary storage, presently known as main memory, is the only one directly accessible to the CPU. The
CPU continuously reads instructions stored there and executes them as required. Any data actively
operated on is also stored there in uniform manner. However, the primary memory can hold
information only while the computer system is ON. As soon as the computer system is switched off or
rest, the information hold in primary memory disappears. Also it has limited storage capacity because it
is very expensive. It is made up of semiconductor devices. Ex. RAMs and Semiconductor memories.
Secondary Memory
Secondary storage, sometimes called auxiliary storage, is all data storage that is not currently in a
computer's primary storage or memory. This is computer memory that is not directly accessible to the
processor but uses the I/O channels. It is for storing data not in active use and preserves data even
without power, meaning it is non-volatile.In a personal computer, secondary storage typically consists
of storage on the hard disk and on any removable media, if present, such as a CD or DVD. Ex Hard
Disk, CDs etc.
Arithmetic Logical Unit
An arithmetic logic unit (ALU) is a digital circuit that performs arithmetic and logical operations. The
ALU is a fundamental building block of the central processing unit (CPU) of a computer, and even the
simplest microprocessors contain one for purposes such as maintaining timers. The processors found
inside modern CPUs and graphics processing units (GPUs) accommodate very powerful and very
complex ALUs; a single component may contain a number of ALUs. Most ALUs can perform the
following operations:
1).Integer arithmetic operations (addition, subtraction, and sometimes multiplication and division).
2).Bitwise logic operations (AND, NOT, OR, XOR)
3).Bit-shifting operations (shifting or rotating a word by a specified number of bits to the left or right,
with or without sign extension). Shifts can be interpreted as multiplications by 2 and divisions by 2.
Control Unit
It manages and co-ordinates the operations of all the other components of the computer system. It reads
and interprets (decodes) instructions in the program one by one. The control system decodes each
instruction and turns it into a series of control signals that operate the other parts of the computer.
Control systems in advanced computers may change the order of some instructions so as to improve
performance. its functions are:
1.Read the code for the next instruction from the cell indicated by the program counter.
2. Decode the numerical code for the instruction into a set of commands or signals for each of the other
systems.
3. Increment the program counter so it points to the next instruction.
4. Read whatever data the instruction requires from cells in memory (or perhaps from an input device).
The location of this required data is typically stored within the instruction code.
5. Provide the necessary data to an ALU or register.
6. If the instruction requires an ALU or specialized hardware to complete, instruct the hardware to
perform the requested operation.
7. Write the result from the ALU back to a memory location or to a register or perhaps an output
device.
8. Jump back to step (1).

Central Processing Unit


The control unit and ALU of a computer system are jointly known as the CPU. The CPU is the brain of
computer system. It takes all calulations and comparisons in a computer systems and it s also
responsible for activating and controlling the operations of other units of computer system.
Operating System

An Operating System acts as a communication bridge (interface) between the user and computer hard-
ware. The purpose of an operating system is to provide a platform on which a user can execute pro-
grams in a convenient and efficient manner.
An operating system is a piece of software that manages the allocation of computer hardware. The
coordination of the hardware must be appropriate to ensure the correct working of the computer system
and to prevent user programs from interfering with the proper working of the system.
An operating system is a set of programs that coordinates all the activities among computer hardware
devices. It also supports the application software that we run.
It is designed to work with a specific type of computer such as a PC or a Macintosh. Examples of
popular Operating Systems are:-
•Disk Operating System (DOS)
•Linux
•Mac OS X
•Unix
•Windows XP

Important functions of an operating System:

Security –
The operating system uses password protection to protect user data and similar other techniques. it also
prevents unauthorized access to programs and user data.

Control over system performance –

Monitors overall system health to help improve performance. records the response time between
service requests and system response to have a complete view of the system health. This can help
improve performance by providing important information needed to troubleshoot problems.

Job accounting –

Operating system Keeps track of time and resources used by various tasks and users, this information
can be used to track resource usage for a particular user or group of user.

Error detecting aids –

Operating system constantly monitors the system to detect errors and avoid the malfunctioning of
computer system.

Coordination between other software and users –

Operating systems also coordinate and assign interpreters, compilers, assemblers and other software to
the various users of the computer systems.
Storage Management
Operating System also Controls the all the Storage Operations means how the data or files will be
Stored into the computers and how the Files will be Accessed by the users etc.
Process Management : The Operating System also Treats the Process Management means all the
Processes those are given by the user or the Process those are System ‘s own Process are Handled by
the Operating System.
Memory Management: Operating System also Manages the Memory of the Computer System means
Provide the Memory to the Process and Also Deallocate the Memory from the Process.
Device Management –

An OS manages device communication via their respective drivers. It performs the following activities
for device management. Keeps tracks of all devices connected to system. designates a program
responsible for every device known as the Input/Output controller. Decides which process gets access
to a certain device and for how long. Allocates devices in an effective and efficient way. Deallocates
devices when they are no longer required.

File Management –

A file system is organized into directories for efficient or easy navigation and usage. These directories
may contain other directories and other files. An Operating System carries out the following file
management activities. It keeps track of where information is stored, user access settings and status of
every file and more… These facilities are collectively known as the file system.

Extended Machine : Operating System also behaves like an Extended Machine means Operating
system also Provides us Sharing of Files between Multiple Users, also Provides Some Graphical
Environments and also Provides Various Languages for Communications and also Provides Many
Complex Operations like using Many Hardware’s and Software’s.
Mastermind: Operating System also performs Many Functions and for those Reasons we can say that
Operating System is a Mastermind. Operating System also controls the Errors, recovery of the System
when the System gets damaged, provides us the Backup Facility.
Types of OS
In multiprogramming system, when one program is waiting for I/O transfer; there is another program
ready to utilize the CPU. So it is possible for several jobs to share the time of the CPU. But it is
important to note that multiprogramming is not defined to be the execution of jobs at the same instance
of time. Rather it does mean that there are a number of jobs available to the CPU (placed in main
memory) and a portion of one is executed then a segment of another and so on.

Multitasking is a logical extension of multiprogramming system that supports multiple programs to


run concurrently. In multitasking more than one task are executed at the same time. In this technique
the multiple tasks (processes), share common processing resources such as a CPU. In the case of a
computer with single CPU, only one job can be processed at a time. Multitasking solves the problem by
scheduling and deciding which task should be the running task and when a waiting task should get turn.
This attempt is done with the help of interrupt (a signal) which is attended by CPU by keeping the
current activity aside, saves its present status in buffer and returns to another important job whatever
task it was doing earlier. The act of re-assigning a CPU from one task to another one is known as
context switch.
A time sharing system allows many users to share the computer resources simultaneously. In other
words, time sharing refers to the allocation of computer resources in time slots to several programs
simultaneously.
The time sharing systems were developed to provide an interactive use of the computer system. A time
shared system uses CPU scheduling and multiprogramming to provide each user with a small portion
of a time-shared computer. It allows many users to share the computer resources simultaneously. As
the system switches rapidly from one user to the other, a short time slot is given to each user for their
executions.
The time sharing system provides the direct access to a large number of users where CPU time is
divided among all the users on scheduled basis. The OS allocates a set of time to each user. When this
time is expired, it passes control to the next user on the system.

Real-time
A Real-Time Operating System (RTOS) is a computing environment that reacts to input within a
specific time period. A real-time deadline can be so small that system reaction appears instantaneous.
The main objective of real-time operating systems is their quick and predictable response to events.

Distributed
A distributed operating system manages a group of independent computers and makes them
appear to be a single computer. Distributed computations are carried out on more than one
machine. When computers in a group work in cooperation, they make a distributed system.

Q Write down a short note on MS DOS. Describe its five commands.


Answer: Microsoft Disk operating system, MS-DOS is a non-graphical command line operating
system. MS-DOS allows the user to navigate, open, and otherwise manipulate files on their computer
from a command line instead of a GUI like Windows.
Disk operating system , originally developed by microsoft for IBM.
DOS is still a 16-bit operating system and does not support multiple users or multitasking.

DOS Commands are divided into 2 types:

1.Internal Commands: An Internal command, which is a command embedded into the


command.com file. These are for performing basic operations on files and directories and
they do not need any external file support.

2. External Commands: An external command, which is not embedded into command.com and
therefore requires a separate file to be used. For example, if your computer does not have the
fdisk.exe file and you try using the fdisk command, you would receive an error "Bad command
or file name" error message. Fdisk is an external command that only works if fdisk.exe, or in
some cases, fdisk.com, is present.
These external commands are for performing advanced tasks and they do need some external
file.
Most Commonly Used Internal DOS Command
 DATE
This command is used to display the system current date setting and prompt you to enter a new
date. The syntax is: DATE[/T | date]

If you type DATE without parameters then it displays current date and prompts to enter new
date. We should give new date in mm-dd-yy format. If you want to keep the same date just
Press ENTER. DATE command with /T switch tells the command to just output the current
system date, without prompting for a new date.

2. TIME

This command is used to displays or set the system time.


The syntax is: TIME[/T | time]

Same as DATE command, typing TIME with no parameters displays the current time and a
prompt for a new one. Press ENTER to keep the same time. TIME command used with /T
switch tells the command to just output the current system time, without prompting for a new
time.

3. COPY CON
It is used to create a file in the existing directory. Here CON is a DOS reserved word which
stands for console.
Syntax is: COPY CON filename after that press Enter and start typing your text and after
you're done typing your text, to save and exit hit F6 key.

4. REN: This command is used to change/modify the name of a file or files.


Syntax is: REN[drive:][path]filename1 filename2.

Here, filename1 is source file for which you wanted to change the name, and filename2 will obviously
becomes your new file name. Also note that you cannot specify a new drive or path for your destination
file.
5. TYPE : This command is used to display the contents of a text file or files. The syntax is: TYPE
[drive:][path]filename.
6. CLS: It is used to clear the screen. Syntax is CLS

Q Explain the architecture of Linux operating system.


Answer:
Linux System Architecture is consists of following layers
 Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
 Kernel - The kernel is the central module of an operating system (OS). It is the part of the
operating system that loads first, and it remains in main memory. Because it stays in memory, it
is important for the kernel to be as small as possible while still providing all the essential
services required by other parts of the operating system and applications. The kernel code is
usually loaded into a protected area of memory to prevent it from being overwritten by
programs or other parts of the operating system.

Typically, the kernel is responsible for memory management, process and task management, and
disk management. The kernel connects the system hardware to the application software. Every
operating system has a kernel. For example the Linux kernel

 Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes
commands from user and executes kernel's functions.
 Utilities - Utility programs giving user most of the functionalities of an operating systems.

Q Explain important features of linux operating system.

Answer: Following are some of the important features of Linux Operating System.
 Portable - Portability means softwares can works on different types of hardwares in same way.
Linux kernel and application programs supports their installation on any kind of hardware
platform.
 Open Source - Linux source code is freely available and it is community based development
project. Multiple team works in collaboration to enhance the capability of Linux operating
system and it is continuously evolving.
 Multi-User - Linux is a multiuser system means multiple users can access system resources like
memory/ ram/ application programs at same time.
 Multiprogramming - Linux is a multiprogramming system means multiple applications can
run at same time.
 Hierarchical File System - Linux provides a standard file structure in which system files/ user
files are arranged.
 Shell - Linux provides a special interpreter program which can be used to execute commands of
the operating system. It can be used to do various types of operations, call application programs
etc.
 Security - Linux provides user security using authentication features like password protection/
controlled access to specific files/ encryption of data.
Short Notes on windows
Microsoft Windows is a popular operating system software for computers. Windows is made by
the Microsoft company. Almost 90% of desktop and laptop computers have Windows installed
(included). The newest version of Windows is Windows 8.1, though Windows 10 is currently being
developed and will come out later in 2015.

Windows makes it easier to run programs (applications) than DOS did. It also helps people keep their
files safe and in order.
Some programs are included with Windows. Some examples are:

 Wordpad – to write simple documents.


 Photo viewer – to look at pictures.
 Paint – to make simple drawings.
 Internet Explorer web browser – to use the Internet to look at web pages and download files.
 Windows Media Player – to listen to music and watch videos.

Short notes on Android Operating system


Android is a mobile operating system developed by Google. It is used by several smartphones, such as
the Motorola Droid, the Samsung Galaxy, and Google's own Nexus One.
The Android operating system (OS) is based on the open Linux kernel. Unlike the iPhone OS, Android
is open source, meaning developers can modify and customize the OS for each phone. Therefore, dif-
ferent Android-based phones may have different graphical user interfaces GUIs even though they use
the same OS.
Android phones typically come with several built-in applications and also support third-party pro-
grams. Developers can create programs for Android using the free Android SDK (Software Developer
Kit). Android programs are written in Java and run through Google's "Davlik" virtual machine, which
is optimized for mobile devices. Users can download Android "apps" from the online Android Market.
Definitions hardware, software, Assembler, Compiler, Interpreter
Main parts of digital computer are:
Hardware
Software

Computer hardware is the collection of physical elements that constitutes a computer system.
Computer hardware refers to the physical parts or components of a computer such as the monitor,
mouse, keyboard, computer data storage, hard drive disk (HDD), system unit (graphic cards, sound
cards, memory, motherboard and chips), etc. all of which are physical objects that can be touched
(known as tangible). In contrast, software is instructions that can be stored and run by hardware.

Software is any set of machine-readable instructions that directs a computer's processor to perform
specific operations. A combination of hardware and software forms a usable computing system.

The two main classifications of softwares are:

System software
Application software

System software (systems software) is computer software designed to operate and control the computer
hardware and to provide a platform for running application software. System software can be separated
into two different categories, operating systems and utility software.
System software controls a computer and provides the environment for users to run application
software. It is a collection of programs, with different functions and purposes, most notably the
Operating System (OS) that controls an entire computer. Also included in system software are utilities
and device drivers. In contrast to this, computer users typically run application software to perform
tasks, play games, listen to music, and otherwise make use of a computer.

Application software, or simply applications, are often called productivity programs or end-user
programs because they enable the user to complete tasks such as creating documents, spreadsheets,
databases, and publications, doing online research, sending email, designing graphics, running
businesses, and even playing games! Application software is specific to the task it is designed for and
can be as simple as a calculator application or as complex as a word processing application.

General purpose application software

General purpose application software is a type of software that can be used for a variety of tasks. It is
not limited to one particular function. For example a word processor could be classed as general
purpose software as it would allow a user to write a novel, create a restaurant menu or even make a
poster.

Special purpose application software

Special purpose application software is a type of software created to execute one specific task. For
example a camera application on your phone will only allow you to take and share pictures. Another
example would be a chess game, it would only allow you to play chess.
Translators in system softwares

Assembler

An assembler translates assembly language into machine code. Assembly language consists of
mnemonics for machine opcodes so assemblers perform a 1:1 translation from mnemonic to a direct
instruction. For example:

LDA #4 converts to 0001001000100100

Conversely, one instruction in a high level language will translate to one or more instructions at
machine level.

Advantages of using an Assembler:


1. Very fast in translating assembly language to machine code as 1 to 1 relationship
2. Assembly code is often very efficient (and therefore fast) because it is a low level language
3. Assembly code is fairly easy to understand due to the use of English-like mnemonics

Disadvantages of using Assembler:


1. Assembly language is written for a certain instruction set and/or processor
2. Assembly tends to be optimised for the hardware it's designed for, meaning it is often incompatible
with different hardware
3. Lots of assembly code is needed to do relatively simple tasks, and complex programs require lots of
programming time

Compiler

A Compiler is a computer program that translates code written in a high level language to a lower level
language, object/machine code. The most common reason for translating source code is to create an
executable program (converting from a high level language into machine language).

Advantages of using a compiler


1. Source code is not included, therefore compiled code is more secure than interpreted code
2. Tends to produce faster code than interpreting source code
3. Produces an executable file, and therefore the program can be run without need of the source code

Disadvantages of using a compiler


1. Object code needs to be produced before a final executable file, this can be a slow process
2. The source code must be 100% correct for the executable file to be produced

Interpreter

An interpreter program executes other programs directly, running through program code and executing
it line-by-line. As it analyses every line, an interpreter is slower than running compiled code but it can
take less time to interpret program code than to compile and then run it — this is very useful when
prototyping and testing code. Interpreters are written for multiple platforms, this means code written
once can be run immediately on different systems without having to recompile for each. Examples of
this include flash based web programs that will run on your PC, MAC, games console and Mobile
phone.

Advantages of using an Interpreter


1. Easier to debug(check errors) than a compiler
2. Easier to create multi-platform code, as each different platform would have an interpreter to run the
same code
3. Useful for prototyping software and testing basic program logic

Disadvantages of using an Interpreter


1. Source code is required for the program to be executed, and this source code can be read making it
insecure
2. Interpreters are generally slower than compiled programs due to the per-line translation method

Linker: In high level languages, some built in header files or libraries are stored. These libraries are
predefined and these contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function then it informs to compiler and then compiler generates an error. The compiler automatically
invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a
longer program is divided into smaller subprograms called modules. And these modules must be
combined to execute the program. The process of combining the modules is done by the linker.

Loader: Loader is a program that loads machine codes of a program into the system memory. In
Computing, a loader is the part of an Operating System that is responsible for loading programs. It is
one of the essential stages in the process of starting a program. Because it places programs into
memory and prepares them for execution. Loading a program involves reading the contents of
executable file into memory. Once loading is complete, the operating system starts the program by
passing control to the loaded program code. All operating systems that support program loading have
loaders. In many operating systems the loader is permanently resident in memory.

A mistake in coding is called Error, error found by tester is called Defect, defect accepted by
development team then it is called Bug, build does not meet the requirements then it Is Failure.

There are mainly five types of errors exist in C programming:


 Syntax error.
 Run-time error.
 Linker error.
 Logical error.
 Semantic error.

Syntax error

Syntax errors are also known as the compilation errors as they occurred at the compilation time, or we
can say that the syntax errors are thrown by the compilers. These errors are mainly occurred due to the
mistakes while typing or do not follow the syntax of the specified programming language. These mis-
takes are generally made by beginners only because they are new to the language. These errors can be
easily debugged or corrected.

For example:

1. If we want to declare the variable of type integer,


2. int a; // this is the correct form
3. Int a; // this is an incorrect form.

Commonly occurred syntax errors are:

o If we miss the parenthesis (}) while writing the code.


o Displaying the value of a variable without its declaration.
o If we miss the semicolon (;) at the end of the statement.
Run-time error

Sometimes the errors exist during the execution-time even after the successful compilation known as
run-time errors. When the program is running, and it is not able to perform the operation is the main
cause of the run-time error. The division by zero is the common example of the run-time error. These
errors are very difficult to find, as the compiler does not point to these errors.

Let's understand through an example.

#include <stdio.h>
int main()
{
int a=2;
int b=2/0;
printf("The value of b is : %d", b);
return 0;
}

Linker error

Linker errors are mainly generated when the executable file of the program is not created. This can be
happened either due to the wrong function prototyping or usage of the wrong header file.

#include <stdio.h>

int main()
{
extern int i;

i=5;
printf("%d",i);
return 0;
}

Logical error

The logical error is an error that leads to an undesired output. These errors produce the incorrect output,
but they are error-free, known as logical errors. These types of mistakes are mainly done by beginners.
The occurrence of these errors mainly depends upon the logical thinking of the developer.

#include <stdio.h>
int main()
{
int sum=0; // variable initialization
int k=1;
for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
{
sum=sum+k;
k++;
}
printf("The value of sum is %d", sum);
return 0;
}

Semantic error

Semantic errors are the errors that occurred when the statements are not understandable by the compil-
er.eg-

Errors in expressions
int a, b, c;
a+b = c;

Algorithm- An algorithm is a set of instructions designed to perform a specific task. It is the analytical
way of solving a problem. Algorithm is done step by step and in any case First step is named as start
and last as stop.

Characteristics of algorithm

Precision – the steps are precisely stated (defined).

Uniqueness – results of each step are uniquely defined and only depend on the input and the result of
the preceding steps.

Finiteness – the algorithm stops after a finite number of instructions are executed.

Input – the algorithm receives input.

Output – the algorithm produces output.

Generality – the same algorithm can be implemented in different ways


Q1. Write an algorithm to add two numbers.

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

Q2.Write an algorithm to find out number is odd or even

Ans.

step 1 : start

step 2 : input number

step 3 : rem←number mod 2

step 4 : if rem=0 then

print "number even"

else

print "number odd"

endif

step 5 : stop

Q3. 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

Q4. Write an algorithm to find the factorial of a number entered by user.

Step 1: Start

Step 2: Declare variables n,factorial and i.

Step 3: Initialize variables

factorial←1

i←1

Step 4: Read value of n

Step 5: Repeats the steps until i=n

5.1: factorial←factorial*i

5.2: i←i+1

Step 6: Display factorial

Step 7: Stop

Q5. Write an algorithm to check whether a number entered by user is prime or not.

Step 1: Start
Step 2: Declare variables n,i,flag.

Step 3: Initialize variables

flag←1

i←2

Step 4: Read n from user.

Step 5: Repeats the steps until i<(n/2)

5.1 If remainder of n÷i equals 0

flag←0

Go to step 6

5.2 i←i+1

Step 6: If flag=0

Display n is not prime

else

Display n is prime

Step 7: Stop

Q6. Write an algorithm to find the Fibonacci series till term≤1000.

Step 1: Start

Step 2: Declare variables first_term,second_term and temp.

Step 3: Initialize variables first_term←0 second_term←1

Step 4: Display first_term and second_term

Step 5: Repeats the steps until second_term≤1000

5.1: temp←second_term

5.2: second_term←second_term+first term

5.3: first_term←temp
5.4: Display second_term

Step 6: Stop

Q7. Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.

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

Flowchart

A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the steps
as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution model to a given problem. Flowcharts are used in analyzing,
designing, documenting or managing a process or program in various fields.

Symbols Used In Flowchart


More symbols

Connector Symbol

Indicates that the flow continues where a matching


symbol (containing the same letter) has been placed.

Q1. Draw a flowchart to add two numbers entered by user.


Q2. Draw flowchart to find the largest among three different numbers entered by user.

Q3. Draw flowchart to find all the roots of a quadratic equation ax2+bx+c=0
Q4. Draw a flowchart to find the Fibonacci series till term≤1000.

Definition of Editor: an editor is a software program that allows users to create or manipulate plain
text computer files.
Or
Editor of any language is a software which provide environment to develop any program in that
particular language.
There are several kinds of editors.

Examples of text editors

Notepad, WordPad, = Microsoft Windows included text editors.


TextEdit = Apple computer text editor.
Emacs = Text editor for all platforms that is a very powerful text editor once you've learned all of its
commands and options.

Computer language or programming language is a coded syntax used by computer programmers to


communicate with a computer. Computer language establishes a flow of communication between
software programs. The language enables a computer user to dictate what commands the computer
must perform to process data. These languages can be classified into following categories.
Machine Language
Machine language or machine code is the native language directly understood by the computer’s cen-
tral processing unit or CPU. This type of computer language is not easy to understand, as it only uses a
binary system, an element of notations containing only a series of numbers consisting of one and zero,
to produce commands.
Assembly Level Language
Assembly Level Language is a set of codes that can run directly on the computer’s processor. This type
of language is most appropriate in writing operating systems and maintaining desktop applications.
With the assembly level language, it is easier for a programmer to define commands. It is easier to un-
derstand and use as compared to machine language. Tranlators like assemblers are needed to translate
assembly language into machine language.
High Level Language
High Level Languages are user-friendly languages which are similar to English with vocabulary of
words and symbols. These are easier to learn and require less time to write.
They are problem oriented rather than ‘machine’ based.
Program written in a high-level language can be translated into many machine language and therefore
can run on any computer for which there exists an appropriate translator, like interpreter or compiler.

NUMBER SYSTEM CONVERSION


There are many methods or techniques which can be used to convert numbers from one base to another.
We'll demonstrate here the following
 Decimal to Other Base System
 Other Base System to Decimal
 Other Base System to Non-Decimal
 Shortcut method - Binary to Octal
 Shortcut method - Octal to Binary
 Shortcut method - Binary to Hexadecimal
 Shortcut method - Hexadecimal to Binary

Decimal to Other Base System


Steps
 Step 1 - Divide the decimal number to be converted by the value of the new base.
 Step 2 - Get the remainder from Step 1 as the rightmost digit (least significant digit) of new
base number.
 Step 3 - Divide the quotient of the previous divide by the new base.
 Step 4 - Record the remainder from Step 3 as the next digit (to the left) of the new base number.
Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in Step 3.
The last remainder thus obtained will be the most significant digit (MSD) of the new base number.

Example
Decimal Number: 2910
Calculating Binary Equivalent:
Step Operation Result Remainder

Step 1 29 / 2 14 1

Step 2 14 / 2 7 0

Step 3 7 / 2 3 1

Step 4 3 / 2 1 1

Step 5 1 / 2 0 1

As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so that the first
remainder becomes the least significant digit (LSD) and the last remainder becomes the most
significant digit (MSD).
Decimal Number: 2910 = Binary Number: 111012.

Other base system to Decimal System


Steps
 Step 1 - Determine the column (positional) value of each digit (this depends on the position of
the digit and the base of the number system).
 Step 2 - Multiply the obtained column values (in Step 1) by the digits in the corresponding
columns.
 Step 3 - Sum the products calculated in Step 2. The total is the equivalent value in decimal.

Example
Binary Number: 111012
Calculating Decimal Equivalent:
Step Binary Number Decimal Number

4 3 2 1 0
Step 1 111012 ((1 x 2 ) + (1 x 2 ) + (1 x 2 ) + (0 x 2 ) + (1 x 2 ))10
Step 2 111012 (16 + 8 + 4 + 0 + 1)10

Step 3 111012 2910

Binary Number: 111012 = Decimal Number: 2910

Other Base System to Non-Decimal System


Steps
 Step 1 - Convert the original number to a decimal number (base 10).
 Step 2 - Convert the decimal number so obtained to the new base number.

Example
Octal Number: 258
Calculating Binary Equivalent:

Step 1: Convert to Decimal


Step Octal Number Decimal Number

1 0
Step 1 258 ((2 x 8 ) + (5 x 8 ))10

Step 2 258 (16 + 5 )10

Step 3 258 2110

Octal Number: 258 = Decimal Number: 2110

Step 2: Convert Decimal to Binary


Step Operation Result Remainder

Step 1 21 / 2 10 1

Step 2 10 / 2 5 0

Step 3 5 / 2 2 1

Step 4 2 / 2 1 0

Step 5 1 / 2 0 1

Decimal Number: 2110 = Binary Number: 101012


Octal Number: 258 = Binary Number: 101012

Shortcut method - Binary to Octal


Steps
 Step 1 - Divide the binary digits into groups of three (starting from the right).
 Step 2 - Convert each group of three binary digits to one octal digit.

Example
Binary Number: 101012
Calculating Octal Equivalent:
Step Binary Number Octal Number

Step 1 101012 010 101

Step 2 101012 28 58

Step 3 101012 258

Binary Number: 101012 = Octal Number: 258

Shortcut method - Octal to Binary


Steps
 Step 1 - Convert each octal digit to a 3 digit binary number (the octal digits may be treated as
decimal for this conversion).
 Step 2 - Combine all the resulting binary groups (of 3 digits each) into a single binary number.

Example
Octal Number: 258
Calculating Binary Equivalent:
Step Octal Number Binary Number

Step 1 258 210 510

Step 2 258 0102 1012


Step 3 258 0101012

Octal Number: 258 = Binary Number: 101012

Shortcut method - Binary to Hexadecimal


Steps
 Step 1 - Divide the binary digits into groups of four (starting from the right).
 Step 2 - Convert each group of four binary digits to one hexadecimal symbol.

Example
Binary Number: 101012
Calculating hexadecimal Equivalent:
Step Binary Number Hexadecimal Number

Step 1 101012 0001 0101

Step 2 101012 110 510

Step 3 101012 1516

Binary Number: 101012 = Hexadecimal Number: 1516

Shortcut method - Hexadecimal to Binary


Steps
 Step 1 - Convert each hexadecimal digit to a 4 digit binary number (the hexadecimal digits may
be treated as decimal for this conversion).
 Step 2 - Combine all the resulting binary groups (of 4 digits each) into a single binary number.

Example

Hexadecimal Number: 1516


Calculating Binary Equivalent:
Step Hexadecimal Number Binary Number

Step 1 1516 110 510


Step 2 1516 00012 01012

Step 3 1516 000101012

Hexadecimal Number: 1516 = Binary Number: 101012

Q. What do you understand by memory hierarchy? Name the general classes of storage media
that might make up a memory hierarchy.

Ans: There is a trade-off to be made while designing the systems architecture in the context of
computer memory, among the three key characteristics of memory, namely cost, capacity
and access time. The plan is not to rely on a single memory component to technology, but to
employ a memory hierarchy, as shown below. Going down the hierarchy, the following
thing occurs:
• Decreasing cost per bit
• Increasing Capacity
• Increasing access time i.e. slower memory
• Decreasing frequency of access of the memory by the CPU

Following is a traditional memory hierarchy.

Q. Distinguish between the following:


(i) Syntactic error and semantic error
(ii) Run time error and logical error
Ans:(i)Syntactic error and semantic error
Syntactic errors also known as compilation errors are caused by violation of the grammar rules of the language.
The compiler detects, isolate these errors and give terminate the source program after listing the errors. Some of
the common syntactic errors are:
• missing or misplaced ; or }
• missing return type for a procedure
• missing or duplicate variable declaration
Semantic errors are logical errors. If there is a semantic error in a program, it will run successfully, in the sense
that the computer will not generate any error messages, but it will not do the right thing. The problem is that the
meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires
working backward by looking at the output of the program and trying to figure out what it is doing.
(ii) Run time error and logical error
Run-time errors: Errors such as mismatch of data types or array out of bound error are known as runtime errors.
These errors are generally go undetected by the compiler so programs with run-time error will run but produce
erroneous results.
Logical errors: These are the errors related with the logic of the program execution. These errors are not
detected by the compiler and are primarily due to a poor understanding of the problem or a lack of clarity of
hierarchy of operators. Such errors cause incorrect result.

Unit II
C FundamentalS:
Data Types: C language provides various data types for holding different kinds of values. There
are several integral data types, a character data type, floating point data types for holding real
numbers and more.

C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the location.

The value of a variable can be changed any time.

C has the following basic built-in datatypes.

 int

 float

 double

 char

Please note that there is not a boolean data type. C does not have the traditional view about logical
comparison

The data types explained above have the following modifiers.

 short
 long
 signed
 unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is
not cast in stone. ANSI has the following rules:

short int <= int <= long int


float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and
the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:
Type Bytes Range
---------------------------------------------------------------------
short int 2 -32,768 -> +32,767 (32kb)
unsigned short int 2 0 -> +65,535 (64Kb)
unsigned int 4 0 -> +4,294,967,295 ( 4Gb)
int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
signed char 1 -128 -> +127
unsigned char 1 0 -> +255
float 4
double 8
long double 12

These figures only apply to todays generation of PCs. Mainframes and midrange machines could use
different figures, but would still comply with the rule above.

We can find out how much storage is allocated to a data type by using the sizeof operator discussed
in Operator Types Session.

Here is an example to check size of memory taken by various datatypes.

Int
main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));

return 0;
}

Qualifiers

Size qualifiers are short and long


Type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying
whether:

 The value of a variable can be changed.


 The value of a variable must always be read from memory rather than from a register

Standard C language recognizes the following two qualifiers:

 const
 volatile

The const qualifier is used to tell C that the variable value cannot change after initialisation.

const float pi=3.14159;

Now pi cannot be changed at a later time within the program.

Another way to define constants is with the #define preprocessor which has the advantage that it does
not use any storage

The volatile qualifier declares a data type that can have its value changed in ways outside the control or
detection of the compiler (such as a variable updated by the system clock or by another program). This
prevents the compiler from optimizing code referring to the object by storing the object's value in a reg-
ister and re-reading it from there, rather than from memory, where it may have changed. You will use
this qualifier once you will become expert in "C". So for now just proceed.

Variable Types:

A variable is just a named area of storage that can hold a single value (numeric or character). The C
language demands that you declare the name of each variable that you are going to use and its type, or
class, before you actually try to do anything with it.

The Programming language C has two main variable types

 Local Variables

 Global Variables

Local Variables

 Local variables scope is confined within the block or function where it is defined. Local vari-
ables must always be defined at the top of a block.

 When a local variable is defined - it is not initalised by the system, you must initalise it your-
self.

 When execution of the block starts the variable is available, and when the block ends the vari -
able 'dies'.
For example:--

main()

{ int i=4;

int j=10;

i++;

if (j > 0)

/* i defined in 'main' can be seen */

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

if (j > 0)

/* 'i' is defined and so local to this block */

int i=100;

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

}/* 'i' (value 100) dies here */

printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/

This will generate following output

i is 5

i is 100

i is 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i+
+ is equivalent to i = i + 1;

You will see -- operator also which is called decremental operator and it idecrease the value of any in-
teger variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any func-
tion that may reference it.

Global variables are initalised automatically by the system when you define them!

Data Type Initialser


Int 0
Char '\0'
Float 0
Pointer NULL
If same variable name is being used for global and local variable then local variable takes preference in
its scope. But it is not a good practice to use global variables and local variables with the same name.

int i=4; /* Global definition */

main()
{
i++; /* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}

func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}

This will produce following result


Value of i = 11 -- func() function
Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to
11. When control returns to main the internal variable will die and and any reference to i will be to the
global.
Format Specifiers :-- Special codes which starts with % and used format the data for input and ouput
o %d decimal
o %o Octal
o %x or %X Hexa Decimal
o %i Integer
o %f Fixed Float
o %e or %E Scientific Float
o %g or %G General Float
o %lf double and long double

o %c Char
o %s String (Do not accept space in input)
o %[^\n] String (Allows to read any data including spaces till Enter key is
 pressed)

o %u Unsigned
o %ld long int
o %p Show to addresses in Hexa Decimal

Escape Sequence Characters -- Special characters made of two or more characters but represent as
one character are called as Escape Sequence Character. Such characters starts with \
 \n New Line
 \t Horizontal Tab (8 spaces)
 \r Carriage Return – Send cursor to start of current line
 \0 Null Character
 \a or \007 Alert Beep
 \\ Print \
 \” Print “

Case 1
void main()
{
printf("Pakistan\rIndia");
getch();
}

Output
Indiatan
Case 2
WAP to print the following
He said, “\n” is made for new line
void main()
{
printf("He said,\"\\n\" is made for new line");
getch();
}
String Literals Strings are enclosed in double quotes. Each string is terminated by a NULL character.
char name[]=”Vikas”; //6 bytes
Case 1
What is the output of the following?
void main()
{
char str[]="vikas\007\a";
printf("%d",sizeof(str));
getch();
}

Operators
1. Arithmetic Operators
2. Type Cast Operator
3. Relational or Conditional Operators
4. Logical Operators
5. Bitwise operators
6. Assignment operators
Arithmetic Operators
+
-
*
/ (5/2=2) (5.0/2 or 5/2.0 = 2.5)
%
Note: use math.h header file for other mathematical functions
What is the output of the following?
#include<stdio.h>
void main()
{
int a=5,b=2;
float c=a/b;
printf("Division of %d and %d is %f",a,b,c);
getch();
}

Type Cast Operator


An operator used to convert one kind of data to another kind of data is called as type cast operator.
Enclose the data type inside the brackets to make the type cast operator.
#include<stdio.h>
void main()
{
int a,b;
float c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
c=(float)a/b; //type cast operator
printf("Division of %d and %d is %f",a,b,c);
getch();
}
Relational Operators
Used to compare two values and return the result as 0 or 1
If the condition is true then returns 1
If the condition is false then returns 0

There are six relational operators


== equals to
!= not equals to
> Greater than
>= Greater than or equals to
< Less than
<= Less than or equals to
Example
void main()
{
int n=5 + 7 > 6; //12 > 6 = 1
printf("%d",n);
getch();
}
Example
void main()
{
int n=5 + (7 > 6); //5 + 1 = 6
printf("%d",n);
getch();
}
void main()
{
int n=12 - 2 > 6; //10 > 6 = 1
printf("%d",n);
getch();
}

Logical Operators
Operators used to combine two conditions are called as logical operators
&& Logical And
|| Logical Or
! Logical Not
Truth Tables
For &&
F F  F
F T  F
T F  F
T T  T
For ||
F F  F
F T  T
T F  T
T T  T

For !
T  F
F  T
Notes
1. In case of &&, if first condition is false then second is not checked
2. In case of ||, if first condition is true then second is not checked
3. All values other than 0 are treated as true
What is the output of the following?
int n=6 && printf(“%d”,printf(“%d”,printf(“Hello”)));
printf(“%d”,n);
Output
Hello511

What is the output of the following?


int n=6 || printf(“%d”,printf(“%d”,printf(“Hello”)));
printf(“%d”,n);
Output
1
Bitwise Operators
The operators which first convert a number into bits then operate.
& Bitwise And
| Bitwise Or
^ Bitwise XOR
~ Bitwise Not
<< Left Shift
>> Right Shift
Example
int n=6 & printf(“Hello”);
printf(“%d”,n);
Output
Hello4
Example
int n=6 | printf(“Hello”);
printf(“%d”,n);
Output
Hello7
Example
int n = 6 << 3;
printf(“%d”,n);

Output
48
1. WAP to input a number and check it to be divisible by 7 and 9.
2. WAP to input and check its right most digit to be greater than second rightmost digit
3. WAP to input an alphabet and check it to be vowel or consonant

a=567;
ld=a%10; //ld is 7 and a is 567
a=a/10; // 56
sld=a%10; //6

storage class
Every variable in C programming has two properties: type and storage class. Type refers to the data
type of variable whether it is character or integer or floating-point value etc. And storage class deter-
mines how long it stays in existence.

There are 4 types of storage class:

1. automatic
2. external
3. static
4. register

Automatic storage class


Keyword for automatic variable

auto

Variables declared inside the function body are automatic by default. These variable are also known as
local variables as they are local to the function and doesn't have meaning outside that function

Since, variable inside a function is automatic by default, keyword auto are rarely used.

External storage class


External variable can be accessed by any function. They are also known as global variables. Variables
declared outside every function are external variables.

In case of large program, containing more than one file, if the global variable is declared in file 1 and
that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is
used in file 2 to indicate that, the variable specified is global variable and declared in another file.

Example to demonstrate working of external variable

#include
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}

void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global variable ------- */
printf("a=%d\n",a);
}

Output

a=10

Register Storage Class


Keyword to declare register variable

register

Example of register variable

register int a;

Register variables are similar to automatic variable and exists inside that particular function only.

If the compiler encounters register variable, it tries to store variable in microprocessor's register rather
than memory. Value stored in register are much faster than that of memory.

In case of larger program, variables that are used in loops and function parameters are declared register
variables.

Since, there are limited number of register in processor and if it couldn't store the variable in register, it
will automatically store it in memory.

Static Storage Class


The value of static variable persists until the end of the program. A variable can be declared static using
keyword: static. For example:

static int i;

Here, i is a static variable.

Example to demonstrate the static variable


#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}

Output

0 5 10

During first function call, it will display 0. Then, during second function call, variable c will not be ini-
tialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third call.

If variable c had been automatic variable, the output would have been:

0 0 0

Branching statements in C
C language executes program statements in a sequence. Sometimes we need to alter the flow of
sequence of statements. This is possible using Branching statements offered by C language. They are
also known as control statements. Programmer can jump from one part of the program to other with the
help of such statements. C language Branching Statements are given below:

1. if statement
2. if…else statement
3. nested if statement
4. Ladder of if else statement
5. switch statement

Go through the slides of branching statements


Unit-III

Control Statements:

Program Blocks and Loops:

A program block is a group of statements that have the following two characteristics: They have a sin-
gle entry point and a single exit point. A loop has a program block at its heart. A loop is used to re-
peatedly perform an operation or a block of code through the use of a conditional expression.

Control Structures:

The C language control statements include the if/else, the do/while, the while, the for loop, and the
switch/case. The nature of the loop or control structure used determines the number of times the state-
ments (or code block) are executed, if executed at all. This section will introduce and apply the control
statements to perform useful tasks that add "intelligence" to the software. With the above listed control
statements, a block of code can be executed once, executed repeatedly, executed a certain number of
times, or skipped over completely. These control statements are key in writing structured software.
Nesting of control structures also allows for more detailed and complex software.

Structured programming is a technique for organizing and coding programs that reduces complexity,
improves clarity, and facilitates debugging and modifying. The benefits are listed below:

1. Operation is simple to trace


2. Structures are self-documenting
3. Structures are easy to define in flowcharts
4. Structured programming increases programmer productivity
5. Structures lead to functions

IF / Else:

The IF/ELSE statement can be referred to as a "fork in the road". This statement directs the flow of
the software according to the result of the conditional expression. The conditional expression in an if
statement is a comparison between two values. If the conditional expression is true, then the "true"
block of code is executed. If the conditional expression is evaluated as false, then the else branch or
block of code is executed. It should be noted that not having the microcontroller perform any task in
the event that the conditional is false is quite common. Therefore, the else condition may be omitted
altogether.

The flowchart for both an IF and an IF / ELSE structure are shown below. The distinguishing charac-
teristic that identifies an IF statement over the other control structures is the flow of the program after
the decision and resulting process. In either an IF or IF / ELSE structure, the program flow continues
to go down the page.
if (the conditional expression is true)
{

perform these statements

}
else
{

perform these statements if the conditional is false

While Loop:

In a While Loop, the expression is evaluated when the program enters the top of the loop. If the ex-
pression is true, the statements within the loop are executed. When the bottom of the code block is
reached, program flow is directed back to the top of the loop and the conditional is re-evaluated. As
long as the conditional is evaluated as true, the process repeats. IF the conditional is evaluated as false,
then the code block is skipped. Again, the flowchart for a While Loop is shown below.
while (some conditional expression is true)
{

perform the statements located between the braces

DO / While:

The Do/While loop is very similar to the while loop. The major difference is that the expression or
conditional is tested at the bottom of the loop. This means that the body of the loop is executed at least
one time regardless of the results of the conditional. If the result of the conditional is true, then the
loop body is repeated. This process is repeated until the conditional is evaluated as false.

do
{

perform the statements located between the braces

} while (this conditional expression is true)

The while and do/while loops are frequently used to monitor a particular input or register in control
type applications.
For Loop:

The For Loop is traditionally used to perform a task or repetitive event for a known number of itera-
tions or in other words, it is used to implement count-controlled loops. The for loop is made up of an
initial condition, a conditional expression, a modifier, and the body or the code block. When the for
loop is encountered, the initial condition is executed. The conditional expression is then evaluated as
either true or false. If the conditional is determined to be true, then the body of the loop is executed.
Upon reaching the bottom of the loop, the modifier is executed. Program control is then returned to the
conditional. The conditional expression is re-evaluated, and if true, the body of the loop is executed
again. Each time the bottom of the code block is reached, the modifier is executed. The loop continues
to be executed until the conditional is evaluated as no longer true.

for ( variable initialized ; conditional expression ; variable modifier )


{

perform these statements while the conditional expression is true

The resemblance or similarities between the For Loop and While Loop go beyond the fact that the
flowcharts look similar. In actuality, any For Loop can be replaced or implemented with a While
Loop. However, not all While Loops can be replaced by a For Loop.
Switch / Case:

The Switch Case structure is similar to a host of if statements. The switch case structure may have a
default condition that is executed if none of the statements match. A switch/case structure is used when
one statement must be chosen from many.

switch ( variable of interest )


{

case value1:
code to be executed.
break;
case value2:
code to be executed.
break;
case value3:
code to be executed.
break;

……………

default:
code to be executed.
break;

}
Switch structures both have their program flow going towards the bottom of the flowchart.

/* WAP to get an alphabet and check it to be vowel or consonant */


void main()
{
char ch;
printf("Enter an alphabet : ");
ch=getchar();
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
switch(ch)
{
case 'a' : case 'A' :
case 'e' : case 'E' :
case 'o' : case 'O' :
case 'i' : case 'I' :
case 'u' : case 'U' :
printf("%c is a vowel",ch);
break;
default: printf("%c is a consonent",ch);
}
}
else
printf("Sorry! %c is not an alphabet",ch);
getch();
}
/*WAP to get two numbers and print the bigger one */
void main()
{ int a,b;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
printf("Greater is %d",a>b?a:b);
getch();
}
/*WAP to get three numbers and print the biggest one */
void main()
{
int a,b,c,g;
printf("Enter three numbers : ");
scanf("%d%d%d",&a,&b,&c);
g=a>b? (a>c?a:c) : (b>c?b:c);
printf("Greatest is %d",g);
getch();
}
Example 1
/* WAP to input a number and print table of it */
/* Using while loop */
void main()
{
int n,i;
printf("Enter the number : ");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
}
getch();
}
Example 2
/* WAP to input a number and print table of it */
/* Using for loop */
void main()
{
int n,i;
printf("Enter the number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
getch();
}
Example 3
/* WAP to input a number and print table of it */
/* Using do-while loop */
#include<stdio.h>
void main()
{
int n,i;
char ans;
do
{
printf("Enter the number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
printf("\n\nMore Tables [Y/N] ? ");
fflush(stdin); ans=getchar();
}while(ans=='y' || ans=='Y');
}
Example 4
/* WAP to input a number and print table of it */
/* Using goto statement */
#include<stdio.h>
void main()
{
int n,i=1;
printf("Enter the number : ");
scanf("%d",&n);
top:
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
if(i<=10) goto top;
getch();

Assignment
1. WAP to print all even numbers between 1 and 20
2. WAP to input two numbers and print sum of all numbers in range e.g. 2 and 5 means
2+3+4+5
Solution 2
/* WAP to input two numbers and print sum of numbers in range */
void main()
{
int a,b,n,sum=0;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
n=a;
while(n<=b)
{
sum=sum+n;
n++;
}
printf("Sum is %d",sum);
getch();
}
/* WAP to input a number and print factorial of it */
int main()
{
int n,i;
unsigned long f=1;
printf("Enter the number : ");
scanf("%d",&n);

for(i=n;i>=1;i--)
f=f*i;

printf("Factorial of %d is %lu",n,f);
getch();
}

/*WAP to input a number and print sum of five digits */


int main()
{
int n,temp,d,sum=0;
printf("Enter a number : ");
scanf("%5d",&n);

temp=n;
while(temp)
{
d=temp%10;
sum=sum+d;
temp=temp/10;
}

printf("Sum of digits of %d is %d",n,sum);


getch();
}
/* WAP to get a number and check it to be prime number */
void main()
{
int n,d,cut=0;
printf("Enter a number : ");
scanf("%d",&n);
d=2;
while(d<=n/2)
{
if(n%d==0)
{
cut=1;
break;
}
d++;
}
if(cut)
printf("%d is not a prime",n);
else
printf("%d is a prime number",n);
getch();
}

What is a function: --
A set of statements clubbed together to perform some action is called as function. Functions can be of
three types
1. Library Functions
2. User Defined Functions
3. System Defined Functions
Library Functions
Function pre-provided by a compiler under special files called as header files.
1. stdio.h
a. printf()
b. cprintf()
c. scanf()
d. gets()
e. puts()
f. getchar()
g. putchar()
2. conio.h
a. getch()
b. getche()
c. clrscr()
d. gotoxy(column, row)
i. Screen size can be 25x80 or 50x80
e. clreol()
i. To clear the current line
f. textcolor()
g. textbackground()
3. ctype.h (Character Related Function)
a. toupper(ch) – Convert the character in capital
b. tolower(ch) – Convert the character in small letter
c. isalpha(ch) – returns true if alphabet
d. isupper(ch)
e. islower(ch)
f. isdigit(ch)
4. string.h (String Related Functions)
a. strupr(s)
i. Convert to upper case
b. strlwr(s)
i. Convert to lower case
c. strlen(s)
i. return the length of string
d. strrev(s)
i. Reverse the string
e. strcpy(target, source)
i. To copy a string from source to target
f. strcmp(s1,s2)
i. Compare two strings and return a number as case sensitive
1. s1==s2 returns 0
2. s1>s2 returns > 0
3. s1<s2 return s<0
g. strcmpi(s1,s2)
i. to check two string as case insensitive
h. strcat(s1,s2)
i. To concatenate two strings
5. stdlib.h (Standard Library)
a. atoi(s)
i. String to integer conversion
b. atof(s)
i. String to float conversion
6. math.h
a. log(n)
b. pow(n,p)
c. abs(n)

Creating User Defined Functions


A function has three components
1. Function Declaration
2. Function Definition
3. Function Call
Function Declaration
When we create a function we need to declare the functions using different elements
1. Function Name
2. Number of arguments
3. Type of arguments
4. Return type
Based on return type, functions can be of two types
1. void functions
2. non-void functions
void functions do not return any value
non-void functions return some value.
If no return type is specified then default type is int.

Note: A function can return only one value and void function do not return any value.

Examples
1. Declare a function to get a character and return its ASCII value
2. Declare a function to get a year and check it to be leap year
3. Declare a function which takes a number as argument and returns its factorial
4. Declare a function which takes length and width of a rectangle and prints area of the rectangle

[1]
int toascii(char);
or
int toascii(char ch);

[2]
int isleapyear(int);
or
int isleapyear(int year);

[3]
long factorial(int num);

[4]
void area(int length, int width);
Function Definition
Used to provide the real functioning to the method
int toascii(char ch)
{
return ch;
}
int isleapyear(int y)
{
if((y%4==0 && y%100!=0) || y%400==0)
return 1;
else
return 0;}

long factorial(int num)


{
long f=1;
int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
void area(int length, int width)
{
printf("Area is %d",length*width);
}
Function Call
When using a function is called as function call.
Solution 1
int toascii(char ch);
int isleapyear(int year);
long factorial(int num);
void area(int length, int width);
int main()
{
printf("Character 'A' has value %d\n",toascii('A'));
if(isleapyear(2012))
printf("2012 is leap year\n");
else
printf("2012 is not a leap year\n");

printf("Factorial of 7 is %ld\n",factorial(7));
area(5,6);
getch();
}
int toascii(char ch)
{
return ch;
}
int isleapyear(int y)
{
if((y%4==0 && y%100!=0) || y%400==0)
return 1;
else
return 0;
}
long factorial(int num)
{
long f=1;
int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
void area(int length, int width)
{
printf("Area is %d",length*width);
}

Note: If definition is provided above main() then declaration is not required


Solution 2
int toascii(char ch)
{
return ch;
}
int isleapyear(int y)
{
if((y%4==0 && y%100!=0) || y%400==0)
return 1;
else
return 0;
}
long factorial(int num)
{
long f=1;
int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
void area(int length, int width)
{
printf("Area is %d",length*width);
}

Passing Arguments to the functions


C allows to pass arguments using two ways
1. Pass by value
2. Pass by address
C++ allows to pass arguments using three ways
1. Pass by value
2. Pass by address
3. Pass by reference
Passing arguments by value
When passing arguments by value, value of actual arguments get copied to formal arguments.
Duplicate variables get created as formal argument. If we make any changes to formal arguments they
will not be reflected in actual arguments. It gives data safety to our arguments.
//Using Pass by value
void update(int a) //formal argument
{
a=a+7;
printf("After update data is %d\n",a);
}
void main()
{
int a=5;
printf("Actual data is %d\n",a);
update(a);//actual argument
printf("Data after udpation %d",a);

getch();}
Pass by address
When passing as argument by address, address of actual argument get passed to formal argument. If we
make any changes to formal arguments, they will be reflected in actual arguments.
//Using Pass by address
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int x=5,y=6;
swap(&x,&y); //passing address
printf("x=%d and y=%d",x,y);
getch();
}
//Using pointers
void manyresults(int n, int *sq, int *cb)
{
*sq=n*n;
*cb=n*n*n;
}
int main()
{
int x=6,y,z;

manyresults(x,&y,&z);
printf("Square of %d is %d and cube is %d",x,y,z);
getch();
}
Unit-IV
Arrays:

An array is a finite set of variables of the same basic type. Instead of giving each variable a name, we
use enumeration and group all of them in an array The enumeration of elements within an array
always starts with 0. If the array has N elements, the last element is in position N-1 The C compiler
does not check the array boundaries "this is a very typical error that it is very difficult to find (usually
happens inside loops that traverse the array) "always check the array boundaries before accessing a
variable in an array. For example:

#include <stdio.h>
float data[5]; /* data to average and total */
float total; /* the total of the data items */
float average; /* average of the items */
main() {
data[0] = 34.0;
data[1] = 27.0;
data[2] = 45.0;
data[3] = 82.0;
data[4] = 22.0;
total = data[0] + data[1] + data[2] + data[3] +
data[4];
average = total / 5.0;
printf("Total %f Average %f\n", total, average);
return (0);
}
Structures and Unions
1. Introduction

As we know array is a collection of elements of the same data type under a common name. However, there may
be a requirement to represent a collection of data elements belonging to different data types under a common
name. For this purpose, C supports structure. A structure consists of packing elements of different data types as
a single unit under the same name. A structure may consist of elements of the type float, int and char. Pointers,
arrays and other structures can also be included as elements within a structure.
Closely associated with the structure is another user defined data type called the union which also contains
elements of different data types under a common name. However, a union differs from a structure in the manner
in which the member elements are allocated memory and its usage.
2. Defining a Structure

A structure is a user defined data type that is defined in terms of its individual elements. Subsequently, the
variables of this data type can be declared and used.
The definition of a structure consists of defining the elements of the structure and their data types. The elements
of the structure are also called its members. The definition of a structure takes the following general form:
struct structure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
};

In the above definition, struct is the keyword and structure_name is the name that will be given to the structure
data type; member_1, member_2 ,………, member_n are the elements or members of the structure data type that
may be of different data types.

For example, we declare the structure type student as follows:

struct student
{
int roll_no;
char name[20];
float marks;
};

The structure definition is only a template that can be used to declare variables of its type; the definition itself
does not declare any variable. Thus there is a clear distinction between the structure definition and declaration of
variables of the structure type.

3. Declaring Structure Variables

Once the structure data type has been defined, the individual variables of the structure type can be declared as
follows:

struct structure_name var_1, var_2,……………var_m;

where struct is the keyword, structure_name is the name of the structure type and var_1, var_2……… var_m are
the variables of the structure type.

For example, we can declare the variables of the structure type student, declared earlier, as follows :

struct student, s1, s2, s3;

where s1, s2 and s3 are the variables of the structure type student.

It is important to note that the members of a structure type are not variables themselves and do not occupy any
memory space. It is only the structure variables that occupy memory space.

Another important point to be taken care of is that a member of the structure cannot be initialized within the
structure definition.

For example, the structure definition


struct student
{
int roll_no =20; /* invalid */
char name[20];
float marks;
};

is invalid because of the initialization of the member roll_no because this would mean that the member roll_no
will have a value 20 in all the variables of the structure which may not be possible in the real world.

It is also permitted to combine the structure definition and the declaration of its variables in a single statement in
the form shown:

struct structure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
} var_, var_2, ……….,var_m;

For example,

struct student
{
int roll_no;
char name[20];
float marks;
}s1, s2,s3;

The structure_name is optional in this case as follows:

struct
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_type member_n;
} var_, var_2, ……….,var_m;

For example,

struct
{
int roll_no;
char name[20];
float marks;
}s1, s2,s3;

4. Structure Variable As Member of Another Structure

A structure variable can be defined as a member of another structure as follows:

struct date
{
int dd;
int mm;
int yy;
}

struct student
{
int roll_no;
char name[20];
float marks;
struct date dob;
};

The variable dob of the structure type date is a member of the structure student.

In such a case where a structure variable is member of another structure, the definition of the embedded structure
must appear before the definition of the outer structure. In the example, the definition of the structure date
appears before the definition of the structure student in which the variable dob of the type date is embedded.

5. Initialization of Structure Variables

The members of a structure variable can be initialized in the same way as the variables of any other data type.
The general form is:

struct structure_name variable_name = {value_1, value_2, ………., value_n);

The initial values must appear in an order in which they will be assigned to the members of the structure
variable.

For example,

struct student
{
int roll_no;
char name[20];
float marks;
};

struct student s1={127, “Amit”,67};


struct student s2={134, “Vijay”, 98};
In the first initialization, 127 will be assigned to the member roll_no of student s1, “Amit” will be assigned to the
member name of student s1 and 67 will be assigned to the member marks of student s1. Similarly the values will
be assigned to the members of variable s2.

Another way of writing the same initialization is:

struct student
{
int roll_no;
char name[20];
float marks;
} s1={127, “Amit”,67};

6. Accessing the Structure Members

The structure members are processed individually as separate entities. However, as they are not variables
themselves, they are required to be linked to the corresponding structure variables at the time of usage such as
accessing, assigning the values and computations etc. The individual structure members can be used as follows

structure_variable.member

The period or dot (.) that separates the structure variable and the member is an operator called the dot operator
or member operator or period operator.

For example,

s1.marks refers to the member marks of the variable s1 of type student.

The members associated with the structure variables can be used just like ordinary variables in C. For example,

s1.marks /*valid*/
scanf(“%d”, &s1.roll_no); /*valid*/
s1.marks = s1.marks + 5; /*valid*/
printf(“%d %s %f”, s1.roll_no, s1.name, s1.marks); /*valid*/

are all valid C statements/expressions.

Illustration 1 : Write a program to illustrate the use of members of a structure variable using the member
operator.

struct complex /* Structure Definition */


{
int real;
int imag;
};

void main()
{
struct complex c1, c2, sum; /* Declaration of variables of the type complex */
printf("Enter the real and imaginary parts of the first number:");
scanf("%d %d", &c1.real, &c1.imag); /*Use of member operator in reading members of variable c1*/
printf("\nEnter the real and imaginary parts of the second number:");
scanf("%d %d", &c2.real, &c2.imag); /*Use of member operator in reading members of variable c2*/
sum.real = c1.real + c2.real; /*Use of member operator in processing members of variables c1
and c2*/
sum.imag = c1.imag + c2.imag; /*Use of member operator in processing members of variables c1
and c2*/
/*Use of member operator in printing members of variable sum*/
printf("\nThe new number is Real Part :%d Imaginary Part : %d", sum.real, sum.imag);
}

Test Run:
Enter the real and imaginary parts of the first number: 3 2
Enter the real and imaginary parts of the second number: 5 1
The new number is Real Part :8 Imaginary Part : 3

More complex expressions involving the repeated use of the dot operator can also be written in the form

structure_variable.member.sub_member

where member refers to a member of the structure variable and sub_member refers to the member of an
embedded structure variable.

Illustration 2 : Write a program to illustrate the use of member operator in embedded structures.

struct date
{
int dd;
int mm;
int yy;
};

struct student
{
int roll_no;
float marks;
struct date dob; /* dob is variable of the embedded structure date*/
/*structure date must be defined before structure student */
};

void main()
{
struct student s;
printf("Enter the details of the student");
printf("\n Roll_no");
scanf("%d", &s.roll_no);
printf("\nMarks");
scanf("%f", &s.marks);
printf("\n Date of Birth in dd mm yy format");
scanf("%d %d %d", &s.dob.dd, &s.dob.mm, &s.dob.yy);
printf("\n The student details are :");
printf("\n Roll_no : %d", s.roll_no);
printf("\n Marks : %0.2f", s.marks);
printf("\n Date of Birth :%d/%d/%d", s.dob.dd, s.dob.mm, s.dob.yy);
}

Test Run :

Enter the details of the student


Roll_no 34
Marks 56.5
Date of Birth in dd mm yy format 3 6 90
The student details are
Roll_no :34
Marks :56.50
Date of Birth :3/6/90

If the member of a structure is an array, then the individual array elements are used as

structure_variable.member[index];

For example, s1.name[3];

Illustration 3 : Write a program to illustrate the use of array as structure member.

struct student
{
int roll_no;
int marks[3];
};

void main()
{
struct student sx;
int i, sum = 0;
float avg;
printf("Enter the roll_no of the student:");
scanf("%d", &sx.roll_no); /* Use of array member */

printf("\nEnter the marks of the student");


for(i=1; i<=3; i++)
{
printf("\nMarks%d : ", i);
scanf("%d", &sx.marks[i]); /* Use of array member */
}

for(i=1; i<=3; i++)


sum = sum + sx.marks[i]; /* Use of array member */
avg = (float)sum/3;
printf("\n Average Marks = %0.2f", avg);
}

Test Run :
Enter the roll_no of the student:23
Enter the marks of the student
Marks1: 23
Marks2: 45
Marks3: 56
Average Marks = 41.33

7. Operations on Structures

Most operations – arithmetic, relational and logical – can be carried out only on the individual structure
members and not on the structure variable as a whole. The only operation that can be performed on the structure
variable is the assignment operation.

For example, if s1 and s2 are two variables of the structure student (defined earlier in this chapter), then the
statements
s1 = s2; /*valid statement */
s2 = s1; /*valid statement */

are valid.

When the statement


s1=s2;
is processed, it is equivalent to
s1.roll_no = s2.roll_no;
s1.marks = s2.marks;
strcpy(s1.name, s2.name);

i.e. the values of the individual members of s1 are assigned to those of s2.

However, the statements or expressions such as

s3 = s1 + s2; /*invalid statement */


s1 == s2; /*invalid expression */
s1 != s2; /*invalid expression */
s1 > s2; /*invalid expression */

are not valid. Such operations can be performed only on the individual structure members.

Illustration 4: Create the structure point with data members x and y. Create two variables p1 and p2 of
the type point and find if p1 and p2 represent the same points.

struct point
{ int x;
int y;
};

void main()
{
struct point p1, p2;
printf("Enter point p1:");
scanf("%d %d", &p1.x, &p1.y);
printf("\nEnter point p2:");
scanf("%d %d", &p2.x, &p2.y);
if((p1.x ==p2.x) && (p1.y == p2.y)) /*Comparison of individual structure members */
printf("\nThe points are the same");
else
printf("\nThe points are not the same");
}

Test Run 1:

Enter point p1: 2 3


Enter point p2: 2 3
The points are the same

Test Run 2:

Enter point p1: 2 3


Enter point p2: 4 5
The points are not the same

Illustration 5: Use the structure point to create two variables p1 and p2 and assign the value of p1 to p2.

struct point
{
int x;
int y;
};

void main()
{
struct point p1={3,4} , p2;
printf("Point p1 is x=%d y=%d", p1.x, p1.y);

p2.x = p1.x; /* Assignment of member x of p1 to p2 */


p2.y = p1.y; /* Assignment of member y of p1 to p2 */
printf("\nPoint p2 is x=%d y=%d", p2.x, p2.y);
}

Test Run :
Point p1 is x=3 y=4
Point p2 is x=3 y=4
8. Arrays of Structures

Just like the arrays of ordinary variables, we can also declare and use arrays of structure variables. The general
form is

struct structure_name array_name[index];

For example

struct student S[3];

declares an array S of the type student and having 3 elements.


The following code shows the initialization of an array of structures
struct point
{
int x;
int y;
};
struct point p[3] = {{1,2},{3,4},{6,7}};

Illustration 6 : Write a program to define a structure named student with members roll_no and marks. Use
the structure to create an array of students. Input data and find the average marks of the students.
struct student
{
int roll_no;
int marks; };
void main()
{
struct student s[3]; /* Array s of type student */
int i, sum = 0;
float avg;
printf(“Enter the student details”);
for(i=0; i<3; i++)
{
printf(“\n Student %d: ”, i);
scanf("%d %d", &s[i].roll_no, &s[i].marks); /* Input the structure members */
}
printf(“\n The student details are :”);

for(i=0; i<3; i++)


{
printf(“\n Student %d:”, i);
printf("%d %d", s[i].roll_no, s[i].marks);/* Access the structure members */
}
for(i=0;i<3;i++)
sum = sum + s[i].marks;
avg = (float)sum/3;
printf("\nAverage Marks = %0.2f", avg);
}
Test Run:
Enter the student details
Student0: 3 45
Student1: 4 65
Student2: 5 89
The student details are :
Student0: 3 45
Student1: 4 65
Student2: 5 89
Average Marks = 66.33

In the above program, s[i].roll_no and s[i].marks are used to access the members of the structure variables s[i]
as the value of i varies from 0 to 2.

9. Size of Structures
The sizeof operator can be used to find the size of a structure or a structure variable. The general form is
sizeof(structure_name);
or
sizeof(variable_name);

For example,
If we have a structure

struct point
{
int x;
int y;
};

then the expression

sizeof(point);

will return the number of bytes (4 in this case) required to hold all the members of the structure point.

If p is a variable of the type point, then the expression

sizeof(p);

will return the number of bytes required to hold the members of the variable p. The expression will return 4.

If px is an array of the type point, then

sizeof(px);

will return the total number of bytes that the array p requires.

10. Pointers to Structures


The starting address of a structure variable (i.e. the address of the first member of the structure variable) can be
accessed using the address of (&) operator. Also we can declare a pointer variable that can point to a structure
variable. The general form is
struct structure_name *variable;
where struct is the keyword, structure_name is the name of the structure whose variable is being created and
variable is the pointer variable of the type structure_name.

For example, consider the following code

struct point
{
int x;
int y;
};
struct point *ptr, p1;

The pointer variable ptr of the type point can be used to store the address of a structure variable of the type point
as follows
ptr = &p1;
where p1 is a variable of the type point.

The individual structure members can be accessed in terms of the corresponding pointer variable by using the
member selection operator or arrow operator (->).

For example

ptr -> x;
ptr ->y;
Illustration 7 : Write a program to illustrate the use of pointers to structures.
struct point
{
int x;
int y;
};

void main()
{
struct point p1={3,4};
struct point *ptr; /* ptr is a pointer of the type point */
struct point new_point;
ptr = &p1; /* ptr stores the address of the variable p1 of type point */
new_point.x = ptr-> x+3;
new_point.y = ptr-> y+3;
printf("\nThe original point is %d,%d", ptr->x, ptr->y);
ptr = &new_point; /* Now ptr points to variable new_point */
printf("\nThe new point is %d,%d", ptr->x, ptr->y);
}
Test Run:
The original point is 3,4
The original point is 6,7

In illustration 7, the statement

struct point *ptr;

creates a pointer variable of the type point i.e. the pointer ptr can point to structure type point
The statement

ptr = &p1;

assigns the address of the variable p1 of type point to the pointer variable ptr.

The statements
new_point.x = ptr-> x+3;
new_point.y = ptr-> y+3;

access the members of point p1 using the pointer ptr.

The statement
ptr = &new_point;

points the pointer ptr to the structure variable new_point.

The members of new_point are accessed through the pointer ptr in the statement

printf("\nThe new point is %d,%d", ptr->x, ptr->y);

Defining Structures with typedef


We have already studied the typedef feature in C. This feature allows users to define new data types that are
equivalent to existing data types.
The typedef feature is particularly convenient in defining structures as it eliminates the need to repeatedly use
the keyword struct whenever a structure is referenced. The general form is
typedef struct structure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
};

For example,
typedef struct student
{
int roll_no;
char name[20];
float marks;
};

The variable declaration for the structure student is


student s1, s2;
Unions
Unions, like structures, are composition of members of different data types. However, all the members within a
union share the same memory space whereas each member within a structure is assigned its unique storage area.
Thus, though a union may consist of several members it can handle only one member at a time.
Thus unions are used to conserve memory and are used in applications involving multiple members but the
values need not be assigned to all the members at the same time.
A union is declared using the keyword union in the following general form

union union_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_type member_n;
};

For example
union test
{
int x;
float y;
char z;
};

test is a union with three data members of different data types. A variable temp of the union data type test can be
declared as

union test temp;

The memory allocated to the variable of a union is the memory required to hold the data member with the largest
memory requirement. This memory is shared by all the data members and only one member can use the memory
at a time. The memory allocated to the variable temp is 4 bytes which is the memory required by the member y
of the union variable.

The union members can be accessed using the dot or member operator. For example
temp.x
temp.y
temp.z

are all valid members.

Since the memory allocated to a union is shared by all the members and only one member can use this memory
at a time, when a member is assigned a new value, the new value overwrites the value of the previous member in
the shared memory.

For example,

temp.x = 3;

allocates the memory to the member x and hence the memory contains the value 3.

The statement

printf(“%d”, temp.x);

will display 3.

Now the statement

temp.y = 67.3;

overwrites the value in the memory to 67.3. The statement

printf(“%d”, temp.y);

will display 67.3

While accessing the member of a union, we must take care that we access only that member whose value is
currently stored in the memory.
For example, the code

temp.z = ‘y’;
printf(“%f”, temp.z);

will produce an erroneous output as the value in the memory is of char type whereas we are attempting to access
a float type value.

Only one member of the union variable can be initialized and most compilers will accept the initial value only
for the first member of the union. For example,

union temp1 = {3};

is a valid initialization whereas the initializations

union temp1 = {5.6};

and

union temp1 = {‘g’};

are invalid.

Enumerated Types

Enumerated Types are a special way of creating your own Type in C. Enumerated types are used
to make a program clearer to the reader/maintainer of the program.
For example, say we want to write a program that checks for keyboard presses to find if the down
arrow or up arrow has been pressed. We could say: if ( press_value == 32 ). 32 is the computers
representation of the down arrwo. Or, we could create our own enumerated type with the key words:
down_arrow and up_arrow. Then we could say: if ( press_value == down_arrow ). This second version
is much more readable and understandable to the programmer.
An enumeration is a user-defined data type consists of integral constants and each integral
constant is give a name. Keyword enum is used to defined enumerated data type.

enum type_name{ value1, value2,...,valueN };

Here, type_name is the name of enumerated data type or tag. And value1, value2,....,val-
ueN are values of type type_name.

By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can
change the default value.

Example:
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
OUTPUT: 4

Command line argument:


It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
specially when you want to control your program from outside instead of hard coding those values inside
the code.

The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly:

#include<stdio.h>
int main( int argc, char *argv[ ] )
{ if (argc==2)
Printf(“ The argument supplied is %s\n”, argv[1]);
else if (argc>2)
Printf(“ Too many arguments supplied.\n”);
else
printf("One argument expected.\n");
}
Unit-V

Pointers A variable that can hold address of another variable of its data type. To declare a pointer
type variable use indirection operator *
int *p; // p is a pointer variable that can hold address of some other int type variable
double *k;
char *ch;
void *ptr; // ptr can hold address of any data type also called as Generic Pointer
All pointers take equal size which is 2 bytes in Turboc and 4 bytes in other compilers like GCC, BCC
etc.
Example
void main()
{ char *x;
int *y;
double *z;
void *p;
printf("%d %d %d %d",sizeof(x),sizeof(y),sizeof(z),sizeof(p));
getch(); }

Pointers are used for


1. Indirect Memory Referencing
2. Dynamic Memory Allocation

Indirect Memory Referencing


int a=6;
int *p; // p is a pointer type variable to hold address of int type variable
p=&a; //referencing
*p=55; // value at the address in p (de-referencing) i.e. a is now 55
Example
//Indirect memory referncing
void main()
{
int a=5,b=6;
int *p;
p=&a;
*p=33;
p=&b;
*p=44; //value at the address
printf("%d %d",a,b);//33 44
getch();
}
Dynamic Memory Allocation
We can allocate the memory on demand using functions of malloc.h and calloc.h like malloc() and
calloc().
datatype *ptr=(dataype *)malloc(items * sizeof(datatype));
datatype *ptr=(dataype *)calloc(items, sizeof(datatype));

Example
WAP to ask the number of items, input that much of numbers and show sum of all those
numbers.
#include<malloc.h>
void main()
{
int *p;
int n,i=0,s=0;
printf("No of elements : ");
scanf("%d",&n);
p=(int *) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter data %d : ",i+1);
scanf("%d",p+i);
s=s+*(p+i);
}
printf("Sum is %d",s);
getch();
}
Pointer as Array
#include<malloc.h>
void main()
{
int *p;
int n,i=0,s=0;
printf("No of elements : ");
scanf("%d",&n);

p=(int *) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter data %d : ",i+1);
scanf("%d",&p[i]);
s=s+p[i];
}
printf("Sum is %d",s);
getch();
}

File Handling
A system to manage data on disc permanently. We can create files on disc and manage the record in
that files with different operations
 Open a file
 Close a file
 Save new record
 Search a record
 Update a record
 Delete a record
C provides a built-in structure called FILE which is used to manage the files.
C provides functions inside stdio.h header file
 fopen()
o To open a file
 fclose()
o To close a file
 fwrite()
o To write a record in file
 fread()
o To read a record from file
 fseek()
o To lookup a file position
 rewind()
o To go back to start of the file
 remove()
o To remove a file
 rename()
o To rename a file
 fputc()
o To a character to the file
 fgetc()
o To get a character from file
 fputs()
o To write a string into file
 fgets()
o To read a string from file

 fprintf()
o To write formatted data to a file
 fscanf()
o To read formatted data from file

File Types
1. Text File (default)
2. Binary File – Use b for binary file

File Opening Mode Purpose


“r”  Open an existing file for read only
 If file does not exist, an error is generated
 The file pointer points to the beginning of the file
“w”  Open a new file for writing only
 If a file with the specified filename currently exists, it
will be deleted and a new file will be created in its
place
 The file pointer points to the beginning of the file
“a”  Open an existing file for appending (i.e. for adding
new information at the end of the file)
 A new file will be created if the file with the specified
filename does not exist
 The file pointer points to the position where the data
is to be appended
“r+”  Open an existing file for both reading and writing
 If file does not exist, an error is generated
 The file pointer points to the beginning of the file
“w+”  Open a new file for both reading and writing
 If a file with the specified filename currently exists, it
will be deleted and a new file will be created in its
place
 The file pointer points to the beginning of the file
“a+”  Open an existing file for both reading and appending.
 A new file will be created with a file with the
specified filename does not exist
 The file pointer points to the position where the data
is to be appended

Difference between r+ and w+?


In case of r+, the file must exist. If file does not exits returns NULL
In case of w+, if the file exists, overwrites it contents and if not found, creates a new file
How to open a file?
- Use fopen() function
o FILE *fopen(“filename”,”mode / purpose”)
FILE *fp=fopen("book.dat","rb+");
if(fp==NULL)
fp=fopen("book.dat","wb+");
Closing a file
fclose(fp);

Macros:-- A replaceable code which get replaced at the time compilation. Use #define pre-processor
directive to create the macros
#define P printf
#define S scanf
#define go(r,c) gotoxy(c,r)
#define cl() clreol()
Example
#include<stdio>
#include<conio>
#define P printf
#define S scanf
Example
#include<conio.h>
#define p(a,b) a*b //6+4*10+7 = 53
void main()
{
int n=p(6+4,10+7);
printf("%d",n);
getch();
}

Macros:-- A replaceable code which get replaced at the time compilation. Use #define pre-processor
directive to create the macros
#define P printf
#define S scanf
#define go(r,c) gotoxy(c,r)
#define cl() clreol()
Example
#include<stdio>
#include<conio>
#define P printf
#define S scanf

Example
#include<conio.h>
#define p(a,b) a*b //6+4*10+7 = 53
void main()
{
int n=p(6+4,10+7);
printf("%d",n);
getch();
}

You might also like