CP 1141- Introduction to Programming
Module -I
Chapter: 1
Introduction
• A computer is an electronic device which is used for processing/ Computing.
• It takes the data as input, processes it as per the instructions and gives the desired
output.
• Computing is an operation that involves processing of data by making use of a
computer.
• Computation involves arithmetic and logical operations (+,-, *, / ,&&, ||, ~)
Components of a Computer:
• Input Device
• Output Device
• CPU
• Main Memory/ Storage Device
Input Devices:
• Users are allowed to input data and other instructions to the computer
• Keyboard, mouse, scanners, readers etc
• Input devices are electro - mechanical in nature(mechanical means is digitized)
Output Devices:
• Output devices are used by the computer to convey messages back to the users.
• Monitor(displays), printer, speakers, plotters etc.
• Both i/p and o/p devices are called peripheral devices / auxiliary devices, they
are auxiliary in nature because their existence is not mandatory unlike the cpu or
the memory.
CPU:
• All the processing activities takes place in CPU
• CPU consist of arithmetic logic unit(ALU) and Control Unit(CU)
• CU is called the brain of the computer, it is responsible for generating control
signals. It controls the working of various components within a computer.
• The registers present inside the CPU are high speed storage devices (General
purpose registers and special purpose registers to hold special data and
instructions.)
• A processor register is one of a small set of data holding places. A register may
hold an instruction, a storage address or any kind of data.
Memory/ Storage:
• This unit is for the data storage purposes.
• It has various access speeds and volatility.
• Access speed is the time taken to store and retrieve the data from the memory.
• Volatility is the duration of time the data is stored in the memory.
• The classifications of memory are as follows:
• RAM- Random Access Memory. It is volatile in nature, because it loses all the
information stored in it as soon as the power to the computer is switched off.
• RAMs are divided in to two categories as Static RAM (SRAM) and Dynamic
RAM (DRAM).
• SRAM uses transistors to store a single bit of data and it does not need to be
periodically refreshed.
• DRAM uses a separate capacitor to store each bit of data and it needs to be
periodically refreshed to maintain the charge in the capacitors.
• ROM – Read Only Memory. Non Volatile in nature. It does not allow any write
operations and the data stored in it can be retained. The information's are stored
permanently in it during the time of manufacture.
• A ROM stores the instructions that are required to start the computer.
• This operation is referred to as bootstrap.
• ROM chips are not only used in Computer but also in washing machine,
microwave oven etc
• PROM, EPROM, and EEPROM are three types of ROM.
• Programmable Read Only Memory
• Erasable and Programmable Read only Memory
• Electrical Erasable and Programmable Read Only Memory
• The difference between PROM, EPROM and EEPROM is that PROM is
programmable only once while EPROM is re-programmable by erasing the
content on exposing to ultraviolet light and EEPROM is re- programmable by
erasing the content on it through an electric charge. In brief, EEPROM is
commonly used than PROM and EPROM.
Concept of Hardware, Software, Firmware(3 wares)
Hardware :- refers to the physical elements of a computer or a physical entity.
• Examples of hardware in a computer are the keyboard, the monitor, the mouse
and the central processing unit.
• A computer's hardware is comprised of many different parts, but perhaps the
most important of these is the motherboard. The motherboard is made up of even
more parts that power and control the computer.
• Hardware and software are interconnected, without software, the hardware of a
computer would have no function and vice versa.
Software:- set of instructions...commonly known as programs or apps, consists of all
the instructions that tell the hardware how to perform a task .
Software provides the means for accomplishing many different tasks with the same
basic hardware. Computer systems divide software systems into two major classes:
•System software: Helps run the computer hardware and computer system itself.
System software includes operating systems, device drivers, diagnostic tools and
more. System software is almost always pre-installed on your computer.
•Application software: Allows users to accomplish one or more tasks. It
includes word processing, web browsing and almost any other task for which you
might install software. (Some application software is pre-installed on most
computer systems.)
Firmware:- Firmware is software embedded within a piece of hardware.
Or firmware is a software for hardware. Eg:- video card, sound card, disk drive and
Remote.
Operating System:-
• An operating system is a software which performs all the basic tasks like file
management, memory management, process management, handling input
and output, and controlling peripheral devices - disk drives and printers.
• An OS acts as an interface between the user and the hardware.
• The widely used OS are LINUX, Windows, UNIX, macOS
Translator:
• It is a type of system software
• Translates a program written in one programming language to another
• Compiler, assembler, interpreter are the common translators.
• Any program that is written in HLL is converted into machine or binary (1’s &
0’s)
Compiler:
• It is also a system software that converts the HLL to ML(0,1)
• It compiles one program at a stretch
• C, C++,Java are the common HLL.
Assembler:
• It translates an ALP(Assembly language program) into machine language. ALP
used the concept of mnemonic codes(ADD,SUB,MUL,DIV.....)
• ML uses the corresponding binary operation codes for these mnemonics.
Interpreter:
• This is also a translator.
• It translates an HLL program to Low level/ ML program
• This translates line by line interpretation.
Loader:-It is system s/w that loads a program to be executed from secondary memory
to the main memory.
Linker:
• The linker links all the object codes belonging to all the functions of a
programmed forms an executable code, and they are stored in the secondary
memory and can be reloaded into the main memory whenever it is required for
execution.
Chapter: 2
Programming through Algorithms & Flowcharts
• Whenever a problem is given, the user has to identify the logic of solving the
problem. This logic is independent of the programming language.
• The logic is represented through the simple tools. Algorithms and Flowchart
are 2 such tools used to depict the method of solving the actual problems.
• These tools should be capable of representing different statements of a program
(Imperative statements(action), Condition statements(>,<,=), Iterative
statements (repetitive))
Algorithms:
• Algorithm is a finite set of unambiguous instructions, which, when executed
performs a task correctly
• Algorithm is a step by step instruction which tells the how the inputs are
processed and how the output is generated.
• Each instruction tells what task is to be performed.
Features of an Algorithm:
• A number of quantities are provided to an algorithm initially before the algorithm
begins. These quantities are the inputs, which are processed by the algorithm.
• The processing rules in the algorithm should be precise, unambiguous and lead
to a specified action.
• Each instruction should be sufficiently basic such that it can be carried out.
• The total time to carry out all the steps in the algorithm must be finite.
• The algorithm must have one more outputs.
Simple algorithm:
• Develop an algorithm to find the sum of 2 numbers
Algorithm: Sum
Step 1: START
Step 2:Declare the variables A,B and C.
Step 3: Add the contents of A and B and store the result in C or C=A + B
Step 4: Print the result in C
Step 5: STOP
• Develop an algorithm to find the average of 3 numbers.
Algorithm : Average
Step - 1 : START
step -2 : Declare the variables A,B,C,D
Step 3: D=(A +B+C) / 3
Step 4: print the result in D
Step 5 : stop
• Develop a program to find the largest of 2 numbers
Algorithm: Largest of 2 Numbers
Step 1: Start
Step 2: Declare 2 variables A, B
Step 3: if A>B go to step 4, else go to step 5
Step 4: Print A is greater, go to step 6
Step 5: Print B is greater
Step 6: Stop
• Develop an algorithm to find whether the entered number is even or odd
step 1:start
step 2: declare a variable num
step 3: divide the num by2. If the remainder is 0 goto step 4,else go to step 5
step 4:print the num is even. Go to step 6
step 5: print the num is odd
step 6 : stop
• Algorithm for largest of 3 numbers
Step 1: Start
Step 2: Declare 3 variables A, B, C
Step 3: if A>B go to step 4, else go to step 6
Step 4: if A > C go to step 5, else go to step 8
Step 5: Print A is greater go to step 9
Step 6: check if B > C , then go to step 7, else go to step 8
step 7: Print B is greater, go to step 9
Step 8: Print C is greater
Step 9: Stop
• Algorithm for finding the power of a number
Step 1: Start
Step 2: Read m, n, pow=1,count=1
Step 3: pow=pow * m
count = count +1
Step 4: if (count <=n)repeat step 3, else go to step 5
Step 5: Print pow;
Step 6: Stop
Flowchart
Flowchart is a pictorial representation of an algorithm. Flowchart uses different shapes
(symbols) to indicate different types of instruction and these boxes are connected by
solid lines having arrow marks to indicate the flow of operation.
A flowchart depicts the flow of operation in pictorial form and thus any error in the
logic of the procedure can be easily located.
Basic Flowchart symbols:
Chapter: 3
Introduction to programming Languages
• Computer programming is a form of giving instructions to the computers about
what they should do next.
• The instructions given are known as code, and computer programmers write
code to perform a task or solve problems.
• A program is a process of step-by-step instructions that directs the computer to
do the tasks you want it to do and produce the results you want.
• A program can be written in any of the languages.
• A language consist of grammar, set of rules, to create the constructs.
Types of Programming Languages:
Programming languages are classified into 3 types -
• Low level or machine level language: The program is written in 1’s and 0’s.
This language is used by the computer for its processing. The first generation of
programming languages used the machine level language. We can write the
programs in high level or in assembly lang, and it is been translated to the m/c
language.
• Assembly level language: The assembly language used mnemonic codes(ADD,
SUB, MUL. POW, DIV, MOV etc) and symbols for address of storage locations.
Assembler is used to translate the ALP to m/c level.
• High level Language: The high level language are more english type statements
to solve a problem and are termed as procedure oriented languages. Compilers
and interpreters are used to convert HLP to m/c level.
Steps/ Process of Program Development
Developing a program involves steps very much similar to any problem-solving
process.
There are 5 main steps in the programming process:
a. Defining the problem: (Problem Analysis)
- Studying the problem in detail
-Identifying the input variable, output requirements and constraints in the problem.
b. Planning the solution(Algorithm development)
-identifying the procedure to solve the problem
-generating alternate ways of solutions
-selecting the best method among the alternatives
-preparing the list of procedures or steps towards solution
c. Coding the program
-The necessary language is selected.
-converting the algorithm into program / code.
-program is developed, compiled and executed
d. Testing the program
-bug means error
-Testing and debugging(to locate and fix the bug/errors)
-Human testing(manual testing) and computer - based testing.
-Different type of errors - syntax, run-time, logical and latent errors
e. Documenting the program
-Documentation of the program
-type of i/p, expected o/p, constraints, troubleshooting
-future maintenance
Design Methodologies
When programs are developed to solve real-life problems like inventory management,
payroll processing, student admissions, examination result processing, etc. they tend to
be huge and complex. The approach to analyzing such complex problems, planning for
software development and controlling the development process is called programming
methodology.
Types of Programming Methodologies
There are many types of programming methodologies prevalent among software
developers, they are as follows:
1. Procedural Programming:
Problem is broken down into procedures, or blocks of code that perform one task each.
All procedures taken together form the whole program. It is suitable only for small
programs that have low level of complexity.
Example − For a calculator program that does addition, subtraction, multiplication,
division, square root and comparison, each of these operations can be developed as
separate procedures. In the main program each procedure would be invoked on the
basis of user’s choice.
2. Object-oriented Programming:
Here the solution revolves around entities or objects that are part of problem. The
solution deals with how to store data related to the entities, how the entities behave and
how they interact with each other to give a cohesive solution.
Example− If we have to develop a payroll management system, we will have entities
like employees, salary structure, leave rules, etc. around which the solution must be
built.
3. Functional Programming:
Here the problem, or the desired solution, is broken down into functional units. Each
unit performs its own task and is self-sufficient. These units are then stitched together
to form the complete solution.
Example − A payroll processing can have functional units like employee data
maintenance, basic salary calculation, gross salary calculation, leave processing etc.
4. Logical Programming:
Here the problem is broken down into logical units rather than functional units.
Example: In a school management system, users have very defined roles like class
teacher, subject teacher, lab assistant, coordinator, academic in-charge, etc. So the
software can be divided into units depending on user roles. Each user can have
different interface, permissions, etc.
Software developers may choose one or a combination of more than one of these
methodologies to develop a software. Two approaches are mainly used:
1. Top-down approach
2. Bottom-up approach
Top-down Approach: The problem is broken down into smaller units, which may be
further broken down into even smaller units. Each unit is called a module. Each
module is a self-sufficient unit that has everything necessary to perform its task.
• The top level component represents the whole system.
• The design method starts from the top level component to the lower level
component
• As the hierarchy moves downwards, the problem becomes more simple.
• Most of the programming languages follow this methodology for its design
• C -Language uses Top down design
Bottom-up Approach: In bottom-up approach, system design starts with the lowest
level of components, which are then interconnected to get higher level components.
This process continues till a hierarchy of all system components is generated.
• This is the reverse of top down design
• First the basic components are designed then based on that the next higher level
components are designed.
• Object oriented programming language(C++) uses bottom-up approach.
Source Code & Object Code:
The main difference between source program and object program is that a source
program is a collection of instructions written using a programming language,
while an object program is an output generated after compiling the source
program.
• A program is a set of instructions that directs the computer to perform a task. A
programmer writes the program using a specific programming language, and this
program is called the source program.
• The compiler compiles the source code to generate the object program. Overall,
the programmer understands the source program but does not understand the object
program.
• On the other hand, the machine does not understand the source program but
understands the object program.
Executable File: An executable file is a file that is used to perform various functions or
operations on a computer. Unlike a data file, an executable file cannot be read because
it's compiled.
On Windows systems, compiled programs have an .EXE file extension and are often
referred to as "EXE files.".
Chapter: 4
Basic Concepts of C Language
• C programming is a general-purpose, procedural, imperative computer
programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone
Laboratories to develop the UNIX operating system.
• C is the most widely used computer language.
• C is an offspring of ALGOL, Basic Combined Programming Language(BCPL)
and B.
Fig: History of ANSI C
Facts about C:
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard
Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
Characteristics & Importance of C
• C is a robust language with a set of built-in functions and operators.
• C compiler combines and accommodates the feature of assembly and high-level
language.
• Programs written in C are fast and efficient due to the usage of variety of data
types and powerful operators.
• C has 32 keywords
• C is portable, here the programs written for one computer can be run on another
machine with lesser or no modification.
• C supports the structured programming, so there are several functional modules
or blocks.
• The structure of C program makes the program debugging, testing and
maintenance easier.
• C has an ability to extend itself. C has a collection of functions that are supported
by the C library. We can add our own functions to the C library.
Sample Program :1
#include<stdio.h>
main()
{
/* ……………….printing begins………...*/
printf(“Hello, Welcome to the first Program in C”);
/* ……………….printing ends………...*/
}
• The first line tells the system that the name of the program is main() and the
execution starts from this line.
• Main() is a special function used by C language to tell the computer here the
program starts.
• Every program must have only one main function.
• Main() is immediately followed by an empty pair of parenthesis that indicates
that function has no arguments.
• The opening { is the beginning of function main and the closing } indicates the
end of the function or the end of the program.
• All the statements between the { } is the function body
• The statements are either executable or non executable statements
• The printf is the executable statement.
• The line beginning with /* */ are the comment lines.
• Comment lines are used for readability and better understanding, they are non
executable and ignored by the compiler
• Comment lines can be inserted at the beginning, middle or end of a line , but
never used in the middle of the word.
• The printf statement prints the content within “ “.
• printf ends with a semicolon. Every statement in C should end with a semicolon ;
Basic Structure of a C program
Documentation Section
Link Section
Definition Section
Global Declaration Section
main ()function Section
{
Declaration Part
Executable Part
}
Sub Program Section
Function 1
Function 2
Function 3
• Documentation Section:- consist of set of comments regarding the name of the
program, author name, date created etc.,
• Link Section:- provides the instructions to the compiler to link the functions
from the system library(#include<stdio.h> all standard input and output header
files)
• Definition Section:- defines all the symbolic constants
• The variables that are used in more than one function can be declared as global
variables in the global declaration section.
Elements of C
• Every language has some basic elements and grammatical rules.
• A programming language is designed to process some data that consists of a
number, characters, strings and to produce output called information.
• Processing of data is performed by executing a sequence of precise instructions
called a program
• These instructions are formed on the basis of some rigid rules called syntax
rules(grammar)
• C language has its own grammar and elements
• The common elements of C are:
1. Character set
2. Reserved words/ Keywords
3. Data types
4. Identifiers
5. Variables
6. Constants
7. Expressions
8. Escape sequences
9. Delimiters
[Link]
[Link]
Character set:
The basic character set in C are
• Letters: It has upper case letters A – Z and lower case a-z
• Digits: all decimal digits 0-9
• Special characters: +, -, % , *, :, ”,{ etc.,
• White spaces: white spaces are used to separate the words. Blank space,
New line, Horizontal and vertical tab.
Reserved words/ Keywords:
• The words which are reserved for doing specific task are called as
Reserved words or Keywords.
• C supports 32 Keywords.
• They have standard, predefined meaning.
• They can be used in programs, but cannot be modified.
• Auto, int, char, float, double, break, const….
Data types:
• C language is rich in data types.
• ANSI C supports 3 classes of data types:
• 1. Primary /Primitive / Basic or fundamental data types
2. Derived data types
3. User defined data types
• All C compilers support five fundamental data types:
1. integer(int)- used to store an integer value
2. character(char)- used to store any single character
3. floating point(float)- used to store real numbers with six digit precision
4. double-precision floating point (double)-used to store 14 digit precision
5. void – has no values. It is used to specify the type of functions
Type Qualifiers: Type qualifiers are used to get more different types of data. There are
2 type of type qualifiers
1. Size Qualifiers – short, long
2. Sign Qualifiers – signed, unsigned
• Unsigned integers specifies that the number is always positive, whereas
signed integer may be positive or negative.
• The range of values for signed data types is less than unsigned type because in the
signed type the leftmost bit is used to represent the sign
• while in the unsigned type this bit is also used to represent the value.
• The size and range of different data types on a 16 bit machine is as follows:
Identifiers:
• All the words that are used in our C program are Keywords or Identifiers.
• Identifiers are user defined words and are used to give name to variables,
functions and arrays.
• There are some rules for the usage of identifiers:
• The name should consist of only alphabets(upper, lower), digits, underscore sign
• First character should be an alphabet or _
• Identifier should not be a keyword.
• White space is not allowed.
• C is case sensitive, so uppercase and lower case letters are considered different.
• Identifiers can be long. Only first 31 characters are significant.
• It is better to use short and precise idenitifier
• Ex: Valid identifiers…
Variables:
• Variable is a name that can be used to store values.
• Variables can take different values but one at a time, and these values are
changed during the execution of the program.
• Variable must begin with a letter.
• It should not be a keywords
• white space is not allowed.
• Uppercase and lowercase letters are significant.
• Ex: John, Delhi, mark ,sum1,total_avg,
Declaration of Variables:
• Variable must be declared before it is used in the program
• It specifies what type of data the variable will hold.
• Syntax: datatype variable;
• datatype variable1,variable2….,variableN;
• Example: int x;
float salary; int a;
• We can declare more than one variable in a single declaration
• Example: int x, y, z;
• float x, total, price;
Initialization of variables:
• When the variable is declared it contains un-defined values called garbage
value, so while declaring the variables itself we can initialize it by assigning the values.
• Int sum=0,temp=0;
• Ex: int a=10, b=20;
int a,b,c=10;
float sum=59.8;
char ch=’x’;
Constants:
• Constant is a value that cannot be changed during the execution of the program.
• The different type of constants are
1. Numeric constant
2. Character constant
Numeric Constant: Numeric constant consist of numeric digits, the rules are
• Numeric constant should have at least 1digit.
• No comma or space is allowed within the numeric constants
• Numeric constant can either be +ve or -ve.
• Default is always +ve.
Integer Constant:
• These are whole numbers which have no decimal point.
• 3 types of integer constant are:
• Decimal constant – 0,1,2,3,4,5,6,7,8,9 (0-9, base 10)
• Octal constant – 0,1,2,3,4,5,6,7 (0-7, base 8)
• Hexadecimal constant – 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F(0-9,A-F, base 16)
Example: (Invalid for integer constant)
2.5 - illegal character.. so no decimal point is allowed
3#2 - illegal character, no other characters are allowed
98 5 - no space is allowed
082 - first digit cannot be a Zero
2,346 - comma not allowed
Example: (Valid for octal constant)
• An octal integer constant begins with Zero(0)
• 02 05 06 08(invalid)
• 0,077
• The hexadecimal integer constant has the first 2 characters as 0x or 0X
• 0x23, 0XAB
Real or Floating point constant:
• These are numeric constant that contains decimal point (eg: 0.5, 0.00097)
• The number is written in mantissa and exponent form
• mantissa is a real number but exponent(‘e’ or ‘E’)can be only an integer(+ve or -ve).
• Ex: 7500000000 === 75E8 or 7.5E9
0.0000076 ===== 7.6 *10-6 or 7.6E-6
Character constant:
• A single character that is enclosed within single quotes is the character constant.
• Ex: ‘a’ ,’x’, ‘6’, ‘#’
• only one character is allowed
• Double quotes is not allowed (“a”, “x”, ‘sum’ are invalid)
• Every character constant has an integer value associated with it.
• A-Z the ASCII value range is 65 – 90
a- z the ASCII value range is 97 – 122
0–9 the ASCII value range is 48 – 57
String Constant:
• String constant is enclosed within double quotes
• It has zero, one or more than one character
• The character may be letters, numbers, special characters and blank space.
• The compiler automatically attaches \0 (Null) at the end of the string.
• Ex: “A”, “sum”, “Hello”
“A” and ‘A’ are different.
Expressions:
• Expression is a combination of operators, constants, variables and function calls.
• Expression can be arithmetic(+,- ,/, *), logical (&&,||,!) or relational(<,>,<=,==)
• Ex: a + b -------------->arithmetic operator
a = b + c -------------> arithmetic operator with 2 operators = , +
a > b -----------------> relational expression
a = = b ----------------> logical expression
f(a, b) -------------------> function call
Escape sequences:
• Characters are printed on the screen from the keyboard as input. But some
characters like tab, backspace… cannot be printed like other characters.
• C supports the combination of backslash ( \ ) and the characters from C character
set to print these characters.
• The escape sequences has 2 characters. The first is “ \ “ and the second is from the
C character set.
Delimiters
• Delimiters are used to give a syntactic/ special meaning for the statements in C.
• Delimiters are one or more characters that separate strings
Symbol Name Purpose
: Colon Used for label
; Semicolon End of statements
() Parenthesis Used in expression
[] Square bracket Used in array
{} Curly braces Used for a block of statements
, Comma Variable delimiter
# Hash Pre processor directive
Statements
• All the instructions are written in the form of statements.
• Statements are executable, and it performs the actions.
• Each statements end with a semicolon, but there are some exemptions ;
• Different statements are as follows:
• Expression statements ……………. a = b+c, A>B, a == b, a = b+c+d
• compound statements / block of statements ………... {}
• selection statements …………. if, if...else, switch
• Iterative statements ……….. for, while, do - while
• Jump statements ………… goto, continue, break, return
• Label statements………...case, default, label statement
Comments
• This provides readability of the program
• helps in better understanding.
• comments are within / * ……… */
• The comment lines are ignored by the C compiler
• Comments are non-executable statements.