C Language Contents Chapter - I: PREPARED BY: Mansi Tyagi .
C Language Contents Chapter - I: PREPARED BY: Mansi Tyagi .
C LANGUAGE CONTENTS
CHAPTER - I
Basic structure of C program
C tokens
Data types and sizes
Declaration of variables
Assigning values
Operators
Type conversions,
Expressions and evaluation
Input-Output statements
CHAPTER - II
If and switch statement,
While
Do-While
For statement
.CHAPTER – III
One dimensional & two dimensional arrays
Strings and String handling functions
Functions, Recursive functions, Storage classes, and Scope rules
CHAPTER - IV
Pointers, Pointers and Arrays, Pointers and function arguments,
Pointers to functions.
Structures
Unions
CHAPTER – V
Console & File I/O
UNIT-I
Introduction
Now a days computers are playing very vital role in each and every
field of problem solving. The communication medium between a computer and a human
being is a typical 'language' i.e.. Humans are able to communicate with the computer
system in some form of language. There are basically three types of languages viz..
Machine Understandable Language. Assembly Level Language and High Level
Language. There are number of high level languages developed in the past three decades
like FORTRAN, Pascal and Basic, C Language etc. Clearly, no other language has had so
much of influence in the computing as 'C'-language. Evolution of 'C'- as a programming
language has made application development very easy.
ALGORITHM
An algorithm is a method of representing the step-by-step procedure for solving a
problem. An algorithm is useful for finding the right answer to a problem or to a difficult
problem by breaking the problem into simple cases.
An algorithm must possess the following properties:
i) Finiteness : An algorithm should terminate in a finite number of steps.
ii) Definiteness : Each step of the algorithm must be precisely stated.
iii) Effectiveness : Each step must be effective, in the sense that it should be easily
convertible into program statement and can be performed exactly in a finite amount
of time.
iv) Generality : The algorithm should be complete in itself so that it can be used to
solve all problems of a given type for any input data.
v) Input/Output : Each algorithm must take zero, one or more quantities as input data
and yield one or more output values.
Flow chart
Flow chart is diagrammatic representation of an algorithm. It is built using
different types of boxes of symbols. The operation to be performed is written in the box.
All symbols are interconnected by arrows to indicate the flow of information and
processing.
Following are the standard symbols used in drawing flowcharts. (see in next page)
Oval Terminal Start/stop/begin/end
symbol
Parallelogram Input/Output Making data available
for processing (input) or
recording of the
processed
information(output)
Rectangle Process Any processing to be
performed. An
assignment operation
normally represented by
this symbol
Diamond Decision Decision or switching
type of operations that
determines which of the
alternative paths is to be
followed.
Circle Connecter Used for connecting
different parts of flow
chart.
Arrow Flow Joins two symbols and
also represents
executions flow.
Bracket with broken Annotation Descriptive comments
line or explanations
Double sided Predefined Modules or subroutines
rectangle process given elsewhere
Introduction to C:
1) It is a robust language, whose rich set of built-in functions and operators can
be used to write any complex program.
2) Programs written in C are efficient and fast. This is due to its variety of data
types and powerful operators.
3) C’s code is very portable, in the sense that it is easy to adapt software written
for one type of computer or operating system to another type.
4) C has very small key words (only 32). Its strength lies in its built-in functions.
These built-in functions can be used for developing programs.
5) C language is well suited for structured programming, thus requiring the user
to think of a problem in terms of functions (or) blocks. A proper collection of
these functions would make a complete program. This modular structure
makes program debugging, testing and maintenance easier.
6) Another important feature of C is its ability to extend itself.
Basically a C program is a collection of functions that are supported by the
C library. We can add our own functions to the C library. With the availability of
a large number of functions, the programming task becomes simple.
Before discussing any features of C, we shall look at some sample C program and
analyze and understand how they work.
main()
{
Printf(“welcome to GITAM”)
}
Explanation:
i) main():
i) The ‘main()’ is a special function used by the C system to tell the computer
where
the program starts.
ii) Every program must have exactly one main function.
iii) Opening brace ‘{‘ and closing brace ‘}’ are the delimiters of any function.
iv) All the statements between these two braces are called as function body.
v) The lines beginning with /* and ending with */ are known as comment lines.
These lines are not executable statements and therefore anything between /* and */ is
ignored by the compiler.
ii) printf() function:
printf is a predefined, standard C function for printing output. ‘Predefined’ means
that it is a function that has already been written and compiled, and linked together with
our program at the time of linking.
The printf function causes everything between the starting and the ending
quotation marks to be printed out. In the above example, the out put will be
welcome to RGMCET
Every statement in C should end with a semicolon(;) mark.
that the construction crews actually begin work. Programming requires this same pains
taking processes, with the end result standing or falling by the amount of care and
attention invested in the planning stage.
5. Selecting test data:
How can one ensure that once a program is eventually working the results it
produces are ‘correct’? The answer is simple commonsense. Try the program out on
some data to which the answers have been worked out in advance. If they match, the
program should be all right. Selecting effective test data is a serious exercise and the
more significant the program, the more care needs to the taken in the selection.
6. The actual coding (Implementation):
At this stage, one can begin to code the detailed program designs into program
instructions of a given language. If all the previous steps have been completed with due
diligence, this coding should be almost ‘automatic’. The chances are high that a fairly
successful program will result first time around. Although it may still contain bugs, these
should be fewer and relatively easy to identify and correct.
7. Testing:
The program can be tested with the test data, results checked and any errors
amended. When all is correct the program can be released and set to work on live data.
7. ‘C’ programs can be run on any of the different computer with little or no
alteration.
8. ‘C’ is widely available commercial ‘C’ compilers are available on most personal
computers, mini and main frames.
9. ‘C’ language allows reference to a memory location with the help of pointer
which holds the address of the memory location.
10. ‘C’ language allows dynamic allocation of memory i.e. a program can request the
operating system to allocate/release memory.
11. ‘C’ language allows manipulations of data at the lowest level i.e. bit level
manipulation. This feature is extensively useful in writing system software
programs.
12. ‘C’ is a case sensitive language.
Basic structure of C program:
A ‘C’ program can be viewed as a group of building blocks called functions. A
function is a sub-routine that may include one or more statements designed to perform a
specific task. To write a ‘C’ program we first create functions and then put them together.
A ‘C’ program may contain a one or more sections as given below.
Function n
1) The documentations section consists of comment lines giving the name of the
program ,the author and other details which the programmer would like to use later.
these comments beginning with the two Characters \* and ending with the characters*\.
2) The link section provides to the compiler to link functions from the system library
/*Simple C Program */
main()
{
The first and fourth lines are commented lines. These are used in a program to
enhance its readability and understanding .the line beginning with \* and ending
with*\ are known as comment lines. Comment lines are not executable statements
and anything between \*and *\is ignored by the compiler. These comment lines
can be inserted wherever we want, it cannot be nested i.e. cannot have comments
inside comments.
The second line informs the system that the name of the program is main() and
the execution begins at this line. The main () is a special function by the C system
to tell the computer where the program starts. Every program must have exactly
one main function. If we use more than one main function cannot know where the
program begins.
The opening brace “{“ in the third line marks the beginning of the function
main and the closing brace”}” in the last line indicates the end of the function .
the statements between these two braces
The function body contains two statements, one of them is printf line is an
executable statement. It is a predefined standard C function. The printf function to
be printed out everything which appears in between quotations marks, here the
output will be ”welcome to C world”.
C Tokens
The smallest individual units are called tokens. C programs are written using
these tokens and the syntax of the language. The C has six types of tokens as shown
below:
1. key word
2. identifiers
3. constants
4. operators
5. strings
Character set:
The characters that can be used to form the words, numbers and expressions
depend upon the computer on which the program is run. The characters in C are grouped
into four categories.
1. letters
2. digits
3. special characters
4. white spaces
With these characters are combined to form data types, constants, variables and
key words
Keywords are the tokens used in C program which have predefined meaning and
these meanings cannot be changed by the programmer. There are 32 keywords. They are
also called as Reserved words. We cannot use them for any other purpose.
Standard key words:
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
2) Identifiers:
Identifiers refer to the names of the variable, function and arrays. These are user
defined names and consists of sequence of letters and digits.
Rules for giving name to an identifier:
1. Identifiers can consist of letters and digits, must begin with in the alphabets or
underscore, should not contain white space.
2. Both upper case and lower case are permitted although an upper is not equal to
the corresponding lower case letter.
3. It cannot be a keyword.
4. An identifier can be of any length while most compilers of ‘C’ recognize only the
first eight characters.
Constants
Numeric Character
For example in the equations 5x+2y=45 since 5, 2 and 45 cannot change , these are
called constants, where as the quantity X&Y can vary or change hence these are called
variables .
Numeric constants:
i) Integer constants: It refers to a sequence of digits, it has to fallow the below rules:
1. Integer constants must have at least one digit
2. It must not have a decimal point
3. It could be either positive or negative
4. If no sign precedes an integer constant it is assumed to be positive
5. No commas, blank space are allowed.
6. The allowable range for integer constants is -32768 to +32767 (16-bit machine)
integer constants can be specified in decimal, octal, or hexa decimal notation.
i) A decimal integer constant:
It consists of sequence of one or more decimal digit 0 through 9 preceded by an
optional – (or) + sign.The first digit of the sequence cannot be 0 unless the decimal
integer constant is 0.
Ex: 0 276 3412 31467 -7123
Note: Embedded spaces, commas, and non-digit characters are not permitted between
digits.
Ex: 12 727
23,879 are illegal numbers.
$1772
ii) An Octal Integer constant: It consists of any combination of digits from the set 0
through 7,with a leading 0.
Ex: 012
07134
07777
iii) A hexa Decimal integer constants:
It consists of the digit 0, followed by one of the letter x (or) X, followed by a
sequence of one more hexadecimal digits 0 through 9 or letter a through f (or) A through
F represent the numbers 10 through 15.
Ex: 0X1F
Real Constant: A real constant are sequence of digits with a decimal point(fractional
part) like 45.382.Such numbers are called real(or floating point) constants.
Rules for constructing Real Constants:
1. A Real constant must have least one digit.
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. No commons, black space are not allowed.
Ex: 1.0 1. 0.712 34.576 -7.123
These numbers are shown in decimal notation, having a whole number fallowed
by a decimal point. It is possible to omit digits before the decimal point or digits after the
decimal point.
Ex: 215. .39 -.92 +5. are valid real numbers.
The real numbers may also be expressed in exponential (or, scientific) notation.
For example, the value 215.65 may be written as 2.1565e2 in exponential notation.(e2
means multiply by 10
The general form:
mantissa e exponent
The scientific notation is often used to express numbers that are either very small
or very large.
Ex: 7500000000 may be written as 7.5e9 or 75e8.
Similarly, -0.000000368 is equivalent to -3.68E-7.
Character constant:
Single character constants:
Rules for constructing character constants:
1. A character constant is a single alphabet, a single digit or a single special symbol
enclosed with in a pair of single inverted commas. Both the inverted commas
should point to the left. For example ‘A’ is not valid character constant where as
‘A’ is valid.
2. The maximum length of a character constant can be one character constant.
3. character constants have integer values known as ASCII values.
4. The valid range of a character constant -128 to127. it appears surprising that the
character constant should have a numeric range. Character and integer constant
are often used interchangeably. For example ‘A’ and 65 are one and the
something, since when we say ‘A’ it is replaced by ASCII value, which is 65.
Example; ‘0’ ‘A’ ‘F’ ‘Y’
String constant: A string constant is a sequence of characters enclosed with in a pair of
double inverted commas. The characters may be letters, numbers, special characters and
blank space ……
Ex: ”hello” “1999” “5+4+6” “good bye”
Backslash character constants:
C supports some special backslash character constants that are used in output
functions. Each one of them represents one character, although they consist of two
characters. These character combinations are known as escape sequences.
Constant Meaning
‘\a’ Alert(bell)
‘\b’
‘\n’ backspace
‘\\’ new line
‘\” back slash
‘\v’ double quotation
Variables: A variable is a data name which can be used to store a data value and a
variable may take different values at different times, during execution.
For example, in the equation 5X+2Y = 45 since 5,2 and 45 cannot change, these
are called constants, where as the quantities X &Y can vary or change hence these are
called variables.
Rules for constructing variable names:
1. A variable name is any combination of alphabets, digits and the
underscore character. ANSI standard recognizes a length of 31 characters.
However, the length should not be normally more than 8 characters, since
only the first 8 characters are treated as significant by many compilers.
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces allowed.
4. No special symbol other than an underscore can be used
Ex: bas_pay , net_salary , month etc.
5. Uppercase and lowercase are significant. That is, the variable Amount is
not the same as amount or AMOUNT.
6. Variables name should not be a keyword.
Data types:
Each data type has predetermined memory requirement and an associated range
of legal values. Every programming language has its own data types. Storage
representations and machine instructions to handle constants differ from machine to
machine.
ANSI C supports four classes of data types.
1. primary (or fundamental) data types
2. user defined data types
3. derived data types
4. Empty data set.
int short int long int int short int long int
Integers:
C provides three different types of integers they are int, short int and long int. the
difference between these three integers is the number of bytes. The variables of these
types occupy and subsequently the range of values. A short int occupies 2 bytes, an int
occupies 2 bytes and the long int occupies 4 bytes.
Float:
Like integers floats are divided into three types. They are float, double and long
double. The difference between these three floats are the number of bytes, the variable of
these types occupy and subsequently the range of values. A float occupies 4 bytes, a
double occupies 8 bytes and the long double occupies 10 bytes.
Characters:
A char is a data type which can store an element of machine character set. A
single character can be defined as a character (char) type data. Characters are usually
stored in 8 bits (1 byte) of internal storage. The character set is usually the ASCII. These
are two types, they are signed and unsigned characters. The differences between these
two types are the range of values. Both will occupy one byte.
Global variables are declared outside all functions where as local variables are
defined inside a function.
where type refers to an existing data type and identifier refers to the new name given to
the data type.
Ex:
typedef int Sno;
typedef float salary;
Here Sno symbolizes int and salary symbolizes float. These can be used to declare
variables as follows.
Sno c1,c2;
salary e1,e2;
Note: The main advantage of typedef is that we can create meaningful data type names
for increasing the readability of the program.
Another user defined data type is enumerated data type provided by ANSI .
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. After that we can
declare variables to be of this new type.
For example,
enum day{Monday=1,Tuesday, ……., Saturday};
here, the constant Monday is assigned the value 1.The remaining constants are assigned
values that increases successively by 1.
There are some derived data types which are supported by C such as arrays,
functions, structures, and pointers.
It is also known as void data types. It indicates that no other data types has been
used with the given identifier.