C Programming - Lecture Notes
C Programming - Lecture Notes
CCCJ
Module 1
Brief History of C
Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its
popularity as a programming language. Naturally we will be studying many of these aspects
throughout the course.
• Small size
• Extensive use of function calls
• Loose typing -- unlike PASCAL
• Structured language
• Low level (BitWise) programming readily available
• Pointer implementation - extensive use of pointers for memory, array, structures and
functions.
C - has now become a widely used professional language for various reasons.
Its main drawback is that it has poor error detection which can make it off putting to the
beginner. However diligence in this matter can pay off handsomely since having learned the
rules of C we can break them. Not many languages allow this. This if done properly and
carefully leads to the power of C programming.
C Program Structure
• Preprocessor Commands
• Type definitions
• Function prototypes -- declare function types and variables passed to function.
• Variables
• Functions
C Statements
Running C Programs
Editing
You type the program directly into any C or C++ Editor and save the file as <filename>.c. This is
often referred to as the source file.
Compiling
You cannot directly execute the source file. To run on any computer system, the file must be
translated into machine language. This process produces an intermediate object file – with the
extension .obj, the .obj stands for Object.
Linking
Why is linking necessary? The main reason is that many compiled languages come with library
routines, which can be added to your program. These routines are written by the manufacturer
of the compiler to perform a variety of tasks, from input/output to complicated mathematical
functions. In the case of C the standard input and output functions are contained in a library
(stdio.h) so even the most basic program will require a library function. After linking the file is
.exe which are executable files.
All pre-processor directives begin with a #. The commonest directive to all C program is:
#include <stdio.h>
Note the use of the angle brackets (<and>) around the header’s name. These indicate that the
header file is to be looked for on the system disk, which stores the rest of the C program
application.
Executing
The text editor produces .c source files, which go to the compiler, which produces .obj object
files, which go to the linker, which produces .exe executable file. You can then run .exe files.
A comment is a note to yourself (or others) that you put into your source code. The compiler
ignores all comments. Comments are used primarily to document the meaning and purpose of
your source code.
First C program:
main()
{
}
NOTE:
.1
..2
...3
Variables
On UNIX systems all ints are long ints unless specified as short int explicitly.
NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.
Defining Global Variables - Avoid the use of global variables when programming
short number,sum;
int bignumber,bigsum;
char letter;
main()
{
It is also possible to pre-initialise global variables using the = operator for assignment.
a=3;
b=3;
c=3;
d=3;
This kind of assignment is only possible if all the variable types in the statement are the same.
Reserved words and an example
C programs are constructed from a set of reserved words which provide control and from
libraries which perform special functions. The basic instructions are built up using a reserved set
of words, such as main, for, if, while, default, double, extern, for, and int, to name just a few.
These words may not be used in just any old way: C demands that they are used only for giving
commands or making statements. You cannot use default, for example, as the name of a
variable. An attempt to do so will result in a compilation error.
C requires all of these reserved words to be in lower case. (This does mean that, typed in upper
case, the reserved words could be used as variable names, but this is not recommended.)
auto d if
break int d
case long d
char d register d
continue return
default short d
do sizeof
double d static d
else struct
entry switch
extern d typedef d
float d union d
for unsigned d
goto while
enum d
void d
const d
signed d
volatile d
Words used in included libraries are also, effectively, reserved. If you use a word which has
already been adopted in a library, there will be a conflict between your choice and the library.
Libraries provide frequently used functionality and, in practice, at least one library must be
included in every program: the so-called C library, of standard functions. For example, the stdio
library, which is part of the C library, provides standard facilities for input to and output from a
program.
In fact, most of the facilities which C offers are provided as libraries that are included in
programs as plug-in expansion units. While the features provided by libraries are not strictly a
part of the C language itself, they are essential and you will never find a version of C without
them. After a library has been included in a program, its functions are defined and you cannot
use their names.
= assignment
== equality
do do while loop
{
}
while (..);
if (..) if statement
{
}
else
{
}
/* .... */ comments
struct record
Format Specifiers
Operators
x+= y means x = x + y
x-=y means x = x – y
x*=y means x = x * y
x/=y means x = x / y
== equal to
!= not equal to
Logical Operators
&& AND
|| OR
! NOT
Order of Precedence
(a + b) * c
or
a + (b * c)
All operators have a priority, and high priority operators are evaluated before lower priority
ones. Operators of the same priority are evaluated from left to right, so that
a-b-c
is evaluated as
(a-b)-c
From high priority to low priority the order for all C operators (we have not met all of them yet)
is:
( ) [ ] -> .
! - * & sizeof cast ++ -
(these are right->left)
*/%
+-
< <= >= >
== !=
&
|
&&
||
?: (right->left)
= + = - = (right->left)
, (comma)
Thus
is interpreted as
( a < 10 ) && ( ( 2 * b ) < c )
The ? operator
The ? (ternary condition) operator is a more efficient form for expressing simple if statements.
It has the following form:
It simply states:
z = (a>b) ? a : b;
if (a>b)
{
z = a;
}
else
{
z=b;
}
Consider the following example where we read in integer values and process them according to
the following conditions. If the value we have read is negative, we wish to print an error
message and abandon the loop. If the value read is great than 100, we wish to ignore it and
continue to the next value in the data. If the value is zero, we wish to terminate the loop.
if (value < 0)
{
....;
} /* end while value != 0 */
MODULE 2
FUNCTIONS
Functions
Functions are easy to use; they allow complicated programs to be parcelled up into small
blocks, each of which is easier to write, read, and maintain. We have already encountered the
function main and made use of I/O and mathematical routines from the standard libraries. Now
let's look at some other library functions, and how to write and use our own.
Calling a Function
The call to a function in C simply entails referencing its name with the appropriate arguments.
The C compiler checks for compatibility between the arguments in the calling sequence and the
definition of the function.
Library functions are generally not available to us in source form. Argument type checking is
accomplished through the use of header files (like stdio.h) which contain all the necessary
information. For example, as we saw earlier, in order to use the standard mathematical library
you must include math.h via the statement
...statements...
return return-value;
}
If return-type is omitted, C defaults to int. The return-value must be of the declared type.
A function may simply perform a task without returning any value, in which case it has the
following layout:
...statements...
}
void main()
{
int n;
char string[50];
/* strcpy(a,b) copies string b into a */
/* defined via the stdio.h header */
strcpy(string, "Hello World");
Arguments are always passed by value in C function calls. This means that local ``copies'' of the
values of the arguments are passed to the routines. Any change made to the arguments
internally in the function are made only to the local copies of the arguments. In order to change
(or define) an argument in the argument list, this argument must be passed as an address,
thereby forcing C to change the ``real'' argument in the calling routine. This is called passing by
reference.
As an example, consider exchanging two numbers between variables. First let's illustrate what
happen if the variables are passed by value:
void main()
{ /* WRONG CODE */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(a, b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
void exchange(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", a, b);
}
Run this code and observe that a and b are NOT exchanged! Only the copies of the arguments
are exchanged. The RIGHT way to do this is of course to use pointers:
void main()
{ /* RIGHT CODE */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(&a, &b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
temp = *a;
*a = *b;
*b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", *a, *b);
}
Local Variable – are declared within a function. They are created anew each time the function
is called, destroyed on return from the function. Values are passed to the function as
arguments can also be treated like local variables.
Global Variables – don’t die on return from a function. Their value is retained, and is available
to any other function, which accesses them. Global variables may lead to side- effects and
therefore should be avoided.
Function Prototyping
Before you use a function C must have knowledge about the type it returns and the parameter
types the function expects.
The ANSI standard of C introduced a new (better) way of doing this than previous versions of C.
(Note: All new versions of C now adhere to the ANSI standard.)
Basically if a functions has been defined before it is used (called) then you are ok to merely use
the function.
If NOT then you must declare the function. The declaration simply states the type the function
returns and the type of parameters used by the function.
It is usual (and therefore good) practice to prototype all functions at the start of the program,
although this is not strictly necessary.
To declare a function prototype simply state the type the function returns, the function name
and in brackets list the type of parameters in the order they appear in the function definition.
e.g.
NOTE: Functions can be prototyped and variables defined on the same line of code. This used
to be more popular in pre-ANSI C days since functions are usually prototyped separately at the
start of the program. This is still perfectly legal though: order they appear in the function
definition.
Contains many useful functions to convert and test single characters. The common functions
are prototypes as follows:
Suppose we had a set of grades that we wished to read into the computer and suppose we
wished to perform some operations on these grades, we will quickly realize that we cannot
perform such an operation until each and every grade has been entered since it would be quite
a tedious task to declare each and every student grade as a variable especially since there may
be a very large number.
In C we can define variable called grades, which represents not a single value of grade but a
entire set of grades. Each element of the set can then be referenced by means of a number
called as index number or subscript.
Declaration of arrays:
Like any other variable arrays must be declared before they are used. The general form of
declaration is:
type variable-name[50];
The type specifies the type of the elements that will be contained in the array, such as int float
or char and the size indicates the maximum number of elements that can be stored inside the
array for ex:
float height[50];
Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid.
In C the array elements index or subscript begins with number zero. So height [0] refers to the
first element of the array. (For this reason, it is easier to think of it as referring to element
number zero, rather than as referring to the first element).
As individual array element can be used anywhere that a normal variable with a statement such
as
G = grade [50];
The statement assigns the value stored in the 50th index of the array to the variable g.
More generally if I is declared to be an integer variable, then the statement g=grades [I];
Will take the value contained in the element number I of the grades array to assign it to g. so if I
were equal to 7 when the above statement is executed, then the value of grades [7] would get
assigned to g.
A value stored into an element in the array simply by specifying the array element on the left
hand side of the equals sign. In the statement
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array.
The ability to represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the elements
in the array by varying the value of the variable that is used as a subscript into the array. So the
for loop
Will sequence through the first 100 elements of the array grades (elements 0 to 99) and will
add the values of each grade into sum. When the for loop is finished, the variable sum will then
contain the total of first 100 values of the grades array (Assuming sum were set to zero before
the loop was entered)
In addition to integer constants, integer valued expressions can also be inside the brackets to
reference a particular element of the array. So if low and high were defined as integer variables,
then the statement
Just as variables arrays must also be declared before they are used. The declaration of an array
involves the type of the element that will be contained in the array such as int, float, char as
well as maximum number of elements that will be stored inside the array. The C system needs
this latter information in order to determine how much memory space to reserve for the
particular array.
The declaration int values[10]; would reserve enough space for an array called values that could
hold up to 10 integers. Refer to the below given picture to conceptualize the reserved storage
space.
values[0]
values[1]
values[2]
values[3]
values[4]
values[5]
values[6]
values[7]
values[8]
values[9]
Initialization of arrays:
We can initialize the elements in the array in the same way as the ordinary variables when they
are declared. The general form of initialization off arrays is:
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element if the number
of values in the list is less than the number of elements, then only that many elements are
initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler allocates
enough space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. this approach works fine as
long as we initialize every element in the array.
Often there is a need to store and manipulate two dimensional data structure such as matrices
& tables. Here the array has two subscripts. One subscript denotes the row & the other the
column.
The declaration of two dimension arrays is as follows:
data_type array_name[row_size][column_size];
int m[10][20]
A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks
[0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.
Like the one dimension arrays, 2 dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,01,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done row
by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
date_type array_name[s1][s2][s3]…..[sn];
int survey[3][5][12];
float table[5][4][5][3];
Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a
four dimensional array containing 300 elements of floating point type.
/* example program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrix\n”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be added\n”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
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”,&a[i][j]);
printf(“\n”);
}
}
strcmp(string1, string2) – compare string1 and string2 to determine alphabetic order – returns
a value less than 0 if string1 is lexically less than string 2; zero if string1 and string2 are lexically
equal; greater than zero if string1 is lexically greater than string2.