Module 1
Introduction to C:
Content
Introduction to computers
input and output devices
designing efficient programs.
Introduction to C
Structure of C program
Files used in a C program,
Compilers,
Compiling and executing C programs,
variables,
constants,
Input/output statements in C
Introduction to computers
BASIC ORGANIZATION OF A COMPUTER
A computer is an electronic device that performs five major
operations:
◦ Accepting data or instructions (input)
◦ Storing data
◦ Processing data
◦ Displaying results (output)
◦ Controlling and coordinating all operations inside a
computer
BASIC ORGANIZATION OF A COMPUTER
Figure shows the interaction between the different units of a
computer system.
BASIC ORGANIZATION OF A COMPUTER
[Link]:This is the process of entering data and instructions
(also known as programs ) into the computer system.
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.
[Link] 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.
Storage Primary storage
Secondary storage
Primary storage, also known as the main memory , is the
storage area that is directly accessible by the CPU at very high
speeds.
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.
[Link] 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.
4. 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.
[Link]
The process of performing operations on the data as per the
instructions specified 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 final 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.
[Link] and output devices
[Link] Devices
[Link]
[Link] Devices
[Link] Devices
[Link] Devices
[Link] Input Devices
[Link] Devices
[Link] Copy Devices
[Link] Copy Devices
2.1 Input devices
Keyboard
Pointing Devices
Handheld devices
Optical devices
Audiovisual input devices
2.1 Input devices
• 1:Keyboard:The keyboard is the main input device for
computers
• Using a keyboard, the user can type a document, use keystroke
shortcuts, play games and perform numerous other tasks.
• Most keyboards have 80 and 110 keys which include the
following
1) Typing keys
2) Numeric keys
3) Function keys
4) Control keys
2.1 Input devices
2.1 Input devices
2:Pointing Devices: Example- Mouse,Trackball,Touchpad
Mouse:
The mouse is an input device that was invented in 1963.
It can be used to handle the pointer easily on the screen to
perform various functions such as opening a file or program
Some of the popular mouse types are
Mechanical mouse
Optical mouse
Cordless mouse/wire
less
Trackball:It is a pointing device. It is similar to a mouse.
This is mainly used in notebook or laptop computer, instead of
a mouse.
This is a ball which is half inserted, and by changing fingers
on the ball, the pointer can be moved.
The user rolls the ball with their thumb, fingers or the palm of
their hand to move a cursor without moving their arm.
Touchpad:A touchpad is a small,flat, rectangular stationary
pointing device with a sensitive surface of 1.5-2 square inches.
User has t slide his or her fingertips across the surface of the
pad to point to a specific object on the screen
Input devices
3:Handheld devices: Example
Joystick
Stylus
touchscreen
4:Optical devices:
Example: Barcode Reader, Image scanner, OCR device and
OMR Device
4:Audiovisual input devices
Audio devices,Video input devices are Examples of
Audiovisual input devices
2.2 Output devices
Soft copy devices
Hard copy devices
Soft copy devices:
Example: Monitors , projectors and speakers
Hard copy devices
Examples: Printers, Impact printer, non impact printer and
plotter
Designing efficient
programs
Content
Programming paradigms
Example of a structured program
Design and implementation of efficient programs
Program design tools: Algorithms,flowcharts and
pseudocodes
Types of errors
Testing and debugging approaches
Programming paradigms
A programming paradigm is a fundamental style of
programming that defines how the structure and basic
elements of a computer program will be built.
The style of writing programs and the set of capabilities
and limitations that a particular programming language has
depends on the programming paradigm it supports.
While some programming languages strictly follow a single
paradigm, others may draw concepts from more than one.
The sweeping trend in the evolution of high-level
programming languages has resulted in a shift in
programming paradigm.
Programming paradigms
• Monolithic programming emphasizes on finding a solution
• Procedural programming lays stress on algorithms
• Structured programming focuses on modules
• Object-oriented programming emphasizes on classes and
objects
• Logic-oriented programming focuses on goals usually
expressed in predicate calculus
• Rule-oriented programming_ makes use of if-then-else'
rules for computation
• Constraint-oriented programming utilizes invariant
relationships to solve a problem
Programming paradigms
[Link] programming
Programs written using monolithic programming
languages such as assembly language and BASIC
consist of global data and sequential code.
The global data can be accessed and modified from any
part of the program
A sequential code is one in which all instructions are
executed in the specified sequence.
[Link] programming
In procedural languages, a program is divided into
subroutines that can access global data
To avoid repetition of code, each subroutine performs a well-
defined task.
A subroutine that needs the service provided by another
subroutine can call that subroutine.
FORTRAN and COBOL are 2 popular procedural
programming languages.
Structured programming
Structured programming, also referred to as modular
programming, was first suggested by mathematicians, Corrado
Bohme and Guiseppe Jacopini in 1966.
It was specifically designed to enforce a logical structure on the
program to make it more efficient and easier to understand and
modify.
Structured programming employs a top-down approach in which
the overall program structure is broken down into separate
modules.
This allows the code to be loaded into memory more efficiently
and also be reused in other programs.
Object-Oriented
programming
With the increase in size and complexity of programs, there
was aa need for a new programming paradigm that could help
develop maintainable programs.
To implement this the flaws in previous paradigm had to be
corrected.
Consequently OOP was developed
This is task and data based language
Here all the relevant data and tasks are grouped together in
entities known as objects.
Program design tools
1. Algorithms
2. Flowcharts
3. Pseudocodes
Flowcharts:
It’s a graphical or symbolic representation of a process.
Its used to design and document virtually complex process
to help the viewers to visualize the logic of the process,
so that they can gain a better understanding of the process
Flowcharts
Symbols in the flowchart are linked together with arrows to
show the flow of login the process.
Symbols used in flowchart include:
Arrows
Generic processing step
Input/output symbols
A conditional or decision symbol
Labelled connectors
Start and end symbols
Flowcharts
Flowcharts
[Link] and end symbols:
known as terminal symbol
Represented as circle, ovals or rounded rectangles
It’s a 1st and last symbol in flowchart
[Link]:
It shows the exact sequence in which the instructions are
executed.
[Link] processing step
Also called as an activity
Its represented using rectangle
Arithmetic and data movement instructions
Flowcharts
[Link]/ouput symbol:
Represented using parallelogram
Get input and display results
5.A conditional or decision symbol:
Represented using diamond
Used to depict a yes/no question
It can have more than 2 arrows
[Link] connectors:
Represented by circle
Connector
Significance of Flowcharts
A flowchart is a diagrammatic representation that illustrates the
sequence of steps that must be performed to solve a problem.
It facilitates communication between programmers and users.
Flowcharts are very important in the programming of a
problem as they help the programmers to understand the logic
of complicated and lengthy problems.
Once a flowchart is drawn, it becomes easy for the
programmers to write the program in any high-level language.
Hence, the flowchart has become a necessity for better
documentation of complex programs.
A flowchart follows the top-down approach in solving
problems.
Programming in C
Contents
Introduction to c
Characteristics of c
Uses of c
Structure of a c program
Writing the first c program
Files used in c
Compiling and executing c
Using comments,c tokens,character set, keywords ,identifiers,
basic data types in c, variables, constants, input/output
statement in c
Introduction
The programming language C was developed in the
early 1970s by Dennis Ritchie at Bell Laboratories to
be used by the UNIX operating system.
It was named 'C' because many of its features were
derived from an earlier language called 'B'.
C is one of the most popular programming languages.
It is being used on several different software
platforms.
Characteristics of C
C is a robust language whose rich set of built-in functions and operators
can be used to write complex programs.
C is a high-level programming language, which enables the programmer
to concentrate on the problem at hand and not worry about the machine
code on which the program would be run.
Small size-C has only 32 keywords. This makes it relatively easy to learn
as compared to other languages.
C makes extensive use of function calls.
C is well suited for structured programming. In this programming
approach, C enables users to think of a problem in terms of
functions/modules where the collection of all the modules makes up a
complete program. This feature facilitates ease in program debugging,
testing, and maintenance.
Unlike PASCAL it supports loose typing
Structured language as the code can be organized as a collection of
one or more functions.
Stable language.
Quick language as a well written C program is likely to be as quick as
or quicker than a program written in any other language. Since C
programs make use of operators and data types, they are fast and
efficient.
Facilitates low level (bitwise) programming.
Supports pointers to refer computer memory , arrays, structures, and
functions.
Core language. C is a core language as many other programming
languages (like C++, Java, Perl, etc.) are based on C.
C is a portable language, i.e., a C program written for one computer
can be run on another computer with little or no modification.
C is an extensible language as it enables the user to add his own
functions to the C library.
Uses of C
C is a very simple language that is widely used by software professionals
around the globe. The uses of C language can be summarized as follows:
C language is primarily used for system programming.
The portability, efficiency, the ability to access specific hardware
addresses, and low runtime demand on system resources make it a good
choice for implementing operating systems and embedded system
applications.
C has been so widely accepted by professionals that compilers, libraries,
and interpreters of other programming languages are often written in C.
For portability and convenience reasons, C is sometimes used as an
intermediate language for implementation of other languages.
Basically, C was designed as a programming language and was not
meant to be used as a compiler target language. Therefore, although C
can be used as an intermediate language it is not an ideal option.
C is widely used to implement end-user applications.
Structure of a C Program
A C program is composed of preprocessor commands, a global
declaration section, and one or more functions (Figure 9.2).
The preprocessor directives contain special instructions that indicate
how to prepare the program for compilation.
One of the most important and commonly used preprocessor
commands is include which tells the compiler that to execute the
program, some information is needed from the specified header file.
A C program contains one or more functions, where a function is
defined as a group of C statements that are executed together. The
statements in a C function are written in a logical sequence to
perform a specific task.
The main () function is the most important function and is a part of
every C program. The execution of a C program begins at this
function.
All functions including main () are divided into two
parts the declaration section and the statement section.
The declaration section precedes the statement section
and is used to describe the data that will be used in the
function. Note that data declared within a function are
known as local declaration as that data will be visible
only within that function. Stated in other terms, the
life-time of the data will be only till the function ends.
The statement section in a function contains the code
that manipulates the data to perform a specified task.
Writing the first C Program
To write a C program, we first need to write the code.
For this, open a text editor. If you are a Windows user you may use Notepad and if
you prefer working on UNIX/Linux you can use emacs or vi.
Once the text editor is opened on your screen, type the following statements:
#include <stdio.h>
int main()
{
printf ("\n Welcome to the world of C ");
return 0;
}
Output
Welcome to the world of c
#include<stdio.h>
int main()
Every C program contains a main() function which is the starting point of the
program.
int is the return value of the main( )function. After all the statements in the
program
{} The two curly brackets are used to group all the related statements of the
main function. All the statements between the braces form the function body.
The function body contains a set of instructions to perform the given task.
printf("\n Welcome to the world of c");
The printf function is defined in the stdio.h file and is used to print text on
the screen.
The message that has to be displayed on the screen is enclosed within double
quotes and put inside brackets.
return 0;
This is a return command that is used to return the value O to the operating
system to give an indication that there were no errors during the execution of
the program.
Files used in a C program
Source Code Files
The source code file contains the source code of the program.
The file extension of any C source code file is .c‘
Header Files
When working with large projects, it is often desirable to separate out
certain subroutines from the main() function of the program.
Object Files
Object files are generated by the compiler as a result of processing the
source code file.
Object files contain compact binary code of the function definitions.
Binary Executable Files
The binary executable file is generated by the linker.
Compiling & Executing C
prgrm
C is a compiled language. So once a C program is written, you must run it
through a C compiler that can create an executable file to be run by the
computer.
While the C program is human-readable, the executable file, on the other
hand, is a machine-readable file available in executable form.
The mechanical part of running a C program begins with one or more program
source files, and ends with an executable file, which can be run on a computer.
The programming process starts with creating a source file that consists of the
statements of the program written in C language. This source file usually
contains ASCII characters and can be produced with a text editor, such as
Windows notepad, or in an Integrated Design Environment.
The source file is then processed by a special program called a compiler.
The compiler translates the source code into an object code. The object code
contains the machine instructions for the CPU, and calls to the operating
system API (Application Programming Interface)
Therefore, in the next step, the object file is processed with another special
program called a linker.
Using Comments
Comments are just a way of explaining what a
program does.
Compiler ignores comments when forming the object file.
This means comments are non executable statements.
C supports 2 types of comments
[Link] comment(//)
[Link] comment(/*
*/)
Line comment is used to comment a single statement
Block comment is used to comment multiple statement
Using Comments
It’s a good practice to put always a comment at the
top of a program that tells you what the program
does.
It can be used anywhere in the pogram
You can also use comments in between your code to
explain piece of code that is a bit complicated.
Commented statements are not executed by the
compiler
C tokens
Tokens are the basic building blocks in C
language
Program is constructed using a combination
of these tokens.
There are 6 main types of tokens in C.
Character set in C
In C, a character means any letter from English Alphabet,
a digit or a special symbol used to represent information.
These characters when combined together form tokens
that act as basic building blocks of a C program.
Character set of C, therefore can be given as
English alphabet :Include both lower case and upper
case
Digits: 0 to 9
Special Characters: >,”,&,%........
White space characters: \b,\t,\v,\r,\f,\n
Escape sequence:
Keywords
Like every computer language, C has a set of
reserved words often known as keywords that cannot
be used as an identifier
All keywords are a sequence of characters that have a
fixed meaning
Keywords must be written in lowercase letters.
Example for keywords: auto, break, case, char, const,
continue, default, switch, if, do, while, for etc
Identifiers
As the name suggests ,help us to identify data and
other objects in the program.
Identifiers are the names given to program elements
such as variables, arrays, and functions
Identifiers may consist of sequence of
letters ,numerals or underscores
Rules for forming Identifiers names
It cannot include any special characters or
punctuation marks except the underscore
There cannot be two successive underscores
Keywords cant be used as identifiers
It must begin with a letter or an underscore
It can be of any reasonable length
Its good to use meaningful identifier names
Example: roll_no, DEEN, marks
Example for invalid identifers:23_st,
%marks,@name,(DA),-hta
Basic data types in c
It provide very few basic data types
Variable
Variable is defined as a meaningful name given to a data storage
location in computer memory.
When using a variable, we actually refer to address of the
memory where the data is stored.
C supports 2 kinds of variables
[Link] variables
[Link] variables
[Link] variables: Its used to store either integer values or
floating point values.
Integer value is a whole number without a fraction part or
decimal point. Floating point can have decimal point
variables
[Link] variables:
These are just single characters enclosed within single
quotes.
These character can be any character from ASCII
character set-letters(‘a’,’A’),numerals(‘2’), or special
characters(‘&’)
Example:2 is treated a integer value, but ‘2’ is treated
as character not an integer
Variables
Declaring variables:
Each variable to be used in the program must be declared.
Declaration: specify the data type of variable followed by
its name.
Data type indicates the kind of values that the variable will
store
Variable declaration always ends with semicolon.
Example: int emp_name;
float salary;
char grade;
Variables
Initializing variables:
While declaring variables, we can also initialize them
with some value
example: int emp_num=7;
float salary= 254.9;
Char grade= ‘A’;
Constants
Constants are identifiers whose values do not change
Values of variable can be changed at any time, values of
constants can never be changed
Its used to define fixed values
Its an explicit data value specified by the programmer.
Value of constant is known to compiler at the compile
time.
C allows programmer to specify constants of integer type,
floating point type, character type and string type
constants
Integer constants:
Example :1, 34,567 -integer constants
1234l, 123L long integer constants
12U, 23u unsigned integer constants
0X12,0X7Fhexadecimal notation
Decimal integer consist of set of digits(0 to 9),preceded by an optional +
or -.
Example: -123, +34,-56
While writing integer constants , spaces, commas and non digit
characters are not allowed
Example: 12 45,
12,56
$89
constants
Floating point constants
Integer numbers are inadequate to express numbers that
have a fractional part
A floating point constants consists of an integer part,
decimal point, a fractional part, and an exponent field
containing an e or E
Its not necessary all FPC must contain all these parts
Example: 0.02,-0.23,12.78, +0.34 12
Literal like 0.07 treated as of type double by default
To make it float type literal, specify it using suffix F or f
Valid floating point literals: 0.02F, 0.76f, 2.14E-3
constants
Character constants
It consist of single characters enclosed in single quotes
Example: ‘a’,’&’
String constants
It’s a sequence of characters enclosed in double quotes
Length of string constant is equal to number of characters in the
string plus 1(for null character)
Length of string literal ‘hello’ = 6
Declaring constants
To declare constant, precede normal variable declaration with
const keyword and assign it a value
Example: const float pi = 3.14; or # define pi 3.14159
Input/Output statements
in C
Streams
Stream is a source of data as well as destination of
data
Its associated with a physical device such as monitor
or a file stored on the secondary memory.
C uses 2 forms of streams
Input/output statement in
c
In a text stream, sequence of characters is divided into lines
with each line being terminated with a new line character.
Binary stream consist of data values using their memory
representation
Formatting input /output
C language supports 2 formatting functions printf and scanf.
Printf is used to convert data stored in program into a text
stream for output to the monitor
Scanf is used to convert text stream coming from keyboard to
data values and store them in program variables
Input/output statement in c