18BCS23C-U1
18BCS23C-U1
Semester : II
Subject Title : C PROGRAMMING
Sub Code : 18BCS23C
UNIT – I :Over view of C-Importance of C-Sample C programs-Basic structure of C programs - Constants, Variables, and
Data Types - C tokens - Keywords and Identifiers – Constants – Variables-Data types -Operators and Expressions –
Arithmetic Operators-Relational operators-Logical operators- Assignment operators-Increment and decrement operators-
Conditional operator-Bitwise operators - Special operators-Type conversion in expressions-Operator precedence and
associativity .
UNIT – II :Managing Input and Output Operations -Reading a character-Writing a character-Formatted input -Formatted
output - Decision Making and Branching-Decision making with IF statement-Simple IF statement-The IF ELSE statement--
The switch statement-The?: Operator-The GOTO statement - Decision Making and Looping-The WHILE statement-The DO
statement-The FOR statement
UNIT – III: Arrays – Introduction-One dimensional arrays-Two dimensional arrays-Multidimensional arrays.
Character Arrays and Strings-Declaring and initializing string variables-Reading strings from terminal- Writing strings to
screen-Arithmetic operations on characters- Putting strings together -Comparison of two strings – String-Handling functions.
UNIT – IV User-Defined Functions – Introduction-Need for user-defined function-The form of C functions Return values
and their types-Calling a function-Category of functions – Recursion-Functions with arrays-The scope and lifetime of
variables in functions.
Structures and Unions-Structure definition Giving values to members-Structure initialization-Comparison of structure
variables-Arrays of structure variables-Arrays within structures-Structures within structures-Structures and functions –
Unions-Size of structures-Bit fields.
UNIT – V Pointers-Understanding pointers-Accessing the address of a variables-Declaring and initializing pointers-
Accessing a variable through its pointer-Pointer expressions-Pointers and arrays-Pointers and character strings-Pointers and
functions-Pointers and structures.
File Management in C-Defining and opening a file-Closing a file-Input/Output operations on files Error handling during I/O
operations-Random access to files-Command line arguments.
TEXT BOOKS 1. E.Balagurusamy,”Programming in ANSI C”, Seventh Edition McGraw Hill Education India Private Ltd,
2017
UNIT I
CHAPTER I
1.1 OVERVIEW OF C
C Language is a
Structured
High-level
Machine independent language
History of C
The root of all modern languages is ALGOL (introduce in 1960s).
ALGOL uses a structure programming.
ALGOL is popular in Europe
Computer scientists like Corrado Bohm, Guiseppe Jacopini and
Edsger Dijkstra popularised the structured programming concepts.
In 1967, Martin Richards developed a language called BCPL
(Basic Combined Programming Language)
Contn…
Primarily BCPL is developed for system software.
In 1970, Ken Thompson created a new language called B.
B is created for UNIX os at Bell Laboratories.
Both BCPL and B were “typeless” languages
C was developed by Dennis Ritchie at the Bell Laboratories in 1972.
Added new features and concepts like “data types”.
C was evolved from ALGOL, BCPL and B.
It was developed along with the UNIX operating system.
It was strongly integrated with the UNIX operating system.
In 1983 American National Standards Institute (ANSI) appointed a
technical committee to define a standard for C.
The committee approved a version of C in December 1989 which is now
known as ANSI C.
In 1990 International Standards Organization (ISO) has approved C and
this version of C is referred to as C89.
1.2 IMPORTANCE OF C
It is a robust language whose rich set of built-in functions and operators
can be used to write any complex program.
The C compiler combines the capabilities of an assembly language with
the features of a high-level language and therefore it is well suited for
writing both system software and business packages.
Programs written in C are efficient and fast.
C is highly portable.
C language is well suited for structured programming.
Ability to extend itself.
A C program is basically a collection of functions that are supported by the
C library.
1.3 SAMPLE PROGRAM 1
Output
Hello Program
SAMPLE PROGRAM 2
main()
{
int number;
float amount;
number =100;
amount=30.75+75.35;
printf(“%d\n”,number);
printf(“%5.2f”,amount);
}
Output
100
106.10
1.4 BASIC STRUCTURE OF C PROGRAM
Documentation Section optional
Link Section
Definition Section optional
Global Declaration Section optional
main() Function Definition
{
Declaration part
Executable part
}
Subprogram Section optional
Function 1
Function 2
--- User-defined functions
---
Function n
Documentation section
A set of comment lines giving the name of the program, the author
and other details.
Link section
Provides instructions to the compiler to link functions from the
system library.
Definition section
defines all symbolic constants.
Global declaration section
There are some variables that are used in more than one function.
Such variables are called global variables.
Global variables are declared in the global declaration section that is
outside of all the functions.
Also declares all the user-defined functions.
Main() function
Every c program must contain main() function section.
This section contains two parts
Declaration part
Executable part
These two parts must appear between the opening and closing braces
({ }).
Declaration part
Declares all the variables used in the executable part
Executable part
There is atleast one statement in the executable part.
The closing brace of main function sections is the logical end of the program.
All statements in the declaration and executable parts end with the
semicolon(;).
Subprogram section
contains all user-defined functions that are called in the main
function.
User-defined functions are generally placed immediately after the
main function , although they may appear in any order.
Syntax Yes
Errors ?
NO Object Code
Link With System
System Library
Library
Executable Object Code
Input Data Execute Object Code
NO Errors
Correct Output Stop
1.6 WRITING AND EXECUTING A C
PROGRAM IN UNIX
Create a c program
write the c-program using some text editors (eg. vi or ed)
– ed filename
– vi filename
The program must be entered into a file.
The file name can consists of letters, digits and special character, followed
by dot(.) and a letter c.
Example
firstcpgm.c
If the file existed before, it is loaded.
Otherwise the file has to be created so that it is ready to receive the new
program.
The program that is entered into the file is called source program.
Compiling and linking
use an existing compiler (gcc, cc etc) to compile your program an make an
executable
Example
cc filename
cc filename1, filename2, filename3 ………
Common options:
• –lm : library math
• -c : Compiles without linking. binaries are saved as "filename.o"
• -o exename: compiled binary with specified filename. (a.out default)
• cc –o myprog firstprog.c
C TOKENS
Special
Identifiers
Symbols
2.2.1 KEYWORDS AND IDENTIFIERS
All keywords have fixed meaning and these meanings cannot be
changes.
Keywords serve as basic building blocks for program statements.
There are certain words reserved for doing specific task, these words
are known as reserved word or keywords.
These words are predefined and always written in lower case or small
letter.
These keywords cannot be used as a variable name as it assigned with
fixed meaning.
ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
IDENTIFIERS
Identifiers are user defined word used to name of entities like variables,
arrays, functions, structures etc.
Rules for naming identifiers are:
1) Must consists of alphabets (both upper and lower case), digits and
underscore (_) sign.
2) First characters must be an alphabet or underscore.
3) Only first 31 characters are significant.
4) Cannot use a keyword.
5) Must not contain whitesoace.
C is a case sensitive, the upper case and lower case considered
differently, for example code, Code, CODE etc. are different identifiers.
identifiers are generally given in some meaningful name such as value,
net_salary, age, data etc.
Some invalid identifiers are 5cb, int, res#, avg no etc.
2.2.2 CONSTANTS
Fixed values that do not change during the execution of a program.
CONSTANTS
Single
Integer Real String
Character
Constants Constants Constants
Constants
Integer Constants
An integer constant refers to a sequence of digits.
Integer Constants
Decimal Hexadecimal
Octal Integers Integers
Integers
Character Constants
Single Character
String Constants
Constants
C DATA TYPES
Primary or
Fundamental Derived Data User-defined
Data Types Type Data Type
PRIMARY OR FUNDAMENTAL DATA TYPES
Character Long
Integer float
char double
signed char
unsigned char double
unsigned
signed
short int
int
long int
FLOATING POINT TYPE
Floating point numbers are stored in 32-bits, with 6 digits of precision.
float
double
long double
CHARACTER TYPE
A single character can be defined as a character (char) type data.
Characters are stored in 8 bits of internal storage.
The qualifier signed or unsigned may be explicitly applied to char.
VOID TYPE
has no values.
Used to specify the type of functions.
The type of function is said to be void when it does not return any value to
the calling function.
Play the role of a generic type, ie it can represent any of the other stamdard
type.
TYPE KEYWORD SIZE RANGE
(BITS)
char or 8 -128 to 127
Character signed char
unsigned char 8 0 to 255
int or 16 -32,768 to 32767
signed int
unsigned int 16 0 to 65535
short int or 8 -128 to 127
Integer signed short int
unsigned short int 8 0 to 255
long int or 32 -2,147,483,648 to
signed long int 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
Real
long double 80 3.4E-4932 to
1.1E+4932
2.4 DECLARATION OF VARIABLES
Declaration does two things
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary type declaration
A variable can be used to store a value of any data type.
data_type v1,v2,v3,….,vn;
v1,v2,v3,…vn are the name of the variables.
Variables are separated by commas.
Declaration statement end with a semicolon.
Example:
int count;
float total;
double ratio;
User-defined type declaration
1. “type definition” – allows users to define an identifier that would
represent an existing data type.
The user-defined data type identifier can be used to declare variables later.
typedef type identifier;
Where type refers to an existing data type,
identifier refers to the new name given to the data type.
The existing data type may belong to any class of type, including the user-
defined type.
Example:
typedef int units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float.
units batch1,batch2;
marks name[10];
Advantage of typedef
We can create meaningful data type names for increasing the readability of
the program.
2. “enumerated”
Enum identifier (value1,value2,…..,valuen);
The ‘identifier’ is a user-defined enumerated data type which can be used to
declare variables
That can have one of the values enclosed within the braces – enumerated
constants.
enum identifier v1,v2,…..,vn;
The enumerated variables v1,v2,…..,vn can have one of the values
value1,value2,…..,valuen.
V1=value3;
V3=value5;
Example:
Enum day(Moday,Tuesday,…..,Sunday);
Enum day week_st,week_end;
Week_st=Monday;
Week_end=Friday;
2.5 DECLARATION OF STORAGE CLASS
Storage class provides the information about their location and visibility.
The storage class decides the portion of the program within which the variables are
recognized.
i. Global variables:
Global variables are known throughout the program.
The variables hold their values throughout the programs execution.
Global variables are created by declaring them outside of any function.
It need not be declared in other function.
A global variable is also known as external variable.
Global variables are defined above main () in the following way:
int n, sum;
int m,l;
char letter;
main()
{
}
it is also possible to pre-initialize global variables using the = operator for
assignment.
Example:
float sum = 0.0;
int n= 0;
char c=`a';
main()
{
}
This is the same as:
float sum;
int n;
char letter;
main()
{
sum = 0.0;
n= 0;
c=`a';
}
is more efficient.
C also allows multiple assignment statements using =
Example:
a = b = 1;
This is same as
a = 1;
b = 1;
Note :
The assignment is valid if all the variable types are the same data type.
ii. Local variables:
Variable that are declared inside a function are called “local variables”.
Local variables are referred to as “automatic variables”.
Local variables may be referenced only by statements that are inside the
block in which the variables are declared.
Local variables exist only while the block of code in which they are declared is
executing.
Local variables are not known to other function block.
Any changes are made in local variables does not affect its value in the other.
Example:
void func1 (void)
{
Int n;
n = 0;
}
void func2 (void)
{
int n;
n = 99;
}
The integer variable n is declared in func1 () & func2 ().
n is only known to the code with in the same block as variable declaration.
Storage class
There are four types of storage class specifiers
1. auto
2. register
3. static
4. extern
Automatic
Storage class meaning
initialization
Garbage value
Local variable known to the function in
auto (undefined
which it is declared. Default is auto.
value)
register Local variable which is stored in the register --
Local variable which exists and retains its
Static value even after the control is transferred to 0
the calling function.
Global variable known to all function in the
extern 0
file
Declaring a variable as constant
The value of the variable to remain constant during the program execution.
The variable can be declared with the qualifier const at the time of
initialization.
const data_type variable_name=constant;
Example
const int n=50;
The value of n cannot be modified.
2.6 ASSIGNING VALUE TO VARIABLES
Variablename = constant;
Example:
n=5;
count=count+1;
datatype variable_name=constant;
Example:
int n=5;
float x=5.5;
CHAPTER III
OPERATORS AND EXPRESSIONS
3.1. INTRODUCTION
• A symbol use to perform some operation on variables, operands or with the
constant is known as operator.
• Some operator required 2 operand or Some required single operand to
perform operation.
• C operators can be classified into a number of categories.
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators
7) Bitwise operators
8) Other operators
An expression is a sequence of operands and operators that reduces to a single
value.
The value can be any type other than void.
3.1.1. ARITHMETIC OPERATORS
Operator Meaning Expression values Integer Real
Addition or unary Arithmetic Arithmetic
+
plus a+b a=10, b=3 13 13.0
- Subtraction or a-b a=10, b=3 7 7.0
unary minus a*b a=10, b=3 30 30.0
* Multiplication a=10, b=3 3 3.3333333
a/b
/ Division a=15, b=3.0 5(lhs int) 5.0
Modulo division a=10, b=3 1
% Cannot be
a=-14, b=3 -2 used with
a%b
a=-14, b=-3 -2 real
operands
a=14, b=-3 2
3.1.2 RELATION OPERATORS
Relation operators and meaning Syntax
ae-1 relational operator ae-2
Operator Meaning
Examples
== Equal
Relational Result
!= Not equal expression
4.5<10 true
< Less than
4.5<=10 true
<= Less than or equal
4.5 ==10 false
> Greater than
4.5 !=10 true
>= Greater than or
equal 4.5 >10 false
4.5>=10 false
3.1.3 LOGICAL OPERATORS
Logical Operators and Meaning Syntax
Op-1 logicaloperator op-2
Operators Meaning Truth Table
&& Logical AND Value of the Expression
Op-1 Op-2
Op-1&&op-2 Op-1||op-2
|| Logical OR
Non- Non-
1 1
! Logical NOT zero zero
Non-
zero 0 0 1
Non-
0 zero 0 1
0 0 0 0
3.1.4 ASSIGNMENT OPERATORS
Assignment Operators and Meaning Operators and Examples
Assignment operators are used to assign
the result of an expression to a variables.
Operators Example Equivalent
Syntax
+= a+=1 a=a+1
v op=exp;
Where v is a variable, exp is an expression and -= a-=1 a=a-1
op is a binary arithmetic operator. *= a*=n+1 a=a*(n+1)
The assignment statement /= a*=n+1 a=a/(n+1)
v op=exp;
%= a%=b a=a%b
is equivalent to
v=v op (exp);
Advantages
1. What appears on the left-hand side need
not be repeated and therefore it becomes
easier to write.
2. The statement is more concise and easier
to read.
3. The statement is more efficient.
3.1.5 INCREMENT & DECREMENT OPERATORS
operators
1. Pre-increment & decrement-prefix ++ and -- Examples
2. Post-increment & decrement-postfix ++ and
-- m=5;
Prefix operator adds 1 to the operand and then
the result is assigned to the variable on left.
Postfix operator first assigns the value to the operator Expression Result M
variable on left and then increments the value
operator.
Prefix y=++m y=6 m=6
Rules
++
1. Increment and decrement operators are unary
operators. Prefix -- y=--m y=4 m=4
2. When postfix ++ (or --) is used with a variable
in an expression, the expression is evaluated
Postfix y=m++ y=5 m=6
first using the original value of the variable and ++
then the variable is Increment (or decrement)
by one.
Postfix - y=m-- y=5 m=4
3. When prefix ++ (or decrement) is used in an -
expression, the variable is incremented (or
decremented) first and then the expression is
evaluated using the new value of the variable.
4. The precedence and associatively of ++ and –
operators are same as those of unary + and
unary -.
3.1.6 CONDITIONAL OPERATOR
Operator and syntax Example
• A ternary operator pair “?:” is called a=10;
conditional operator. b=15;
Syntax x=(a>b)?a:b;
exp1?exp2:exp3; output
Where exp1, exp2 and exp3 are x=10
expression. The above code is equivalent to
Exp1 is evaluated first. if (a>b)
If it is true(nonzero) then the x=a;
expression exp2 is evaluated and
else
becomes the value of the expression.
y=b;
Otherwise exp3 is evaluated and its
value becomes the value of the
expression.
3.1.7 BITWISE OPERATORS
Bitwise operators
Priority levels
High priority * / %
Low priority + -
3.3 OPERATOR PRECEDENCE AND ASSOCIATIVITY
Operator Description Associativity Rank
() [] function call and array element reference left to right 1
Example: