CS 3251
PROGRAMMING IN C
UNIT I
BASICS OF C PROGRAMMING
Introduction to programming paradigms – Applications of C
Language – Structure of C program – C programming: Data
Types – Constants – Enumeration Constants – Keywords –
Operators: Precedence and Associativity – Expressions –
Input/Output statements, Assignment statements – Decision
making statements – Switch statement – Looping statements
– Preprocessor directives – Compilation process
UNIT II
ARRAYS AND STRINGS
Introduction to Arrays: Declaration,
Initialization – One dimensional array – Two
dimensional arrays – String operations:
length, compare, concatenate, copy –
Selection sort, linear and binary search.
UNIT III
FUNCTIONS AND POINTERS
Modular programming – Function prototype,
function definition, function call, Built-in functions
(string functions, math functions) – Recursion,
Binary Search using recursive functions – Pointers
– Pointer operators – Pointer arithmetic – Arrays
and pointers – Array of pointers – Parameter
passing: Pass by value, Pass by reference
UNIT IV
STRUCTURES AND UNION
Structure – Nested structures – Pointer and
Structures – Array of structures – Self
referential structures – Dynamic memory
allocation – Singly linked list – typedef –
Union – Storage classes and Visibility
UNIT V
FILE PROCESSING
Files – Types of file processing: Sequential
access, Random access – Sequential access
file – Random access file – Command line
arguments
TEXT BOOKS:
1. ReemaThareja, “Programming in C”,
Oxford University Press, Second Edition,
2016.
2. Kernighan, B.W and Ritchie,D.M, “The C
Programming language”, Second Edition,
Pearson Education, 2015.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “C How to Program with an
Introduction to C++”, Eighth edition, Pearson Education, 2018.
2. Yashwant Kanetkar, Let us C, 17th Edition, BPB
Publications, 2020.
3. Byron S. Gottfried, “Schaum’s Outline of Theory and
Problems of Programming with C”,McGraw-Hill Education,
1996.
4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and
Programming in C”, Second Edition, Oxford University Press,
2013.
6. Anita Goel and Ajay Mittal, “Computer Fundamentals and
Programming in C”, 1st Edition, Pearson Education, 2013.
INTRODUCTION TO C
B is a programming language developed at
Bell Labs circa 1969 by Ken Thompson and
Dennis Ritchie.
B was a pared-down version of BCPL (
Block-structured procedural languages)
Successor of B language is C
INTRODUCTION TO C
C is a General purpose programming Language.
It is developed by Dennis Ritche at Bell Laboratories in 1972.
It is a powerful , efficient, portable and robust
The language is closely associated with UNIX operating
System. The Source of UNIX OS is coded in C.
C Language runs under number of OS like MS-DOS
The Source Code of C written in one computer can be run on
another with little or no modification.
C is also Structural Programming Language, small modules for
easy debugging, testing and maintaince.
Characteristic of C
It is a highly Structured Language.
It can handle bit level operations.
C is a machine-independent language, highly portable.
It supports variety of data-types and powerful set of
operators.
It supports dynamic memory management by using Pointers.
It enables hierarchical and modular programming with help
of functions.
C can extend itself by addition of functions to its library
continuously.
The Basic Structure Of C Program
The C program is number of building blocks called
functions.
Each function performs a specific task.
A function is subroutine that may consists of one or
more statements.
STRUCTURE OF C PROGRAM
STRUCTURE OF C PROGRAM
Documentation Section
Comments are not necessary in the program.
However, in order to understand the flow of a program
It is useful for documentation.
ex /* This is a multiple lines statement */
// This is single line statement
Header file section (Link Section)
C program depends upon some header files for function
definition that are used in program.
Each header file by default is extended with .h.
The header file should be included using # include
directive function.
ex : #include<stdio.h> or #include "stdio.h“
STRUCTURE OF C PROGRAM
Global declaration
This section declares some variables, known
as global variables that are used in more
than one function.
This section must be declared outside of all
the functions.
ex : int a,b;
float c,d;
STRUCTURE OF C PROGRAM
Function main :
Every program written in C Language must containing
main() function.
Empty parenthesis after main is necessary.
Except main() function, other section may not be necessary.
The program starts from the opening brace{ and ends with
closeing brace } , the program should declare this section
contain two parts declaration and executable part.
ex : main()
STRUCTURE OF C PROGRAM
Declaration part
The entire variables that are used in exactable part.
The initialization of variable can be initialized with some
values.
ex : int a=10, b=20;
Executable part
The part contains a set of statements following the declaration
of the variables.
Ex :
{
c=a+b;
printf ("the sum is=%d",c) ;
}
STRUCTURE OF C PROGRAM
Sample C program
/* This is sample program */
# include <stdio.h>
#include <conio.h>
void main()
{
int a=10,b=20;
printf("Hello, welcome to C program\n");
c=a+b;
printf("the sum of c is =%d",c);
}
Output
Hello,welcome to C program
the sum of c is=30
Programming rules
1. Statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constant.
3. The programmer can also write the statement within the two
brace
4. The statements should end with semicolon(;)
5. Every program must have exactly one main function, more that
one main function the compiler cannot understand.
6. The opening and closing brace should be balanced.
Compiling and Executing the program
1.Program should be written in C editor.
2.The filename store with ".C" extensions.( No need include .c
extension)
3.The Source program into object program which is required
for compilation. If no error compilation it converts ".obj" file.
4.Suppose any error, then the programmer should correct it.
Linking also essential process.
5.After the compilation executable code will be loaded in the
main memory. If any error in the logic (runtime error) error the
source program is altered and compiling and linking and get
the output.
Character set
A character set is used to define the valid characters that
can be used in the programming. A character set contain
alphabets, numbers and symbols that can be used in
writing the source code.
1.Alabhabets both in lower and upper case (A,B,C...Z and
a,b,c...z)
2.Digits (0 to 9)
3.White Space ( enter,tabs, blankspace,etc.,)
4.Special symbols ( !,@,#,^,& , etc.,)
we are not permitted to use any other characters
apart from the above while preparing the source code
in C.
Character set
White Spaces
Blank Space
Horizontal Tab
Carriage Return
New Line
Form Feed
Keywords:
Keywords are the reserved words which have a special
functionality while used in the source of the program. These
worlds cannot be used as an identifier
There are 32 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
Keywords: (rules)
All the above mentioned keywords have a special
meaning in the C compiler.
These cannot be used as variable names which is not
allowed by the C compiler.
These keywords are also called as Reserved words.
Keywords are always written in smaller case.
C is a case sensitive language. so, int is treated as a
keyword and INT or Int will not be treated as keywords.
So, these cannot be used as variable names
C -Tokens
C-Tokens (cont…)
Constant
Integer Constants
An integer constant refers to a sequence of digits, There are three types
integers, namely, decimal, octal, and hexa decimal.
Decimal Constant
◦ An Decimal constantt consists of whole number which has no
decimal point
◦ Embedded spaces, commas and non-digit characters are not
permitted between digits.
Eg:123,-321 etc.,
Octal Constant
◦ An octal integer constant consists of any combination of digits from
the set 0 through 7,with a leading 0.
Eg: 1) 037 2) 0435
Hexadecimal Constant
◦ A sequence of digits preceded by 0x or 0X is considered as
hexadecimal integer. They may also include alphabets A through F or
a through f.
Eg: 1) 0X2 2) 0x9F 3) 0Xbcd
Constant
Real Constants
It contains are the numbers which hold the
decimal point (Floating point)
Certain quantities that vary continuously,
such as distances, heights etc., are
represented by numbers
Eg:0.0083,-0.75 etc.,
A real number may also be expressed in
exponential or scientific notation.
Eg:215.65 may be written as 2.1565e2
Constant
Single Character Constants
A single character constants contains a single
character enclosed within a pair of single
quote marks.
Eg: ’5’ ‘X’ ‘;’
String Constants
A string constant is a sequence of characters
enclosed in double quotes. The characters may
be letters, numbers, special characters and
blank space.
Eg:”Hello!” “1987” “?….!”
Constant
Backslash Character Constants
•C supports special backslash character constants that are
used in output functions.These character combinations are
known as escape sequences.
C-Tokens
VARIABLES /IDENTIFIERS
A variable is a data name that may be used to store a data
value.
A variable may take different values at different times of
execution and may be chosen by the programmer in a
meaningful way.
It may consist of letters, digits and underscore character.
Identifiers refer to the names of variables, functions and
arrays.
They are user-defined names and consist of a sequence of
letter or underscore as a first character.
Both uppercase and lowercase letters are permitted.
The underscore character is also permitted in identifiers.
Ex : Value,code,rec_no (Vaid)
Ex: 5bc,int,rec#,avg no (invalid)
Variable
Rules for defining variables
They must begin with a letter. Some systems permit underscore as the first
character.
ANSI standard recognizes a length of 31 characters. However, the length should
not be normally more than eight characters.
Uppercase and lowercase are significant.
The variable name should not be a keyword.White space is not allowed.
DECLARATION OF VARIABLES
The syntax is
Data-type v1,v2…..vn;
Ex : int a,b,c;
Ex : int a, float b, char c;
Ex : int a=10,float =0.5,char c=‘x’, string=“welcome”;
Rules for Constructing Identifiers
in C
Capital letters A-Z, lowercase letters a-z,
digits 0-9, and the underscore character
First character must be a letter or
underscore
Usually only the first 32 characters are
significant
There can be no embedded blanks
Keywords cannot be used as identifiers
Identifiers are case sensitive
Identifiers refer to the names of data types, constants,
variables, and functions
Data Types in C
DATA TYPES
INTRODUCTION
ANSI C supports four classes of data types
◦ Primary or Fundamental data types.
◦ User-defined data types.
◦ Derived data types.
◦ Empty data set.
A Data Type
A data type is
◦ A set of values AND
◦ A set of operations on those values
A data type is used to
◦ Identify the type of a variable when the variable is
declared
◦ Identify the type of the return value of a function
◦ Identify the type of a parameter expected by a
function
A Data Type (continued)
When the compiler encounters a declaration for a
variable, it sets up a memory location for it
An operator used on a variable or variables is legal
only if
◦ The operator is defined in that programming language for
a variable of that type
◦ The variable or variables involved with the operator are of
the same or compatible types
Two Classifications of Data
Types
Built-in data types
◦ Fundamental data types (int, char, double,
float, void, pointer)
◦ Derived data types (array, string, structure)
Programmer-defined data types
◦ Structure
◦ Union
◦ Enumeration
PRIMARY DATA TYPES
Fundamental Data Types
void – used to denote the type with no
values
int – used to denote an integer type
char – used to denote a character type
float, double – used to denote a floating
point type
int *, float *, char * – used to denote a
pointer type, which is a memory address type
Fundamental Data Types
int elevationIndicator;
char inputSymbol;
float totalCost;
int main (void)
{
double grossProduct;
int *temperatureValuePtr;
grossProduct = 4567.89;
inputSymbol = 'a';
return (0);
} // End main
Derived Data Types
Array – a finite sequence (or table) of
variables of the same data type
String – an array of character variables
Structure – a collection of related
variables of the same and/or different
data types. The structure is called a
record and the variables in the record are
called members or fields
Uses of Derived Data
Types
int elevationTable[20];
char inputSymbols[] = "Hello World";
struct operationsStruct
{
double heatReading;
int temperatureValue;
float speedMeter;
char actionCode;
}; // End struct
struct operationsStruct currentOperations;
The typedef Keyword
The typedef keyword can be used to create a synonym for a
data type. It is most often used to simplify the naming and
use of record types (i.e., structure types).
typedef struct
{
double heatReading;
int temperatureValue;
float speedMeter;
char actionCode;
} operationsRecordType;
operationsRecordType currentOperations;
operationsRecordType futureOperations;
Enumumerated
Another user defined data types is enumerated data type
which can be used to declare variables that can have one of
the values enclosed within the braces.
enum identifier {value1,value2,……value n};
include <stdio.h>
int main()
{
enum Days
{Sunday,Monday,Tuesday,
Wednesday,Thursday,
Friday,Saturday};
….
….
}
Storage class
Declaration of storage class
Variables in C can have not only data type but also storage class that provides information
about their locality and visibility.
Here the variable m is called the global variable. It can be used in all the functions in the
program. The variables bal, sum and i are called local variables. Local variables are visible
and meaningful only inside the function in which they are declared
/*Example of storage class*/
int m;
main()
{
int i;
float bal;
……
……
function1();
}
function1()
{
int i;
float sum;
……
……
}
Variables
ASSIGNING VALUES TO VARIABLES
The syntax is
Variable name=constant
Eg:1) int a=20;
2) bal=75.84;
3) yes=’x’;
C permits multiple assignments in one line.
Exe:
initial_value=0;final_value=100;
Declaring a variable as constant
Eg: 1) const int class_size=40;
This tells the compiler that the value of the int variable
class_size must not be modified by the program.
READING DATA FROM KEYWORD
Another way of giving values to variables is to input data
through keyboard using the
scanf function.The general format of scanf is as follows.
scanf(“control string”,&variable1,&variable2,….);
The ampersand symbol & before each variable name is an
operator that specifies the
variable name’s address.
Eg: 1) scanf(“%d”,&number);
INTRODUCTION TO C
DEFINING SYMBOLIC CONSTANTS
We often use certain unique constants in a program. These constants
may appear repeatedly in a number of places in the program.
ex : 3.142, represent to “pi”.
We face two problems in the subsequent use of such programs.
◦ Problem in modification of the programs.
◦ Problem in understanding the program
A constant is defined as follows:
#define symbolic-name value of constant
Eg: 1) #define pi 3.1415
2) #define pass_mark 50
INTRODUCTION TO C
Rules
◦ Symbolic names have the same form as variable names.
◦ No blank space between the sign ‘#’ and the word define is permitted
◦ ‘#’ must be the first character in the line.
◦ A blank space is required between #define and symbolic name and between the
symbolic name and the constant.
◦ #define statements must not end with the semicolon.
◦ After definition, the symbolic name should not be assigned any other value
within the program by using an assignment statement.
◦ Symbolic names are NOT declared for data types. Their data types depend on
the type of constant.
◦ #define statements may appear anywhere in the program but before it is
referenced in the program.