C Language (1) - 11235

Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

C language

Composed and compiled


By
Corporate Learning Centre

ECIL

CONTENTS
TOPIC -1 (Basics)

ª Introduction to programming languages


ª Types of programming languages
ª Briefing on compilers and interpreters
ª Comparison between machine language and high level language
ª Programming errors types and debugging

TOPIC –2 (Introduction)

ª Introduction to C
ª Character Set
ª Variables & Constants
ª Variable names
ª Data types & declarations
ª Operators & Precedence of Operators

TOPIC – 3 (Statements)

ª Types of statements
ª Declaration statements
ª Input / Output statements
ª Format Specifications
ª Field Widths etc.,

TOPIC - 4 (Control statements)

ª If - else Statement
ª Switch Statement
ª While Loop
ª Do - While Loop
ª For Loop
ª Goto and Break, Continue Statements etc.,

TOPIC - 5 (Arrays)

ª Definition
ª Types of Arrays
ª Multi-dimensional arrays
ª Matrices manipulation

TOPIC - 6 (Functions)

2
ª Definition & Declaration
ª Types of functions
ª Returning values from a function
ª Recursive Function
ª Passing arrays to the function

TOPIC – 7 (Pointers)

ª Definition & Declaration


ª Pointers & Addresses
ª Pointers to Arrays
ª Pointers to Functions

TOPIC - 8 (Structures and unions)

ª Definition & Declaration


ª Structures and Functions
ª Pointers to Structures
ª Unions
ª C preprocessor

TOPIC - 9 (File Operations)

ª File handling concepts and types of files


ª File opening, writing and reading.
ª File Appending
ª File Encryption
ª File Decryption

TOPIC - 10 (Introduction to data structures)

ª Basic concepts on linked lists, stacks and queues


ª Types of linked lists etc.

3
Basics

Just you try to recollect the basic definition of a computer. A computer


is an electronic device or machine, which accepts raw information and
processes it and outputs the processed information (data) in required fashion.
The term process involves execution of set of instructions, which is called as
program.

So in the current module we are going to concentrate only on the term


program., Like what is programming and types of programming languages.
And how to make use of some programming languages to fulfill our aim i.e. to
write a program for our task.

Communicating with computer (that is with computer hardware)


involves with speaking the language which computer understands. So
whenever we wish to speak with computer to perform a task, which may be of
our own, then we need to issue instructions. And this instructions should be
in legitimate form (called as source program) and understandable to the
computer, as we know already. To do this, simply place all the instructions in
one file, just compile and run to achieve the required task. Of course, it is not
so simple as it told to write a program and at the same time it is not so hard
or difficult also to attempt the same. The terms like source program, compile
etc. will be discussed after a little bit later.

ª Types of programming languages

We can classify the languages broadly in to two categories. One is


machine-oriented languages or low-level languages and the other is High Level
Language.

Machine languages:

The instructions were written in the form of strings of binary numbers,


which a computer directly understands.
Advantages:
4
1. These languages will have better machine efficiency.
2. Program execution time (run time) will be very less.
Disadvantages:
1. It is very cumbersome to work with and
2. Different types of computers have its own unique instruction set to be
followed.
Thus a machine language program written for one type of computer can not be
run on another type of computer without significant modifications.
Examples are Assembly Languages / machine languages.

High Level Languages

It is also called as problem oriented languages. Usually, programs will


be written in High Level Language, whose instruction set is similar with
human languages. A single instruction in a High Level Language is equivalent
to several instructions in machine language. Further more the rules for
programming in a particular High Level Language is almost same for all
computers. So that a program written for one computer, generally can be run
on any other computer.

Advantages:
1. Simplicity
2. Uniformity and
3. Portability

Now let us have a glance on the comparison of these two languages.


FACTOR MACHINE LANGUAGE HIGH LEVEL LANGUAGE
Machine Efficiency Better Less
Program Execution Faster Slower
Program Efficiency Less Better
Program Development Much Time Less Time

Examples for High Level Language are BASIC, FORTRAN, PASCAL, COBOL
etc.,
5
ª BASIC CONCEPTS OF High Level Language
A computer program written in a High Level Language is referred to as
SOURCE program. A program that is written in High Level Language (i.e.
SOURCE program) must be translated in to machine language before it can be
executed. This is known as compilation (some time interpretation). So a
COMPILER is a machine language program that translates (or compiles) the
SOURCE program (of High Level Language) in to machine language, which is
known as “OBJECT PROGRAM”. The object program is the input to the
computer to perform the required task. You know already some High Level
Languages like BASIC, COBOL, PASCAL, FORTRAN etc., and every High Level
Language will have its own COMPILER program to generate an object
program.

SOURCE PROGRAM COMPILER MACHINE LANGUAGE


(HLL) PROGRAM PROGRAM (OBJECT PRG.)

As you know every computer must have its own COMPILER for
particular High Level Language. During this module you are going to learn
BASIC language and then followed by other High Level Languages, for which
material will be provided separately in due course.

ª SYNTAX AND SYNTAX OF STATEMENT

SYNTAX means Rules governing the procedures of programming. Or


grammar of programming language. It studies the interrelation among
symbols of different expressions.

SYNTAX ERROR is said to occur, when rules of the programming


languages are violated.

In the statements the value of the term, right of the equal sign
(=operator) is assigned to the variable on the left. While assigning the value

6
both left and right terms must be of same type. A numerical value can not be
assigned to a string variable or vice versa.

ª SEMANTIC (LOGICAL) ERROR

The mistaken use of wrong symbols or operators in the program. These


are valid symbol / operator used in the program, so syntax of the program will
be correct, but such mistake (error) cannot serve the purpose of the program.

∗ ERRORS AND TYPES

Now we will see errors and types that may come across while writing
and running the programs. It is practically almost impossible for a
programmer to write a program and enter it into the computer with out
making an occasional mistake. Therefore we must have a way to correct typing
errors and to add, delete or change statements once it has been transmitted to
computer. Incorrectly typed characters can be deleted or corrected by using
keyboard key like del key or backspace key.

∗ ERROR DIAGNOSTICS

Programming errors often remain undetected until an attempt is made


to run the program. Once the RUN command has been issued, however, the
presence of certain errors will become readily apparent, since such errors will
present in the program from being interpreted, i.e., transformed in to machine
language program.

Some common errors of this type are a reference to an undefined


variable or right / left hand parentheses that do not balance, failure to
terminate the main function etc., and such errors are called as syntactical
errors. Compiler will generate diagnostic messages when this type of error
occurs.

∗ LOGICAL DEBUGGING

7
We have seen that syntax errors and certain types of logical errors will
cause diagnostic messages to be generated when compiling or executing a
program. Errors of this type are easy to find and correct. Usually however,
logical errors are much more difficult to detect, because the diagnostics gives
error-free. So in this case, a bit of ‘detective work’ is required which is called
logical debugging.

Once it has been established that a program contains a logical error,


some resourcefulness and ingenuity may be required to find the error. Error
detection should always begin with the programmer should carefully review
the each group of statements in the program. If the error can not be found, it
sometimes helps to set the program aside for a while. It is not unusual for an
overly intent programmer to miss an obvious error the first time around.

Thus the programmer should anticipate that a certain amount of


debugging would be required as a part of the overall effort in writing a realistic
meaningful program. Programming is a skill. It cannot be learned simply by
reading books. Rather, the reader must become actively involved in writing,
editing, saving, testing, executing, and debugging his/her programs.

8
Introduction to C

ª Introduction to C

While there were around plenty of languages existing in the world of


Computers, today the software professionals are showing increasing
preference for C. According to one estimate as much as 75 percent of total
software developed in the world today, was written in C / C++ / VC++/VC.net
what makes C, such a success and popular is because it is simple, reliable,
capable, portable and easy to use. C’s compactness and coherence is mainly
due to the fact that it is a one-man language rather than a product of the
committees. It was developed by DENNIS RITCHIE, at AT & T’s Bell Lab., USA
in 1972, but known to software world only after 1978.

⇒ Character Set

‘C’ language has a character set similar to any other language.

Lower case Alphabets a to z


Upper case Alphabets A to Z
Numerical digits 0 to 9
Special characters +- / * ( ) [ ] { } . , % & ^ = <
> : ~
; ! | _ \ ? “ ‘ space

‘ C ’ language is Case significant (sensitive). It means lowercase letters


are different from upper case letters. And ‘ C ’ language is block-structured
language. And programs are combination of different functions. Any ‘C’
program must have one function whose name is main( ). This main( ) is called
the function header and what follows next ( statements ) is called body. So
every program will have a header and body. And the body should be enclosed
within the curved braces.

Header: main( )
9
Body: {body}

ª Constants & Variables

CONSTANTS will have fixed values and they cannot be changed during the
program execution.
EX:

main()
{
int num; /* int is data type and num is variable name */
num=35; /* here 35 is constant */
}

VARIABLE NAMES can contain letters (lower or upper), digits and


underscore. But lower case and upper case names contain different meaning.
The following rules are to be followed while declaring a variable.

Rules:

1. Variable name must have to start with an alphabet or underscore


2. Other than under score no other symbol is allowed in the variable name.
3. Length of the variable (name) can be up to 32 characters (this is system
dependent feature, that why this may vary.)
4. Variables must not contain any key words .

The Variables indicate the compiler how much space (memory) is required
by the particular variable depending upon the data type it holds. And these
are to be declared at the beginning of the program. Variables can change their
values during the execution of the program. So variable can be defined as a
tool to reserve memory to hold the data value. In the above example num is
the name of the variable.

ª Data types & declarations


10
INTEGERS are whole numbers. Integer variables can be declared by the
keyword int. Integer will occupy 2 bytes of memory and can store any number
between -32768 to 32767. That is 216 . (This range is machine dependent)

Rules:
1. It must have at least one digit
2. It must not contain decimal point (value).
3. It can be either positive or negative value ( which should be prefixed with +
or - )
4. By default, if there is no sign that will be assumed as positive.
5. It can hold numbers in the range –32 768 to 32767.

Types of integers declarations:


int or short or short int are same.
long int or long is same. ( And will occupy 4 bytes of memory)
unsigned short ( used to store only +ve integers)
unsigned long ( used to store only +ve integers)

/* different types of int declarations */


main()
{
int num;
short num1;
short int num2;
long s_no;
long int s_no1;
unsigned int age;
unsigned age1;
}

FLOAT is used to store real values, which contain fractional part also.
The keyword used is float. Double is used where more accuracy is required in
fractional numbers calculations. The keyword is double.

11
Rules:
1. It must have at least one digit
2. It must contain decimal point (value).
3. It can be either positive or negative value (which should be prefixed with +
or - )
4. By default, if there is no sign that will be assumed as positive.
5. It can hold numbers in the range – 3.4E38 to 3.4E38

/* Different types of float declarations */

main()
{
float weight;
double weight1;
}

CHAR is used to store characters and its keyword is char. It occupies a


memory of 1 byte.

Rules:

1. It must contain only one character ( let that be a alphabet or numerical or


symbols)
2. The character must be embedded with in single quotes as shown in
example.
3. Single quotes must be faced towards left side only.

/* Declaring the char type */

main()

12
{
char name;
name=’A’;
}

ª Operators & Precedence of Operators

C language is very rich in terms of operators. And we have around 45


numbers of operators in this language under different categories as given in
the next page.
• Operators

Arithmetic operators
Increment and decrement operators
Relational operators
Logical operators
Assignment operators
Conditional operators
Sizeof operator
Bit wise operators

Arithmetic operators:

Addition + is used to add two operands of any data type


Subtraction - Subtracts second operand from the first operand
Division / divides the first operand by the second operand
Multiplication * is used to multiply two operands
Modulus % gives remainder when first operand is divided by
the second operand)

Addition Example:

/* WHEN CHAR, FLOAT, INT ARE ADDED STORAGE CLASS IS FLOAT */


13
main()
{
int basic;
float cca,total;
char answer;
basic=4500;
cca=99.5;
answer=’y’;
total=basic+cca+answer;
}

Subtraction Example:

main()
{
int result;
int first;
int second;
result=first-second;
}

Division, Multiplication and Modulus Operators Example:

main()
{
int first,second,result;
first=10;
second=100;
result=first*second; /* first and second are multiplied and result will
be 1000 */

14
result=second/first; /* second is divided by first and result will be
10 */
result=second%first; /* remainder is stored in result =0 */
}

Increment and Decrement Operators:

++ is known as increment operator and it increments the value of the


operand by one.
-- is known as decrement operator and it decrements the value of the
operand by one

Example:
main()
{
int age;
age=39;
age++; /* age is incremented by one so age=40 */
age--; /* age is decrements by one so age=38 */
}

Relational Operators:

These operators check the relation between the two operands. If the result is
TRUE it returns ‘1’ else’0’.

Equality ==
Lesser than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Not equal to !=

Logical Operators:
15
AND is logical operator, it returns TRUE i.e. 1 if both the conditions evaluates
to true.
OR is logical operator, it returns TRUE i.e. 1 if any one of the condition
evaluates to true.
NOT is negation operator, it converts TRUE to FALSE or FALSE to TRUE.

AND && Returns TRUE i.e. 1 if both conditions evaluate to TRUE.


OR || Returns TRUE i.e. 1 if any one of the conditions
evaluates to TRUE.
NOT ! Returns TRUE to FALSE or FALSE to TRUE.

ASSIGNMENT OPERATORS:

VARIABLE OPERATOR CONSTANT ACTION / RESULT


age = 53 AGE = 53
age += 53 AGE=AGE+53
age -= 53 AGE=AGE-53
age /= 53 AGE=AGE/53
age *= 53 AGE=AGE*53
age %= 53 AGE=AGE%53

Conditional Operator :

?: Is called a conditional operator who evaluates the specified condition and


decides the routing.

Expression 1 ? Expression 2 : Expression 3

If Expression 1 is True Expression 2 is executed otherwise (means if


Expression 1 is False) Expression 3 is executed.

Example:
16
main()
{
int age,age1,age2;
age=30;
age1=35;
age2=(age1>age) ? age1 : age;
}
sizeof Operator:

sizeof operator is used to know the number of bytes that a particular data
type will occupy in the memory of the system.

SYNTAX IS:
sizeof(int), sizeof(long), sizeof(float), sizeof(double), sizeof(char) etc.,

Precedence of Operators:

Generally when more than one operator is encountered in the expression


written in our program, the priority of the operator, which should be executed,
first will be the criteria. At this moment there are some standards to be
followed, which are called precedence of operators.

³Precedence:

() braces Any
++, -- ,! Increment, decrement operators, negation R to L
sizeof sizeof operator R to L
*, /, % Multiplication, division, modulus L to R
+,- Addition and subtraction L to R
<, <=, >, >= ,==, != Relational operators L to R
&&, | | Logical operators L to R
?: Conditional operator R to L
=,+=,-=,*=,/=,%= etc. Assignment operators R to L

STATEMENTS
17
³Input / Output statements

C Language provides built-in functions required to the input for the


programs and to print the output of the programs to console. Although there
were plenty of functions, now let us discuss only two of them, which are
necessary right now.

printf() to print output on the console ( screen ).


scanf() to read input required by the program. (Inputted through
key board)

Rules
1. Every Statement should be terminated by ; (semi colon ).
2. All comments should be prefixed with /* and suffixed by */
3. Do not use “ \n ” in scanf() function.

printf() function is used to print output of the program on the screen. The type
of data that we want to print should be specified in certain specification. The
type of data and its respective format specifications were given below.

syntax:
printf(“format string”,list of variables);
Format specification starts always with ‘ % ’

int %d
long %l
unsigned %u
float %f
char %c
string %s
octal %o
hex %x

These special characters start with ‘ \ ’


18
New line \n
Tab \t
Form feed \f
Carriage return \r
Back slash \\
Double quote \”
Beep \a

Ex1:
/* simple printf() statement implementation */

main()
{
printf(“Corporate Learning Centre\n”);
}

Ex2:
/* printf() statement implementation with integer format */
main()
{
int num=20;
char sex=’M’;
printf(“%d\t%c”,num,sex);
}

scanf() reads input from keyboard and stores the content in the memory
location named by variable declaration. It reads all data types with certain
limitations. While reading the data the type of data should be specified in the
format specification. The data type and respective specifications were given in
the earlier topic. It is to note that while reading the data type of char, int, and
float the ‘&’ character should be prefixed as shown in the example.

19
Ex1.
/* scanf () function implementation for reading int,char,float */
main()
{
char name;
int basic;
float da;
printf(“Input the DA , BASIC and Initial NAME of an employee\n”);
scanf(“%f%d%c’,&num,&basic,&name);
printf(“%c\t%d\t%f”,name,basic,da);
}

Ex2:
/* scanf() function implementation for reading string */
main()
{
char name[20];
printf(“Enter your name\n”);
scanf(“%s”,name);
printf(“%s”,name);
}

FIELD WIDTH:

Field width specifies the width of the argument occupies when printing
takes place. It should be mentioned in the format specification. For example if
we mention %8d that argument will occupy a width of 8 characters space and
if the integer is less than 8 digits, then the number will be automatically right
aligned leaving blanks in the left side. To make the argument to be left aligned
use %-8d.

Example:
/* makes use of field width in the format specification */
20
main()
{
long cno=999999;
printf(“%10d\n”,cno); /* right aligned */
printf(“%-10d”,cno); /* left aligned */
}

/* to specify the precision */

main(0
{
float value=23.5667;
printf(“%80.2f”,value); /* output is 23.57 */
printf(“%80.1f”,value); /* output is 23.6 */
}

Control flow
21
Statements are executed in the increasing (sequential) order. However,
there are certain statements which can (or required to) be altered the
sequence of execution of the program by directing (passing) the control to
some other statement other than the following statement. And some times it is
required to repeat the set of statements for certain number of times depending
upon some condition. This can be accomplished by using control statements.
We usually refer these branching and loops. Again branching can either
conditional or unconditional branching or jumping (or transfers of control).

³If - else Statement

If given condition is true one set of statements followed by the if statement


is executed otherwise another set of statements followed by the else are
executed. So if and else are used to pass the control flow. if can be used
alone with out else in the condition depending upon requirement. If
statements can be nested to any level and else statement always corresponds
to the nearest if statement unless parentheses are used.

Syntax:
if <condition>
Statement;
else
Statement;

Example1:
/* Implementation of if and else */
main()
long num=989822;
if(num==989822)
printf(“your number is: %ld\n”,num);
else
printf(“your number is not %ld”,num);
}
Example 2:

22
/* Implementation of if and else in nesting */

main()
{
int age=53;
int age1=60;
if(age == 53)
{
if(age1==60)
printf(“ age is %d and age1 is %d”,age,age1);
}
else
printf(“ages are not matching”);
}

Example 3:

/* Improper usage of if and else */


main()
{
int age=30;
int age1=35;
if(age==30)
if(age==40)
printf(“age is 30 and age1 is 40\n”);
else
printf(“age is not 30”);
}

IF - ELSE CONTROL

23
START

IS
TRUE COND FALSE
?

STATEMENTS STATEMENTS

STOP

Ex.
main()
{
int num=55;
if(num==51)
printf(“The number is %d\n”,num);
else
printf(“The number is not 51”);
}

ª Switch Statement:

By using. if and else control, we have only two way branching facility. But
where as some times we need multiple branching of control. Here we use
switch statement in which there is no limit of number of branches. If a
condition is true that part of the switch statement is executed and none of the
other will comes in to picture. If none of the conditions are true, then default
condition statements (if present) will be executed.

24
Note: Every condition in the switch statement must be terminated with break,
so as to come out of the switch body.

Example:

main()
{
int num=2;
switch(num)
{
case 1:
printf(“This is case 1\n”);
break;
case 2:
printf(“This is case 2\n”);
break;
case 3:
printf(“This is case 3\n”);
break;
case 4:
printf(“This is case 4\n”);
break;
default:
printf(“none of the conditions are true”);
}
}

ª WHILE LOOP

As long as the condition mentioned in the while loop is true, the


statements followed by the while is executed continuously. If more than one
statement are to be executed, then using braces, that is nothing but making a
block will enclose them.

Syntax:
25
while(<condition>)
{
statement1;
statement2;
...
}
Example:
/* Implementation of while loop */
main()
{
int age =10;
while(age <= 50)
printf(“%d\t”,age++);
}

WHILE LOOP

START

AGE=10

IS
NO AGE<=50

YES

PRINT AGE
STOP
AGE=AGE+1

The following is an example implementing increment operator in while loop.

26
main()
{
int num=1;
while(num++<10)
printf(“%d\n”,num);
}

ª Do - While Loop

This is similar to while loop except that the condition will be tested at the
end of the loop, whereas in while condition is tested at the beginning. So the
statement or statements in do while loop will be executed at least once.

Syntax:
do
{
statement1;
statement2;
...
}
while(<cond>);

Example:

/* Implementation of do while loop */

main()
{
int num=5;
do
printf(“%d\n”,num++);
while(num<=5);
}

ª FOR LOOP

For loop checks a condition and as per the result it performs an operation
and reevaluates the counter. It is nothing but initialization, testing and
incrementation / decrementation.

Syntax:

for(initiate counter; test <condition>; reevaluate counter)


27
{
statement1;
statement2;
...
}

/* Implementation of for loop */

main()
{
int num;
for(num=0;num<=10;num++)
{
printf(“%d\t”,num);
}
}

The following is an another example, which increments the variable


twice during each
Iteration. In the for loop num is initialized with 1 and the same value has
been printed in the
body’s printf statement and the num variable has been incremented to 2,
the moment it enters
into the for loop. Here again the num has been incremented to 3 and with
value of 3, the num
is checked in the condition. Because it is true, printf statement printed the
value 3.

Ex.

main()
{
int num;
for(num=1;num<10;num++)
{
printf(“%d\t”,num++);
}
}

28
DO WHILE CONTROL

START

NUM=1

PRINT NUM

NUM=NUM+1

YES IS NO
NUM<10 STOP
?

Example.

main()
{
int num;
num=1;
do
printf(“%d\t”,num++);
while(num<10);
}

The following example will print the body of the for loop infinitely, because
of there is no initialization, testing and incrementation. Some times this type
of loops required, which is going to be implemented in due course.

/* Infinite for loop */

29
main()
{
for(;;)
{
printf(“This is infinite loop\n”);
}

ª BREAK & CONTINUE:


As long as the condition in the loop is true loop will be executing its
statements. When there is specific requirement to discontinue the loop (come
out of the loop ) we will find a useful keyword break. This break can be used
in for, switch, while or do-while.

Example:
/* Implementation of break statement */
main()
{
int num,num1=20;
for(num=0;num<=num1;num++)
{
if(num==10)
break;
printf(“%d\t”,num);
}
}

CONTINUE is useful for skipping all statements in a loop without coming out
of the loop and going back to the condition checking statement of the loop.

Example:
/* Implementation of continue statement */
main()
{
int num,num1=20;
for(num=0;num<=num1;num++)
{
if(num<=10)
continue;
printf(“%d\t”,num);
}
}

³Nesting of for loops

30
One loop can be embedded with in another (called as nested loop) if
necessary to repeat a loop more than once. And in fact, there can be several
levels of nesting. The rules we implement / apply, while writing single loops
also applies to nested loops absolutely. There should be no overlap between
the outer and inner loops. The inner loop must be completely embedded with
in the outer loop. The nesting can be implemented using either WHILE or FOR
depending upon requirement. The following examples given you an idea how
to implement the nesting using for.

Example for nested loops using for.

main()
{
int num,num1;
for(num=1;num<=3;num++)
{
for(num1=0;num1<=3;num1++)
printf(“%d\t”,num*num1);
printf(“\n”);
}
}

START

NUM=1 NUM <10 NO

NUM++

YES

IS
NUM==5 YES
BREAK

NO NEXT

PRINT NUM

Program for the above flow chart.

31
main()
{
int num;
for(num=1;num<=10;num++)
{
if(num == 5)
break;
else
printf(“%d\t”,num);
}
}

FLOW CHART FOR CONTINUE STATEMENT

START

NUM=1 NUM <10 NO NEXT STATEMENTS


AFTER FOR LOOP
NUM++

YES

IS YES
NUM==5 CONTINUE

NO

PRINT NUM

ª GOTO STATEMENT:
Goto takes over the control to the specified-labeled location in the program.
Label name should not be any standard C program keywords or function
names. This statement is normally used to come out of deeply nested loops
and to go to a specified statement. Goto cannot be used in between two
functions. It can be used within one function only. However goto statement is
not suggestible to use in programming.

Syntax:
goto clc;
Statements;
32
…..
clc:
Statements;
...

Example:
main()
{
int num,num1=10;
num=20;
printf(“I am learning c language\n”);
if(num!=num1) goto clc;
printf(“Jajam Institute of Information Technology\n”);
clc:
printf(“Goto statement implemented”);
}

ARRAYS
‰ Definition
33
Collection of similar data elements stored in adjacent memory is called an
array. The elements of an array can be of any data type. Arrays of int, char,
float and double etc. are possible. Arrays are two types. Generally single
dimension and multi-dimension arrays. If the elements occupy only in one row
(row arrays) that array is known as single array. Whereas multi-dimension
arrays consists of both row and column elements.

ª Declaration: The declaration of an array contains the name of the array


followed by square brackets with number of elements written inside the
brackets, is also known as dimension of the array.

ª Dimension is optional if we initialize the array when it was declared.

ª Element numbering starts from zero always.

int num[10]; declares an integer num array containing 10 elements starting


from 0 to 9. And we can assign values directly to the elements (initialization
of arrays) of this array as follows:

num[0]=32;
num[1]=45;
....
num[9]56;
int num[10]={20,21,22,23,24,25,26,27,28,23}; /* single dimension array */

Multi-dimension array contains both rows and columns and it can be


considered as table or matrix, and is as follows:
int num1[2][3]={
{23,24,25},
{12,13,14}
};

Position or order of elements in the above array will be as follows:


int num1[2][3]={

34
{num1[0][0] num1[0][1] num1[0][2]}
{num1[1]0] num1[1][1] num1[1][2]}
};

Printing of elements of the array on the console is as follows:


printf(“%d”,arrary name[row][colum]);

Strings

35
Now let us see how a character array can be declared. Character should
be initialized or declared with in single quotes and strings should be declared
with in the double quotes as shown below. And one more point is that at the
end of the every string the compiler will automatically append a null
character ‘\0’ as terminator. Even for an empty string the only character
available in that string is the null character.

'A’ is a single character and “A” is the string with combination of


“A” and a null character.

Multiple string array can be declared and read as follows:

main()
{
char name[40]={“corporate learning center”};
printf(“%s”,name);
}

Three dimension array:

main()
{
char name[2][2][30]={
{“First Row First Column”, “First Row Second Column”},
{“Second Row First Column”, “Second Row Second Column”}
};

Example:

36
main()
{
int row,col;
char name[2][2][40]={
{“Corporate Learning Center”,”ECIL”},
{“ASRao”, “Nagar”}
};
for(row=0;row<=1;row++)
{
for(col=0;col<=1;col++)
printf(“%s\t”,name[row][col]);
}
}
A header file called string.h contains the functions like strcpy(), strlen(), strcat(), strcmp()
etc., Now let us see in detail how exactly these functions will work and how to make use of
these functions.

³String functions

strcpy()
The usage of this function is to copy a string (which is second argument)
to the another string (which is first argument).

Example:
main()
{
char source[10],target[10];
source[]={“corporate”};
strcpy(target,source);
printf(“%s”,target);
}

strcat()

37
The usage is this function is to combine two strings given as arguments.
The second argument (string) is appended to the first argument (string).
Example is as follows.
main()
{
char string1[30]={“corporate ”};
char string2[20]={“ _learning”};
strcat(string1,string2);
printf(“%s”,string1);
}

strlen()

The usage of this function is to find out the length of the string (given in
the argument)
Example:
main()
{
char string1[30]={“Corporate learning center”};
int length=0;
length=strlen(string1);
printf(“Length is %d”,length);
}

strcmp()

The usage of this function is to compare two strings for equality. If both
the strings are equal then it will return true that is zero else false that is non
zero number. Example is like

main()
{
char string1[]={“electronics”};
char string2[]={“electronics”};
if(strcmp(string1,string2)==0) printf(“Two strings are identical”);

38
else
printf(“Two strings are unidentical”);
}

strrev()

main()
{
char a[20]={“computer”};
strrev(a);
puts(a);
/* output is retupmoc */
}

strupr ()
main()
{
char a[20];
puts(“Enter some text”);
gets(a);
strupr(a);
puts(a);
}

input is : computer
output is: COMPUTER

Similarly strlwr () will convert the upper case text to lowercase.

Functions
39
ª Definition & Declaration

A set instructions or block of code designed to perform certain task is


known as function. As said earlier each C program must have at least one
function called main(). And execution of any C program starts with main()
function only. All function declarations starts with the name of the function
followed by the parenthesis. And every function will have a header (name of
the function) and body (set of statements).

Limitations:

Function name should have to start with alphabet and can contain
alphabets, numbers and underscore. Other rules, what ever we apply to
declare a variable name, will also applies to function header declaration.

Purpose / Usage:

Where ever and when ever certain process is repeated many times in the
program, instead of writing lengthy code, it is recommended to write a
function for that task and call the same as many times as we require. This is
nothing but just to avoid repetition of code in the program and provides good
readability and improves efficiency.

Example:

main()
{
printf(“Control is passing to function test\n”);
test(); /* calling a function */
printf(“Function test is completed and returned to main function.”);
}

40
test() /* called function */
{
printf(“This is function test\n”);
}

³A function can call an another function as shown in the following example:

main()
{
printf(“This is main function\n”);
fun1();
printf(“Returned to main function.”);
}

fun1()
{
printf(“This is first function\n”);
fun2();
printf(“Returned to first function from second function\n”);
}

fun2()
{
printf(“This is second function\n”);
}

³Recursive function:

Recursive function can be defined as basically a function in which one of


the instruction is calling it self.

41
Main()
{
callme();
printf(“Return is not possible from callme function”);
/* control will not reach here */
}
callme()
{
printf(“This is recursive function\n”);
printf(“use ctrl+c to quit\n”);
callme(); /* this is infinite loop */
}

³Arguments:

Arguments are given in the parenthesis of the function. If we give


arguments in the calling function, these arguments are called actual
arguments. And if we give arguments in the called function, these are called
formal arguments. Formal arguments must be declared before the opening
brace of the function called.

Example:

main()
{
int num;
printf(“Enter some number\n”);
scanf(“%d”,&num);
printf(“%d”, square(num));
/* num is actual argument passed to function */
}

42
square(int num1) /* num1 is formal argument to be declared */
{
return(num1*num1); /* returning the value back to main function */
}

In the above example the integer value what ever inputted was stored in
the variable num and Function Square passed the actual argument num. And
at the receiving end in the called function formal argument num1 will be
assigned with the value of the num (the actual argument). In this example
only one argument is passed to the function but multiple arguments can be
passed as shown in the following example.

Example:
main()
{
int num,num1,total;
num=10;
num1=20;
char cod=’A’;
total=calcu(num,num1,cod);
printf(“%d”,total);
}

calcu(no,no1,let)
int no,no1;
char let;
{
return(let+no*no1);
}

The data type of actual arguments and formal arguments must be same.
By default all the functions are of integer type. If a function required to
perform either float or other data type, then it should be declared in the
calling function it self explicitly.

43
ª Passing arrays to functions:

Arrays are passed by reference to the functions. Array name is passed to


the function as argument and in fact the address of the first element in the
array only will be sent to the called function.

Example:
main()
{
int total,num=5;
int marks[]={20,30,40,50,60};
total=fun(marks,num);
printf(“%d”,total);
}

fun(marks,num)
int marks[],num;
{
int sum=0;
while(num--!=0)
sum+=marks[num];
return(sum);
}

If the function required is other than integer type then we have to


declare the function prototyping as in the following program :

Example:
main()
{
float fun(); /* declaration of function type or prototype */
float num=2.5;
printf(“%f”,fun(num));
}

44
float fun(float num1)
{
return(num1+num1);
}

ª Intrinsic functions:

ªC language is providing some built in functions called library functions.


These are available in header files like stdio.h, conio.h, io.h, etc

Pointers
45
ª Definition & Declaration:

Pointer is nothing but a one type of variable, which stores the address of
the another variable. We can access the variable which has its address stored
in pointer variable. Pointer variable also permits to supply the address of the
variable, which is stored in it, to some other variable to access the same. And
assigning the values of the first variable to the second variable through the
pointer variable is a technic known as indirection.

& Is known as address of operator and it is used whenever we want to access


the address of particular variable.

* Is known as pointer (indirection) and is used to fetch the contents from the
particular address of a variable.

In short cut pointer can be remembered as: value at

main()
{
int first,*second,third;
first = 200;
second = &first;
third = *second;
printf(“%d”,third);
} Variables

First second third


Value value value
200 5645 200
5645 6785 7865

Location
(address)

46
Let us see exactly what happens in the above example. First and third
are declared as integer variables and second is declared as pointer variable
which is prefixed with *. The value of first is assigned to third through the
pointer second. Second stores the address of first and *second assigns the
value at address of first to third. And finally we print the output to console.

Example 2:
main()
{
int num, *point;
point=&num;
printf(“Address of num is %u\n”,&num);
printf(“Address of num is %u\n”,point);
printf(“Address of point is %u\n”,&point);
printf(“Value of num is %d\n”,*point);
printf(“Value of num is %d\n”,num);
printf(“value of num is %d\n”,*(&num));
}

Similar analogy can be applied to other data types like char, float.
Suppose if we declare float *pie, it does not mean that pie is going to contain a
floating-point value (real numbers). Remember that pointer variable will hold
only the address of the variable float but not float value.

• Pointer mechanism to strings:

Pointer to string points at the address of the first character in the string.
Operators like + and - will work on addresses stored.

¾ Pointer to pointer:

The concept of pointer mechanism can be further extended. Recall that


pointer is a variable, which contains the address of another variable. Now this
another variable itself could be an another pointer. Let us see how it works:
Example:

47
main()
{
int num=20;
int *point1;
int **point2;
point1 = &num;
point2 = &point1;
printf(“Address of num is %u\n”,&num);
printf(“Address of num is %u\n”,point1);
printf(“Address of num is %\n”,*point2);
printf(“Address of point1 is %u\n”,&point1);
printf(“Address of point1 is %u\n”,point2);
printf(“Address of point2 is %u\n”,&point2);
printf(“value of num is %d %d %d”,num,*point1,**point2);
}

ª Passing address to functions

a) Sending the value of arguments is known as “call by value”.


b) Sending the address of arguments is known as “call by reference”.

We already seen how to pass value of an argument to a function in the


previous functions topic and now let us see how to send a address to the
called function.

main()
{
int radi;
float area;
printf(“Enter radius :\n”);
scanf(“%d”,&radi);
areafun(radi,&area);
printf(“area is %f”,area);
}

48
areafun(int r,float *a)
{
*a = 3.14 * r * r;
}

In the above example radi is an argument which is passed by value and


area is an argument which is passed by address in the calling function in the
main(). And in the called function , the final value is assigned to float pointer
which will return automatically to the main() function. Function can return
only one value. But here we need not to write return statement. Using the
pointers we can have more than one values returned from a function. We can
pass any number of arguments from the main () by sending the address of the
arguments to the functions and can be collected with out any limitations.

Example:
/* To return more values to the calling function i.e. main() */

main()
{
int num=50,num1=100,num2=150,num3=200;
result(&num,&num1,&num2,&num3);
printf(“%d\t%d\t%d\t%d”,num,num1,num2,num3);
}

result(n1,n2,n3,n4)
int *n1,*n2,*n3,*n4;
{
*n1 = *n1 + *n1;
*n2 = *n2 * *n2;
*n3 = *n3 * 10;
*n4 = *n4 + 5;
}

ª Pointers and Arrays:


49
We can implement pointer concept even to arrays also. When we want to
store the address of an array to the pointer variable, the base address of the
array is stored to the pointer variable. Suppose we have an array like int
marks [100]. Instead of storing the base address to some pointer variable, we
can even store the in between address of the marks array as shown below.

Example:
main()
{
int num, marks[10]={2,3,4,5,6,7,8,9,1,12};
int *result;
result = &marks[9];
for(num=0;num<=9;num++)
printf(“%d\t”,*result--);
}

In the above example we stored the last element address &marks [9] to
the pointer variable result and while printing the out put to console we started
reading from last element to first element through a for loop. Similarly we can
move from any required element to the destination element by selecting the
base address and then add the number of elements to move as shown.

int *result;
int marks[50];
result = marks + 10;

Now the pointer is moved the 11th element of the marks array. Similarly
we can travel in any fashion in the array. Comparison of two pointers can be
made as follows. Both the pointers must be pointed to the same element in the
array, otherwise we will get some unreliable results. Pointers can be
incremented or decremented, as we require. But Note that no two pointers
will be added, multiplied or divided in any case. Which will result some
unpredictable / unreliable behavior in the system itself.
Example:

50
main()
{
int num, *point1,*point2,arr[11]={11,12,13,14,15,16,17,18,19,20,21};
point1 = arr;
point2 = arr +10;
for(num=0;num<=5;num++)
{
if(*point1 == *point2)
printf(“ Both the pointers are at element %d”,num);
point1++;
point2---;
}
}

¾ Pointers to multi-dimensional arrays


We can access all the or any of the elements of an multidimensional array
by assigning the base address of the array to pointer variable as shown in the
following example.
Example:
main()
{
int *point, arr[3][3]={ {12,13,14},
{15,16,17},
{18,19,20}
};
point = arr;
printf(“first row first col arr[0][0] is %d\n”,*point);
point++;
printf(“first row sec col arr[0][1] is %d\n”,*point);
point++;
printf(“first row third col arr[0][2] is %d\n”,*point);
point++;
printf(“sec row first col arr[1][0] is %d\n”,*point);
}

51
In the above example we can move with in the limits and can access the
elements in the array. And now let us see a character multi-dimensional array
example:

Example:

main()
{
char *point, city[3][15]={“Andhra ”,
“Telangana”,
“Rayalaseema”,
};
point = city;
printf(“%c\n”,*(point+0));
}

In the above example in the printf statement pointer *(point+0) was used
to read and print the contents of the character array’s zeroth row, zeroth
column. In the place of *(point+0) zero can be replaced with any other required
number to access that particular element.

Structures and Unions


52
STRUCTURES

³Definition & Declaration:


Structure can be defined as the “collection of dis-similar data types” as
per our requirement and which can be placed under one tag name. So
structure itself is a extrinsic / explicit/user defined data type. The key word
used to declare a structure is struct. Members of the structure can be of any
data type. If we declare a structure it will not occupy any memory and it
cannot be used directly to store data because it is only a template. After
defining the template, we can use the template and declare structure
variables.

Syntax of the structure is as follows:

struct <template name / tag name>


{
Different data type declarations; /* as per our requirement */
};
The part of usage of this structure is followed by the definition like
struct <tag name> clc; now here the clc is a variable, which can store data.
Example:
main()
{
struct clc{
int no;
char sex;
float basic;
};
struct clc c1;
int num;
printf(“Enter number, sex and basic\n”);
scanf(“%d%c%f”,&c1.no,&c1.sex,&c1.basic);
printf(“%d\t%c\t%f”,c1.no,c1.sex,c1.basic);}

53
Initialization of the structures can also be done as follows:

main()
{
struct student{
int rno;
int marks;
char name[10];
};
struct student s1; /* declaration of the structure variable */
s1.rno = 12345; /* initialization of the structure elements */
s1.marks = 9400;
strcpy(s1.name , “CLC”);
printf(“%d\t%d\t%s”,s1.rno,s1.marks,s1.name);
}

³Definition of the structure can be after the main function as shown in


previous examples or even before the main() function. If it is defined before
the main() that structure will be available through out the program, even
in functions and it is known as global declaration. And that variable is
called as global variable. The structure variable declaration can be done
even when it was defined it self as shown below:

/* Global declaration */

struct alarm
{
int num;
char ch;
};
alarm samp;

54
main()
{
....
....
}

Structure can be a member of another structure subject to the condition


that the member structure must be defined before it was used as shown
below:

main()
{
struct exam{
int h_no;
int marks;
};
struct exam1{
char name[20];
struct exam rec;
};
struct exam1 stud;
}

¾ To access the elements in the above example:

scanf(“%s”,stud.name);
scanf(“%d%d”,stud.rec.h_no,stud.rec.marks);

¾ Assigning the complete values of one structure to another structure can be


done only when both the member elements are of same type like:
struct emp
{
int cno;
int basic;
};

55
struct emp1{
int cno;
int basic;
};
struct emp e1;
struct emp1 e2;
e1.cno=1234; /* initialization */
e1.basic=14200;
e2 = e1;
/* assigning the total values of e1 structure to e2 structure */

ª Array of structures:

While declaring the structure itself, the number of elements of that


structure variable requires can be declared as follows:

Example

main()
{
struct samp
{
int cno;
char sex;
};
struct samp emp[5];

/* to initialize the members of the above : */


emp[0].cno=12345;
emp[0].sex=’A’;
emp[1].cno=23456;
emp[1].sex=’B’; /* can be initialized up to emp[4].cno etc., similarly */
}

56
Example 2:

main()
{
struct samp
{
char sex;
int cno;
};
struct samp emp[5];
int num;
for(num=0;num<=4;num++)
{
printf(“Enter sex and code no.\n”);

scanf(“%c%d”,&emp[num].sex,&emp[num].cno);
}
for(num=0;num<=4;num++)
{
printf(“%c\t%d”,emp[num].sex,emp[num].cno);
}
}

ª Structures and Functions

Structure should be declared as global and can be passed to a function as


shown in the following example:

struct samp
{
int cno;
int basic;
};
samp e1;

57
main()
{
e1.cno=12345;
e1.basic=4200;
func(e1);
}

func(struct samp rec)


{
rec.basic+=200;
printf(“%d\t%d”, rec.cno,rec.basic);
}

ª Pointers to Structures :

Pointer concept can also be extended to structures. Normally pointer is


denoted by ( . ) But where as a structure pointer is denoted by < -> >. As we
increment the pointer, it points to the next element in the structure.

main()
{
struct emp{
int cno;
int basic;
};

struct emp e1, *sptr; /* declares a structure e1 and pointer to


structure *sptr */
sptr = &e1; /* address of the zeroth element of the structure is stored in
pointer variable sptr */

e1.cno=12345; /* initialization of structure members */


e1.basic=4200;
printf(“%d\t%d”,sptr->cno,sptr->basic);
}
58
In the above example sptr->cno, sptr->basic are same as e1.cno, e1.basic
respectively. We can even apply the pointer mechanism to structure arrays.

ª UNIONS:
Unions like structures are derived data types, which group together a
number of variables. However, union members declared in the union will use
the same memory.
Example:
main()
{
union samp{
int cno;
int basic;
}emp;
emp.cno=12345;

printf(“%d\t%d”,emp.cno,emp.basic);
}
In the above example the emp.cno is initialized with 12345 and while we
try to see the output of emp.cno and emp.basic through printf() on the console
both the members will show the same value because as said earlier both are
utilizing the same memory of the system. Even if we declare a character also it
will use the same memory space.

¾ C PREPROCESSOR:
As the name suggests, preprocessor is a program that processes our source
program before passing it for compilation. It helps in better coding of a
program. The common preprocessor directives are:
1. Macro Expansion
2. File Inclusion &
3. Conditional Compilation.

¾ Macro Expansion
#define NUM 100 /* macro template */
#define SQUARE(x) (x*x)
59
main()
{
int num=5;
if(SQUARE(num)<=NUM)
printf(“num is less than NUM”);
else
printf(“num is more than NUM”);
}

¾ File inclusion

This will allow including one file in to another. The presence of a #include
statement in a program causes the entire contents of the added (included) file
to be available at that point in the existing program.
#include <filename>
A typical use of this feature would be to store frequently used functions
and macros definitions in a single file and #include it in whichever file we
require.

ª TYPE CASTING:

Some times we need to force the compiler to explicitly convert the value of
an expression to a particular data type. This would be seen from the following
example.

Example:
main()
{
float result;
int num=10,num1=4;
result= num/num1;
printf(“\nThe value of result=%f”,result);
}

60
In the above program result=1.00 but not 1.5. This is because the num,
num1 are integers and then it yielded an integer to result. But don’t want the
quotient to be truncated. So the solution is to make the num or num1 to
declare as float. But the program requirements are like that num should be an
int only. In such a situation we use type casting as follows:

main()
{
float result;
int num=10,num1=4;
result= (float) num/num1; /* type casting */
printf(“\nThe value of result=%f”,result);
}

One more example on type casting which is float is converted to int is as


follows:

main()
{
float real=10.55;
printf(“\nvalue of real=%f”,real);
printf(“\nvalue of real after type casting=%d”,(int)real);
}

ª TYPEDEF:

This is used to rename the data types. This technique will come in to usage
in some situations to help in clarify the source code of the program. It is
nothing but redefining the name of the existing variable type.

typedef unsigned long int TEST;

Now we can declare variables of the type unsigned long int by writing:

TEST num, num1; is nothing but unsigned long int num, num1;
61
This typedef provided a short and meaningful system to call a data type.
Generally uppercase letters are used to make clear that we are dealing with a
renamed data type. While the easy readability is probably not a great in this
example, but it can be significant when the name of a particular data type is
long and unwieldy, as we often see in structure declarations like:

struct employee{
char name[30];
int age;
float basic;
};
struct employee e1,e2;

It can be renamed as:


typedef struct employee EMP;
EMP e1,e2;

ª ENUMERATED DATA TYPE:


This data type will allow you to invent your own data type and define what
values the variable of this data type can take. Using enumerated data type you
can also reduce programming errors.
Example:
enum week{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday
};
enum week test;

This is similar to structure definition and declaration except that it


declares the data types and its values. These values are called ‘enumerators’,
and later it declares the variables of this data type. Internally the compiler
treats the enumerators as integers starting from zero. So
Sunday=0,Monday=1.... Saturday=6 respectively. The programmer can
override this by initializing the enumerators to different values as shown:
62
enum week
{
Sunday=10,Monday=20,Tuesday=30,Wednesday=40,Thursday=50,Friday=60,
Saturday=70
};
enum week test;

The weakness of enum variables is that there is no way to use the enum values
directly in I/O functions like printf() , scanf().

Example:
enum group
{
CLC,ITD,SPD,RID
};
struct emp
{
char name[30];
long cno;
enum group gr;
}e1;
strcpy(e1.name,”xxxxxx”);
e1.cno = 12345;
e1.gr = 1;
if(e1.gr = = “CLC”)
printf(“\nEmployee from CLC”);
else
printf(“\nEmployee from other DIVISION”);

63
ª ASCII CHARACTERS:

There are 256 distinct characters used by microcomputers. Their values


range from 0 to 255 and they can be grouped as:

Character type Number of characters.

Upper case alphabets 26


Lowercase alphabets 26
Digits 10
Special symbols 32
Control characters 34
Graphic characters 128

Out of this 256 characters first 128 characters are often called as ASCII
(American standard code for information interchange) characters and next 128
characters are called as extended characters.

ASCII values of:

A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57

64
File Operations
The input and output (I / O) is entirely the responsibility of the
operating software. With different operating software, the way the I/O is done
would obviously be different. Wisely, keeping the standard library of functions
common, the functions themselves have been written differently for different
operating software s. Hence, we can use printf(), scanf() etc., any other
standard functions in any environment like DOS. UNIX etc., to achieve the
same result. This is what actually the portability and power of C.

Library functions can be classified as:


• Console I/O functions:
These are intended to receive input from keyboard and write output to the
VDU.
• Disk I/O functions:
These are to perform I/O operations on a Hard disk drive or Floppy disk drive.
• Port I/O functions:
These functions are used to perform I/O operations on various ports.

Under the category of Console I/O functions, there are functions available for
handling char, int and strings.
9 Console I/O functions
INPUT:
char getch() Gets a char from keyboard, Enter key not required.
getche() Similar to getch() but it echoes on the screen.
fgetchar() Gets the char, echoes it on the screen AND
Enter key is required.
getchar() A macro, similar to fgetchar()
string gets() Accepts a string until Enter key is hit.

OUTPUT:
char putch() Prints the character on console.
fputchar() Similar to putch().
putchar() A macro, similar to putch().
String puts() Outputs a string to the console.
65
9 Disk I/O functions:
Disk I/O functions are either high level (also called standard I/O or stream
I/O ) or low level (or system I/O). The basic difference between them is that in
the high level functions the buffer management is done by the functions them
selves, where as in low level functions this is the responsibility of the
programmer. The files that are to be accessed for I/O must be opened. The
function fopen() is used to open a file in high level language disk I/O operation
as

file pointer = fopen(“filename”, “mode”);

Text / Binary Operation

“r” / “rb” Reading from file


“w” / “wb” Writing to file
“a” / “ab” Appending the existing file
“r+” / “rb+” Reading and appending a file
“w+” / “wb+” Read and write a file
“a+” / “ab+” Reading and appending a file

Function input/output data type level

getc() input char H


putc() output char H
fgetc() input char H
fputc() output char H
fscanf() input char, int, strings H
fprintf() output - do - H
fread() input - do - H
fwrite() output - do - H
read() input chunks of bytes L
write() output - do - L

66
stdin : Reads from keyboard
stdout : Displays on console
stderr : Displays on console
stdaux : Serial port
stdprn : Parallel port

All the above five files will be opened by default and we need not to open
them on our own whenever we open a program. If any error occurs while
opening file, a null is being returned.

Once the file have been opened it is required to access the specific part of the
file. Positioning the file pointer at the desired position in the file does this. The
functions available for this task are rewind () and fseek(). rewind() positions
the pointer at the beginning of the file and fseek() places the file pointer
virtually anywhere in the file.
Syntax:
fseek(file pointer,+/- no.of bytes,anchor);

Anchor can be selected one among the following three:


SEEK_SET 0 BEGINNING OF THE FILE
SEEK_END 2 END OF FILE
SEEK_CUR 1 CURRENT POSITION

After the file is opened and worked with the same, it is must that the file is to
be closed before exiting by using the function fclose();

9 Port I/O functions:


C will use certain functions for reading and writing data through ports by
using specified addresses as their arguments.

Function I/O no.of bytes accesses


inportb() input 1
outportb() output 1
inportw() input 2
outportw() output 2

67
The following program simply reads the contents of the file temp until
the end of the file and prints its contents to the screen.

Example 1:

/* this program will reads from file temp and displays on console */

#include <stdio.h>
main()
{
char ch;
FILE *fp;
fp=fopen(“temp”, “r”);
if(fp = = NULL) exit();
while(!feof(fp))
{
ch=fgetc(fp);
putch(ch);
}
fclose(fp);
}

Example 2:

/* this program will reads from file temp and writes to file test */

#include <stdio.h>
main()
{
char ch;
FILE *fs,*ft;
fs=fopen(“temp”, “r”);
ft=fopen(“test”, “w”);
if((fs==NULL||ft==NULL) ) exit();

68
while(!feof(fs))
{
ch=fgetc(fs);
putc(ch,ft);
}
fcloseall();
}
Example 3:

/* This program will reads from file temp and writes alternate characters to
file test */

#include <stdio.h>
main()
{
char ch;
FILE *fs,*ft;
fs=fopen(“temp”, “r”);
ft=fopen(“test”, “w”);
if((fs==NULL||ft==NULL) ) exit();
rewind(fs);
while(!feof(fs))
{
fseek(fs,1l,1);
ch=fgetc(fs);
putc(ch,ft);
}
fcloseall();
}

69
Example 4:
/* This program will reads from KB and writes to file test */
#include <stdio.h>
main()
{
char ch[20];
long cno;
int basic;
FILE *fs;
fs=fopen(“temp”, “w”);
if(fs = = NULL) exit();
fscanf(stdin, “%s%ld%d”,ch,&cno,&basic);
fprintf(fs, “%s\t%ld\t%d”,ch,cno,basic);
fclose(fs);
}

Example 5:
/* Passing arguments in main */
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
char ch;
fp = fopen(argv[1],"r");
while(!feof(fp))
{
ch = getc(fp);
printf("%c",ch);
}
fclose(fp);
}

70
Example 6:

/* TO CHANGE LOWER CASE TO UPPER CASE OF THE SOURCE FILE */

#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp;
char ch,s[15];
if(argc!=2)
{
printf("Enter file name:\n");
scanf("%s",s);
}
else
strcpy(s,argv[1]);
fp=fopen(s,"r+");
if(fp==0)
{
printf("File < %s > not found",s);
exit();
}
while((ch=fgetc(fp))!=EOF)
if(ch>='a' && ch<='z')
{
fseek(fp,-1l,1);
putc((ch=ch-32),fp);
fseek(fp,0l,1);
}
fclose(fp);
}

71
Example7:
/* USAGE OF FPUTS, GETS (string storing) */

#include<stdio.h>
main()
{
FILE *fp;
char s[80];
fp=fopen("xxx","w");
printf("\nEnter some lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
}

Example 8:
/* FILE DELETION PURPOSE USING REMOVE */
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"w");

if(argc!=2)
{
printf("Enter file name to be deleted:");
exit();
}
fclose(fp);
remove(argv[1]);
}

72
Example 9:

/* FILE RENAMING PURPOSE USING RENAME */

#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
fp=fopen(argv[1],"r");
if(argc!=3)
{
printf("Enter source file name followed by required name of the file:\n");
exit();
}
fclose(fp);
rename(argv[1],argv[2]);
}

73
Data Structures
‰ DYNAMIC MEMORY ALLOCATION
‰ Necessity
Consider a declaration < int marks[100];> such a declaration would
typically be used if hundred student’s marks are to be stored in
memory. The declaration will reserve 200 bytes of memory for storing
100 integers. Never the less, some times it may happen that when we
actually run the program, we might be interested in storing only 50
student’s marks. In this case, the memory used is 100 bytes (50x2) only,
which would result in wastage of the remaining 100 bytes, which was
reserved by declaration. Subsequently, sometimes we need to store more
than 100 student’s marks, but our declaration provides us (limits us)
only with 100 marks. There is no mechanism to either increase or
decrease the size of an array during the program run. The reason is
arrays use static memory allocation. To over come this, we have an
alternative with the use of standard library functions.
The standard library function malloc() and calloc() functions
allocates memory during the program run as per user requirement and
this memory allocation is known as dynamic memory allocation. Let
us examine the following example.
#include <alloc.h>
main()
{
int n,avg,I,*p,sum=0;
printf(“Enter number of students:”);
scanf(“%d”,&n);
p=(int*)malloc(n*2);
if(p==NULL)
{
printf(“Memory allocation failed”);
exit();
}

74
for(i=0;i<n;i++)
{
printf(“Enter marks of %d student”,i+1);
scanf(“%d”,(p+i));
}
for(i=0;i<n;i++)
sum=sum+*(p+i);
avg=sum/n;
printf(“Average is %d”, avg);
free(p);
}

In the above example using dynamic memory allocation facility


accommodates the flexibility. The memory required by the program is
calculated only after reading the user required number of students by using
the malloc() function. Some times system memory may not be sufficient to
spare for the user requirements, then malloc() will return NULL and then we
are terminating the program.
The calloc() function also similar to malloc(), except for the fact that it
needs two arguments as against the one argument required by malloc() like

main()
{
int *p,n;
printf(“Enter some number”);
scanf(“%d”,&n);
p=(int*)calloc(n,2);
}
Another difference between malloc() and calloc() is that, by default the
memory allocated by malloc() contains garbage values, where as that allocated
by calloc() contains all zeros. Another good practice is to free the reserved
memory blocks, soon after the task is over, as last statement in the program.

75
⇛ LINKED LIST

Linked lists are extensively used in data base management systems,


operating systems and editors etc. The primary advantage of linked lists over
array is that the linked lists can grow and shrink in size during the
application. In fact, the maximum size of the linked lists need not be known in
advance, unlike an array. Linked list is a very common data structure often
used to store similar data in memory. While the elements of an array occupy
contiguous memory locations, those of linked lists are not constrained to be
stored in adjacent locations.
The individual elements are stored some where in memory, but still bound
together. The order of elements is maintained by explicit links between them.
For instance, the following linked list is how the data can be stored in a linked
list.
Link
Data

Data link Data link Data link Data Null

NODE

In the above figure, observe that the linked list is a collection of


elements called nodes, each of which stores two items of information namely
one in data, the other is link i.e. pointer (address of next data element) to next
node. The data part of each node consists of some data and next part is a
pointer to link the next node. The null indicates last node of the linked list.

76
⇛ DOUBLE LINKED LISTS

In the linked lists we have seen each node provides information about
where is the next node in the list. Each node will establish a link to the
successor, but not with the predecessor. It means that the current node in
the list does not know previous node address. While accessing the elements
of a single linked list, suppose if we are at 10th node and would like to
access the 9th node, then only way we have to follow is to start traveling
from first node. To overcome this difficulty, we have an another facility
called double linked lists. Here we can travel either to next node or
previous node as shown.

Null Data Next Prev Data Next Prev Data Null

⇛ STACKS AND QUEUES

Stacks and queues are two very useful data structures. These data
structures are often implemented using arrays since most programming
languages provide array as a predefined data type, and such an
implementation is quite easy.

Never the less, when implemented as an array these data structures


suffers from the basic limitation of an array. (As we know already array
dimension can not be either increased or decreased once it is declared) This
difficulty can be eliminated when implemented these data structures using
linked lists. Before the implementation, we formally define these data
structures. A stack is a data structure in which addition of new element or
deletion of existing element always takes place at the same end. This end is
often known as top of stack. There are several applications where stack
can be put in use. This is based on concept of LIFO (Last In First Out).
On the other hand, unlike a stack, in a queue the addition of new
elements takes place at the end (called rear), where as deletion takes place
at the other end (called front). This is based on concept of FIFO (First In
First Out).
77
TOP FRONT REAR
Data

Data Data Data Data

QUEUE
Data

STACK

⇛ CIRCULAR LINKED LISTS

The linked lists that we have seen so far are often known as linear linked
lists. First setting up a pointer pointing to the first node in the list and then
traversing the entire list-using pointer can access all elements of such a
linked list. Although a linear list is a useful data structure, it has several
shortcomings. For example, given a pointer P to node in a linear list, we
can not reach any of the nodes that precede the node to which P is
pointing. This disadvantage can be overcome by making a small change to
the structure of a linear list such that the link field in the last node
contains a pointer back to the first node rather than a null. Such a list is
called circular linked lists and is shown in next page.

Data Link Data Link Data Link

78
ISSUED FOR PARTICIPANTS AS COURSE MATERIAL

BY CORPORATE LEARNING CENTRE OF

ELECTRONICS CORPORATION OF INDIA LIMITED

HYDERABAD-062

COMPOSED & COMPILED


BY
CLC: ECIL

79

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy