You are on page 1of 54

UNIT -1

INTRODUCTION
C Programming and Data
Structures

Introduction to Computers:
System Software
Program Developing Steps
Algorithms
Flowcharts
Introduction to C:
Structure of C- Program
Variable Names
Data Types

Constants
Operators
Type Conversions
Expressions
Precedence and Order of Evaluation
Managing I/O:
Input-output Statements
Formatted I/O

What is a computer?
Definition:

A computer is an electronic device


that takes data and instructions as
an input from the user ,process the
data, and provides useful information
known as output.
The electronic devices are known as
hardware and the instructions is
known as software.

Block diagram of a computer .It consists of 5 parts.


1. Input device : is usually a keyboard where programs and data are entered into the
computer.
2. Central processing unit (CPU) : is responsible for executing instructions.
3. Primary Storage : also known as main memory is a place where the programs and
data are stored temporarily during processing.
4. Output device : is usually a monitor or a printer to show output.
5. Auxiliary storage devices : also known as secondary storage is used for both input
and output.

What is Hardware &


Software?
Hardware:
Computer hardwareis the collection of physical
elements that constitute acomputersystem. It
refers to the physical parts or components of a
computer such as monitor, keyboard, Computer
data storage, hard drive disk, mouse, etc. all of
which are physical objects that you can actually
touch.
Software:
The software is the collection of programs (instructions) that
allow the hardware to do its job.

What are the types of


software?
Software is divided into two categories.

System software manages the computer resources


and provides the interface between the hardware and
the users but does nothing to directly serve the user
needs. E.g.. Operating system, text editors,
Application software is directly responsible for
helping users to solve their problems.

Program developing steps


Program Development is a multi
step process as follows
Understand the Problem
Develop a Solution - Algorithm Pseudo code Flowchart
Write a Program
Test it.

A. Understand the problem :The first step in solving


any problem is to understand it. We begin by reading
the requirements statements carefully. When we think that
we fully understand it, we review our understanding with
the user and the system analyst.
B. System requirement: We do planning of functional
requirements - Softwares Version, Non-functional
requirements - Resources - Internet , table , A/cs ,
Coffee. User functional requirements - Problem Oriented
and Language used is in simple english.

C. Analysis: User requirements are transformed to


technical terms like Blueprint and also look for
different alternatives considering all risks.

D. Design: In UML software users will develop flowcharts,


structure charts, data flow diagrams
1. Choose the best way to find solution among
different alternatives.

E. Code:
Unimportant in Software development life cycle
1. Uses software for code generation
( forward energy ).
2. Otherwise go for manual coding.
3. Basic testing is done ( compilation ).

F. System Test :
To test if user requirements are met.
Blackbox Testing: Test programs together, make
sure system works as a whole.
Whitebox Testing: Release -version to customer,
according to his/her feed back we develop Version: - version is released to selected
group of people.
G. Maintenance :

Algorithm
Definition:
Algorithm concept was developed by an Arab mathematician.
It is step-by-step approach to solve a given problem.
It is represented in an English like language and has some
mathematical symbols like ->, >, <, = etc.
To solve a given problem or to write a program we approach
towards solution of the problem in a systematic way.
Step-by-step way is called Algorithmic approach.
Algorithm is a penned strategy(to write) to find a solution.

Properties of Algorithm
Algorithm should satisfy the following criteria (OR) properties of
algorithm
1. Input : Zero or more quantities are externally supplied.
2. Output : At least one quantity is produced.
3. Definiteness : Each instruction is clear and unambiguous.
Ex: Add B or C to A
4. Finiteness : Algorithm should terminate after finite number
of steps when traced in all cases
Ex: Go on adding elements to an array
5. Effectivenes:
Every instruction must be basic i.e., it
can be carried out, by a person using pencil and paper.
Algorithm must also be general to deal with any situation.

Algorithm
Advantages
provides the core
solution to a given
problem.
It facilitates program
development by acting
as a design document or
a blue print.
It eases identification
and removal of logical
errors in a program.
Finds out best solution.

Disadvantages
In large algorithms the
flow of program
control becomes
difficult to track.
Algorithms lack visual
representation of
programming
constructs like
flowcharts; thus
understanding the
logic becomes
relatively difficult.

Example of Algorithm
Example1 :

Add two numbers.


Step 1:
Start
Step 2:
Read 2
numbers as
A and B
Step 3:
Add
numbers A and
B and
store result in C
Step 4 :
Display C
Step 5:
Stop
Example2: Average of 3
numbers.
1.
Start
2.
Read the
numbers a , b , c
3.
Compute the
sum and
divide by 3
4.
Store the
result in
variable d
5.
Print value of

Example3: Average of n
inputted numbers.
1.
Start
2.
Read the number
n
3.
Initialize i to zero
4.
Initialize sum to
zero
5.
If i is greater than
n
6.
Read a
7.
Add a to sum
8.
Go to step 5
9.
Divide sum by n
&
store the result in avg
10.
Print value of avg
11 .
End

Flow chart
Definition:
A

flowchart

sequence

of

is

steps

visual

representation

for solving

of

the

a problem . (or)

The diagrammatic representation of the way in which to


solve a given problem is called flow chart.
Flow charts are drawn using certain special purpose symbols
such as Rectangles, Diamonds, Ovals and small circles.
These symbols are connected by arrows called flow lines.

Symbols Used In Flow Chart

Flow Chart
Advantages of a Flowchart :

Flowchart is an important
aid in the development of
an algorithm itself.
Easier to Understand
than a Program itself.
Independent of any
particular programming
language.
Proper documentation.
Proper debugging.
Easy and Clear
presentation.

Limitations of a Flowchart :

Complex logic is
difficult to be
represented.
Drawing is time
consuming.
Technical details are
hidden.

Examples of Flow chart


swapping 2 numbers

Flowchart To

Find

The

Largest Among Three Numbers.

Introduction to c

Structure of C- Program
Documentation section:
This section consists of a
set of comment lines giving
the name of the program,
and other details.
Ex:- /**/
Link section:
Link section provides
instructions to the compiler
to link functions from the
system library.
Ex:- # include<stdio.h>
# include<conio.h>

Definition section:
Definition section defines all symbolic constants.
Ex:- # define A 10
Global declaration section:
Some of the variables that are used in more than one function
throughout the program are called global variables and declared
outside of all the functions. This section declares all the userdefined functions.
Main Program:
Every C program must have one main ( ) function section. This
contains two parts.
i) Declaration part: This part declares all the variables used in
the executable part.
Ex:- int a, b;
ii) Executable part: This part contains at least one statement
.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. All the statements in the declaration
and executable parts end with a semicolon (;).
Sub program section:
This section contains all the user-defined functions, that are called
in the main () function. User- defined functions generally places

C CHARACTER SET

In c the characters that can be used to form words,


numbers and expressions depend upon the computer
on which the program is run. The characters in c are
grouped into the following categories.
Letters (A-Z,a-z)
Digits (0-9)
Special characters (, , &,.,^,;,*,:,,?,
+,,<,,#,!,>,|,/,(,\,),~,[,_,],$,{,},%)
White spaces (blank space, tab, carriage return, new
line, form feed)

C TOKENS

Theseare the basic


buildings blocks in C
language which are
constructed together
to write a C program.
Each and
everysmallest
individual units in a C
program are known as
C Tokens.
C Tokens are of six
types.

KEYWORDS
Keywords are pre-defined
words in a C compiler.
Each keyword is meant to
perform a specific function in a
C program.
Since keywords are referred
names for compiler, they cant
be used as variable name.
All keywords must be written in
lower case.
C keywords can also be called
as reserved words.
C language supports 32
keywords which are given
below

Variable Names
Definition:
It is a data name that may be used to store a data value. It
cannot be changed during the execution of a program. A variable
may taken different values at different times during execution.
Rules:
Variable names may consist of letters, digits and under score( _ )
character.
First char must be an alphabet or an -
Length of the variable cant exceed up to 8 characters, some C
compilers can be recognized up to 31 characters.
No , and no white space, special symbols allowed.
Variables name should not be a keyword.
Both upper & lower case letters are used.

Primary type declaration of variables: It


tells the compiler about the name of the
variable and its type before they are used in
the program.
Syntax: data-type name of variables(v1,v2,
vn);
Ex:- int count;
Assigning values to variables: values can be
assigned to variables using the assignment
operator =
Variable-name = constant;
Ex:- initial-value = 0;
balance = 75.84;
Final-value = 100; yes = x;

Declaring a variable as constant:- The value of


certain variables to remain constant during the
execution of a program. We can achieve this by
declaring the variable with the qualifier const at
the time of initialization.
Ex:- const int class_size = 40;
Const is a new datatype qualifier. This tells the
compiler that the value of the int variable class_size
must not be modified by the program.
Declaring a variable as volatile: Another qualifier
volatile that could be used to tell explicitly the
compiler that a variables value may be changed at
any time by some external sources(from outside the
program).
Ex:- volatile int date;

Defining symbolic constants:Some constants may appear


repeatedly at a number of different
places in the program. One example
of such a constant is 3.142
representing the value of the
mathematical constant pi.
Assignment of such constants to a
symbolic name frees us from this
problem.
Ex:- # define PI 3.14
# define MAX 200

Data Types
Data type is the type of the
data that is going to be
accessed within the
program. C supports
different data types. Each
data type may have predefined memory requirement
and storage representation.
C supports 4 classes of data
types.

Primary or (fundamental) data


type(int, char, float, double)
User-defined data type(type def)
Derived data type(arrays, pointers,
structures, unions)
Empty data type(void)

User defined data types: C supports


a feature known as type definition that
allows users to define an identifier that
would represent an existing type.
Ex:- typedef data-type identifier;
Where data-type indicates the existing datatype
Identifier indicates the new name that is given to
the data type.
Ex:- typedef int marks;
Marks m1, m2, m3;

Constants
TYPES OF C CONSTANTS
1. Integer constants
2. Real constants
3. Character constants
4. String constants
1. Integer constants: An integer constant refers to a sequence of
digits. There are three types of integers, namely, decimal integer,
octal integer and hexadecimal integer.
Examples of Integer Constant:
426
,+786 , -34(decimal integers)
037, 0345, 0661(octal integers)
0X2, 0X9F, 0X (hexadecimal integers)
2. Real constants: These quantities are represented by numbers
containing fractional parts like 18.234. Such numbers are called real
(or floating point) constants.
Examples of Real Constants:
+325.34
426.0
-32.67 etc.

The exponential form of representation of real constants is


usually used if the value of the constant is either too small or
too large. In exponential form of representation the Real
Constant is represented in two parts. The first part present
before 'e' is called Mantissa and the part following 'e' is
called Exponent.
For ex. .000342 can be written in Exponential form as
3.42e-4.
3. Single Character constants: Single character constant
contains a single character enclosed within a pair of single
quote marks.
For ex. 'A',5,;,
Note that the character constant5 is not same as the number
5. The last constant is a blank space. Character constant has
integer values known as ASCII values. For example, the
statement
Printf(%d, a); would print the number 97,the ASCII value of
the letter a. Similarly, the statement printf(%c,97);
would output the letter a
String constants: A string constant is a sequence of character

Operators
An operator is a
symbol that
performs certain
mathematical or
logical
manipulations.
Operators are
used in
programs to
manipulate data
variables.

OPERATOR
TYPE

NAME OF THE
OPERATOR

EXAMPLE

Addition

C=a+b;

Subtraction

IC

C=a-b;

Multiplication

C=a*b;

OPERATO

Division

C=a/b

Modulo division

C=a%b;

<

is less than

5<6

is less than or
equal to
is greater than t

6<=7
12>=12

==

is greater than or
equal to
is equal to

!=

is not equal to

3!=2

ARIHMET

RS

RELATIO
NAL
0PERATO
RS

OPERATOR
SYMBOL
+

<=
>
>=

7>3
3==3

OPERATOR
TYPE

OPERATOR
SYMBOL
&&
||
!

Logical AND
Logical OR
Logical NOT

(x>y)&&(x!=5)
X==y || y==6
!x

EQUAL TO

X=10;

+=

PLUS EQUAL
TO

A=A+10;
//a+=10;

-=

MINUS EQUAL
TO

B=b-20; //b=20;

*=

* Equal to

j=j*5;
//j*=5;

/=

/ equal to

K=k/10;
//k/=10;

comma

Int a,b;

&

Address of

&s; //address
of s

Sizeof()

Size of a

Sizeof(int);

LOGICAL
OPERATO
RS

ASSIGNM
ENT
OPERATO
RS
SPECIAL
OPERATO

NAME OF THE EXAMPLE


OPERATOR

OPERATOR
TYPE

OPERATOR
SYMBOL

++a;
Post
increment

a ++;

--

Pre
decrement

--a;

(unary)

Post
decrement

a --;

?=
(ternary )

Conditional
operator

(a>b)?a:b;

&

Bit Wise AND

X&Y

Bit Wise OR

X|y

Bit Wise EXOR

X^y

CONDITION
AL
OPERATOR

OPERATO

EXAMPLE

++

INCREMENT
AND
DECREMENT
OPERATOR

BIT WISE

NAME OF THE
OPERATOR

Type Conversions
Converting a variable value or a
constant value temporarily from one
data type to other data type for the
purpose of calculation is known as
type conversion.
There are two types of conversions
automatic type conversion (or)
implicit
casing a value (or) explicit

1. Implicit:
In this higher data type can be
converted into lower data
type.
. Float value can be converted
into integral value by
removing the fractional part.
. Double value can be
converted into float value by
rounding of the digits.
* Long int can be converted
into int value by removing
higher order bits.

2. Explicit:
In this type of conversion, the
programmer can convert one
data type to other data type
explicitly.
Syntax: (datatype)
(expression)
Expression can be a constant or
a variable
Ex: y = (int) (a+b)
y= cos(double(x))
double a = 6.5;double b = 6.5
int result = (int) (a) + (int) (b)
result = 12 instead of 13.
int a=10
float(a)->10.00000

Expressions
Expressions are evaluated using an assignment statement of the
form:
Syntax: variable = expression;
Variable is any valid C variable name. when the statement is encountered,
the expression is evaluated first and the result then replaces the previous
value of the variable on the left-hand side. All variables used in the
expression must be assigned values before evaluation is attempted.
Ex:- x = a*b-c;
Y = b/c*a;
Z = a-b / c+d;
Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression becomes.
x = 9-12/3 +3*2-1
Step1: x = 9-4+3*2-1
Step2: x = 9-4+6-1
Step3: x = 5+6-1
Step4: x = 11-1
Step5: x = 10

Precedence and Order of Evaluation


Various relational operators have different priorities or precedence. If an arithmetic
expression contains more operators then the execution will be performed
according to their properties. The precedence is set for different operators in C.

Important note:
Precedence rules decide the order in which different operators are
applied
Associativity rule decides the order in which multiple occurrences of the
same level operator are applied.

Managing I/O
Input Output functions:The program takes some I/P- data, process it and
gives the O/P.
We have two methods for providing data to the
program
Assigning the data to the variables in a program.
By using I/P-O/P statements.
C language has 2 types of I/O statements; all these
operations are carried out through function calls.
Unformatted I/O statements
Formatted I/O statements

Unformatted I/O statements

getchar( ):- It reads single character from standard input


device. This function dont require any arguments.
Syntax:- char variable_name = getchar( );
putchar ( ):- This function is used to display one
character at a time on the standard output device.
Syntax:- putchar(char_variable);
getc() :- This function is used to accept single character
from the file.
Syntax: char variable_name = getc();
Ex:char c;
c = getc();
putc():- This function is used to display single character.
Syntax:- putc(char variable_name);
Ex:- char c; Putc(c);
These functions are used in file processing.

gets( ):- This function is used to read group of


characters(string) from the standard I/P device.
Syntax:- gets(character array_variable);
Ex:- gets(s);
Puts( ):- This function is used to display string to the
standard O/P device.
Syntax:- puts(char array_variables);
getch():- This function reads single character directly from the
keyboard without displaying on the screen. This function is
used at the end of the program for displaying the output
(without pressing (Alt-F5).
Syntax: char variable_name = getch();
Ex:- char c;
c = getch();
getche():- This function reads single character from the
keyboard and echoes(displays) it to the current text window.
Syntax:- char variable_name = getche();

Input-Output Statements
Formatted I/O Functions: Formatted I/O refers to input and output that
has been arranged in a particular format.
Formatted I/P functions
scanf( ) , fscanf()
Formatted O/P functions--- printf() ,
fprintf()
scanf( ) :- scanf() function is used to read information from the standard I/P
device.
Syntax:- scanf(control_string, &variable_name);
Ex:- int n;
Scanf(%d,&n);
Control string represents the type of data that the user is going to accept. &
gives the address of variable.(char-%c , int-%d , float - %f , double-%lf).
Control string and the variables going to I/P should match with each other.
Simple format specification as follows
%w type specified ex:- %4d , %6c
Here w represents integer value specifies total number of columns.
Ex:- scanf(%5d,&a);
a = 4377

Printf( ): This function is used to output any


combination of data. The outputs are produced in
such a way that they are understandable and are in
an easy to use form. It is necessary for the
programmer to give clarity of the output produced
by his program.
Syntax:- printf(control string, var1,var2);
Control string consists of 3 types of items
Chars that will be printed on the screen as they
appear.
Format specifications that define the O/P format for
display of each item.
Escape sequence chars such as \n , \t and \b..