C language Unit-1 Notes
C language Unit-1 Notes
, I Semester
SYLLABUS
Unit 1
General fundamentals: Introduction to Computers-
Block diagram of computers- Characteristics and limitations of computers-Applications of computers-
Types of computers-Computer generations.
Introduction to algorithms and programming languages
Algorithm- Key features of algorithms- Flowcharts-Programming languages-Generations of programming
languages-Structured programming language-Design and implementation of correct efficient and
maintainable programs.
Unit 2
Introduction to C
Introduction-Structure of C program-Writing the first C program-Files used in C program-Compiling and
Executing C programs- Using comments-Keywords-Identifiers-Basic data types in C-Variables-Constants-
I/O statements in C-Operators in C-Programming examples
Decision control and looping statements
Introduction to decision control statements- Conditional branching statements-Interactive statements-Nested
loops-Break and continue statements.
Unit 3
Arrays
Introduction-Declaration of arrays- Accessing elements of the array-Storing values in array-Operations on
arrays-One dimensional-Two dimensional and multidimensional arrays-Character handling and Strings.
Unit 4
Functions
Introduction- Using functions-Function declaration/prototype-Function definition-Function call -return
statement-Passing parameters-Scope of variables-Storage classes-Recursive functions.
Structure, Union and Enumerated data types
Introduction-Nested structures-Arrays of structures-Structures and functions-Union- arrays of unions
Variables-Union inside structures-Enumerated data types
Unit 5
Pointers
Understanding Computer memory-Introduction to pointers- declaring pointer variables- pointer expressions
and pointer arithmetic-Null pointers- Passing arguments to functions using pointer-Pointer and arrays-
Memory allocation in C programs-Memory usage-Dynamic memory allocation-Drawbacks of pointers.
Files
Introduction to files- Using files in C- Reading data from files- Writing data to files- Detecting the End Of
File- Error handling during file operations-Accepting command line arguments.
Unit – I
Introduction to computers
Computer Definition:
Computer is an electrically electronic mechanical device which accepts certain information (data) as the input, stores it
in its memory, processes it according to the instructions given by the user. There by producing the result as the output.
In a simpler way, a computer is an electronic device that takes data and instructions as an input from
the user, process data and provides useful information known as an output.
DATA: Data is a meaningless collection. It is also called as raw data. Data is defined as collection of facts,
figures and numbers.
PROCESS: Process is a set of actions (or) set of instructions given to computer to do a specific task.
I/p O/p
Data Process Information
Set of Instruction
a) Keyboard
b) Mouse
C) Scanner
a) Keyboard: Key board is an input device used to type the information into the system. The standard
keyboard includes alpha numeric keys, function keys, modifier keys, cursor, movement keys, space bar,
escape key, numerical keypad and some special keys such as page up, page down, home, end, insert, delete.
b) Mouse: Mouse is used to point to a specific object and select it. The mouse allows the user to select
elements on the screen ,such as tools, icons buttons by pointing and clicking them .The mouse is also known
as a pointing device because it helps changing the position of the pointer (or) cursor on the screen.
c) Scanner: Scanner is an input device that converts documents and images as digitized images
understandable by the computer system. There are three types of scanner that can be used to produce
digitized images.
1) Flat bed scanner
2) Drum scanner
3) Slide scanner
2. Output devices:
An output device is a device which provides the result as the output to the user. The output device includes
monitors, printers, plotters and speakers.
1. Monitors: Monitor is also called as visual display unit (or) output screen. It provides visual display
generated by the computer. Here we get the soft copy of the output. Types of monitors are
1) C R T - Cathode ray tube monitors.
2) L C D - Liquid crystal display monitors.
C R T monitor are large, occupy more space where as L C D are thin, light, weighted and occupy less space.
2. Printers: The printer is an output devise that transfer the result displayed on the screen, on to the paper
sheets that can be used by the end user.
The various types of printers used in the market are generally categorized as
1) Dot matrix printer 2) Inkjet printers 3) Laser printers
1) Dot matrix printers are commonly used in low quality and high volume application like in voice printing
caste register etc.
Department of Computer Science Page 3
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., I Semester
2) Inkjet printers are slower than dot matrix printers and generate high quantity photographic prints.
3) Laser printers consist of microprocessor, RAM and ROM. they can produce high quantity print in quicker
time without being connected to a computer.
3. Plotters: The plotter is another commonly used o/p device that is connected to a computer to print large
documents, such as engineering (or) constructional drawing.
Plotters are classified on the basis of their performance, as follows
1) Drum plotter 2) Flat bed plotter 3) Inkjet plotter 4) Electrostatic plotter.
4. Speakers: Speakers converts an electrical signal into sound. Speakers are attached to a computer as output
devices to provide audio output, such as warnings, sounds and internet audio.
Memory
Cache memory:
Cache memory is a small, fast and expensive memory that stores the copies of data that needs to be
accessed frequently from the main memory. There are two types of cache memory found in the computer
system.
Primary cache: It is also known as level 1 cache (or) internal cache. This cache is located inside the C.P.U. It
is smaller but fastest type of cache that provides quick access to the frequently accessed data by the micro
processor.
Secondary cache: It is also known as level 2 (or) cache (or) external memory. This cache is located outside
the C.P.U .It is normally positioned on the mother board of a computer. The secondary cache is large but
slower than primary cache.
Memory of a computer is an ordered sequence of large locations called memory cells. Each memory
cell has a unique address that indicates its relative position in memory.
A memory cell is actually a grouping of smaller units called bytes. A byte is the amount of storage
1 byte= 8 bits
Applications of Computers:
Following list demonstrates various applications of computer
1. Business: A compute has high speed of calculations, reliability or versatility which made it an
integrated part in all business organization. Computer is used in business organizations for the
following purpose
Budgeting
Sales Analysis
Financial Forecasting
Maintenance of stock etc
2. Banking: Today banking is totally dependent on computer. Banks provide following facilities like
online accounting facility which include current balances, deposits, overdrafts, interest charges,
shares and trustee records and ATM machines are making it easier for customers to deal with banks.
3. Insurance: Insurance companies are keeping all records up to the date with the help of computers. It
maintains a database of all clients with the following information such as
Department of Computer Science Page 6
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., I Semester
4. Education: The computer has provided a lot of facilities in the education system like Computer
based Education which controls, delivery and evaluate learning.
5. Marketing: In marketing the uses of computer are as follows-Advertising, home shopping etc
6. Health Care: Computers have become important part in hospitals, labs and dispensaries to keep the
record of patients and medicines. It is also used in scanning and diagnosing different diseases. ECG,
EEG, Ultrasounds and CT are also done by computerized machines.
7. Engineering: Computers are used in CAD (Computer Aided Design) that provides creation and
modification of images. In Structural Engineering computers are used to analyse stress and strain of
the material to design the ships, buildings, airplanes etc. In Architectural Engineering computers are
used for planning towns, designing buildings, determining arrangement of buildings on a site
providing 2D and 3D view of drawings.
8. Military: Computers are used to implement computerized control systems in defence. Some of the
military areas where computer are used are Missile control, Military communication, Military
operations and planning, smart weapons.
9. Communication: Communication means conveying the message or video or speech or picture that is
received and understood clearly and correctly by the person for whom it is meant for. Some of the
categories are E-Mail, Chatting, and Video Conference.
10. Government: Computer plays an important role in government fields. Some major fields where
computers are used are Budgets, Sales tax Department, income tax department, male female ratio,
Computerization of voter’s lists, computerization driving licence system, etc.
temperature, pressure, volume, force, current, velocity, acceleration etc. and convert them to
Analogous quantities. It has limited memory. Analog computes are particularly used in chemical
processes where continuous measurement is needed.
B) Digital Computers: These computers operate on discrete data represented by a finite sequence
of digits and perform arithmetic and logical operations on such data and produce discrete data as
an output. It is used in large scientific and business applications. All the modern computers are of
digital type. The digital computers are classified into two categories depending upon the
applications
Special purpose Computers: These computers are designed to perform a specific application.
These computers are used in mining. Aircraft control systems, missile guidance systems.
Computer aided De4sign, Computer aided manufacturing are few applications of special purpose
Computers. These computers are also used to control Industrial Robots.
General purpose Computers: These computers are designed to meet the needs of many
different applications. These are also used in scientific and business applications.
C) Hybrid Computers: Hybrid computers possess the capabilities of both analog as well as digital
computers. These are used in controlling of space vehicles and also used in medical department
to monitor the patient’s health condition.
d) Mainframe computers: Computers with large storage capabilities and very speed in processing
compared to micro computers and mini computers are known as mainframe computers the
earliest computers were called mainframes due to their size their memory capacity varies from
64mb to 256 MB the speed is in the order of 5200 m i p s the word length is generally 64 bits are
more mainframe computers are used in scientific research and big organisations like BHEL
ONGC etc.
e) Super Computers: Super computers are the largest and the fastest computers and generally
used for more complex scientific applications. These computers perform billions of operations
per second these machines have word length in the order of 64 bits to 128 bits. Super computer
are mainly used in defence, research, weather forecasting and medicine. Their price is in the
range of 10 to 20 crores.
The development of computer system is normally discussed as the development over different generations.
1. First generation:
The period 1942-1956 roughly considered as a first generation of Computer. The first generation computers
were developed by using vacuum tube or thermionic valve machine. The input of the system was based on
punched cards and paper tape however the output was displayed on printouts. The first generation computers
work on binary coded concept (language of zeros and ones).
Examples are ENIAC, EDVAC etc.
2. Second generation:
The period 1956 to 1963 is rapidly considered as a period of second generation of computers. The second
generation computers were developed by using transistor technology. In comparison to the first generation
the size of the second generation was smaller. In comparison to computers of the first generation the
computing time taken by the computers of the second generation was lesser.
3. Third generation:
The period 1963 to 1971 is roughly considered as a period of third generation of computers. The third
generation computer was developed by using the Integrated circuit Technology. In comparison to the
computers of the second generation the size of the computers of the third generation was smaller. In
comparison to the computers of the second generation the computing time taken by the computers of 3rd
Generation was lesser. The third generation computers consume less power and also generated less heat. The
maintenance cost of the computers in the third generation was also low. Computers of third generation were
easier for commercial use.
4. Fourth generation:
The period 1972 to 2010 is roughly considered as a fourth generation of computers. The fourth generation
computer was developed by using microprocessor technology. By coming to fourth generation-computer
become very small in size, it became portable. The mission of 4th generation started generating very low
amount of heat. It is much faster and accuracy became more reliable. The production cost reduced to very
low in comparison to the previous generations. It became available for the common people as well.
5. Fifth generation:
The period 2010 to till date and beyond, roughly considered as a period of 5th generation of computers. By
the time the computer generation was being categories on the basis of hardware only, but the fifth generation
Technology also included software. The computer of the fifth generation had high capability and large
memory capability. Working with computers of this generation was fast and multiple tasks could be
performed simultaneously. Some of the popular advanced Technologies of the fifth generation include
Artificial intelligence, Quantum computation, Nano technology, Parallel processing etc.
2) Decision: Decision statements are used when the outcome of the process depends on some condition.
For example, if X=Y, then print “Equal”. Hence, the general form of the ‘if’ construct can be given as
if condition then process
A decision statement can also be stated in the following manner:
if condition
then process1
else
process2
The above form is commonly known as the ‘if-else’ construct. Here, if the condition is true then “process1”
is executed, else “process2” is executed.
An algorithm to check the equality of two numbers is written as follows:
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: if A=B
then print “Equal”
else
print “Not equal”
Step 4: End
3) Repetition: Repetition involves executing one or more steps for a number of times. This can be
implemented by using the constructs such as the while, do-while and for loops. These loops execute one
or more steps until some condition is true.
Algorithm to print first 10 natural numbers.
Step 1: [initialize] set I=1, N=10
Step 2: Repeat steps 3 & 4 Until I<=N
Step 3: print I
Step 4: Set I=I+1
Step 5: End
➢ Examples on Algorithms:
1. Write an algorithm for swapping two values
Solution:
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: print A, B
Step4: assign temp=A
Step 5: assign A=B
Step 6: assign B=temp
Step 7: print A, B
Step 8: End
2. Write an algorithm to find the largest among two numbers
Solution:
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: if A>B
then print A
else if A<B
then print B
else
print “The numbers are equal”
Step 4: End
3. Write an algorithm to find whether a given number is an even or odd.
Solution:
Step 1: Input the first number as A
Step 2: if A%2=0
then print “Even”
else
print “Odd”
Step 3: End
-----------------------------------------------------------------------------------------------------------------------------------
Flowcharts:
A flowchart is a graphical or symbolic representation of a process. It is basically used to design and
document virtually complex processes to help the viewers to visualize the logic of the process.
When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description. The symbols in the flowchart are linked together with arrows to show
the flow of logic in the process. The symbols of a flowchart include:
1. Start and End symbols (oval or rounded rectangle): Start and end symbols are also known as the
terminal symbols and are represented as oval or rounded rectangle. Terminal symbols are always the
first and the last symbols in a flowchart.
2. Arrows: Arrows depict the flow of control of the program. They illustrate the exact sequence in which
the instructions are executed.
3. Processing symbol (rectangle): Processing is also called as an activity, is represented using a
rectangle. Activities include instructions such as “add a to b”, “save the result”. Therefore, a processing
symbol represents arithmetic and data movement instructions.
4. Input/output symbols(parallelogram): Input and output are represented using a parallelogram and
are used to get inputs from the users or display the results to them.
5. Conditional or decision symbol (Diamond box): Condition symbol is represented using a diamond. It
is basically used to depict a Yes/No question or True/False test. The two links coming out of it, one
from the bottom point and the other from the right point corresponds to Yes and No respectively. A
decision symbol in a flowchart can have more than two arrows, which indicate that a complex decision
is being taken.
6. Labeled connectors (circle): Connector are represented by an identifying label inside a circle and are
used in complex diagrams to substitute for arrows. For each label, the ‘outflow’ connector must have
one or more ‘inflow’ connectors. A pair of identically labeled connectors is used to indicate a continued
flow when the use of lines becomes confusing.
Advantages of Flowchart:
1. It helps to understand the flow of program control in an easy way.
2. Developing program code by referring its flowchart is easier in comparisons to developing the program
code from scratch.
3. It helps in avoiding semantic errors.
4. Any concept is better understood with the help of visual representation. This fact also holds true for
flowcharts. It is easier to understand the pictorial representation of a programming logic.
5. A flowchart acts as documentation for the process or program flow.
6. The use of flowcharts works well for small program design.
Disadvantages of Flowcharts:
1. For a large program, the flowchart might become very complex and confusing.
2. Modification of a flowchart is difficult and requires almost an entire rework.
3. Flowcharts require pictorial representation of programming elements, it becomes a little tedious and
time consuming to create a flowchart.
4. Excessive use of connectors in a flowchart may confuse the programmers.
Examples on Flowcharts:
1. Draw a flowchart to find the sum of two numbers.
Solution: Start
Read A, B
Sum = A+B
Display Sum
Stop
Department of Computer Science Page 16
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., I Semester
Read a, b
Is a>b
Is b>c Is a>c
Print b Print a
Print c
Stop
General Special
Purpose purpose
Ex: C, COBOL, Ex: LISP,
Java PROLONG
1. Low-level language: Low level languages are easily understandable by the machine but very difficult for
the user to understand the code. The computer can understand only the binary digits 0’s and 1’s. Instruction
written in binary notation is called machine language programs.
Merits:
➢ It is directly understood by the processor so has faster execution time since the programs written in
this language need not to be translated.
➢ It doesn’t need larger memory.
Demerits:
➢ It is very difficult to write a program since all the instructions are to be represented by 0s and 1s.
➢ Use of this language makes time consuming to complete the task.
➢ It is difficult to find error and to debug.
➢ It can be used by experts only.
2. Intermediate-level language: In order to reduce the burden of the user, symbolic languages are
developed. These languages are called assembly languages. These use symbolic notation to represent the
instructions of the machine language.
Ex: ADD B Add the contents of accumulator to number B.
OUT O/P the contents of accumulator.
Merits:
➢ It is makes programming easier than 1GL since it uses mnemonics code for programming. E.g.:
ADD for addition, SUB for subtraction, DIV for division, etc.
➢ It makes programming process faster.
➢ Error can be identified much easily compared to 1GL.
➢ It is easier to debug than machine language.
Demerits:
➢ Programs written in this language is not directly understandable by computer so translators should be
used.
➢ It is hardware dependent language so programmers are forced to think in terms of computer’s
architecture rather than to the problem being solved.
➢ Being machine dependent language, programs written in this language are very less or not portable.
➢ Programmers must know its mnemonics codes to perform any task.
3. High-level language: High level languages are easily understandable by the user. High level languages
contain the instructions that are much like English. The high level language is easy to learn. It requires
less time to write and is easy to maintain the errors. The high level language is converted into machine
language by one of the two different languages translator programs; “interpreter or compiler”. High
level language can be further categorized as:
General Purpose languages:
These languages are used for writing software in the widest variety of application domains.
Ex: COBOL, C, Pascal, Basic
Merits:
➢ Because of their flexibility, these languages are able to solve a variety of problems.
➢ Programmer does not need to think in term of computer architecture which makes them focused on
the problem.
➢ Programs written in this language are portable.
Demerits:
➢ It is easier but needs higher processor and larger memory.
➢ It needs to be translated therefore its execution time is more.
LANGUAGE TRANSLATORS:
1. Assembler: An assembler is a computer program that translates assembly language statements into
machine language code. The assembler takes each of the assembly language statements from the source code
and generates a corresponding bit stream using 0’s and 1’s.
The O/P of the assembler in the form of sequence of 0’s and 1’s is called ‘Object code’ (or) ‘Machine code’.
This machine code is finally executed to obtain the results.
2. Compiler: Compiler is a computer program that translates the source code written in a high level into the
corresponding object code of the low-level language. This translation process is called ‘Compilation’. The
entire high-level program is converted into executable machine code file.
3. Interpreter: The interpreter is a translation program that converts each high-level program statement into
corresponding machine code. Instead of entire program one statement is translated and executed
immediately.
The high level language is first translated into the target computer’s machine language by the compiler. The
input to the compiler is the source file containing the text of a high level language.
If the program is syntactically correct, the compiler saves in an object file, the machine language instructions
that carry out the program’s purpose. The object file format is binary. If the source file has errors, the
compiler lists these errors but does not create an object file. The user must correct the errors and recompile
the program
Linker program combines the chunks of code called functions that resides in other object files with the
current object file creating a complete machine language program that is ready to run. We call this as
executable file. The file .exe is just stored on disk.
Department of Computer Science Page 20
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., I Semester
To run this .exe file LOADER must copy all its instructions into memory and direct the CPU to begin
execution with first instruction.
----------------------------------------------------------------------------------------------------------------------------------
Generation of Programming Languages
Disadvantages:
• Since Go to statement is not used, the structure of the program needs to be planned
meticulously.
• Lack of Encapsulation.
• Lack of information hiding
• Change of even a single data structure in a program necessitates changes at many places
throughout it, and hence the changes become very difficult to track even in a reasonable sized
program.
• Not much reusability of code.
• Can support the software development projects easily up to a certain level of complexity. If
complexity of the project goes beyond a limit, it becomes difficult to manage.
1. System requirement:
In this phase, the problem is clearly understood & it is necessary to know what are the
requirements used for its solution.
2. Analysis:
It involves identifying the problem i.e, analyzing the input and output.
In this step, the programmer has to know what inputs that is to be given & what are outputs to
be expected from the problem.
If step1 and step2 are not done properly, you will solve the problem wrongly.1st read the
problem statement carefully and obtain a clear idea of the problem & 2nd to determine the input and
output.
3. Design:
Designing is to develop a list of steps called an algorithm, to solve the problem and verify
that the algorithm solves the problem as intended.
4. Implementation or Coding:
Implementing the algorithm involves writing it as a program. You must convert each
algorithm step into one or more statements in a programming language.
5. Testing:
• Testing and verifying the program requires testing the completed program to verify that it
works properly.
• Don’t depend on just on test case run the program several times using different sets of data to
make it sure that it works correctly for every situation provided for in the algorithm.
6. Maintenance:
It means modifying program to remove previously undetected error and to keep it up to date
as company polices changes.
2. Analysis: The problem input is distance in miles and the problem output is distance in kilometers. To
write the program, know the relationship between miles and kilometers. Consulting a metric table shows that
1 mile=1.609 Kilometers.
Algorithm
2. Convert the distance into kilometers using the formula Kilometer=Miles / 1.609
#include<stdio.h>
void main()
{
double m.k;
printf(“ Enter the distance in miles”);
scanf(“%lf”,&m);
Department of Computer Science Page 24
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., I Semester
k=m/1.609;
printf(“That equals %lf kilometers\n”);
}
5. Testing: to verify that the program works properly, enter few more test values of miles.