C Programming Language
C Programming Language
(BSIT 21)
Contributing Author
Syllabus
3. Control Structures of C:- for, while and do loops, if then else statements,
switch statements.
7. Pointers: Definition and operation pointers & structures, linked lists, pointers
& functions
CONTENTS
Unit – I
II C Fundamentals
IV Arrays
Unit – II
I Functions
II Structures
III Files
Unit – III
I Pointers
II Bitwise Operators
III Preprocessor
COURSE INTRODUCTION
In this course, you learn the programming language called “c”. You learn about basic
concepts of programming and the language itself in detail. Just like any other human
language, the programming languages also have a format in which they are to be written. But
the constraints are more stringent. Human beings are capable of understanding sentences
that are not fully grammatical, but a compiler simply rejects a program even if a single
comma or semicolon is not in place. That way we need to be extra careful when writing
programs.
The course itself is divided into 3 units - The first unit talks of the basics of the
language, data formats, control structures and the concept of arrays. In each case, a brief
explanation of what it means is given, followed by the general format of the operation. This
is followed by a large number of sample programs. In fact any study of a programming
language is complete only when one is able to analyze & solve a variety of problems. These
programs are designed in the increasing order of their complexities and many of them also
come with sample outputs. Also the explanation of the programs themselves are given,
wherever deemed necessary.
The second unit gives an insight into concepts like functions, structures and files.
The third unit deals with advanced features like pointers, bitwise operaters,
preprocessors, etc..
UNIT – I
UNIT INTRODUCTION
This unit teaches you about the fundamentals of C language. You may notice that
this unit is bulkier than other units. It is because, to start with you have to know many of the
important features - all at once.
Then afterwards, the basics of the language - the variables, constrants, simple formats
for a typical C program are discussed in the second block. You also get introduced to the
concept of library functions, header files etc..
The third block deals with the control structures in C. They control the flow of
program. Though normally the control flows sequentially, i.e., the first line gets executed
first.
Then the second line, etc., it is possible to alter it by varies methods. You get
introduced to concepts of decision making using If statements, Switch Statements, the
concept of loops, the different types of loops etc..
The fourth block discusses the concept of arrays. When you have a large number of
data items to be handed under a common name, arrays are used. They helps remember and
manipulate data easily.
By now, you will also have picked up the bare fundamentals of C. Hence, we also try
to solve a very large number of programs. Wherever the algorithm is new or needs some
explanation, you see comments being liberally provided. Otherwise, you will straightaway
be able to study and understand them.
BLOCK - I
FLOW CHART
Block introduction: In this block, you are introduced to the concept of flowcharts and
algorithms. Whenever you are asked to solve a problem using a computer, you should first
convert it to a sequence of steps which can be solved by a programming language. While in
the case of very simple programs this can be done mentally, in real time problems, these are
to be done in a systematic manner.
The flowcharts provides a schematic way of doing the same by connecting a sequence
of fundamental blocks to indicate the flow of control. You are introduced to the blocks and
also the methods of interconnecting them.
You are also introduced to the concept of algorithms, which describe the problem in
an English-like language, so that they can be converted into programs.
Let us take an example. Suppose you want to pick up a book from a table. For a
human being, it is enough to say, "Please pick up the book from the table". He will go to the
table and pick up the book. On the other hand, imagine a totally dumb servant, who cannot
reason out any thing by himself but can faithfully follow your instructions. For him you have
to describe the operation in steps like
Go forward by 10 Steps
A computer can be linkened to the servant, who is highly competent and faithful as
long as following the instructions are concerned, but cannot reason out by himself. So, you
as a programmer will have to break the problem into a sequence steps, similar to those
described above for the computer to work with. For this you should know the computer's
language. One of them is "C", which you are going to learn in full detail in this course. But
before that, you should be able to break the problem into the simple steps so that you can
describe these steps in the language.
In simple cases, you would be able to do it straightaway. With some practice, most of
the simple or even medium-sized problems can be directly coded into the computer language.
But when you have really complicated problems on hand, you need to analyze it step by step.
Further, such an analysis will also help you remember what you have done and modify, if
necessary, at a much later date. Also, if some other person wants to know your sequence of
reasoning, obviously it should be possible for you to describe your logic in simple,
unambiguous steps. Because of all these reasons, it is highly essential to develop some form
of intermediary mechanism to describe the problem on hand as a sequence of steps, which
can be later converted to a program. There are two such commonly used and universally
accepted methods of describing the solution process
The flow Chart: As the name suggests, it is a chart to describe the flow of the solution
process. You break up the solution into simple steps and connect them to describe the flow
so that the last of these blocks leads you to the solution.
We briefly describe the commonly used symbols to represent these blocks and how to
combine them to form the solution.
Compare PME<40
PME;40
PME> 40 NO
PME<40 YES
CODE ?
=1 =2 =3 =4 =5\
Algorithms: The other concept is the algorithm. It is a step by step description of the
problem in a language similar to English, but not in full sentences, but as a set of commands.
Some of the examples below will classify the concepts.
START
Step 1: START
INPUT
VALUES FOR
P, T & R
CALCULATE
I= P * T * R
Step 2: Read P T and R
100
PRINT VALUE
FOR I
Step 4 : Write I
Step 5 : End
Example b) Victor Construction Company plans to give a 5% year-end Bonus to each of its
employees earning Rs. 5,000 or more per year, and a fixed Rs. 250 bonus to the other
employees. The flowchart and algorithm for calculation the Bonus for an employee is as
shown in figure
Step 7 : End
END
Example c) The flowchart and algorithm for adding the integers from 1 to 10
START
Step 1: Start
SUM = 0
N=1
Step 2 : Initialize SUM=0 and N=1
Test ?
N> 10 Step 3: If N is greater than 10 then
YES N = N+1
Endif
Step 7: Go to Step 3
Example d) A Flowchart to calculate the largest and the smallest numbers in a list of input
values is as shown in figure. The last input value is 99999.
START
INPUT NUM
LARGE = NUM
SMALL = NUM
INPUT NUM
YES
TEST?
NUM=99999
PRINT
LARGE &
NO SMALL
NO YES
TEST?
NUM>LARGE END
NO
LARGE = NUM
NO TEST? YES
NUM<SMALL
SMALL=NUM
Algorithm: 1
Else
5. if the number is > the present large number, make the new number the largest.
Else
6. If the number < the present small number, make the new number as the smallest.
7. Goto step 4.
Example C: A flow chart to read the marks of a student and classify him into different grades.
If marks greater than or equal to 90 Grade A, greater than or equal to 80 but less than 90
Grade B, Greater than or equal to 65 but less than 80 Grade C otherwise Grade D.
Algorithm:
1. Read marks
2. If marks >= 90
Declare Grade = A
6. Write Grade
7. End
START
READ MARKS
TEST?
MARKS≥90
TEST?
MARKS≥80
GRADE = A
TEST?
GRADE = B MARKS≥65
GRADE = C GRADE = D
WRITE GRADE
END
START
READ A,B,C
D=B*B - 4*A*C
NO YES
TEST?
D>0
NO YES
TEST? REAL1=(-B+SQRT(D)) /(2*A)
D=0 REAL2=(-B-SQRT(D))/(2*A)
REAL = B/2 * A
REAL 2 = B/S * A
END
2. Evaluate D = b2 – 4 * a * c
3. If D> 0,
Else
5. If D = 0
Else
8. End.
BLOCK - II
C-FUNDAMENTALS
BLOCK INTRODUCTION
In this block you get introduced to the C languages. The basic method of storing
data-using variables and constrains is discussed. The rules for framing such variables, the
various arithmetic and logical operators, simple input/output operations and you also learn to
write your first C programs - very simple - but nevertheless complete programs.
C – FUNDAMENTALS
We will now start the study of the programming language – ‘C’. C evolved from a
succession of programming of programming languages developed by Bell Laboratories in
early 1970s. The increasing popularity of the unix operating system, which has C as it’s
“Standard” programming language, further enhanced the usefulness of C making it arguably
the most popular of the programming languages.
We now start with the fundamentals of the language. Any language, as you know is
made of sentences, which are made up of words, which in turn are made up of characters i.e.
we start learning the characters, then learn how to combine them into words, combine the
words into sentences and so on.
Characters of C
Variables of C
A variable in a program is a name to which you can associate a value. For ex. with
the name A you can associate, say, a number 10, so that whenever the number A is
called/used, you get the value 10.
They begin with a letter or underscore(_), and may be followed by any number of
letters, underscores or digits (0-9). But you cannot have special characters or blankspaces in
a variable name.
Prod
sum_total
I
J
_sysflag.
The following are invalid variables
Sum $ total
part total
5load
int
Now based on the previous definition, we leave it to you to decide why they are
invalid. But the last word int appears to be valid as per the definition. It is a invalid variable,
because it is a “Reserved name”. The C compiler, uses a reserved name with a special name
and you can not use it with your own definition. As we go about, we pickup a large number
of such reserved words and their meanings.
One sound advise for choosing the names of variables. You can practically use any
name to store any value. For example A or M can be used to store sum, product, quotient
any thing as long as you know what is it that you have stored. However, it is a good practice
to use meaningful names to store data. You can store the result of addition in sum, product of
two numbers in prod, etc.. When your are writing long programs, such practices help you a
lot in checking the correctness (technically called debugging) and understand the programs.
The concept of variables that we have just introduced to is just to initiate you to the
various ways in which data can be stored in C. We now seek a more formal and complete
description of the various ways in which data can be manipulated in C.
A variable name is one which the stored data can be changed during the execution of
the program. For example if you have store 10 in A initially, you can add or subtract
something to it or even store a totally different value. i.e the data A is “variable”. On the
other hand you can also have certain constants, whose values do not change during execution.
Variables themselves come in different types. They can be integers (whole numbers),
floats (fractional numbers) doubles and characters. Characters as the name suggests are used
to store characters. A number of characters in a string are sometimes called the string (Str)
variables. The data type doubles need some introduction. Normally a C compiler can store
numbers of certain size only. The actual size depends on the computer you are using and the
compiler in use. If you suspect that you are likely to use numbers bigger than this, you should
use double declaration, which will give you twice the number of places. i.e. if your original
limit was 5 places, you may now get to use up to 10 places which will suffice in most cases.
C expects you to list the variables you are using in your program at the beginning
itself and also their types. For ex.
Int a,b,c
Float no,n1,n2;
Char name, title;
makes a,b,c available for storing integer numbers (like 10,20,30), no,n1,n2 store fractional
numbers (like 10.42, 13.56, 15.7 etc) and name and title store character strings (like rama,
student etc.).
The semicolon (;) at the end is used extensively in C to demarcate one statement from
another (Just as . is used in English).
Arithmetic Expressions: Once you have learnt about integers, float etc, the next stage is to
combine them. They can be combined with the usual addition, subtraction symbols.
For ex. A + B, a – c, a * b etc. can be used. However, mere such operations are not enough.
The data that you get after the operation is to be stored in a variables name. Hence, you can
write
a = a + 10;
Sum = a+b;
X=y*z; etc.
In the first case, 10 is added to the original value of a (what ever it was) and is stored
as the new value of a. (the original value is lost). In the second case a and b are added and
the result is stored in sum. In this case, since a and b are not being overwritten, their values
continue to be available to you. In the third case, the product of y and z is stored in x.
Before you can start writing small programs, we also conclude about precedence of
operators. In a long expression with a number of such operators, which one is evaluated
first?
The answer is first all multiplication and division operators are completed. Then all
addition and subtraction are taken up.
If there are more than one multiplication, addition, etc. the computations are done
from left to right.
Ex: a = b + c / d + e * f
c / d is evaluated first, then e * f then b is added to the result of c / d and finally the
result of e * f is added. The entire value is stored in a.
Try evaluating a = (b + c)/d+ e*f with the above given values for a, b, c, d, e and f.
You notice that, by enclosing them within parentheses, we have changed the result. So,
whenever you are evaluating long expressions, it is always desirable to be careful about the
precedence of operators. However, one golden rule is that whenever in doubt, use
parentheses. For ex; in our original example, you want c/d to be evaluated first, there is no
need for parentheses to be used. However, if you are not confident of your judgement,
simply enclose them in parentheses as in a = b + (c / d) + (e * f).
You should note that the expression within brackets need not be as simple as we have
illustrated. They can be as long as you like, there can be parentheses within parentheses and
so on. Again, within these parentheses the same rules of precedence apply, including the fact
that those inside the parentheses are evaluated first. So, in effect the evaluation starts from
the innermost parentheses and proceeds outwards.
Whenever in doubt, use parentheses. Use of extra parentheses will not affect the
results, but not using them when needed changes the final results. Now, we are in a position
to illustrate these with a sample C program. However, before we can write a full program,
we introduce you to one more concept of getting the output from the program. There is a
function printf() which allows you to do this.
# include<stdio.h>
main( )
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = b * c /* multiplication */
result = a / c; /* division */
result = a + b * c; /* predence */
output :
a – b = 98
b* c = 50
a/c=4
a + b + c = 150
a* b + c * d = 300
Whatever we write in between /* and */ is a comment. i.e. the C compiler will not
process it. You can write your comments and explanations so that it will be easier for you to
understand the program, when you go through it at a later date.
Main() indicates that it is a main program, we study more about it later. Notice that
the entire program is enclosed between the brackets { and }. Later, we see that there can be
many more such segments enclosing portions of the program. The declaration int a = 100;
declares a as an integer variable and stores 100 in it. Similarly stores 2 in b, 25 in c and 4 in
d. The variable result is also declared as an integer, but no value is stored in it as of now. As
and when the calculations are done, the result of the calculation are stored in result.
(Note that after a,b,c,d we could have declared an e. But since we are starting the result, we
have called it result, so that we immediately know what to expect in it).
Printf, as we have already described is used to print the output. Now whatever is
between the inverted commas “ and ” is printed as it is, except %d and \n. %d indicates that
an integer value is to be printed at that place and \n indicates that after printing, the cursor
should go to the next line. Now, outside the inverted comma, we have the result, which is an
integer. So the value of integer stored in variable result is printed where %d is appearing.
a - b = is printed as it is
In place of %d, the value of result is printed (What ever is its value)
Because \n is there, the control goes to the next line i.e the next printf comes in the next line.
Now analyse the entire program and the output of the same given above. To make things
more familiar, we write one more very similar program. This will evaluate the expressions
we encountered during the discussion on precedence of operators.
#include <stdio.h>
main()
int a;
int b = 4;
int c = 8;
int d = 2;
int e = 4;
int f = 2;
output :
The value of a is = 16
The value of a is = 14
The value of a is = 1
#include<stdio.h>
main( )
int a = 25;
int b = 2;
int result;
float c = 25.0;
float d = 2.0;
printf(“-a = %d\n”,-a);
output:
6 + a / 5 * b = 16
a / b * b = 24
c / d * d = 25.00000
-a = -25
Note the difference between this and the previous two programs. When evaluate
6 + a / 5 * b, we have not stored it's value in any result, but it is evaluated in the printf
statement itself and printed straight away.
# include <stdio.h>
main( )
{
float num1,num2,product;
num1=300.0;
num2=0.6;
output:
#include<stdio.h>
main( )
int a = 8;
int b = 10;
int c = 4;
int sum,remainder;
float average;
sum = a + b + c;
average = sum / 3;
remainder = sum % 3;
Output:
There are some special types of arithmetic statements in C. Consider the statement
i = i + 1; it states add one to i and store the new value as i. Such statements are very
frequently used in what are called “increment” operation. Suppose you want to perform an
operation 10 times. Then all that you do is to perform the operation once, count i as one,
perform it again, add 1 to i. Perform again. Add one more to i and so on.
Similarly there are decrement statements, for situations when you want to count
backwards - instead for say 1 to 10 suppose you want to count from 10 to 1. Then initially
you put i=10 then keep subtractive i=i-1. For such situation we have i-- and --i post
decrement where subtraction is done after the operation and subtraction is done before the
operation respectively.
C also provides a list of arithmetic and logical operator. These will be useful,
basically for the control structures operation (see next block). We give you the table of such
operators, which can be used to compare two variables or statements.
Scanf() function:
One thing you might have noticed in all the above programs is that we are not giving
any inputs at all. The values needed by the program are being included in the program itself -
only the output is being made available. Obviously, their cannot happen always. We may
not know the input before hand always nor can we go on changing the programs, whenever
the input data changes. So, there should an input function, which asks for input during the
execution time and accepts the values from the keyboard. That function, obviously, is similar
to printf( ) - it is called scanf( );
Whenever a scanf( ) is encountered, the computer waits for the user to give the value
for that particular input from the keyboard and takes that as the value for the variable.
Scanf("%d",&a);
When this statement is executed on the computer, the program waits. If you type in,
say 10, the value of a is taken as 10.
There is a difference though. Instead of simple 'a', we write &a, which is a pointer to
the location where a is stored. Any way, we come back to this topic again, For now, we can
say all scanf( ) parameter come with the ampersand &.
Library functions:
The C compiler wants to make the life of the user easier. It provides small program
modules called library functions which are programs that perform functions that are needed
often by programmers. The user will have to simply call them by their name & use it - he
need not write then again and again. Some of the more frequently used library functions are
listed below:
For that matter even scanf() & printf() with which you are familiar are library
functions.
These functions are available in special files - called header files. For ex: scanf, printf
etc are available in a file called stdio.h, whereas cos, sine etc - are in a file called math.h. If
you want to use these functions, you should include these files using the #include directive at
the beginning of the program.
We have so far used only data type %d, a decimal value. Atleast three more type are
frequently used % f for indicating the floating point(real) numbers, %e to indicate double
length numbers and %c to store characters.
With these fundamentals we now write a large number of fairly simple programs.
Algorithm: 1. Start
2. Enter days
5. Stop
#include<stdio.h>
main ()
int m,d;
printf(“Enter days”);
scanf(“%d”,&d);
m = d/30;
d = d/%30;
Typical Output:
Months = 10 Days = 5.
#include<stdio.h>
main ()
float a,b,c,x,y;
x=a*c+b;
y=a*x*x*+b*x+c;
printf(“x = %f\n”,x);
printf(“y = %f\n”,y);
/* END OF PROGRAM */
Output:
X=16.000000
Y=675.000000
#include <stdio.h>
main ()
char str[20];
scanf(“%s”,str);
/* END OF PROGRAM */
Output:
SUDARSHAN
#include<stdio.h>
main ()
char str[20];
scanf(“%s”,str);
/* END OF PROGRAM */
output:
WELCOME DINESH
LET’S BE FRIENDS
#include<stdio.h>
main ()
int d;
float r,t;
scanf(“%f”,&r);
t = r + 0.5;
d = ((int)t);
/* END OF PROGRAM */
output:
Write a program to find the area and perimeter of a circle given its radius
Solution:
Algorithm: 1. Start
2. Assign Pi ← 3.1415
3. Input radium
peri ← 2*pi*r
6. Stop
#include<stdio.h>
main ()
scanf(“%f”, &r);
area = pi*r*r;
peri = 2 * pi * r;
/* END OF PROGRAM */
output:
Area = 20.59
Perimeter = 16.08.
Write a program to find the area and perimeter of a rectangle having length,l and
breadth b.
Solution:
Algorithm:
1.Start
peri←2*(length + breadth)
4. Output area,peri
5. Stop.
#include<stdio.h>
main ()
float l,b,area,peri;
scanf(“%f”,&l);
scanf(“%f”,&b);
area=l*b;
peri= 2*(l+b);
printf(“\n Area=%10.2f”,area);
printf(“\n Perimeter=%10.2f”,peri);
/*END OF PROGRAM*/
Output:
Area = 8.50
Perimeter = 11.80
Solution:
Algorithm: 1. Start
8. Stop
#include<stdio.h>
main()
scanf(%f",&f);
cel=5.0/9.0*(f-32.0);
scanf("%f",&c);
faren=(c*9.0/5.0)+32.0;
/* END OF PROGRAM */
Output:
#include<stdio.h>
main()
scanf("A=%d B=%d",&a,&b);
temp=a;
a=b;
b=temp;
printf("A=%d B=%d\n",a,b);
b=a + b;
a=b - a;
b = b -a;
/* END OF PROGRAM*/
Output:
A=6 B = 4
BLOCK - III
CONTROL STRUCTURES
BLOCK INTRODUCTION
Here we learn about the control structures of C. The compiler normally takes the
program line by line and executes them in a sequence ( one after another ). But this may not
always be the case. Based on certain conditions existing in the data, we may want to change
the data - Then we use an If statements. In a limiting case, you may need to choose one out
several possible options - by using a Switch statements.
Sometimes you also need to repeat the same set of statements repeatedly. Such
statements are called loops. The number of times you do this may be or may not be known at
the time of writing a program. This will lead us to for, while and DO While loops.
The if statement :
If ( expression)
Program statement
Next statement
i.e if the expression inside the parenthesis is satisfied, then the program statement is
executed & then next statement is executed. If it is false, the program statement is skipped,
but the next statement is executed. A non programming example could be like this.
I go for a walk.
i.e if the weather is cold ( expression is true) I shall wear woolen clothes ( program
statement). (then) I go for a walk ( next statement).
If the weather is not cold(expression false), I go for a walk ( skip the program
statement, go to a next statement) we shall see a more academic example in the following
program.
#include<stdio.h>
main ()
int number;
scanf(“%d “, &number);
if ( number <0)
number = -number;
Output(Re-run)
Else
( Note that these are direct implementations of decision boxes in the chapter on flow
charts)
One other point to not is that statement1 and statement2 need not be single statements,
but they can be a group of statements included between { } )
Solution:
#include<stdio.h>
main()
char status;
float tax,pay;
scanf("%f",&pay);
printf("Enter status\n");
scanf(%c",&status);
if (status = = 's')
tax=0.20 * pay;
else
tax=0.14*pay;
printf("Tax=%f",tax);
#include<stdio.h>
main ()
scanf(“%d”, &number_to_test);
if ( reminder==0)
if (reminder !=0)
Output:
Output (Re-run):
#include<stdio.h>
main ()
scanf(“%d”, &year);
rem_4 = year % 4;
else
Output:
Output ( Re-run)
Output(Re-run)
#include<stdio.h>
main ()
char operator;
if ( operator = = ‘+’)
printf(“%.2f\n”,value1 + value2);
printf(“%.2f\n”,value1 – value2);
printf(%.2f\n”,value1 * value2);
printf(%.2f\n”,value1/value2);
Output:
123.5 + 59.3
182.80
Output (Re-run)
198.7 / 26
7.64
Output ( Re-run)
89.3 * 2.5
223.25
#include <stdio.h>
main ()
max = num3;
max = num1;
max = num2;
Output:
When there are a number of else alternatives as above, way of representing is by the switch
statement.
Switch (expression)
case value1:
program statement
program statement
……
break;
case value2:
program statement
program statement
……
break;
…….
case value’n’:
program statement
program statement
……
break;
default:
program statement
program statement
……
break;
}
/* program to evaluate simple expression of the form value operator value */
#include<stdio.h>
main()
{
float value1, value2;
char operator;
printf(“Type in your expression. \n”);
switch(operator)
case ‘+’:
break;
case ‘-’:
break;
case ‘*’:
break;
case ‘/’:
if(value2 == 0)
else
break;
default:
break
LOOPS
The other type of control structures that we need are loops. Quite often, a set of
instructions will have to be repeated again & again. For example, if you are calculating
salary of 1000 employees, the portion of the program pertaining to the salary of employees
will have to be repeated 1000 times, each time with a different set of data. The easiest way to
do it is to start some sort of a counter, say i, to zero; each time one set of instructions are
completed, the counter is increased by one and when it reaches 1000, we have to stop the
repetitions. This can be done by the programmer also, but C provides special construct to do
this.
In certain other cases, we will not be sure as to how many times the repetitions are to
be done, but we have to continue till some conditions are satisfied - like all records getting
exhausted or as long as some employees remain etc.. C provides facilities for such type of
loops also.
The for loop: This is the simplest form of loops, where you know before hand how many
repetitions ( " iterations" in computer terminology ) are to be done. Like the case of 1000
employees or 100 students of a class etc..
The format is
for (variable = initial ; variable = how long value to continue; amount of increment )
Lines to be repeated
It is obvious that the initial value of variable need not always be 0 or 1; it can be
anything. Similarly after each operation, you need not increment by 1. It can be 2,3 …
anything, even negative you want to count backwards). Note that you are only specifying the
method of incrementing, the actual incrementing is done by the C control. It sets the variable
to the initial value, after each iteration, increments suitably, checks whether the terminating
condition is met with, if not repeats the operations. Of course, it is the duty of the
programmer to ensure that at some stage, the loop terminates - if the terminating condition
never emerges out of the successive increments the program will go into an infinite loop.
Program:
Suppose we want to find the average of N given numbers. Obviously we input the numbers
one after the other, add them into a sum and then divide by N. Let us also presume that N is
also given at run time.
#include <stdio.h>
#include<math.h>
main()
int n,i,num,sum=0;
float avg;
/* N is the number of numbers, num is the number ( read one at a time) &
scanf("%d",&n);
scanf("%d",&num);
sum=sum+num;
avg=sum/n;
a) The computer prints on the terminal, Input how many numbers are there.
b) If, say, 10 numbers are to be added, the number 10 is given as the input.
c) Then, inside the loop, the system keeps asking ( 10 times in this case) input the next
number.
d) Every time, the next number of the set of numbers for which average is to be calculated is
inputted.
The point to be noted is that the loop keeps incrementing itself as long as i< or=n
automatically and stops once n become greater than n i.e. we technically say there were "n
iterations"
Program:
Now we will look one more simple but popular program to find the factorial of a number. It
the number is, say, 5 it's factorial is 5 x 4 x 3 x 2 x 1 i.e the product numbers from 1 to n.
# include<stdio.h>
#include <math.h>
main()
int n,prod=0;
scanf("%d\n",&n);
prod=(prod*i);
of course, the initial value of the loop need not always start with 1.
Program:
Let us illustrate by a simple case. We want to find the sum of the first 50 even numbers.
#include<stdio.h>
main()
int i,sum=0;
sum=sum+i;
BLOCK IV
ARRAYS
BLOCK INTRODUCTION
Whenever we have to handle data which are interrelated - like the marks scored by the
different students of a class in a subject, the salaries of the employees of a dept etc - it is
worthwhile to store and operate them under a single name. This leads us to the concept of
arrays. Arrays need not be the one dimensional cases as above. They can have 2/more
dimensions - like the marks scored by the different students if a class in different subjects, the
salary details like BASIC,DA,HRA & CCA of the employees of a dept etc.. In this block, we
learn to manipulate them.
Also, now that we have gained some confidence over the language, we urite a large
number of programs.
ARRAYS
We have seen how to create variables - integer, float or character types, each variable
is given a unique name and you can store one item under that name. Often, however, we
need several similar items to be grouped under a single name. For example, marks scored by
a student in different subjects, the salaries of employees of a particular department etc..
Ofcourse, if a student has 5 subjects you can declare 5 different variables - say sub1,sub2 ..
sub5 and operate on them. But it is better if we can given a common name to them so that we
can know that they are related to each other. Further, what if there are 100 employees in a
dept? Declaring 100 different variables explicitly is quite difficult. In such cases, a data
structure called "array" is used. ( Incidentally, a data structure can be approximately thought
of as the method of grouping memory location in a particular form )
Sub
1 2 3 4 5
Now all of them have a common name called sub and they can be individually addressed
by their index number 1,2,3,4 & 5. So, the marks scored in subject 1 is stored in sub[1], that
in subject 2 is sub[2] etc..
In C, you can declare arrays in the beginning just like declaring other variables
This means that in the array called sub, 5 different integer values can be stored, under
salary 50 different float values are stored. To access each of them, their specific index
number is to be given. However, in C, the first element index is 0, the second one as 1 etc..
For example sub[0] stores the marks of the first subject…. Sub[4] stores the marks of the fifth
subject.
Just to familiarise ourselves with the way arrays operate, we see the following examples:
Main()
Int rating-counters[11],i,response;
scanf ("%d",&response);
else
++rating_counters[response];
printf("\n\nRating Number of Responses\n");
printf("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n");
for (i=1; i<=10; ++i)
printf("%4d%14d\n",rating_counters[i]);
OUTPUT:
Enter your responses
15
Bad response: 15
5
5
10
---- -------------- -
1 1
2 0
3 1
4 1
5 6
6 4
7 2
8 2
9 2
10 1
main()
int fibonacci[15],i;
fibonacci[0] = 0; /* by definition */
printf("%d\n",fibonacci[i]);
OUTPUT:
13
21
34
55
89
144
233
377
if (p%primes[i] == 0)
is_prime = 0;
if (is_prime)
++prime_index;
printf("%d",primes[i]);
printf("\n");
OUTPUT:
2 3 5 7 11 13 17 19 23 29 31 37
41 43 47
It is also possible to initialize the array elements at the time of declaration itself
Main()
int i;
array_values[i] = i * i;
printf("array_values[%d]=%d\n",i,array_values[i]);
OUTPUT:
Array_values[0] = 0
Array_values[1] = 1
Array_values[2] = 4
Array_values[3] = 9
Array_values[4] = 16
Array_values[5] = 25
Array_values[6] = 36
Array_values[7] = 49
Array_values[8] = 64
Array_values[9] = 81
Arrays need not be only single dimensional. They can be 2,3… dimensional also
10 5 3 7 9
9 6 4 7 9
5 4 -8 6 7
4 1 7 6 -5
Because M has 4 rows (0,1,2,3) and 5 columns(0,1,2,3,4). As before, the array can also be
Int M[4][5]= {
{ 10, 5, 3, 7, 9},
{ 9, 6, 4, 7, 9},
{5, 4, -8 6, 7},
{4, 1, 7, 6, -5}
};
Ofcourse, in all intilisations, not all the elements need to be initialised, you can only
intialise those elements that you need and leave out other elements. They will be initialised
to 0.
#include<stdio.h>
main()
int x[5];
float ave;
scanf(“%f”,&x[i];
large=small=x[0];
if(x[i]>large)
large=x[i];
of(x[i]<small)
small=x[i];
OUTPUT:
Enter number1:50
Enter number2:30
Enter number3:40
Enter number4:10
Enter number5:20
#include<stdio.h>
main()
scanf(%d”,&n);
for (i=0;i<n;i++)
scanf(“%d”,&x[i]);
for (i=0;i<n-1-i;j++)
if(x[i]>x[j+1])
temp=x[j];
x[j]=x(j+1);
x[j+1] = temp;
for(i=0;i<n;i++)
printf(“%d\n”,x[i]);
OUTPUT :
5 4 3 2 1
1 2 3 4 5
#include<stdio.h>
main()
int a[5][5],b[5][5],c[5][5];
int i,j,m,n;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d\t”,c[i][j];
printf(“/n/”);
OUTPUT :
Enter matrix A:
1 1 1
1 1 1
1 1 1
Enter matrix B:
2 2 2
2 2 2
2 2 2
3 3 3
3 3 3
3 3 3
#include<stdio.h>
main()
int a[5][5],b[5][5],c[5][5];
int i,j,m,n;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] - b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d\t”,c[i][j];
printf(“/n/”);
OUTPUT:
Enter matrix A:
3 3 3
3 3 3
3 3 3
Enter matrix B:
2 2 2
2 2 2
2 2 2
1 1 1
1 1 1
1 1 1
#include<stdio.h>
main()
int a[5][5],b[5][5],c[5][5];
int i,j,k,m,n,p,q;
scanf(%d%d”,&m,&n);
scanf(%d%d”,&p,&q);
if (n!=p)
printf(“\n\tCANNOT MULTIPLY”);
exit();
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j];
for(j=0;j<p;j++)
for(k=0;k<q;k++)
scanf(“%d”,&b[j][k];
/*PRODUCT OF MATRICES*/
for(i=0;i<m;i++)
for(k=0;k<q;k++)
c[i][k]=0;
for(j=0;j<n;j++)
c[i][k]+=a[i][j] - b[j][k];
for(i=0;i<m;i++)
for(k=0;k<q;k++)
printf(“%d\t”,c[i][k];
printf(“\n”);
OUTPUT:
Enter matrix A:
2 2 2
2 2 2
Enter matrix B:
3 3
3 3
3 3
18 18
18 18
#include<stdio.h>
main()
char line[50],c;
int v=0,con=0,d=0,ws=0,count=0;
scanf(“%[^\n]”,line);
v++;
con++;
d++;
elseif(c== ‘ ’ || c==‘\t’)
ws++;
++count;
OUTPUT:
Number of Vowels: 9
Number of consonants: 14
Number of Digits:1
#include<stdio.h>
main()
int a[5][5];
int i,j,m,n;
scanf(“%d%d”,&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j];
/*TRANSPOSE OF MATRIX*/
for(i=0;i<n;i++)
for(j=0;j<m;j++)
printf(“%d\t”,a[i][j];
printf(“/n”);
OUTPUT:
Enter matrix :
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
#include<stdio.h>
main()
int a[5][5];
int i,j,k,m,n;
scanf(%d%d”,&m,&n);
if (m!=n)
exit();
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j];
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(a[i][j]!=a[j][i]
exit(0;
printf(“\NMATRIX IS SYMMETRIC\n);
OUTPUT :
Enter matrix :
1 2 3
2 1 4
3 4 1
MATRIX IS SYMMETRIC
main()
int A[10];
int largest,position;
int num,i;
scanf(“%d”,&num);
scanf(“%d”,%A[i]);
largest = A[0];
largest = A[i];
position = i;
OUTPUT :
1 6 7 3 9 7
main()
scanf(“%d”,&num);
scanf(“%d”,%A[i] );
scanf(%d”,&item);
if (item== A[i] )
OUTPUT:
4 9 2 8 3 7 1
main()
int low,high,middle,i,item,n,a[20];
scanf(%d”,&item);
scanf(“%d”,&n);
scanf(“%d”,&a[i] );
low =1;
do
else
low = middle + 1;
if(item == a[middle] )
else
OUTPUT:
3 6 8 10 11 12 13 60
6 is found at position 2
UNIT - II
UNIT INTRODUCTION
In this unit, you are introduced to some of the fairly advance, but still frequently used
concepts of functions, structures and files.
Quite often, the program will not be a single entity. It may have been written in
different " modules", may be even by different people and different types. But, still, we
should be able to combine these modules into a program and execute them. Obviously, such
a scenario demands some sort of discipline in writing each of these modules. Each of them
can be written as a "function" and can be linked to one another and used. We learn to write
and use such functions.
Structures are complex data structures - like the marks scored by a student in different
subjects or the personal details of a credit card holder. To hold such (often
non-homogeneous ) data. We define the concept of structures.
So far, we have been using Scanf & Printf as input & output. I.e whenever we need to
input data, you do so using the keyboard and watch the output on the screen. But this cannot
happen always - especially when the data being handled is huge or when we need it to be
presented for later use. Alternatively, we can save such data in files and use them whenever
we need them. So, we learn how to create and manage such files.
BLOCK I
FUNCTIONS
Block Introduction
There are a number of situations wherein the program is too complex to be visualized
as one single unit. We would rather divide it into a number of smaller tasks, write small
programs to each of them & combine them. In fact each of them may be written by different
people, using their own (local) variable names etc.. Each such unit can be called a function.
They may all be linked and executed.
Such a scenario has two more advantages. One- if a program is to do the same
function repeatedly - say it has to arrange numbers in ascending order in 5 different places -
you need not include the code in all those places - just call the function from these five
places.
Secondly - you need not even write the functions in the first place. If somebody in
some other context has written the function - just use it. A concept used in the context of
library functions.
In this block, you are introduced to the concept of such functions - how to write them
& use them.
FUNCTIONS :
the result. The separate program segment is called a function and the program that calls it is
called a “main program”.
‘C’ went one step further, it divided the entire concept of programming to a
combination of functions. The scanf(), printf(), main() etc.. that we have seen are all
functions. C provides a lot of library functions, in addition you should be able to write your
own functions & use them.
/* This function finds the Greatest Common Divisor of two nonnegative integer values */
gcd (u,v)
int u,v;
int temp;
while( v!=0)
temp=u%v;
u=v;
v=temp;
printf("%d\n",u);
main()
gcd(150,35);
gcd(1026,405);
gcd(83,240);
OUTPUT:
/* This function finds the Greatest Common Divisor of two nonnegative integer values and
returns the result */
gcd (u,v)
int u,v;
int temp;
while( v!=0)
temp=u%v;
u=v;
v=temp;
return (u);
main()
int result;
result=gcd(150,35);
result = gcd(1026,405);
OUTPUT:
float x;
if (x < 0)
x=-x;
return(x);
main()
float result;
result=absolute_value(f1);
printf("f1 = %.2f\n",f1);
printf("result = %.2f\n",result);
result=absolute_value (float) il );
OUTPUT:
Result = 15.50
F1= -15.50
Result = 25.00
Result = 716.00
1.50
In each of these cases, the concept is very simple. Each function is given a name and
a list of parameters. Whenever you want the function to be called, refer to the function name
with a suitable list of arguments. The next line of program executed will be not from the
main execution, the control comes back to the main, to the place where it was called
function
Main()
Function call
But there is no restriction that the main only should call a function. A function can
call another, that another and so on. See figure below:
Function 1 function 2
Main()
( 1) (2)
Function 2
Function1
(4)
float x;
if (x < 0)
x= -x;
return (x);
float x;
OUTPUT:
Now we look into certain terminology encountered w.r.f functions each function is
given a name. It can be any valid variable name. This is called a function declaration. Also
zero or more number of arguments to the function. They are similar to variables, but are used
to transfer values to the function. Often they are called formal parameters. Formal
parameters will also have to be declared inside the function.
In addition several variables are needed for the function. They are declared just like
any other variable. They are called automatic local variables, because (i) They are local:
their effect is limited to the function. (ii) They are automatic since they are automatically
created whenever the function is called. Also their value can be accessed only inside the
function, not from any other function ( some authors also use "auto" to indicate that they are
automatically created).
Again each function should also return back one/more values, the statement return
(expression ) does the job. However, the type of value that the return expression returns (int,
char or float) will also have to be indicated in the name of the function (like int gcd(), float
convert() etc.. ). If, however, no such declaration is made, the function is expressed to return
a int value.
If the function does not return any value, it is called a void function and should be
indicated so. (void main() for example)
However, there is a small problem, since any function can call any other function, it is
also possible that a function which is not yet defined can be used. (see example). In that case
the compiler presumes that the called function returns only int values, even if
Float function 2( )
In this
order
Function 2 Function 2
Returns Returns
Float value Float value
Returns a float?
To overcome this, it is desirable to declare before, how that function 2 return float
(as shown)
minimum_value = values[i];
return (minimum_value);
main()
scanf("%d",&scores[i]);
OUTPUT:
Enter 10 scores
69
97
65
87
69
86
78
67
92
90
Minimum score 65
Sorting:
Sorting is a very popular activity in programming, which essentially arranges a set of
given numbers in ascending/ descending order. One simple way is to simply keep finding the
smallest number one after another and put them in another array ( using the previously
defined method). However, more efficient method are available one of them is called the
exchange sort method.
Here we begin comparing the first element with the second. If the first is smaller than
second, we leave them as it is, otherwise, we "swap" then (i.e interchange them). Next
compare the first element with the third. Again if the first one is smaller, leave it as it is,
otherwise swap the first and third element. This way, if we keep comparing the first element
with all other elements ( and keep swapping if necessary) at the end of the iterations, we end
up with the first element being the smallest of elements.
Now, we can repeat the same with the second element and all other elements; third
element and all other elements etc.. In the end, we will be left with an array in which the
numbers are in ascending order.
Step1: set i to 0
Step2: set j to i + 1
int a[];
int n;
int i,j,temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
main()
int i;
printf(%d",array[i] );
printf("%d", array[i] );
printf("\n");
OUTPUT:
34,-5,6,0,12,100,56,22,44,-3,-9,12,17,22,6,11
-9 -5 -3 0 6 6 11 12 12 17 22 22 34 44 56 100
int scalar;
int row,column;
int row,column;
printf("%5d", matrix[row][column] );
printf("\n");
main()
{ -2, 1, 2, 4, 9 }
};
display_matrix (sample_matrix);
printf("\nMultiplied by 2: \n");
display_matrix (sample_matrix);
display_matrix (sample_matrix);
OUTPUT:
Original matrix:
7 16 55 13 12
12 10 52 0 7
-2 1 2 4 9
Multiplied by 2:
14 32 110 26 24
24 20 104 0 14
-4 2 4 8 18
4 -2 -4 -8 -18
i) Make that variable Global. i.e define them before all functions. Then their vlues will
be available from all the functions and they can be accessed from any of the functions.
Example: #include<stdio.h.
Int a,b,c;
Main()
function()
etc..
Here. a,b,c are global variables and can be accessed from the main as well as all other
functions.
ii) The second method is to call them static in the function in which it is used.
Example:
#include<stdio.h>
main()
function1()
static int a
- --- -
- --- -
Here, the scope of the variable a is only for the function1. I.e. it’s values cannot be
accessed from any other function. However, when we next time come back to function 1, the
previously computed value of a is found to be retained.
Recursive functions
The factorial of a number is defined as the product of all integers from 1 to that
number.
Represented as 4! = 4 x 3 x 2 x 1 = 24
And 5! = 5 x 4 x 3 x 2 x 1 = 120
fact= fact * I;
5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2! And
2! = 2 x 1!
But 1! Is known, it is 1.
n! = n * (n-1)! Until we strike 1, then we can evaluate the factorial of any number n.
This can be done, if a function, when called with an argument n, repeatedly calls itself with
(n-1) until the value of (n-1) reaches 1. ( This value =1 is called the terminating condition).
int n;
if (n == 0)
result = 1;
else
return (result);
main()
int j;
OUTPUT:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10!=3628800
Though in this case, the advantage of using recursive functions, may not be obvious at
first sight, there are situations, when a recursive function reduces the complexity of program
writing significantly.
#include<stdio.h>
main(0
int i,n;
int fibonacci(int,i);
scanf(“%d”,&n);
printf(“%d\n”,fibonacci(i) );
} /* end of main() */
if (( x== 1) || (x = = 2))
return(1);
else
return(fibonacci(x-1) + fibonacci(x-2));
} /* end of fibonacci() */
OUTPUT:
13
21
34
#include <stdio.h>
#include<math.h>
main()
unsigned num1,num2;
gcdnum = i;
return gcdnum;
OUTPUT:
GCD of 25 and 10 is = 5
GCD of 47 and 10 is = 1
GCD of 16 and 64 is = 16
#include <stdio.h>
#include<math.h>
main()
int num;
printf("\nEnter an integer:");
scanf("%u",&num);
if(num < 0)
printf("Invalid entri\n");
else
if (isprime(num))
else
return 1;
sq = sqrt((double)num);
if (num % index = = 0)
return;
return 1;
OUTPUT:
Enter an integer 15
Enter an integer: 29
29 is a prime number
#include<stdio.h>
#include<math.h>
main()
unsigned index,pcnt=0;
int max;
scanf("%u",&max);
if(max < 0)
if (isprime(index))
printf("%u\n",index);
pcnt++;
return1;
sq = sqrt((double)num);
if num%index = = 0)
return 0;
return 1;
Number of primes = 5
#include <stdio.h>
main()
/* Variable declaration */
int n,r;
double val1,val2;
scanf(%d%d",&n,&r);
val1 = factorial(n)/factorial(n-r);
printf("%d!/(%d-%d)! = %d1f\n",n,n,r,val1);
unsigned i;
double fact = 1;
fact = fact * i;
return fact;
OUTPUT:
10!/(10-2)! = 90.000000
10!/10-2)! 2! = 45.000000
5!/(5-3)! = 60.000000
5!/5-3)! 3! = 10.000000
3!/(3-2)! = 6.000000
3!/3-2)! 2! = 3.000000
BLOCK II
STRUCTURES
There are occasions wherein the data we are handling is fairly complex - both in
numbers & in nature. Items like the marks of a student etc.. can be managed with multi-
dimensional arrays. But the problem with arrays is that they can handle only uniform type of
data - all integers, all reals etc. In cases where this is not the case - say the personal details
of an employee - his name is a string, age, salary etc.. are integers; address is a combination
of strings & integers etc. arrays cannot be used. In such situations, we use the concept of
structures. Each field of a structure can be of a different data type. We learn how to declare
& use such structures in this block.
STRUCTURES
We have learnt to create group elements of the same type into a single logical entity-
arrays. If it looks like a jargon, consider this, the variables are being put in a group, they are
referred by a single name - and importantly they were all of the same type. Either all were
integers, all floats etc.. what if we want to group different types of items into one logical
entity say day, month and year to be called the date? Further what if we want to group these
elements into bigger entities?
Consider the following example: every date is made up of 3 parts day, month and
year. Day is an integer, month is a string of character and year an integer. Now suppose, we
want to declare date of birth, date of joining service, date of marriage etc.. each of them are
similar to the variable date - each having a day which is an integer, a month which is a string
of character and year, an integer.
C provides a nice way of declaring and managing such situations. It makes use of a
concept called structure.
Struct date
int day;
char month[3];
int year;
};
This means date is a structure - it has 3 parts - an integer called day, a character string
of 3 elements called month and another integer called year.
Now we can declare date of birth as a structure of the type date structure date
date_of_birth.
And soon.
We can use these as if they are variable names. A few examples will clarigy their
usage.
main()
struct date
int month;
int day;
int year;
};
today.month =9;
today.day = 25;
today.year = 1988;
OUTPUT:
Let us say you have an array class with 20 elements each elements pertaining to a
student of that class. Now, extending the previous example, I can store the dates of birth of
these 20 students, by saying
Suppose I want to find the month of birth of 10th student, I can ask
Birthdays[9].month
Birthdays is the array, 9 indicates it is the 10th student(note that indices start from 0)
and ,month indicates that we are referring to the month.
0 1 2 19
-------- -- -- -
Now suppose we want to store the number of days in each month of the year and take a print
out. The program looks something like this
struct month
int number_of_days;
char name[3]]
};
main()
int i;
months[i].name[0],months[i].name[1],
months[i].name[2],months[i].number_of_days);
OUTPUT:
----- ------------
Jan 31
Feb 28
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 31
Sep 30
Oct 31
Nov 30
Dec 31
In fact, there is some flexibility allowed in the declaration of structure type. Instead
of first declaring the structure and then indicating the element name, they can be included in
one statement
For ex:
Struct date
{
int day;
char month[3];
int year;
date_of_birth, date_of_marriage;
}
BLOCK - III
FILES
Files are one of the most useful concepts in programming. Infact the use of computers
in data processing would not have picked up but for the concept of files.
Since the number of inputs that can be given through the keyboard is limited because
of obvious reasons - it is desirable to store them somewhere ( in the computer memory itself)
and ask the computer to take the input from that place. This is the concept of files ( of
course, files need not always contain only data but still the concept holds). The other
inherent advantage is that the output can also be in another file - which in turn can be
accessed by a second program and so on.
FILES
Quite often, it becomes necessary to manipulate large amounts of data, which cannot
be typed manually through the keyboard. It may also be possible that the output of one
program becomes an input to the other. In such cases, the data are simply stored in files.
Files are what they mean in normal English – they just hold data. Each file is given a name.
Instead of asking for the input from the keyboard, the program simply opens the files and
reads them. Similarly one can ask the program to write it into a file. Obviously this will be a
much faster & more accurate method. It also has another advantage. As we have seen above.
If the output of one program is to become the input to the other, one program will write into
the file and the other will read from it. Such files can also be copied into floppies and
transported.
All this to simply indicate that files can be extremely handles when dealing with large
amounts of data.
Now to the creation of files, every file is given a file name. The data is entered
separately, or it can be even a blank file, into which data is written by the program.
Depending on what operation is done on the program, the file has to be “ opened”.
You cannot operate on the file until it is opened. A file can be opened for one of the three
basic operations – to read data from it, to write data into it or to attach additional data it.
There modes are called read, write and append modes respectively indicated by the letters r,
w and a. The opened files are assigned to a file pointer.
The second line indicates that infile is a pointer to a file. Each file that is being used
by the program should have a separate pointer.
The next line opens a file called “ exam” in the read mode and assigns it to the infile.
(fopen() is a library function used to open files and every files has to be opened in one of the
three modes before it can be used). Now, we can read the contents of the file with commands
similar to scanf() & printf(). The corresponding commands are fscanf & fprintf.
Wherein the integer marks read is stored in the variable marks. Now compare this
with the format of scanf.
The difference is only fscanf instead of scanf & the filename appearing in the
beginning. Otherwise it is the same. The reason is that the compiler considers scanf as a
special case of fscanf. When scanf is used, it presumes that the filename is not necessary but
the input is from the standard i/o file namely the keyboard.
Similarly to write into a file, you open the file in the write mode, and use appropriate
fprintf statements. If you open an existing file in the write mode, the file is overwritten. i.e
the existing data in the file is lost. If this is to be over come, the file should be opened in the
“append” mode. Then the new data is not written “ over” the existing data, but is attached to
the end of the file.
To read or write single characters, just as we have getchar & putchar in normal i/o
mode, we have get c & put c in the file mode.
Each existing file will be marked with a EOE (end of file) in the end which indicates
that the file has ended, and this is useful while reading the file. While writing, the EOF is
automatically attached to the file.
Once all operations are the file are over, it should be closed using a fclose(filename)
command. A program successfully terminates only if all it’s files are closed properly.
Before we start practicing the programs one more information if a file called for
writing into is not existing, the system automatically creates it. However, if a non existent
file is called for reading, it declares an error.
Now let us see a simple program that reads an input file character by character and
unites into another file. The file names of both the files are given at run time.
#include<stdio.h>
main()
{
char in_name[25], out_name[25];
FILE *in, *out;
int c;
printf(“Enter name of file to be copied: ”);
scanf(“%24s”, in_name);
printf(“Enter name of output file:”);
scanf(“%24s”, out_name);
if ( ( in = fopen (in_name, “r”)) = = (FILE *) NULL)
printf(“Couldn’t open %s for reading.\n”,in_name);
else if ( (out = fopen (out_name, “w”)) = = (FILE *) NULL)
printf(“Couldn’t open %s for writing.\n”,out_name);
else
{
while ( (c = getc (in)) !=EOF)
putc (c,out);
printf(“File has been copied.\n”);
}
}
OUTPUT:
Enter name of file to be copied: copyme
Enter name of output file: here
File has been copied.
UNIT – III
UNIT INTRODUCTION
In this, unit, we look at some of the really advanced features of C. In fact some of
them have made C standout as a programming language of a different stature.
The first one is the concept of pointers. Instead of always indicating a variable by its
name, you can indicate it by it's address what is called a " pointer" to the variable - Though at
first it appears fairly complex - why should we complicate the matters by including one more
level of abstraction? - we will see shortly that it is a fairly powerful method with several
options.
The second concept is about bitwise operaters. We know that computers store and
manipulate data in terms of bytes. But often - in certain situations like in system
programming for ex:- We will be interested to know what each bit contains things like
whether the 4th bit is a 1 or 0 may be needed as also certain operations on these bits. The
second block of this unit deals with such bitwise operations.
Another important ability of C is its preprocessing. These are certain user friendly
commands that Unix provides for the benefit of it's users. You see some of them and their
usefulness in the unit.
BLOCK – I
POINTERS
UNIT INTRODUCTION
Instead of always indicating a variable by its name, you can indicate it by it's address
what is called a " pointer" to the variable - Though at first it appears fairly complex - why
should we complicate the matters by including one more level of abstraction? - we will see
shortly that it is a fairly powerful method with several options.
POINTERS
Pointers are one of the very powerful & special features of C. It simply means
instead of using a variable name, you use a pointer ( or indicator) to it. At a simple level, it
can be thought of as an
A A B
10 10
address to the variable. The above figure illustrates the feature. In a variable A, the value 10
is stored. Now to access this, you can ask for variable A. On the other hand, you can ask for
a pointer like B, shown in fig(ii). If you say B is of the pointer type, then you are actually not
interested in the contents of B (which indicates where A is there), but using them you come
back to A.
It is like, say, if you are interested in going to a place, you can either know where that
place is (normal variables) or know a person who in them knows where the place is situated
(pointer variables). Some others also call this " indirection ". You are approaching A
indirectly, through it's pointer B/
At this stage, one question is likely to arise. Why should we go about this round
about way, instead of directly going to the variable. One advantage is as in the case of single
variables, it is easier to work with normal, direct variable names. But, when you are using
large chunks of data, it is easier to work with pointers. Like say when you have 100 items in
an almirah, it is easier to handle a key to the almirah ( a pointer ) rather than the individual
items. if you want to hand over these items to someone, it is easier to hand over the key,
rather than each of the individual contents. Such situations arise, when we are passing
parameter to a function and back. It is easier to pass the pointers to the function, than each of
those individual items.
These are other advantages also, which become evident as we processed through this
chapter. Before that, we see the general format of the pointer variable.
Now, we have to define one more variable, which is a pointer to A, say B (see the fig
above). To distinguish that A is an actual variable and B is a pointer, we indicate B as
int *B
The asterisk * indicates that B is of the type pointer. Now to finally indicate that B
points to A, we write
B= &a
i) Declare A as a variable
X = *B.
Then the control goes to B, takes it’s contents as a pointer to A then goes to A and
gets the contents.
main()
int *int_pointer;
int_pointer = &count;
x = *int_pointer;
OUTPUT:
Count = 10, x = 10
Pointers need not always point to integers only. See the following program
main()
char c = ‘ Q ‘;
c = ‘/’;
*char_pointer = ‘(‘;
OUTPUT:
/ /
( (
/* more on pointers */
main()
int il,i2;
il = 5;
p1 = &il;
i2 = *p1 / 2 + 10;
p2 = p1;
OUTPUT:
These concepts are extremely simple but are very useful and you have to be fully
confident of their usage.
Pointers can be used just like normal variables for arithmetic operations for example
if you want to add 10 to a value pointed to by prt1 (where ptr1 is a pointer variable),
we simply write
*ptr1 = *ptr1 + 10
Pointers to arrays:
When an array of say 100 elements is declared, the compiler creates a storage
of 100 consecutive locations, say starting form 1000. If A[ 0 ] = 1000, a[I]=1000+1;
A[2]= 1000 +2 etc.. i.e the addresses of the first element a[ 0] is called the base
address, to which the location of the element which is required ( 1,2 ….. ) ( which is
called the offset is added to get the actual address. We can as well pass a pointer to
the base address of the array.
*ptr
int array_sum(array,n)
int array[];
int n;
sum += *ptr;
return (sum);
main()
OUTPUT
The sum is 21
Just to become familiar with the various operations using strings, we write down a
few programs that necessarily operate on strings.
char from,to;
*to = *from;
*to = ‘\0’;
main()
copy_string(string1, string2);
printf(“%s\n”,string2);
copy_string(“So is this.”,string2);
printf(“%s\n”,string2);
OUTPUT:
A string to be copied
So is this.
#include<stdio.h>
main()
char a[80];
int n;
gets(a);
n=str-len(&a);
/* END OF MAIN */
/*FUNCTION str-len*/
str_len(s)
char *s;
int i=0;
while (*s!='\0')
i++;
s++;
retrun(i);
OUTPUT:
ENTER A STRING :
Hi! How are you and how are your studies going on ?
OUTPUT:
Write a program to count number of vowels, consonants, digits, blank-space characters and
other characters in a line of text entered form the keyboard.
#include<stdio.h>
main()
char line[50],s;
void scan-line();
scanf("%[^\n]",line);
scan-line(line,&v,&c,&d,&ws,&other);
/* END OF MAIN */
/*FUNCTION scan_line */
char line[ ];
int pv,pc,*pd,*pws,*pother;
char s;
int count=0;
while((s=toupper(line[count])) !='\0')
++*pv;
++*pc;
++*pd;
++*pws;
else
++*pother;
++count;
OUTPUT:
Numbers of Vowels : 14
Number of Consonants:22
Number of digits: 1
Write a program to copy the contents of one string to another string using pointers.
#include<stdio.h>
main()
gets(a);
printf("\n");
strcopy(&a,&b);
output(&b);
/*FUNCTION MAIN */
strcopy(s,d)
char *d,*s;
while (*s!='\O')
*d = *s;
d++;
s++;
*d++ = '\O');
/*FUNCTION output */
output(s)
char *s;
while(*s!='\O')
printf("%c",*s);
s++;
OUTPUT:
#include<stdio.h>
main()
char a[80],b[80],c[160];
gets(a);
gets(b);
stringcat(&a,&b,&c);
output(&c);
/*END OF MAIN */
/* FUNCTION stringcat */
stringcat(s1,s2,d)
char s1,s2,*d;
while(*s1 !='\O')
*d = *s1;
d++;
s1++;
while (*s2!='\O')
*d = *s2;
d++;
s2++;
*d ='\O';
/*FUNCTION output */
output(s)
char *s;
while (*s!='\O')
printf("%c",*s);
s++;
OUTPUT:
Pointers and structures : Pointers can also be used in structures. We have seen,
previously, the “ date” structure as follows:
Struct date
int month;
int day;
int year;
Then, we can go on to access, say the month of the birthday by saying (*date
pointer),month
We see an example
main()
struct date
int month;
int day;
int year;
};
date_pointer = &today;
date_pointer ->month = 9;
date_pointer->year %100);
OUTPUT:
Date_pointer
.month 9
Today .day 25
.year 1988
This was about pointers to structures. We can also have pointers in structures. i.e the
structure elements themselves can be pointers. Something like
int *p1;
int *p2;
};
main()
struct int_pointers
int *p1;
int *p2;
};
int il = 100,i2;
pointers.p1 = &i1;
pointers.p2 = &i2;
*pointers.p2= -97;
OUTPUT:
LINKED LISTS
The concept of linked lists is one of the powerful features in C. It will also bring to
you some of the powerful features of pointers.
Now let us go back to the arrays we have previously said that if an array of 100
elements are is to be declared, the compiler catches hold of 100 consecutive memory
locations and marks them as the elements of the array. Whenever an element is to be visited,
it’s address is calculated based on the offset from the base element ( see the previous section )
We have not addressed one or two other issues with the arrays. Let us say, suppose,
we want to rename the 20th element & shift the other elements back.
A[20] 21 22 - - - - - -
Then what we have to do is to shift the 21st element to 20th location. 22nd element to
21st location etc.. etc.. suppose the array is 1000 elements long. It is still possible, but takes
enormous amount of effort.
Similar is the case, if we want to insert an element we have to push the 1000th element
to ( 1001th place ( if there is space) and push 999th to 1000th place etc.. And if the array is
just declared as only a 1000 element one, then we cannot do the operation all. We have to
create a new array, ( a longer one) and copy these elements to the new one.
i.e if, before hand, we are not sure of the actual size of the array elements, it is
difficult to manage the array.
All these difficulties lead us to the concept of “ desnamic ” allocation. (Arrays are
supposed to be static: you declare them at one time, that is it). Look at the following the
figures. A is an array with 5 elements.
Now I cannot add a new element to this, because of the reasons described above, I can
delete an element, but it needs some effort on my part.
10 20 30 40 50 NIL
The second is what is called a “ linked list” a list of linked elements. Each “ node”
has 2 elements one is a data element and the other a pointer to the next node. Your
knowledge of structures should immediately indicate to you that this can be declared as a
structure. Once done, go back to the difficulties of using arrays, which we had listed above.
Because we are using pointers, the nodes need not be consecutive. We need not even know
before hand how many nodes we need. As and when we want to add new elements, we can
keep creating new nodes and keep connecting them using pointers.
10 20 30 40 50 X
35 New node
i.e create a new node, make the pointer of node 3 point to new node and make the
pointer of new node and make the pointer of new node point to node4.
Similarly, if we want to delete node2, all that we have to do is to make the pointer of
node1 point to node3.
The following examples illustrate how to create & traverse such linked lists.
/* linked lists */
main()
{
struct entry
{
int value;
};
int i;
n1.value = 100;
n2.value = 200;
n3.value = 300;
n1.next = &n2;
n2.next = &n3;
i = n1.next->value;
printf (“%d “,i);
printf(%d\n”, n2.next->value);
OUTPUT
200 300
/* List traversal */
main()
struct entry
int value;
};
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
OUTPUT
100
200
300
In fact, these is a lot of literature available on linked lists, but we stop at this stage and
move on to the other use of pointers.
Now, consider the very simple problem of interchanging two integer values. Suppose
A is storing 5 and B is storing 10, after exchanging A should hold 10 and B should hold 5
obviously another temporary location, temp, is used to hold one of the values, while
interchanging is taking place.
int temp;
temp = *pint1;
*pint1 = *pint2;
*pint2 = temp;
main()
exchange(p1,p2);
exchange(&i1, &i2);
OUTPUT
i1 = -5, i2 = 66
i1 = 66, i2 = -5
i1=-5, i2 = 66
Now consider a more complicated program. The function here searches for a
particular value in a linked list. If it is found, it returns a pointer to the node holding the
value. Otherwise it returns a null pointer.
struct entry
int value;
};
int match_value;
if (lpointer->value = = match_value)
return (lpointer);
else
lpointer = lpointer->next;
main()
int i,search;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
scanf(“%d”, &search);
printf(“Found %d\n”,lptr->value);
else
printf(“Not found.\n”);
OUTPUT
Found 200.
Found 300.
In fact the concept of pointers can keep expending to any extent, you can have an
array of pointers. For example in a class there are 30 students. You have store their names.
While the no. of students is constant at 30, the no. of characters in their names is variable.
Then the simplest thing is to create an array of pointers of size 30, each pointing to a linked
list of one name.
However, we conclude the discussions of pointers at this stage and move on to the
next topic.
BLOCK II
BITWISE OPERATORS
Block Introduction
We know that computers store and manipulate data in terms of bytes. But often - in
certain situations like in system programming for example, we will be interested to know
what each bit contains. Things like whether the 4th bit is a 1 or 0 may be needed, as also
certain operations on these bits. This Block deals with such bitwise operations.
BITWISE OPERATORS
We know that computers operate on one byte at a time i.e. 8 bits of data a
manipulated as one unit. However, these are situations wherein we may need to know and
operate on individual bits, like say depending on whether the 5th bit is 1 or 0, some operations
have to be done. Such situations occur in several applications, like in systems programming.
'C' provides facilities for such operations.
-----------------------------------------------
Symbol Operation
------------------------------------------------
| Bitwise Incluseive-OR
^ Bitwise Exclusive-OR
~ Ones Complement
--------------------------------------------------
For these not familiar with boolean algebra, a brief description of the above operations
follows.
Bitwise AND: this operation on 2 bits. When both bits are 1, the output is one, otherwise it is
Zero.
00001110
00001100
-------------
Result 00001100
-------------
Bitwise inclusive OR: This also operates on two bits. The output is 1 if either of the two bits
is 1, otherwise it is 0.
Consider 10011010
01100011
---------------
---------------
Bitwise Exclusive OR : This operation returns a 1 if either of the two bits (but not both) is a
1.
The ones complement : This works on a single number and simply converts each 1 to 0 and
each 0 to 1.
10010010
The left shift operator: this also works on single number. Each bit of the number is shifted
one bit to it's left. The left most bit is lost and the right most bit, that becomes vacant is filled
with a 0.
Consider 00101000 = 40
Note also that a left shift operation results in the number getting multiplied by 2.
This the reuses of the left shift operator. It just shifts each bit one place to it's right.
The rightmost bit is lost, the left most bit is made 0.
00101000 = 40
becomes 00010100 = 20
Though the concepts presented are simple, we write one program that uses the concept.
Write a program to rotate a given number called value a given number of times, n. If n is
positive rotate it left, otherwise right.
[ Note: Rotation means shifting each bit by one place and recovering the lost bit. For ex. In
left shift, each bit is shifted one place to the left and the leftmost bit, which comes out is
returned to the right most place.]
int n;
return (value)l
n=-n;
else
n= -n;
return (result);
main()
1b5a
5a1b
22ff
bfc8
alb5
BLOCK III
THE PREPROCESSOR
Block Introduction
Another important ability of C is its preprocessing. These are certain user friendly
commands that Unix provides for the benefit of it's users. You see some of them and their
usefulness in the Block.
THE PREPROCESSOR
This is one of the special features available in C, but not found in many other
languages. The preprocessor is a part of C-compilation process that recognizes special
statements (that may be found anywhere in the program) and takes appropriate action(s). The
programmer can use these special statements to make his program easier to read and
modifications, customise or write easily transportable programs. Each preprocessor
statement is identified by a # sign, which must be the first character of the line.
We shall briefly see some of the preprocessor statements and their uses.
The define statements : This is one of the most popularly used C preprocessor statements,
with multiple users. The format I something like
#define TRUE 1
# define false 0
Once this is done, throughout the program, you can use True wherever constant 1 is to be
used and false where 0 is to be used. Note that they can be used only as constants and not
variables. For example we can not add 1 to True etc.
All that the preprocessor does is to scan through the program and replace True with 1 and
false with 0, so that the C compiler can understand them.
You may ask why it is needed at all. Quite often, we need to take decisions based on whether
something is true or false. Unlike other languages (like Pascal, for ex.) C does not have
Boolean variables that can be set to true or false. In such a case, the programmer has to
artificially remember to replace true with 1 and false as 0 (or any other combination for that
matter) and write the program. This may lead to confusions or mistakes. Thus by defining
them in the beginning and then writing the program in the way we think. We will be able to
write better programs. We see an example to classify the simulation.
#define TRUE 1
#define FALSE 0
int number;
int answer;
if (number % 2 = = 0)
answer = TRUE;
else
answer = FALSE;
return(answer);
main()
if (is_even(17) == TRUE)
printf("YES");
else
printf("NO");
printf("YES\n");
else
printf("NO\n");
***Output
NO YES
Now, going back to the format, we specifically insisted that no semicolon should be there
after define. This is because the preprocessor blindly replaces the True value with 1 and false
with 0. Suppose we have written
# define True 1 ;
Then in the place where the statement answer = True; appears, True gets replaced by
1; so the compiler sees a statement answer = 1;; which is invalid. Hence no semicolons
should appear in define.
i) Program extentability : suppose you have written a program which has something to
do with 1000 students. So, your array is of the size 1000, these may be a number of
for loops which terminate at 1000 etc. now, after sometime, the number of students
increases to 1500. Then wherever 1000 appears, you have to change it 1500. This is
easier said than done. You are bound to miss some commit errors etc. An easier
method is to simply define no of students as 1000.
# no_of_students 1000
and wherever 100 is to be used to indicate the students, use the constant
no_of_students like for
(i=0;i<no_of_students;++i)
Whenever the number of students change, we can change only the define statement
and not throughout the program.
Program Portability :
Certain parameters are machine dependent, like the maximum integer you can store
etc. when you go from a 16 bit machine to a 32 bit machine or viceversa, you have to change
them. Instead, you can use a define statement like
#define wordlength 16 , and when you go through a 32 bit machine, simply change the
statement.
Simple Functions: Define need not always be simple numbers. It can be pointers or even
simple equalians consider #define square(s) x*x
This would same almost as a library function and whenever we write say
Consider one more interesting case. You have to check whether a particular year is a leap
year and then take some decisions. Then, wherever we have to check for leap year, we
should write if (year%4 == 0) && (year%100!=0 || year % 400 == 0).
Since define statement s can be used as definitions, they are often called "macros", a form
used for expandible assembly language functions.
If you keep writing a large number of C porgrams, you realise that certain define
functions are needed again and again. Instead of writing them in define functions in every
program, you can collect all of them in a file and include that file in the program.
Now you can have a clear concept of # include files we were using for input/output
functions. Only things stdio.h, math.h etc. file are provided by the system. But you can also
write your won files and include them using the include statement.