POP Using C Module 1 Notes
POP Using C Module 1 Notes
Affiliated to VTU
Dayananda Sagar Academy of Technology & Approved by AICTE
Management Accredited by NAAC with A+ Grade
(Autonomous Institute under VTU) 6 Programs Accredited by NBA
(CSE, ISE, ECE, EEE, MECH, CV)
NOTES
PREPARED BY
SRIDEVI G M
BASIC INFORMATION
Bits, Bytes and Words
Bit: The bit is smallest value which can be stored in computer. The bit is also called as binary
digit. The bit can hold binary value either 0 or 1.
Nibble: The nibble is a collection of four bits.
Byte: The byte is a collection of eight bits. The byte is the standard unit of measurement of computer
memory data storage and transmission speed.
The relationships between these units are expressed in the following manner:
Words: Even though computer memory is measured in bytes (rather mega- or gigabytes), the CPU
handles memory data in larger units, called words, where a word is usually an even multiple of
bytes (two bytes, four bytes, etc.). This number is purely based on processor architecture.
Most machine instructions are one word in size, and because a CPU register must be able to hold an
instruction, it too is one word wide.
Module I
INTRODUCTION TO C
1.1 WHAT IS A COMPUTER?
A computer, in simple terms, can be defined as an electronic device that is designed to accept data,
perform the required mathematical and logical operations at high speed, and output the result. The
processing is fast, accurate and consistent, and is generally achieved without significant human
intervention.
Speed Computers can perform millions of operations per second, which means that data that may
otherwise take many hours to process is output as information in the blink of an eye. The speed
of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond = 1 × 10 −9
seconds and 1 picosecond = 1 × 10 −12 seconds.
Accuracy A computer is a very fast, reliable, and robust electronic device. It always gives accurate
results, provided the correct data and set of instructions are input to it. Hence, in the event of an
error, it is the user who has fed the incorrect data/program is responsible. This clearly means that
the output generated by a computer depends on the given instructions and input data. If the input
data is wrong, then the output will also be erroneous. In computer terminology, this is known as
garbage-in, garbage-out (GIGO).
Automation Besides being very fast and accurate, computers are automatable devices that can
perform a task without any user intervention. The user just needs to assign the task to the
computer, after which it automatically controls different devices attached to it and executes the
program instructions.
Diligence Unlike humans, computers never get tired of a repetitive task. It can continually work for
hours without creating errors. Even if a large number of executions need to be executed, each and
every execution requires the same duration, and is executed with the same accuracy.
Versatile Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fi elds. For example, they are used as personal computers (PCs) for home use, for
business-oriented tasks, weather forecasting, space exploration, teaching, railways, banking,
medicine, and so on, indicating that computers can perform different tasks simultaneously. On
the PC that you use at home, you may play a game, compose and send e-mails, listen to music,
etc. Therefore, computers are versatile devices as they can perform multiple tasks of different
nature at the same time.
Memory Similar to humans, computers also have memory. Just the way we cannot store everything
in our memory and need secondary media, such as a notebook, to record certain important things,
computers also have internal or primary memory (storage space) as well as external or secondary
memory. While the internal memory of computers is very expensive and limited in size, the
secondary storage is cheaper and of bigger capacity.
No IQ Although the trend today is to make computers intelligent by inducing artificial intelligence
(AI) in them, they still do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
Economical Today, computers are considered as short term investments for achieving long-term
gains. Using computers also reduces manpower requirements and leads to an elegant and efficient
way of performing various tasks. Hence, computers save time, energy, and money. When
compared to other systems, computers can do more work in lesser time.
• Program input was provided by punched cards and output was obtained on paper.
• First-generation computers were only used for scientific work and were not deployed
commercially.
Mainframes
• These are multi-user machines that can support hundreds or thousands of users using the
feature of time sharing supported by systems like Linux.
• Users interact with this system using a terminal and keyboard, which is akin to the
way we use PCs.
• Mainframes can concurrently run multiple programs even with a single CPU.
• The processor speed in a mainframe is measured in mip (million instructions per second).
• Mainframes are generally used to handle data and applications related to the organization
as whole.
• The mainframes are employed to handle online transactions (stock exchange transactions,
for instance).
• The capability to handle large amounts of data makes the mainframe suitable for use in
government, banks and financial institutions, and large corporations.
Note:
Minicomputers
• Minicomputers or midrange computers as they can be considered as downsized
mainframes since they have the essential features of mainframes.
• Minicomputers can serve hundreds of users and are small enough to partially occupy a
room. But they are not affordable enough to be used in the home.
• The minicomputer, which Digital Equipment Corporation (DEC) introduced in the 1970s,
is thus rightly positioned between a mainframe and a micro-computer.
• Minicomputers are used in smaller organizations or a department of large one captive
machines of turnkey equipment running specialized software.
Microcomputers
• The microcomputer or personal computer (PC) introduced by Apple and later endorsed by
IBM.
• This computer is a single-user machine powered by a single microprocessor; Today's PCs
are very powerful machines having gigabytes of memory and a terabyte or two of disk
storage.
• They are used both in the standalone mode (at home) and in a network (in office).
• A microcomputer takes the form of a desktop, notebook (laptop) or a netbook (smaller
Laptop).
• Even though a PC has a single CPU, high-end PCs support microprocessors comes with
multiple cores like the Intel Core i5 and i7 etc. Each core can be considered with some
approximation processor by itself.
• PCs today are powered by three types of operating systems Windows, Mac OS and Linux.
• Businesses and individuals use the PC for word processing, spread sheet handling and
desktop publishing; PCs also support Internet browsing software like Firefox and Google
Chrome.
• All PCs are multimedia ready, they can handle images, audio and video files the PC is also
an entertainment device.
• A variant of the microcomputer is the workstation which essentially is a microcomputer
with a more powerful processor, high resolution terminal and high quality graphic
capabilities (like CAD/CAM).
• The smartphone has a powerful processor, usually with multiple cores like the quad- core
Snapdragon 820).
• It also supports gigabytes of main memory but doesn't have a hard disk for secondary
storage. This requirement is met by flash memory (1.10.4).
• Smartphones today run well-developed operating system (Android or iOS), and can run a
wide range of application (popular called “apps”).
2. Embedded computers:
• The embedded computer is a small computer-like that is part of a larger system. Embedded
computers (also called microcontrollers) arrived before smartphones.
• These are very small circuits containing CPU, non-volatile memory and input and output
handling facilities.
• They are embedded into many of the machines that we ears, washing machines, MP3
players and cameras.
• The processor here in a single modifiable program stored in memories embedded
computers can't match the capabilities of a smartphone.
Word Processing software enables users to read and write documents. Users can add images, tables
and graphs. It has automatic correction of spelling mistakes and copy-paste features.
Internet is a network of networks that connects computers all over the world and provides access to
an enormous amount of information. E-mail, Chat software and video conferencing tools
Digital video or audio composition and editing is simpler with computers.
Desktop publishing enables users to create page layouts for entire books
● Government ● Simulation
● Traffic Control ● Geology
● Legal System ● Astronomy
● Retail ● Weather Forecasting
● Sports ● Education
● Music ● Online Banking
● Movies ● Industry and Engineering
● Travel and Tourism ● Robots
● Business and Industry ● Decision Support Systems
● Hospitals ● Expert Systems
In this section, we will discuss all these functions and see how one unit of a computer interacts with
another to perform these operations. Figure 1.11 shows the interaction between the different units of
a computer system.
Input This is the process of entering data and instructions (also known as programs ) into the
computer system. The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner, and trackball. Note that computers understand binary language, which
consists of only two symbols (0 and 1), so it is the responsibility of the input devices to convert the
input data into binary codes.
Storage: Storage is the process of saving data and instructions permanently in the computer so that
they can be used for processing. The computer storage space not only stores the data and programs
that operate on that data but also stores the intermediate results and the final results of processing.
A computer has two types of storage areas:
Primary storage Primary storage, also known as the main memory , is the storage area that is directly
accessible by the CPU at very high speeds. It is used to store the data and parts of programs, the
intermediate results of processing, and the recently generated results of jobs that are currently being
worked on by the computer. Primary storage space is very expensive and therefore limited in
capacity. Another drawback of main memory is that it is volatile in nature; that is, as soon as the
computer is switched off, the information stored gets erased. Hence, it cannot be used as a permanent
storage of useful data and programs for future use. An example of primary storage is random access
memory (RAM).
Secondary storage Also known as auxiliary memory, this memory is just the opposite of primary
memory. It overcomes all the drawbacks of the primary storage area. It is cheaper, non-volatile, and
used to permanently store data and programs of those jobs that are not being currently executed by
the CPU. Secondary memory supplements the limited storage capacity of the primary memory. An
example is the magnetic disk used to store data, such as C and D drives, for future use.
Output Output is the process of giving the result of data processing to the outside world (external to
the computer system). The results are given through output devices such as monitor, and printer.
Since the computer accepts data only in binary form and the result of processing is also in binary
form, the result cannot be directly given to the user. The output devices, therefore, convert the results
available in binary codes into a human-readable language before displaying it to the user.
Control The control unit (CU) is the central nervous system of the entire computer system. It
manages and controls all the components of the computer system. It is the CU that decides the manner
in which instructions will be executed and operations performed. It takes care of the step-by-step
processing of all operations that are performed in the computer. Note that the CPU is a combination
of the arithmetic logic unit (ALU) and the CU. The CPU is better known as the brain of the computer
system because the entire processing of data is done in the ALU, and the CU activates and monitors
the operations of other units (such as input, output, and storage) of the computer system.
Processing The process of performing operations on the data as per the instructions specifi ed by the
user (program) is called processing . Data and instructions are taken from the primary memory and
transferred to the ALU, which performs all sorts of calculations. The intermediate results of
processing may be stored in the main memory, as they might be required again. When the processing
completes, the fi nal result is then transferred to the main memory. Hence, the data may move from
main memory to the ALU multiple times before the processing is over.
RAM A fast CPU is of no use if the computer does not have sufficient RAM. As discussed earlier,
RAM is the computer’s memory which stores information used by applications that are currently
being executed by the CPU. More memory means more applications can be executed at the same
time without degrading the system’s performance.
Hard disk drive (HDD) The HDD of the computer is the secondary memory of the computer system
where information is stored permanently. All types of data, documents, and programs are stored on
the hard disk. The larger the hard disk, the more the amount of data that can be stored on the drive.
Though the size of the HDD does not affect the speed of execution of the program, it does affect the
speed at which the user can access his/ her files.
Video card The video card is a board that plugs into the motherboard of the computer and generates
images for display. Many video cards these days have their own RAM and processor to enhance the
speed of the graphics display. Many computers come with an in-built video chip. In such a computer,
a separate video card is used only if the computer has to be used for high-end multimedia work or to
play video games.
Sound card As with video cards, sound cards are expansion boards that are used to enable a computer
to manipulate sound. For example, sound cards allow the users to plug in speakers and a microphone.
Some sound cards also provide the jacks for hooking your computer up to a common stereo.
Modem A modem (modulator–demodulator) is a device that enables the computer to use a telephone
line to communicate and connect to the Internet.
Network card A network card is used to connect the computer either to other computers or to the
Internet (in case you are using a fast Internet connection such as cable or DSL).
Fans There are one or more fans inside the computer to keep the air moving and the computer cool.
Cables There are multiple wires inside the computer that are fl at, ribbon-like cables. They are used
to provide power and communication to the various parts inside the computer.
Trackball Trackpad
3. Handheld Devices
• Joystick
• Stylus
• Touchscreen
4. Optical Devices
• Barcode Reader
• Image Scanner
• Optical Character Recognition
• Optical Mark Recognition
• Magnetic Ink Character Reader
• Plotter
a. Drum Plotter
b. flatbed plotter
3.1 HISTORY OF C
The root of all modern languages is ALGOL, introduced in the early 1960s. ALGOL was the first
computer language to use a block structure. Although it never became popular in USA, it was
widely used in Europe. ALGOL gave the concept of structured programming to the computer
science community.
In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming
Language) primarily for writing system software.
In 1970, Ken Thompson created a language using many features of BCPL and called it simply B.
B was used to create early versions of UNIX operating system at Bell Laboratories. Both BCPL
and B were "typeless" system programming languages.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972.
C uses many concepts from these languages and added the concept of data types and other
powerful features.
Since it was developed along with the UNIX operating system, it is strongly associated with
UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost
entirely in C.
During 1970s, c had evolved into what is now known as "traditional C". The language became
me popular after publication of the book The C Programming Language' by Brian Kerningham
and Dennis Ritchie in 1978. The book was so popular that the language came to be known as
"K&R C”
To assure that the C language remains standard, in 1983, American National Standards institute
(ANSI) appointed a technical committee to define a standard for C. The committee approved a
version of C in December 1989 which is now known as ANSI C. It was then approved by the
International Standards Organization (ISO) in 1990. This version of C is also referred to as C89.
History of ANSI C
Uses of C
• It is primarily used for system programming. The portability, efficiency, the ability to
access specific hardware addresses and low runtime demand on system resources makes it
a good choice for implementing operating systems and embedded system applications
• Compilers, libraries and interpreters of other programming languages are often
implemented in C
• C is sometimes used as an intermediate language for implementation of other languages
• Widely used to Implement end user applications
NOTE: All sections, except the main function section may be absent when they are not
required.
1. Source code file: contains the source code of the program. The file extension is ‘.c’.
2. Header files: Some of the predefined functions and user defined functions are kept in header
files to reuse the functions without duplication. The file extension is ‘.h’
USING COMMENTS
The data type defines the type of data stored in a memory-location and allocates memory for the data.
The number of bytes allocated is based on architecture of the machine.
C supports three classes of data types:
1. Primary data type
Example: int, float, char, double, void
2. Derived data types Example: array
3. User-defined data types Example: structure
C supports five types of primary data types as illustrated in the figure 2.4.
int (integer)
• An int is a keyword which is used to define integers.
• Using int keyword, the programmer can inform the compiler that the data associated with
this keyword should be treated as integer.
• Integer is used to store whole number with the range of values supported by a particular
machine.
• Generally integer occupies one word of storage of machine which generally varies, (i.e. 16
or 32). In this notes 32 bit machine is considered.
• Integer will come up with signed and unsigned version.
• In signed integers out of allocated bits one bit i.e. MSB bit acts as sign bit and remaining
bits are used store value.
• In unsigned integers all allocated bits are used to store value.
3.7 VARIABLES
• A variable is a data name that may be used to store a data value and which can be changed
during the execution of program.
• A variable may take different values at different times during execution.
• A variable name can be chosen by the programmer in a meaningful way so as to reflect its
function or nature in the program.
• Numeric Variables
• Character variables
• Declaring variables
• Initialising variables
Declaring variables
The declaration does two things
• It tells the compiler what is the name of the variable used
• It specifies what type of data the variable will hold.
The syntax is
|data type variablenamel, variablename2, variablename3;
Where:
data type is any data-type which is supported by C language.
variablenamel, variablename2,... , variablenameN are variable-names which are taken by following
the rules.
Example:
int sum, total, number; float marks, average, area;
Initialising variables
• The variables are not initialized when they are declared. Hence, variables normally contain
garbage values and hence they have to be initialized with valid data.
• To assign a value to variable assignment operator (=) is used.
• The value can be assigned in two ways
• When a variable is declared, such assignment is called initialization.
Syntax:
data type var_name = value;
3.8 C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program. Each and every smallest individual units in a C program are known as C tokens.
C tokens are of six types. They are,
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
1. KEYWORDS
Keywords are reserve words which has predefined meaning in complier and which are used for their
intended purpose only.
There are 32 keywords in ANSI C and they are listed in following table
2. IDENTIFIERS
As the name indicates, identifier is used to identify various entities of program such as variables,
constants, functions etc.
Identifiers are user defined names and consists of sequence of letters and digits.
Rules for identifiers
3. CONSTANTS
A constant is an identifier whose value remains fixed throughout the execution of the program.
C supports several types of constants.
1. Integer constant
In integer there are three types of constants
a. Decimal: Consists of set of numbers between 0 and 9 and sign ‘-’ or ‘+’ are optional.
Example: 112, -150, +652 etc.
b. Hexadecimal: A sequence of digits preceded by Ox or OX is referred as hexadecimal constants.
Example: 0x6, 0X55, OXabe
Octal: It consist of any combination of digits between) through 7, with a leading 0.
Example: 037, 045, 0123
Real Constants
The quantities that represented by numbers containing fractional parts like 3.142, such numbers are
called real (or floating point) constants.
Example: 3.142, -4.124, +444.0 etc.
A real number can also be expressed in exponential (or scientific) notation.
Example: 215.65 can also be written as 2.1565e2
Where e2 means multiply by 102 The general form is
mantissa e exponent
Where
• mantissa is either a real number expressed in decimal notation or an integer.
• exponent is an integer number with an optional plus or minus sign.
• e separates the mantissa and the exponent can be written in either lowercase or uppercase.
String Constants
• The symbolic constants may then appear later in the program in place of the numeric
constants, character constants, etc., that the symbolic constants represent.
Where:
• #define is a pre-processor directive.
• symbolic name is the name taken by following the rules of identifiers.
• value of constant is the value which a symbolic name should hold.
Example:
Since the symbolic names are constants they do not appear in declarations.
The following rules apply to #define statement which defines a symbolic constant:
1. Symbolic names have the same form as variable names. (Symbolic names are written in
CAPITALS to visually distinguish them from the normal variable names, which are written
in lowercase letters. This is only a convention, not a rule.)
2. No blank space between the pound sign and the word define is permitted.
3. must be the first character in the line.
4. A blank space is required between ^define and symbolic name and between the symbolic
name and the constant.
5. #define statements must not end with a semicolon.
6. After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement. For example, STRENGTH = 200; is illegal
constant.
7. Symbolic names are NOT declared for data types. Its data type depends on the type of
8. #define statements may appear anywhere in the program but before it is referenced in the
program (the usual practice is to place them in the beginning of the program).
• However, it can be used on the right side of an assignment statement like any other variable.
• This type of constant is also called as Memory constant.
4. STRINGS
Strings are nothing but an array of characters ended with a null character ('\0'). This null character
indicates the end of the string. Strings are always enclosed in double quotes.
char string[20] = {‘h’, ’e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘w’, ‘o’, ‘r’, ’l’, ‘d’, ‘\0’};
char string[20] = “hello world”;
char string [] = “hello world”;
5. SPECIAL SYMBOLS
{,},[,],?,+,-,*,/,%,!,;,
6. OPERATORS
Operators are symbols that represent operations to be performed on one or more operands. C provides
a wide range of operators, which can be classified into different categories based on their
functionality. Operators are used for performing operations on variables and values.
FORMATTING INPUT/OUTPUT
C language supports two formatting functions printf and scanf.
printf is used to convert data stored in the program into a text stream for output to the
monitor(Standard output device)
scanf is used to convert the text stream coming from the keyboard(Standard input device) to data
values and stores them in program variables.
A program that uses standard I/O functions must contain the statement
#include< stdio.h>
Flags Specify output justification such as decimal point, numerical sign, trailing zeros or octal,
decimal or hexadecimal prefixes.
Width specifies the minimum number of characters to print after being padded with zeros or blank
spaces, that is it specifies the minimum number of positions in the output
Printf examples
Width is an optional argument that specifies the maximum number of characters to be read.
Modifier is an optional argument that can be h, l or L for the data pointed by the corresponding
additional arguments.
Type specifies the type of data that has to be read
Example:
Examples of printf/scanf
errors in Programming can be identified during the program’s compilation or execution, and it’s
crucial to remove them to ensure the program runs smoothly. Here we will discuss the various
types of errors in programming and some of the common causes behind them. So, let’s dive
straight into the topic of Types of Errors in Programming.
Syntax Error
Run-Time Error
Linker Error
Logical Error
Semantic Error
1. Syntax Error
A syntax error is the most common type of error in programming. It occurs when the programmer
writes code that is not in accordance with the syntax of the programming language. Syntax errors
are detected by the compiler, and the compiler reports an error message to the programmer.
#include <stdio.h>
int main()
{
printf( "Hello, world!")
return 0;
}
Output:
;
return 0;
~~~~~~
Explanation:
In the above example, the programmer forgot to add a semicolon after the cout statement, resulting
in a syntax error as shown in the output.
2. Run-time Error
A run-time error occurs during the execution of a program. These errors occur when a program tries
to perform an illegal operation, such as dividing by zero or attempting to access an invalid
memory address. The program compiles without errors, but when it runs, it encounters an error
that causes it to terminate abnormally. Run-time errors are often difficult to detect because they
do not show up until the program is executed.
#include <stdio.h>
int main()
{
int a = 5, b = 0;
int c = a / b;
printf("The result is %d ", c);
return 0;
}
Output:
3. Linker Error
A linker error occurs when a program references a function or variable that is not defined in the
program or the libraries it is linked against. Linker errors typically occur when a program is
compiled and linked. The linker will report an error if it cannot find the necessary files or libraries
to link the program.
#include <stdio.h>
int main()
{
printf( "Hello, world!");
myFunction();
return 0;
}
Output:
4. Logical Error
A logical error occurs when the program compiles and runs without any syntax, run-time, or linker
errors, but the output is incorrect. These errors occur when the program's logic or algorithms are
incorrect. Logical errors are challenging to detect because the program does not generate any
error messages.
#include <stdio.h>
int main() {
int a = 5, b = 7;
if (a > b) {
printf( "a is less than b");
} else {
printf( "b is less than a");
}
return 0;
}
Output:
b is less than a
Explanation:
In the above example, the program intends to check if a is less than b. However, the program checks
if a is greater than b, resulting in incorrect output. The logic for checking the smaller number is
wrong because of the usage of the ‘>’ sign instead of ‘<’.
5. Semantic Error
Semantic errors are errors that occur when the code written by the programmer makes no sense to
the compiler, even though it is syntactically correct. They are different from syntax errors, which
indicate errors in the structure of the program, as semantic errors are related to the meaning and
implementation of the program.
For example,
Using a string instead of an integer or accessing an array index that is out of bounds can cause
semantic errors.
Uninitialized variables and type incompatibility are other common types of semantic errors.
Example of Semantic Error
Here is the code for a better understanding of Semantic Errors in Programming.
#include <stdio.h>
int main() {
int a, b, c;
a * b = c;
// This will generate a semantic error
return 0;
}
Output:
Conclusion
In conclusion, programming is a complex task that requires a high level of attention to detail. Errors
can occur at various stages of the programming process. There are different types of errors in
programming including syntax errors, run-time errors, linker errors, logical errors, and semantic
errors. Syntax errors are the most common type of error, while run-time errors are often the most
challenging to detect. Linker errors occur during the compilation and linking process, while
logical errors and semantic errors occur when the program's algorithms or requirements are
misunderstood.
Algorithm:
STEP 1: Start the program.
STEP 2: Read the values of ‘a’&’b’.
STEP 3: Compute the sum of the entered numbers ‘a’,’b’ as c=a+b.
STEP 4: Print the value of ‘c’.
STEP 5: Stop the program.
Pseudo code:
BEGIN
READ ‘a’&’b’
COMPUTE c=a+b
WRITE ‘c’
END
FLOWCHART SYMBOLS
Example 2: To determine a student’s final grade and indicate whether it is passing or failing. The
final grade is calculated as the average of four marks.
Algorithm:
Step 1: Start
Step 2: Input a set of 4 marks
Step 3: Calculate their average by summing and dividing by 4
Step 4: if average is below 50
Print “FAIL”
else
Print “PASS”
Step 5: Stop
Pseudocode:
BEGIN
Input M1,M2,M3,M4
GRADE (M1+M2+M3+M4)/4
if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
END
Flowchart: