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

Module-1 New

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

MODULE 1

Introduction to C

OBJECTIVES
 To introduce computers and its parts.
 To introduce to C language.
 To understand Files used in a C program.
 To understand the Compilers, Compiling and executing C programs.
 Discuss the variables, constants, Input/output statements in C.

1.1Introduction to Computers
A computer is a programmable machine designed to perform arithmetic and logical
operations automatically and sequentially on the input given by the user and gives the
desired output after processing. Computer components are divided into two major categories
namely hardware and software. Hardware is the machine itself and its connected devices such as
monitor, keyboard, mouse etc. Software are the set of programs that make use of hardware for
performing various functions.
Generally, the term is used to describe a collection of devices that function together as a
system. It performs the following three operations in sequence.
1. It receives data & instructions from the input device.
2. Processes the data as per instructions.
3. Provides the result (output) in a desired form.
Data: It is the collection of raw facts, figures& symbols. Ex : Names of students and their marks in
different subjects listed in random order.
Information: It is the data that is processed & presented in an organized manner. Ex: When the
names of students are arranged in alphabetical order, total and average marks are calculated &
presented in a tabular form, it is information.
Program: Set of instructions that enables a computer to perform a given task.
Characteristics of Computers
The characteristics of computers that have made them so powerful and universally useful
are speed, accuracy, diligence, versatility and storage capacity. Let us discuss them briefly.
Speed:Computers work at an incredible speed. A powerful computer is capable of performing
about 3-4 million simple instructions per second.
Accuracy:In addition to being fast, computers are also accurate. Errors that may occur can usually
be attributed to human error (inaccurate data, poorly designed system or faulty
instructions/programs written by the programmer).
Diligence:Unlike human beings, computers are highly consistent. They do not suffer from human
traits of boredom and tiredness resulting in lack of concentration. Computers, therefore, are better
than human beings in performing voluminous and repetitive jobs.
Versatility: Computers are versatile machines and are capable of performing any task as long as it
can be broken down into a series of logical steps. The presence of computers can be seen in almost
every sphere – Railway/Air reservation, Banks, Hotels, Weather forecasting and many more.
Storage Capacity: Today’s computers can store large volumes of data. A piece of information
once recorded (or stored) in the computer, can never be forgotten and can be retrieved almost
instantaneously.
Cost effectiveness:Computers reduce the amount of paper work and human effort, thereby
reducing costs.
Automation: Computers can be instructed to perform complex tasks automatically (which
increases the productivity).
Limitations of computers:
1. Computers need clear & complete instructions to perform a task accurately. If the instructions
are not clear & complete, the computer will not produce the required result.
2. Computers cannot think.
3. Computers cannot learn by experience.

Computer Organization
A computer system (Fig.1.1) consists of mainly four basic units; namely input unit, storage unit,
central processing unit and output unit. Central Processing unit further includes Arithmetic logic
unit and control unit, as shown in Figure 1.2.
Fig 1.1: Computer System

Fig 1.1: Basic Computer Organization

A computer performs five major operations or functions irrespective of its size and make. These
are:
 It accepts data or instructions as input,
 It stores data and instruction
 It processes data as per the instructions,
 It controls all operations inside a computer, and
 It gives results in the form of output
Functional Units:
Input Unit: This unit is used for entering data and programs into the computer system by the user
for processing.
Storage Unit: The storage unit is used for storing data and instructions before and after processing.
Output Unit: The output unit is used for storing the result as output produced by the
computer after processing.
Processing: The task of performing operations like arithmetic and logical operations is
called processing. The Central Processing Unit (CPU) takes data and instructions from the storage
unit and makes all sorts of calculations based on the instructions given and the type of data
provided. It is then sent back to the storage unit. CPU includes Arithmetic logic unit (ALU) and
control unit (CU)
 Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided,
are carried out withinthe ALU. It performs arithmetic functions like addition, subtraction,
multiplication, division and logical operations like greater than, less than and equal to etc.
 Control Unit:Control unit performs controlling of all operations like input, processing and
output. It takes care of step by step processing of all operations inside the computer.

Memory
Computer’s memory can be classified into two types; primary memory and secondary memory
a.Primary Memory can be further classified as RAM and ROM.
 RAM or Random Access Memory is the unit in a computer system. It is the place in a computer
where the operating system, application programs and the data in current use are kept
temporarily so that they can be accessed by the computer’s processor. It is said to be ‘volatile’
since its contents are accessible only as long as the computer is on. The contents of RAM are no
more available once the computer is turned off.
 ROM or Read Only Memory is a special type of memory which can only be read and contents
of which are not lost even when the computer is switched off. It typically contains manufacturer’s
instructions. Among other things, ROM also stores an initial program called the ‘bootstrap
loader’ whose function is to start the operation of computer system once the power is turned on.

b. Secondary Memory
RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is
storage other than the RAM. These include devices that are peripheral and are connected and
controlled by the computer to enable permanent storage of programs and data. Secondary
storage devices are of two types; magnetic and optical. Magnetic devices include hard disks and
optical storage devices are CDs, DVDs, Pen drive, Zip drive etc.
 Hard Disk
Hard disks are made up of rigid material and are usually a stack of metal disks sealed in a box. The
hard disk and the hard disk drive exist together as a unit and is a permanent part of the
computer where data and programs are saved. These disks have storage capacities ranging from
1GB to 80 GB and more. Hard disks are rewritable.
 Compact Disk
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold
large amount of information such as music, full-motion videos, and text etc. CDs can be either read
only or read write type.
Digital Video Disk
Digital Video Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity.
Depending upon the disk type it can store several Gigabytes of data. DVDs are primarily used to
store music or movies and can be played back on your television or the computer too.
These are not rewritable.
 Flash Drive
It is a small, portable device that can be used to store, access and transfer data. Due to its small
size, it is commonly called Pen drive. It is also called USB drive. We can read, write, copy, delete,
and move data from computer to pen drive or pen drive to computer. It comes in various storage
capacities of 2GB, 4GB, 8GB etc. It is popular because it is easy to use and small enough to be
carried in a pocket. This device is plugged into the USB port of the computer and the computer
automatically detects this device.

1.2 Input and Output Devices


a) Input Devices
An input device is any device that provides input to a computer. There are many input devices, but
the two most common ones are a keyboard and mouse. Every key you press on the keyboard and
every movement or click you make with the mouse sends a specific input signal to the computer.
 Keyboard: The keyboard is very much like a standard typewriter keyboard with a few
additional keys. The basic QWERTY layout of characters is maintained to make it easy to use the
system. The additional keys are included to perform certain special functions. These are known as
function keys that vary in number from keyboard to keyboard. There are different types of keys on
the keyboard. The keys are categorizedas:
 Alphanumerickeys, including letters & numbers.
 Punctuation keys, such as colon (:), semicolon (;) Question mark (?), Single & double
quotes
 Special keys such as arrow keys, control keys, function keys (F1 to F12), HOME, END
etc
 Mouse: A device that controls the movement of the cursor or pointer on a display screen. A
mouse is a small object you can roll along a hard and flat surface (Fig. 1.5). Its name is
derived from its shape, which looks a bit like a mouse. As you move the mouse, the pointer on the
display screen moves in the same direction.
Trackball: A trackball is an input device used to enter motion data into computers or
other electronic devices. It serves the same purpose as a mouse, but is designed with a moveable
ball on the top, which can be rolled in any direction
 Touchpad: A touch pad is a device for pointing (controlling input positioning) on a computer
display screen. It is an alternative to the mouse. Originally incorporated in laptop computers, touch
pads are also being made for use with desktop computers. A touch pad works by sensing the
user’s finger movement and downward pressure.
 Touch Screen: It allows the user to operate/make selections by simply touching the display
screen. A display screen that is sensitive to the touch of a finger or stylus. Widely used on
ATM machines, retail point-of-sale terminals, car navigation systems, medical monitors and
industrial control panels.
 Light Pen: Light pen is an input device that utilizes a light-sensitive detector to select objects on
a display screen.
 Magnetic ink character recognition (MICR): MICR can identify character printed with a
special ink that contains particles of magnetic material. This device particularly finds
applications in banking industry.
 Optical mark recognition (OMR): Optical mark recognition, also called mark sense
reader is a technology where an OMR device senses the presence or absence of a mark, such as
pencil mark. OMR is widely used in tests such as aptitude test.
 Bar code reader: Bar-code readers are photoelectric scanners that read the bar codes or
vertical zebra strips marks, printed on product containers. These devices are generally used
in super markets, bookshops etc.
 Scanner: Scanner is an input device that can read text or illustration printed on paper and
translates the information into a form that the computer can use. A scanner works by digitizing an
image.

b) Output Devices:
Output device receives information from the CPU and presents it to the user in the desired from.
The processed data, stored in the memory of the computer is sent to the output unit, which then
converts it into a form that can be understood by the user. The output is usually produced in one of
the two ways – on the display device, or on paper (hard copy).
 Monitor: is often used synonymously with “computer screen” or “display.” Monitor is an output
device that resembles the television screen It may use a Cathode Ray Tube (CRT) to
display information. The monitor is associated with a keyboard for manual input of
characters and displays the information as it is keyed in. It also displays the program or application
output. Like the television, monitors are also available in different sizes.
 Printer: Printers are used to produce paper (commonly known as hardcopy) output. Based on
the technology used, they can be classified as Impact or Non-impact printers.
Impact printers use the typewriting printing mechanism wherein a hammer strikes the paper
through a ribbon in order to produce output. Dot-matrix and Character printers fall under this
category.
Non-impact printers do not touch the paper while printing. They use chemical, heat or
electrical signals to etch the symbols on paper. Inkjet, Deskjet, Laser, Thermal printers fall
under this category of printers.
 Plotter: Plotters are used to print graphical output on paper. It interprets computer commands
and makes line drawings on paper using multicoloured automated pens. It is capable of
producing graphs, drawings, charts, maps etc.
 Facsimile (FAX): Facsimile machine, a device that can send or receive pictures and text over a
telephone line. Fax machines work by digitizing an image.
 Sound cards and Speaker(s): An expansion board that enables a computer to manipulate and
output sounds. Sound cards are necessary for nearly all CD-ROMs and have become
commonplace on modern personal computers. Sound cards enable the computer to output
sound through speakers connected to the board, to record sound input from a microphone
connected to the computer, and manipulate sound stored on a disk.

1.4. Introduction to C
Programming is the process of taking an algorithm and encoding it into a notation, a programming
language, so that it can be executed by a computer. Although many programming languages and
many different types of computers exist, the important first step is the need to have the solution.
Without an algorithm, there can be no program.

Computer science is not the study of programming. Programming, however, is an important part of
what a computer scientist does. Programming is often the way that we create a representation for
our solutions. Therefore, this language representation and the process of creating it becomes a
fundamental part of the discipline.

Algorithms describe the solution to a problem in terms of the data needed to represent the problem
instance and the set of steps necessary to produce the intended result. Programming languages must
provide a notational way to represent both the process and the data. To this end, languages provide
control constructs and data types.

Control constructs allow algorithmic steps to be represented in a convenient yet unambiguous way.
At a minimum, algorithms require constructs that perform sequential processing, selection for
decision-making, and iteration for repetitive control. As long as the language provides these basic
statements, it can be used for algorithm representation.
All data items in the computer are represented as strings of binary digits. In order to give these
strings meaning, we need to have data types. Data types provide an interpretation for this binary
data so that we can think about the data in terms that make sense with respect to the problem being
solved. These low-level, built-in data types (sometimes called the primitive data types) provide the
building blocks for algorithm development.

Programming paradigms:
A Programming paradigm is a style or “way” of programming.
1. Imperative: The language provides statements, such as assignment statements, which explicitly
change the state of the memory of the computer. In this the emphasize is on the idea of
computation as being about evaluating mathematical functions combined in expressions. While all
languages try to provide a representation of basic functions like addition, functional languages
support a functional way of expressing computations on large and complex structures, although
some such as Scheme also have imperative features. In a pure functional language a mathematical
identity like:fred(x) + fred(x) = 2*fred(x) should hold.

2. Functional: In this paradigm we express computations as the evaluation of mathematical


functions. Languages that reflect this paradigm recognize the fact computers have reusable memory
that can change state. So they are characterized by statements, which affect the state of the
machine, for example: x := x+1 :This can only be understood mathematically by associating a
sequence of values with x let us say x 1, x2,..., where xtdenotes the value the variable x has at some
time t. Thus the above statement can be translated into mathematics as xt+1= xt + 1.

3. Logic: In this paradigm we express computation in exclusively in terms of mathematical logic. It


focusses on predicate logic, in which the basic concept is a relation. Logic languages are useful for
expressing problems where it is not obvious what the functions should be. Thus, for example where
people are concerned, it is natural to use relations. For example consider the uncle relationship: a
given person can have many uncles, and another person can be uncle to many nieces and nephews.

4. Object-Oriented: In this paradigm we associate behavior with data-structures called objects


which belong to classes which are usually structured into a hierarchy. It focusseson the objects that
a program is representing, and on allowing them to exhibit "behavior". This is contrasted with the
typical approach in the imperative paradigm, in which one typically thinks of operating on data
with procedures. In the imperative paradigm typically the data are passive, the procedures are
active. In the O-O paradigm, data is combined with procedures to give objects, which are thereby
rendered active. For example, in theimperative paradigm, one would write a procedure which prints
the various kinds of object in the program. In the O-O paradigm, each object has a print- method,
and you "tell" an object to print itself.
1.5. Structure of C program
Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section;
}
User-defined functions: The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.
The link section provides instructions to the complier to link functions from the system library. The
definition section defines all symbolic constants.
There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions. This
section also declares also declares all the user-defined functions.
Every C program must have one main() function section. This section contains two parts,
declaration part and execution part. There is at least one statement in the executable part. These
two parts must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function section is
the logical end of the program. All statements in the declaration and executable parts end with a
semicolon (;).

1.6. Files used in a C program


Fig 1.3: C program uses four types of files

Source Code File


• This file includes the source code of the program.
• The extension for these kind of files are '.c'. It defines the main and many more functions
written in C.
• main() is the starting point of the program. It may also contain other source code files.
Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions that are
shared between various source files.

Advantages of header files:


1. At times the programmer may want to use the same subroutines for different programs. To do
this, he would just compile the code of the subroutine once and link to the resulting object file in
any file in which the functionalities of this subroutine are required.

2. At times the programmer may want to change or add the subroutines and reflect those changes in
all the programs. For doing this, he will have to only change the source file for the subroutines,
recompile the source code and then recompile and re-link the program.
Standard header files
C provides us with some standard header files which are available easily.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more than one
function of the same file.pile the source code and then recompile and re-link the program.

Object files
• They are the files that are generated by the compiler as the source code file is processed.
• These files generally contain the binary code of the function definitions.
• The object file is used by the linker for producing an executable file for combining the
object files together. It has a '.o' extension.
Executable file
• This file is generated by the linker.
• Various object files are linked by the linker for producing a binary file which will be
executed directly.
• They have an '.exe' extension.

1.7. Compiling and executing C programs


Once the program has been typed it needs to be converted to machine language (0s and 1s) before
the machine can execute it. To carry out this conversion we need another program called Compiler.
Compilation Process
C program depends on information maintained externally, so the compilationprocedure in C is
somewhat different from other languages. Compilation in C is a three-step process that involves the
use of three separate programs:
• The Preprocessor This program acts on lines that begin with a #. They occur mostly atthe
beginning of a program and are called preprocessor directives. A directive may insert
thecontents of a header file at that location (like #include <stdio.h>) or perform a
substitutionin the program itself. The preprocessor thus modifies the source codeto make it
suitable for use in the next phase. This modification is carried out on a copy;the original file
containing the source code is left undisturbed.
• The Compiler This program checks the source code after it has been modified by
thepreprocessor. If the compiler detects one or more syntax errors in this code, it displays
themand stops further processing. Otherwise, the compiler creates intermediate object
code.This code is incomplete and not ready to run because it doesn’t contain the code for
thestandard C functions (like printf and scanf). The compiler merely leaves unresolved
references to these functions.
• The Linker This program acts on the unresolved references left behind by the
compiler.The linker does this by adding the machine code of functions available in separate
libraries tothe object code created by the compiler. The resultant code is a standalone
executable that isrun by the program loader. The linker fills the holes left by the compiler.

Executing the Program
The default name of the standalone executable is system-dependent—a.out on UNIX/Linux
systems, and aout.exe or AOUT.EXE on Windows. (Visual Studio names the executable after the
source file, so foo.cis compiled to foo.exe.) This file can be executed byrunning ./a.out or .\aout
from the operating system’s shell. If you are using C in a GUI environment (like Visual Studio),
you have to use the mouse to select menu options that perform all of the compilation and execution
tasks.
It is possible for a program to pass the compilation and linking phases and still fail in
execution.Programs fail at runtime (i.e., when the program is actually run) on account of semantic
errors thatarise out of mistakes in design. For instance, a division by zero makes the program abort
with an error. Use of = instead of == will also yield unexpected results. Faulty logic that doesn’t
account for all possibilities can make a program behave erratically as well. The solution is the
same; edit the source code and repeat the compilation process before re-execution.
A program can have syntax errors (on accountof wrong use of its grammar) or semantic
errors (because of faulty program logic). The formeris detected during compilation and the latter
during program execution.

1.8. Constants and Variables in C Language


• Constants
As the name suggests the name constants is given to such variables or values in C programming
language, which cannot be modified once they are defined. They are fixed values in a program.
There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.
Every constant has some range. C - Constants and Literals. Constants refer to fixed values that the
program may not alter during its execution. These fixed values are also called literals. the syntax of
declaring constants.
constintvar = 5;
Syntax of declaring constants
The constants in ‘C’ Language are divided into two types 1) Primary Constants and 2) Secondary
Constants.
The primary constants are further divided into two types 1) Numeric and 2) Character
• Variables
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable. The value of the C variable may get change in the
program. C variable might be belonging to any of the data type like int, float, char etc. The
different datatypes supported in C language are shown in Table 1.1.
Rules for naming variables:
⮚ All variable names must begin with a letter of the alphabet or an. underscore (_)
⮚ After the first initial letter, variable names can also contain letters and numbers.
⮚ Uppercase characters are distinct from lowercase characters.
⮚ You cannot use a C++ keyword (reserved word) as a variable name.
Fig 1.4: Different types of constants

Table1.1:DatatypessupportedinC
FORMA
MEMORY
DATATYPE RANGE T
(BYTES) SPECIFIER
shortint 2 -32,768to 32,767 %hd
unsignedshort int 2 0 to 65,535 %hu
unsignedint 4 0 to 4,294,967,295 %u
-2,147,483,648to
int 4 2,147,483,647 %d
-2,147,483,648to
long int 4 2,147,483,647 %ld
unsignedlong int 4 0 to 4,294,967,295 %lu
long longint 8 -(2^63)to(2^63)-1 %lld
unsigned 0 to
8 %llu
longlongint 18,446,744,073,709,551,615
signedchar 1 -128to 127 %c
unsignedchar 1 0 to 255 %c
float 4 %f
double 8 %lf
long double 12 %Lf
Standard header files

C provides us with some standard header files which are available easily.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more than one

a)Input Devices
function of the same file.

An input device is any device that


provides input to a computer. There
are many input devices, but the
two most common ones are a
keyboard and mouse. Every key
you press on the keyboard and
every
movement or click you make with
the mouse sends a specific input
signal to the computer.
Keyboard: The keyboard is very
much like a standard typewriter
keyboard with a few additional
keys. The basic QWERTY layout
of characters is maintained to make
it easy to use the system. The
additional keys are included to
perform certain special functions.
These are known as function keys
that vary in number from keyboard
to keyboard.
There are different types of keys on
the keyboard. The keys are
categorized as :
Alphanumeric keys , including
letters & numbers.
Punctuation keys, such as colon
(:), semicolon (;) Question mark
(?), Single & double quotes
(‗,‖)
Special keys such as arrow keys,
control keys, function keys (F1 to
F12), HOME, END etc
Mouse: A device that controls the
movement of the cursor or pointer
on a display screen. A mouse
is a small object you can roll
along a hard and flat surface
(Fig. 1.5). Its name is derived
from its
shape, which looks a bit like a
mouse. As you move the mouse, the
pointer on the display screen
moves in the same direct

You might also like