Notes All Units
Notes All Units
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).
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.
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.
According to size:
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:
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).
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
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.
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.
Operating system constantly monitors the system to detect errors and avoid the malfunctioning of
computer system.
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.
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.
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
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.
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
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.
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:
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.
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 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 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:
Conversely, one instruction in a high level language will translate to one or more instructions at
machine level.
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).
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.
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.
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:
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.
#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
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.
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Ans.
step 1 : start
else
endif
step 5 : stop
Q3. Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 4: If a>b
If a>c
Else
Else
If b>c
Else
Step 5: Stop
Step 1: Start
factorial←1
i←1
5.1: factorial←factorial*i
5.2: i←i+1
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.
flag←1
i←2
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
else
Display n is prime
Step 7: Stop
Step 1: Start
5.1: temp←second_term
5.3: first_term←temp
5.4: Display second_term
Step 6: Stop
Step 1: Start
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Else
rp←b/2a
ip←√(-D)/2a
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.
Connector Symbol
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.
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.
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
Example
Octal Number: 258
Calculating Binary Equivalent:
1 0
Step 1 258 ((2 x 8 ) + (5 x 8 ))10
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
Example
Binary Number: 101012
Calculating Octal Equivalent:
Step Binary Number Octal Number
Step 2 101012 28 58
Example
Octal Number: 258
Calculating Binary Equivalent:
Step Octal Number Binary Number
Example
Binary Number: 101012
Calculating hexadecimal Equivalent:
Step Binary Number Hexadecimal Number
Example
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
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.
int
float
double
char
Please note that there is not a boolean data type. C does not have the traditional view about logical
comparison
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:
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.
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
const
volatile
The const qualifier is used to tell C that the variable value cannot change after initialisation.
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.
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)
printf("i is %d\n",i);
if (j > 0)
int i=100;
printf("i is %d\n",i);
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!
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 );
}
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();
}
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
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.
1. automatic
2. external
3. static
4. register
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.
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.
#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
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 int i;
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
Control Statements:
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:
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)
{
}
else
{
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)
{
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
{
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.
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.
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.
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();
}
temp=n;
while(temp)
{
d=temp%10;
sum=sum+d;
temp=temp/10;
}
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)
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;}
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);
}
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.
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.
Once the structure data type has been defined, the individual variables of the structure type can be declared as
follows:
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 :
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.
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;
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;
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.
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:
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
{
int roll_no;
char name[20];
float marks;
} s1={127, “Amit”,67};
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,
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*/
Illustration 1 : Write a program to illustrate the use of members of a structure variable using the member
operator.
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 :
If the member of a structure is an array, then the individual array elements are used as
structure_variable.member[index];
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 */
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.
i.e. the values of the individual members of s1 are assigned to those of s2.
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:
Test Run 2:
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);
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
For example
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 :”);
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;
};
sizeof(point);
will return the number of bytes (4 in this case) required to hold all the members of the structure point.
sizeof(p);
will return the number of bytes required to hold the members of the variable p. The expression will return 4.
sizeof(px);
will return the total number of bytes that the array p requires.
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
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;
The statement
ptr = &new_point;
The members of new_point are accessed through the pointer ptr in the statement
For example,
typedef struct student
{
int roll_no;
char name[20];
float marks;
};
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
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
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.
temp.y = 67.3;
printf(“%d”, temp.y);
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,
and
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.
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
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(); }
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
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();
}