Sunteți pe pagina 1din 106

INTRODUCTION TO

PROGRAMMING

UNIT - I
Introduction to Programming:Concept of algorithms, Flow Charts, Data
Flow diagrams etc., Introduction to the Editing tools such as vi or MS-VC
editors, Concepts of the finite storage, bits bytes, kilo, mega and
gigabytes.Concepts of character representation, Number Systems &
Binary Arithmetic.[No. of
Hrs. 8]

UNIT - II
Programming using C:The emphasis should be more on programming
techniques rather than the language itself.The C Programming language
is being chosen mainly because of the availability of the compilers, books
and other reference materials.
Example of some simple C program. Concept of variables, program
statements and function calls from the library (Printf for example)
C data types, int, char, float etc., C expressions, arithmetic operation,
relational and logic operations, C assignment statements, extension of
assignment of the operations.C primitive input output using getchar and
putchar, exposure to the scanf and printf functions, C Statements,
conditional executing using if, else.Optionally switch and break

UNIT - III
Iterations and Subprograms:Concept of loops, example of loops in C using
for, while and do-while.Optionally continue may be mentioned.
One dimensional arrays and example of iterative programs using arrays, 2-d
arrays Use in matrix computations.
Concept of Sub-programming, functions Example of functions.Argument passing
mainly for the simple
variables.[No. of Hrs. 8]

UNIT - IV
Pointers and Strings:Pointers, relationship between arrays and pointers
Argument passing using pointers Array of pointers.Passing arrays as arguments.
Strings and C string library.
Structure and Unions.Defining C structures, passing strings as arguments
Programming
examples.
[No. of Hrs. 8]


TEXT BOOKS:
1.Yashwant Kanetkar, Let us C, BPB Publications,
2ndEdition, 2001.
2.Herbert Schildt, C:The complete reference,
Osbourne Mcgraw Hill, 4thEdition, 2002.
REFERENCE BOOKS:
1.Raja Raman, Computer Programming in C,
Prentice Hall of India, 1995.
2.Kernighan & Ritchie, C Programming Language,
The (Ansi C Version), PHI, 2ndEdition.

What is Computer
Computer is an electronic device that is designed to
work with information.The term computer is derived
from the Latin term computare, this means to
calculate.Computer can not do anything without a
Program.
Computer is an advanced electronic device that takes
raw data as input from the user and processes these
data under the control of set of instructions (called
program) and gives the result (output) and saves
output for the future use.

HARDWARE ORGANIZATION
of a
COMPUTER

Basic Hardware Components

Characteristics of a
computer

High speed
More reliable and accurate
High memory capacity
Can be able to perform various tasks

The Evolution of Programming Languages


A computer language is used by a programmer to
instruct a computer what to do, or in other words, to
write a program (writing instructions) for a computer.
People use languages that are similar to
human language. The results/programs are
translated
into
machine
code,
which
computers understand.

It is a vehicle of communication between computers


and us by enabling us to write programs of computers
to solve problems

Programming languages fall into three broad categories:


Machine Languages
Symbolic Languages
High-Level Languages

Computer Language Evolution

Low Level
Languages

The Evolution of Programming


Languages Machine Language
Machine languages (first-generation languages) are the
most basic type of computer languages, consisting of
strings of numbers (binary 0s and 1s), the computer's
hardware can use.
Different types of hardware use different machine
code. For example, IBM computers use different
machine language than Apple computers.
Format of low level language: opcode operands

PROGRAM

The Multiplication Program in Machine Language

Note
The only language understood by computer
hardware is machine language.

The Evolution of Programming


Languages - Assembly Language
Assembly language (second-generation language) is
somewhat easier to work with than machine
language.
To create programs in assembly language, developers
use cryptic English-like phrases, called mnemonics, to
represent strings of numbers.
Eg. ADD, MUL, LOAD
One of the major disadvantage is that assembly
language is machine dependent.

PROGRAM

The Multiplication Instruction in Symbolic Language

MUL R3, R1, R2; /R3=R1*R2

Note
Symbolic language uses symbols, or mnemonics, to represent
the various machine language instructions.

The Evolution of Programming


Languages Higher-Level Languages

Higher-level languages are more powerful than assembly


language and allow the programmer to work in a more
English-like environment.
Higher-level programming languages are divided into
three "generations," each more powerful than the last:

Third-generation languages

Fourth-generation languages

Fifth-generation languages

Higher-Level Languages Third-Generation Languages


Third-generation languages (3GLs) are the first to
use true English-like phrasing, making them easier
to use than previous languages.
3GLs are portable, meaning the object code created
for one type of system can be translated for use on a
different type of system.
The following languages are 3GLs:
FORTRAN
COBOL
BASIC
Pascal

C
C++
Java
ActiveX

PROGRAM

The Multiplication Program in C

21

Higher-Level Languages Fourth-Generation Languages


Fourth-generation languages (4GLs) are even easier
to use than 3GLs.
4GLs may use a text-based environment (like a 3GL)
or may allow the programmer to work in a visual
environment, using graphical tools.
The following languages are 4GLs:
Visual Basic (VB)
Report Generators

ALGORITHMS
A typical programming task can be divided
into two phases:
Problem solving phase
produce an ordered sequence of steps that
describe solution of problem
this sequence of steps is called an algorithm

Implementation phase
implement the program in some programming
language

Format of an Algorithm
Algorithm name(input,output)
1.
2.
n(Algorithm body which contain
finite no. of steps )
Algorithm can be write in English
language style or English
programming style.

Ex.
Sum(A,B, out)
1. Get the two inputs from the user
2. Assign the inputs to A & B
3. Set out:= A+B or set out <A+B
4. Exit

Algorithm
Example 1: Write an algorithm to
determine a students final grade
and indicate whether it is passing or
failing. The final grade is calculated
as the average of four marks.

Algorithm
Detailed Algorithm

Step 1:
Input M1,M2,M3,M4
Step 2:
GRADE
(M1+M2+M3+M4)/4
Step 3:
if (GRADE < 50) then
Print FAIL
else
Print PASS
endif

Algorithm Analysis
It is analyze in terms of their
efficiency i.e. how much computer
memory space and execution time it
uses, to store and to execute
Space complexity- for fixed and vary
variable
Time complexity- compile time and
run time

Algorithm design is a specific


method to create a mathematical
process in solving problems.
Different techniques used to
Algorithm design such as recursive
algorithm, dynamic programming,
divide-and-conquer

The Flowchart
(Dictionary) A schematic representation of a
sequence of operations, as in a manufacturing
process or computer program.
(Technical) A graphical representation of the
sequence of operations in an information system
or program. Information system flowcharts show
how data flows from source documents through
the computer to final distribution to users.
Program flowcharts show the sequence of
instructions in a single program or subroutine.
Different symbols are used to draw each type of
flowchart.

The Flowchart
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their
interconnections
e.g. control flow from one action to the
next

Flowchart Symbols
Basi
c

Example
START
Input
M1,M2,M3,
M4
GRADE(M1+M2+M3+M
4)/4
N

IS
GRADE<
50

PRINT
PASS

PRINT
FAIL

STOP

Step 1:
Input M1,M2,M3,M4
Step 2: GRADE
(M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then
Print FAIL
else
Print PASS
endif

Example 2
Write an algorithm and draw a
flowchart to convert the length in
feet to centimeter.

Example 2
Algorithm
Step 1: Input Lft
Step 2: Lcm Lft x 30
Step 3: Print Lcm

Flowchart
START

Input
Lft

Lcm

Lft x
30

Print
Lcm

STOP

Example 3
Write an algorithm and draw a flowchart
that will calculate the roots of a
quadratic
ax 2 bx c equation
0

b 2 4ac
Hint: d = sqrt (
) and the
roots are: x1 = (b + d)/2a and x2 =
(b d)/2a

Example 4
Pseudocode:
Input the coefficients (a, b, c) of the
quadratic equation
Calculate d
Calculate x1
Calculate x2
Print x1 and x2

Example 4
START

Algorithm:

Step
Step
Step
Step
Step

1:
2:
3:
4:
5:

Input a, b, c
d sqrt ( b b 4 a c
x1 (b + d) / (2 x a)
x2 (b d) / (2 x a)
Print x1, x2

Input
a, b, c

)
d

sqrt(b x b 4 x a x
c)

x1

(b + d) / (2 x a)

X2

(b d) / (2 x a)
Print
x1 ,x2

STOP

The benefits of flowcharts are as follows:


Communication: Flowcharts are better way of communicating
the logic of a system to all concerned.
Effective analysis: With the help of flowchart, problem can be
analysed in more effective way.
Proper documentation: Program flowcharts serve as a good
program documentation, which is needed for various purposes.
Efficient Coding: The flowcharts act as a guide or blueprint
during the systems analysis and program development phase.
Proper Debugging: The flowchart helps in debugging process.
Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part

Data Flow Diagrams (DFDs)

Graphical system model that shows all main requirements


for an IS in one diagram
Inputs/outputs
Processes
Data storage

Easy to read and understand with minimal training (only 5


symbols used)

40

DFD Symbols
The square is an external agent (a person or
organization, outside the boundary of a system that
provides data inputs or accepts data outputs)
The rectangle with rounded corners is a process
(named Look up item available and can be referred
to by its number, 1)
A process defines rules (algorithms or procedures) for
transforming inputs into outputs
The lines with arrows are data flows (represents
movement of data). Slide shows two data flows
between Customer and process 1: a process input
Item inquiry and process output named Item
availability details
The flat rectangle is a data store (a file or part of a
database that stores information about data entity)
41

Data
Flow
Diagram
Symbols

42

DFD Fragment Showing Use Case


Look Up Item Availability from the
RMO

43

DFD Integrates Event Table and


ERD

44

DFD and Levels of Abstraction

DFD is a modeling technique that breaks the system into a hierarchical set
of increasingly more detailed models

DFD may reflect the processing at either a higher level (more general view of
the system) or at lower level (a more detailed view of one process)

These different views of the system (higher level versus low level) creates
the levels of abstraction

DFDs are decomposed into additional diagrams to provide multiple levels of


detail

Higher-level diagrams provide general views of system

Lower-level diagrams provide detailed views of system

45

Layers of DFD
Abstraction for
Course
Registration
System

46

Context Diagrams
DFD that summarizes all processing
activity for the system or subsystem
Highest level (most abstract) view of
system
Shows system boundaries
System scope is represented by a single
process, external agents, and all data flows
into and out of the system
47

Context Diagrams for a Course


Registration System

48

Notes on Context Diagrams


Useful for showing system boundaries (represents the system
scope within the single process plus external agents)
External agents that supply or receive data from the system are
outside the system scope
Data stores are not usually shown in the context diagram since they
are considered to be within the system scope
It is the highest level of DFD
Context diagram does not show any details of what takes place within
the system

49

What is C?
A

programming language written


by Dennis Ritchie at AT&T Labs of
USA in 1972.
Originally created to design and
support the Unix operating system.

Why use C?
Mainly because it produces code
that runs nearly as fast as code
written in assembly language. Some
examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
This is used mainly because of the portability
that writing standard C programs can offer.
Major parts of popular operating systems like Windows,
UNIX, Linux are still written in C.

History

Early C, UNIX, and Associated


Hardware

Why C Middle level language ?


Relatively good
(as compared
languages)
Relatively good
compared to high

Gateway

programming efficiency
to machine oriented
machine efficiency (as
level languages)

for other professional languages


like C C++ Java

History and development of C

1960

ALGOL

International Group

1967

BCPL

Martin Richards

1970

Ken Thompson

1972

Traditional C

Dennis Ritchie

1978

K&R C

Kernighan & Ritchie

1989

ANSI C

ANSI Committee

1990

ANSI/ISO C

ISO Committee

Feature of C
Hardware independent
Provide functionality through rich set
of function libraries
Case-sensitive

C language is efficient and fast.


C is highly portable.
C language is well suited for
structured programming.
C is a machine independent
language.
C has the ability to extend itself.

PREPROCESSOR
Preprocessor :It is a program that process the source code
before it passes through the compiler
#include directive :C programs are divided into modules
or functions. Some functions are written by users and some
are stored in C library. Library functions are grouped
category wise and stored in different files known as header
files. To access the file stored in the library, it is necessary
to tell the compiler about the files to be accessed. This is
achieved by the preprocessor directive#includeas
follows,
#include<filename>
Filename is the name of the library file that contains
the required function definition. Preprocessor directives are
placed at the beginning of the program.

Basic structure of C
programming
Documentation section
Link section
Definition section
Global declaration section
main () Function section
{
Declaration part
Executable part

Subprogram section
Function 1
Function 2
..
..
Function n

(User defined functions)

i)Documentation section :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.
ii)Link section :The link section provides instructions to the
compiler to link functions from the system library.
iii)Definition section :The definition section defines all symbolic
constants.
iv)Global declaration section :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 all the userdefined functions.

main () function section :Every C program must have one


main function section. This section contains two parts;
declaration part and executable part.
(a)Declaration part :The declaration part declares all the
variables used in the executable part.
(b)Executable 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 is the logical end of the program. All statements in
the declaration and executable part end with a semicolon.

vi)Subprogram section :The subprogram


section contains all the user-defined functions
that are called in themain()function. Userdefined functions are generally placed
immediately after themain()function, although
they may appear in any order.

All section, except themain()function


section may be absent when they are not
required.

Execution of a C program
Executing a C program involves a
series of steps. They are i)Creating the program.
ii)Compiling the program.
iii)Linking the program with
functions that are needed from the
C library.
iv)Executing the program.

Draw the flow chart of theprocess of


compiling and running a C program

STARTING WITH
PROGRAMMING.

A close analogy between learning English


language and learning C language.

C CHARACTER SETS

The alphabets, numbers and special symbols when


properly combined form constants, variables and
keywords.

A token is a language element that can


be used in forming higher level
language constructs
Equivalent to a word in English
language
Several types of tokens can be used to
build a higher level C language
construct such as expressions and
statements
There are 6 kinds of tokens in C:

Reserved words (keywords)


Identifiers
Constants
String literals
Punctuators

Reserved Words
Keywords that identify language entities
such as statements, data types,
language attributes, etc.
Have special meaning to the compiler,
cannot be used as identifiers in our
program.
Should be typed in lowercase.
Example: const, double, int, main, void,
while, for, else (etc..)
Displayed in BLUE color in MS Visual C+
+

KEYWORDS

Manav Rachna College of Engg

Keywords are the words whose meaning has already been


explained to the C compiler (or in a broad sense to the
computer).
The keywords cannot be used as variable names.
The keywords are also called Reserved words.
There are only 32 keywords available in C.

Identifiers
Words used to represent certain
program entities (program variables,
function names, etc).
Example:
int my_name;
my_name is an identifier used as a program
variable

void CalculateTotal(int value)


CalculateTotal is an identifier used as a function
name

Rules for Constructing Identifiers


1. Identifiers can consist of capital letters A to Z, the lowercase a to z, the
digit 0 to 9 and underscore character _
2. The first character must be a letter or an underscore.
3. There is virtually no length limitation. However,, in many
implementations of the C language, the compilers recognize only the first
32 characters as significant.
4. There can be no embedded blanks
5. Reserved words cannot be used as identifiers.
6. Identifiers are case sensitive. Therefore, Tax and tax both different.

Rules for Constructing Identifiers


Examples of legal identifier:
Student_age, Item10, counter, number_of_character
Examples of illegal identifier
Student age (embedded blank)
continue (continue is a reserved word)
10thItem (the first character is a digit)
Principal+interest (contain operator character +)

Recommendations for Constructing Identifiers


1. Avoid excessively short and cryptic names such as x or wt. Instead, use
a more readable and descriptive names such as student_major and
down_payment.
2. Use underscores or capital letters to separate words in identifiers that
consist of two or more words. Example, student_major or studentMajor
are much easier to read than studentmajor.

Constants
Entities that appear in the program code as
fixed values.
4 types of constants:
Integer constants
Floating-point constants
Character constants
String Literal

Integer Constant
Positive or negative whole numbers with no fractional
part
Optional + or sign before the digit.
It can be decimal (base 10), octal (base 8) or
hexadecimal (base 16)
Example:
const int MAX_NUM = 10;
const int MIN_NUM = -90;
const int Hexadecimal_Number = 0xf87;

Integer Constant
Rules for Decimal Integer Constants
1. Decimal integer constants must begin with a
nonzero decimal digit, the only exception being 0,
and can contain decimal digital values of 0 through
9. An integer that begins with 0 is considered an
octal constant
2. If the sign is missing in an integer constant, the
computer assumes a positive value.
3. Commas are not allowed in integer constants.
Therefore, 1,500 is illegal; it should be 1500.
Example of legal integer constants are 15, 0, +250
and 7550
0179 is illegal since the first digit is zero
1F8 is illegal since it contains letter F
1,700 is illegal since it contains comma

Floating Point Constant


Positive or negative decimal numbers with an integer
part(optional), a decimal point, and a fractional
part (optional)
Example 2.0, 2., 0.2, .2, 0., 0.0, .0,345.67
It can be written in conventional or scientific way
20.35 is equivalent to 0.2035E+2 (0.2035 x 102 )
0.0023 is equivalent to 0.23e-2 (0.23 x 10-2)
E or e stand for exponent
Mantissa(.23), Exponent(e-2)
In scientific notation, the decimal point may be
omitted.
Example: -8.0 can rewritten as -8e0

Floating Point Constant


C support 3 type of Floating-point: float (4 bytes),
double (8 bytes), long double (16 bytes)
By default, a constant is assumed of type double
Suffix f(F) or l(L) is used to specify float and long
double respectively
Example:
const float balance = 0.125f;
const float interest = 6.8e-2F
const long double PI = 3.1412L;
const long double planet_distance = 2.1632E+30l

Character constants
A character enclosed in a single quotation
mark
Example:
const char letter = n;
const char number = 1;
printf(%c, S);
Output would be: S

String Literals(constant)
A sequence of any number of characters
surrounded by double quotation marks.
Example:
Human Revolution

String Literals
Escape
Sequence

Name

Meaning

\a

Alert

Sounds a beep

\b

Backspace

Backs up 1 character

\f

Formfeed

Starts a new screen of page

\n

New line

Moves to beginning of next line

\r

Carriage return

Moves to beginning of current line

\t

Horizontal tab

Moves to next tab position

\v

Vertical tab

Moves down a fixed amount

\\

Back slash

Prints a back slash

Single quotation

Prints a single quotation

Double quotation

Prints a double quotation

\?

Question mark

Prints a question mark

Punctuators (separators)(delimiters)
Symbols used to separate different
parts of the C program.
These punctuators include:
[ ] ( ) { } , ; : * #

Usage example:
void main (void)
{
int num = 10;
printf (%i, num);
}

Expressions
It is a combination of operators,
constants,variables and functioncalls.
The function can be arithmetic,
logical or relational.
x+y(arithmetic operator)
a>b (relational expression)
a==b(logical expression)
Func(a,b)(function call)

STATEMENTS
In a C program, instructions are written in
the form of statements. A statement is
an executable part of the program.
Statements can be categorized as:
1)Expression 2)Compound 3)selection(if,
ifelse,switch)
4) Iterative (for,while,do.while)
5)Jump (goto,continue,break,return)
6) Label(case,default,label statement used
in goto)

Expression Statement
Expression statement:
X=5; x=y-z; func(a,b);
;(null statement)
Compound Statement:
{
Int l=4; b=2;h=3;
Int area,volume;
Area= 2*(l*b*h);
Volume=l*b*h ;
}

History and development of C

DATA TYPES
A data type defines a set of
values and a set of operations
that can be applied on those
values.

For example, a light switch can be compared to a


computer type. It has a set of two values, on and off.
Only two operations can be applied to a light switch:
C Data
turn-on and turn-off.
types
Data types
Character
Integer
Float
Double
Void

Data types

VARIABLES
Variable is a quantity that may vary during program
execution.
Variable names are names given to locations in memory,
where a constant is stored.

Ex int a=3;

These locations can contain integer, real or character


constants.
A particular type of variable name can hold only that type
of constant.
Eg. An integer variable can hold only an integer constant, a real
variable can hold only a real constant and a character variable can
hold only a character constant.

Rules for Constructing Variables Names


A variable name is any combination of 1 to 8 alphabets,
digits and underscores (some compilers allow upto 40
characters)
The first character must be an alphabet letter or an
underscore (system variable).
No commas and blanks are allowed within a variable name.
Case matters!
C keywords cannot be be used as variable names .

Examples:

present, hello, y2x3, r2d3, ...

/* OK */

_1993_tar_return

/* OK but dont use it*/

Hello#there

/* illegal */

double

/* shouldnt work */

2fartogo

/* illegal */

Basic Datatypes
There are only a few basic data types
in C

Bytes Required

The letter x (char)

The number 100(int)

The number 12.14 (float)

DATA

Manav Rachna College of Engg

char
int
float
double
All types have a fixed size associated with
them

Variable Declaration
Generic Form
<typename>

Examples:

<varname1>, <varname2>, ... ;

int count;
float a;
double percent, total;
char p;

Initialization
Examples:
int count; /* Set aside storage space for count */
count = 0; /* Store 0 in count */

This can be done at definition:


int count = 0;
double percent = 10.0, rate = 0.56;

Documentation section
Inclusion or link section
Global declaration section
Main () function section
{
Declaration part
Executable part
}

#include<stdio.h> (preprocessor
directive)(standard input output
header file)
#include<conio.h>(console input
output header file)

Simple C Program
A program to print Welcome to c
/* A first C Program*/
# include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
printf(Welcome to C\n");
getch();
}

void main()
This statement declares the main
function.
A C program can contain many
functions but must always have one
main function.
A function is a self-contained module
of code that can accomplish some
task.

{
This opening bracket denotes the
start of the program

printf("Welcome to C\n");
printf is a function from a standard C library
that is used to print strings to the standard
output, normally your screen.
The compiler links code from these standard
libraries to the code you have written to
produce the final executable.
The "\n" is a special format modifier that tells
the printf to put a line feed at the end of the
line.
If there were another printf in this program, its
string would print on the next line.

}
This closing bracket denotes the
end of the program.

Using Scanf() function-Input data


void main ()
{
int num1,num2,sum;
printf ("Enter two numbers\n");
scanf ( "%d%d", &num1,&num2);
sum=num1 + num2;
printf ("\nSum = %d\n", sum);
}

Comments in C

Multi-line comment

/*---- comment ----*/


Single Line comment

//--comment

for
Manav Rachna College of Engg

Comments
are
used
documentation purpose
Two types of comments:

Using Scanf() function-Input data with comments

void main () //Main function


{
int num1,num2,sum; // Variable declaration
printf ("Enter two numbers\n");
scanf ( "%d %d", &num1,&num2); //Input data
sum=num1 + num2; // Add two numbers
printf ("\nSum = %d\n\n", sum);
}

// Display sum

Using the getchar() and putchar()


Function
They are the simplest I/O functions .
getchar() is a function used to read a
character through standard input,
keyboard.
Syntax: c= getchar();
putchar() is used to display a
character on standard output screen.
syntax: putchar(c);

Comments in C

Multi-line comment

/*---- comment ----*/


Single Line comment

//--comment

for
Manav Rachna College of Engg

Comments
are
used
documentation purpose
Two types of comments:

S-ar putea să vă placă și