CHAPTER 1- OVERVIEW OF C
History Of C:
What is C?
Features of C:
Program written in C are efficient and fast due to its variety of data types and
powerful operators. It is many times faster than BASIC.
E.g.: Increment of 0 to 15000 takes about 1 sec in C where as BASIC takes
about 50 sec.
C is highly portable. This means that program written on one computer can run
on another computer with little or no modification.
C language is well suited for structured programming, thus requiring the user to
think of a problem in terms of function modules or block.
Another important feature of C is its ability to extend itself. We can add user
function to C library.
Sample Program:
main( )
{
/* -------- Sample Program ----------
------------------------------------------
*/
printf( WelCome to Young World Computer Institute);
}//End of program
main( )
int main( )
void main( )
main(void)
void main(void)
int main(void)
The empty pair of parentheses indicates that the function has no arguments. This
may be explicitly indicates by using the keyword void inside the parentheses. We
may also specify the keyword int or void before the word main. The key word
void means that the function does not return any information to the operating
system and int means that the function returns an integer value to the operating
system. When int is specified, the last statement in the program must be return
0.
#include <filename>
Filename is the name of the library file that contains the required function
definition. Preprocessor directives are placed at the beginning of a program.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( ) Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function 1
Function 2
- (User Defined functions)
-
Function n
Character Set:
Letters:
Uppercase : A..Z
Lowercase: az
Digits:
All decimals digits 0.9
Special Characters:
White Spaces:
Blank space
Horizontal tab
Carriage return
New line
Form feed
ANSI C Keywords:
Constants:
CONSTANTS
After designing suitable variables names, we must declare them to the compiler.
Declaration does two things:
1. It tells the compiler what the variables name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
The syntax for declaring a variable is as follows:
v1, v2,..,vn are the names of variables. Variables are separated by commas. A
declaration statement must end with semicolon.
E.g.: int count;
int number, total;
double ratio;
Giving the values to variables is to input data through keyboard using the scanf
function. The general format of scanf is as follows:
1. Arithmetic operator
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% modulo division
2. Relational operator
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
3. Logical operator
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
4. Assignment operator
++ for increment
-- for decrement
The operator ++ adds 1 to operand, while subtract 1.
e.g.: ++m; or m++;
--m; or m--;
++m is equivalent to m=m+1; (or m+=1;)
--m is equivalent to m=m-1; (or m-=1;)
6. Conditional operator
7. Bitwise operator
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
8. Special operator
1. Implicit conversion
C uses the rule that, in all expression except assignments, any implicit
type conversions are made from a lower size type to a higher size type as
shown below.
long double
Conversion
Hierarchy double
float
long int
unsigned int
int
short char
2. Explicit conversion:
There are instances when we want to force a type conversion in way that
is different from the automatic conversion. That type of conversion is
called as Explicit conversion.
Example Action
x=(int) 7.5 7.5 is converted to integer by truncation
a=(int) 21.3/(int)4.5 Evaluated as 21/4 and the result would be 5.
b=(double)sum/n Division is done in floating point mode
y=(int) (a+b) The result of a+b is converted to integer
Formatted Output:
The printf statement provides certain features that can be effectively exploited to
control the alignment and spacing of print=outs on the terminals. The general
form of printf statement is
printf(%d,1234)
1 2 3 4
printf(%6d,1234)
1 2 3 4
printf(%2d,1234);
1 2 3 4 pr
printf(6d,1234)
1 2 3 4
printf(%06d,1234)
0 0 1 2 3 4
printf(%7.4f,y)
1 2 . 3 4 5 6
printf(%-7.2f,y)
1 2 . 3 5
printf(%7.2f,.y);
1 2 . 3 5
We use %f for float value, %d for decimal integer value, %c for character value
and %s for string value.
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
Simple if statement:
E.g.:
if ( category = = SPORTS)
{
marks = marks + bonus_marks;
}
printf(%f,marks);
if ( test expression)
{
True block statement(s)
}
else
{
false block statement(s)
}
statement x;
e.g.:
..
if ( code = = 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
printf(Good Bye);
.
.
if (test condition-1)
{
if(test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
e.g.:
if(gender == f)
{
if(balance > 5000)
{
bonus=0.05*balance;
}
else
{
bonus=0.02*balance;
}
else
{
bonus=0.02*balance;
}
balance = balance + bonus;
if ( condition 1)
statement-1;
else if( condition 2)
statement-2;
else if( condition 3)
statement-3;
else
default-statement;
statement-x;
e.g.:
if(marks > 69)
grade=Distinction;
else if(marks > 59)
grade=First Class;
else if(marks > 47)
grade= Second Class;
else if(marks > 34)
grade=Pass Class;
else
grade=Fail;
printf(%s\n,grade);
C has built-in multi way decision statement known as switch. The switch
statement tests value of a given variable (or expression) against a list of case
values and when a match is found, a block of statement associated with that
case is executed. The general form of switch statement is as shown below:
switch( expression)
{
case value-1 :
block-1;
break;
case value-2 :
block-2;
break;
.
.
case value-n :
block-n;
break;
default :
default block;
break;
}
statement-x;
e.g.:
switch(code)
{
case 1:
printf(RED);
break;
case 2:
printf(GREEN);
break;
case 3:
printf(BLUE);
break;
default:
printf(YELLOW);
break;
}
The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid variable name, and must be followed by a colon, The
label is placed immediately before the statement where the control is to be
transferred. The general forms of goto and label statements are shown below:
e.g.:
main ( )
{
double x, y;
read:
scanf(%f,&x);
if (x < 0)
goto read;
y=sqrt(x);
printf(%f %f\n,x, y);
goto read;
}
The test may be either to determine whether the loop has been repeated the
specified number of times or to determine whether a particular condition has
been met.
The test conditions should be carefully stated in order to perform the desired
number of loop executions. It is assumed that the test condition will eventually
transfer the control out of the loop. In case, due to some reason it does not do
so, the control sets up an infinite loop and the body is executed over and over
again.
The C language provides for three constructs for performing loop operations.
They are:
1. The while statement.
2. The do statement.
3. The for statement.
Sentinel Loops:
Based on the nature of control variable and the kind of value assigned to it for
testing the control expression, the loops may be classified into two general
categories;
1. Counter-controlled loops.
2. Sentinels-controlled loops.
When we know in advance exactly how many times the loops will be executed,
we use a counter-controlled loop. We use a control variable known as counter.
The counter must be initialized, tested and updated properly for the desired loop
operations. The number of times we want to execute the loop may be a constant
or a variable that is assigned a value. A counter-controlled loop is sometimes
called definite repetition loop.
often called indefinite repetition loop because the number of repetition is not
known the loop begins executing.
The simplest of all the looping structures in C is the while statement. We have
used while in many of our earlier programs. The basic format of the while
statement is
while(test condition)
{
body of the loop
}
e.g.: .
sum=0;
n=1; //Initialization
while( n <= 10) //Testing
{
sum=sum + n*n;
n=n+1; //Increment
}
printf(Sum=%d\n,sum);
.
..
The do statement:
The while loop construct that we have discussed a test of condition before the
loop is executed. Therefore, the body of the loop may not be executed at all if the
condition is not satisfied at the very first attempt. On some occasions it might be
necessary to execute the body of the loop before the test is performed. Such
situation can be handled with the help of the do statement. This makes the form:
do
{
body of the loop
}
while (test condition) ;
e.g.:
.
do
{
printf(Input a Number:);
number =getnum();
}
while(number > 0) ;
The for loop is another entry-controlled loop that provides a more concise loop
control structure. The general from of the for loop is.
e.g.:
for( x = 0 ; x <= 9 ; x = x + 1)
{
printf( %d , x);
}
printf(\n);
Jumps in Loops:
Exiting from a loop can be accomplished by using the break statement or the
goto statement. When the break statement is encountered inside a loop, the
loop is immediately exited and the program continues with the statement
immediately following the loop. When the loops are nested, the break would
only exit from the loop containing it. That is, the break will exit only a single
loop.
continue;
CHAPTER-6 ARRAYS
We can use arrays to represent not only simple lists of values but also tables of
data in two or three or more dimensions.
Types of arrays:
1. One dimensional array
2. Two dimensional array
3. Multidimensional array
A list of items can be given one variable name using only one subscript and such
variable is called a single-subscripted variable or one-dimensional array. The
subscript can begin with number 0 that is x[0].
If we want to represent a set of five numbers, say (35,40,20,57,19), by an array
variable name number, then we may declare the variable number as
int number [5];
and the computer reserves five storage locations as shown below:
number[0]
number[1]
number[2]
number[3]
number[4]
The values of the array elements can be assigned as:
number[0]=35;
number[1]=40;
number[2]=20;
number[3]=57;
number[4]=19;
This would cause the array number to store the values as:
35
40
20
57
19
Like any other variable, arrays must be declared before they are used. The
general form of array declaration is
the type specifies the type of the element that will be contained in the array, such
as int, float or char and size indicates the maximum number of elements that can
be stored inside the array.
E.g.:
float height [50];
declares the height to be an array containing 50 real elements. Any subscripts 0
to 49 are valid.
The C language treats character strings, simply as array of character. The size of
the character string represents the maximum number of character that the string
can hold.
E.g.:
char name[10];
declares the name as a character array(string) variable that can hold maximum
of 10 characters. Suppose we read the string constant into variable name.
WEL COME
Each character of the string is treated as an element of the array name and is
stored in the memory as follows:
W
E
L
C
O
M
E
\0
When the compiler sees a character string, it terminates it with an additional null
character. Thus the element name [10] holds the null character \0.
When declaring character arrays, we must allow one extra element space for the
null terminator.
After an array declared, its elements must be initialized. Otherwise, they will
contain garbage. An array can be initialized at either of the following stages.
1. At compile Time
2. At run time
E.g:
matrix1[4][3];
Columns
Like the one dimensional array, two dimensional arrays may be initialized by
following their declaration with a list of values enclosed in braces.
E.g:
int table[2][3] = { 0, 0, 0, 1, 1, 1};
int table[2][3] = { {0, 0,0} , {1, 1, 1} };
Multidimensional Array:
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multi-dimensional array is:
type array_name[s1][s2][s3]..[sn];
char string_name[size]
;
E.g.:
char city[10];
char name[30];
Using scanf function. The familiar input scanf can be used with %s format
specification to read in a string of character.
E.g.:
char address[10];
scanf(%s,address);
We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the input string.
scanf(%ws, name);
char name[10];
scanf(%5s,name);
The input RAM wil be stored as:
R A M \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9
K R I S H \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9
x = z 1;
ch >= A && ch <= Z
x= 7 0
then
x=ASCII value of 7 ASCII value of 0
x=55 48
x= 7
C library supports a function that converts a string of digits into their integer
values. The function takes the form
x=atoi(string);
E.g.:
number=1984
year=atoi(number);
strcat() function:
strcmp() function:
strcpy() function:
strlen() function:
C functions can be classified into two categories, namely, library functions and
user-defined functions. main is an example of user-defined functions. printf and
scanf belong to the category of library functions.
Every program must have a main function to indicate where the program has to
begin its execution. While it is possible to code any program utilizing only main
function, it leads to a number of problem. The program may become too large
and complex and as a result the task of debugging, testing, and maintaining
becomes difficult. If the program is divided into functional parts, then each part
may be independently coded and later combined into a single unit. These
subprograms called functions are much easier to understand, debug, and test.
Main Program
B1 B2
E.g.:
void show( ); // Function Declaration
main( )
{
.
show( ); // Function Call
.
}
void show( ) // Function Definition
{
// Function Body
}
Definition of Functions:
All the six elements are grouped into two parts, namely,
Function header (First three elements)
Function body (Second three elements)
Function header:
The function header consists of three parts: The function type (also known as
return type, the function name and the formal parameter list. Note that a
semicolon is not used at the end of the function header.
The function type specifies the type of value (like int or float) that the
function is expected to return to the program calling the function. If the
return type is not explicitly specified, C will assume it is an integer type. If
the function is not returning anything, then we need to specify the return
type as void.
The function name is any valid C identifier and therefore must follow the
same rule of information as other variable names in C. The name should
be appropriate to the task performed by the function.
The parameter list declares the variables that will receive the data sent by
the calling program. They serve as input data to the function to carry out
the specified task. Since they represent actual input values, they are often
referred to as formal parameter. The parameters are also known as
arguments.
E.g:
float volume(float height, float width, float breath) { }
int sum(int a, int b) { }
float div(int a, int b) { }
Function Body:
The function body contains the declarations and statement necessary for
performing the required task. The body enclosed in braces, contain three part, in
the order given below:
If a function does not return any value, we can omit the return statement.
However, note that its return type should be specified as void. Again, it is nice to
have a return statement even for void functions.
Category of Functions:
Recursion:
factorial(int n)
{
int fact;
if(n = = 1)
{
return (1);
}
else
{
fact = n* factorial(n-1);
}
return (fact);
}
We have seen that arrays can used to represent a group of data items that
belong to the same data type, such as float or int. However, we cannot use an
array if we want to represent a collection of data items of different types using a
single name. Fortunately, C supports a constructed data type known as
structures, a mechanism for packing data of different types.
struct tag_name
{
data_type member1;
data_type member2;
.
.
};
struct student
{
char name[20];
char address[30];
int age;
int marks;
};
The keyword struct declares a structure to hold the details pf four data fields,
namely name, address, age, and marks. These fields are called structure
elements or members. Each member may belong to a different data type of data.
student is the name of the structure and is called the structure tag. The tag name
may be used subsequently to declare variables that have the tags structure.
Above described format called as template.
E.g.:
struct student stud1, stud2, stud3;
struct student
{
char name[20];
char address[30];
int age;
int marks;
};
struct student stud1, stud2, stud3 ;
or
struct student
{
char name[20];
char address[30];
int age;
int marks;
} stud1, stud2, stud3 ;
strcpy(stud1.name , Amit);
strcpy(stud1.address , Chopato, Anand);
stud1.age = 23;
stud1.marks= 80;
or
scanf(%s\n, stud1.name);
scanf(%d\n, stud1.age);
Unions:
Unions are a concept borrowed from structure and therefore follow the same
syntax as structure. However, there is major distinction between them of storage.
In structure, each member has its own storage location, whereas all the
members of a union use the same location. This implies that, although a union
may contain members of different types, it can handle only one member at a
time. Like structures, a union can be declared using the keyword union as follow:
union item
{
int a;
float b;
char c;
} code;
The storage of these variables is as follows.
Storage of 4 bytes
1000 1001 1002 1003
c
a
b
CHAPTER-10 POINTERS
A pointer is a derived data type. It is built from the fundamental data types
available in C. Pointers contain memory address as their value. Since these
memory addresses are the locations in the computer memory where program
instructions and data are stored, pointers can be used to access and manipulate
data stored in the memory.
0
1
2
3
4
5
.
.
.
.
.
.
.
65,635
Fig.
Memory addresses are simply numbers; they can be assigned to some variables,
which can be stored in memory, like other variable. Such variables that hold
memory addresses are called pointer variables.
We assign the address of quantity to a variable p. The link between the variables
p and quality can be shown as:
P 5000 5058
Since the value of the variable p is the address of the variable quantity, we may
access the value of quantity by using the value of p and therefore, we say that
the variable p points to the variable quantity. Thus, p gets the name pointer.
p = &quality;
would assign the address 5000 to the variable p. The & operator can be
remembered as address of.
The & operator can be used only with a simple variable or an array element.
data_type *pt_name;
This tells the compiler three thing sabout the vaiable pt_name
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type.
For example:
int *p; //integer pointer
float *p; // float pointer
declares the variable p as a pointer variable that points to an integer or float data
type. Remember that the type int or float refers to the data type of the variable
being pointed to by p and not the type value of the pointer.
int quantity;
int *p; // declaration
p = &quantity; // Initialization