C-Language Hand Out
C-Language Hand Out
1. System Software
2. Application Software.
Software
System software is totally related to your system. Operating Systems, compilers, interpreters etc.. are the
examples of system software.
Application software is a software which is used by the end users examples like Library, Reservations,
Supermarket, Banking etc.
Language:
Low level languages are not easily understood by the ordinary users. It is difficult to write the code and
understand the code.
1. Machine Language
2. Assembly Language
Machine Language:
This Language uses only 0 and 1 to write the code. It is very difficult to write programs in this language.
360digrii
C-language hand book
Assembly Language:
This Language uses mnemonics such as ADD, SUB, MUL, etc, This Language is some what easy to
understand and here we have to remember the addresses of very thing. So, writing programs in this
language is some what difficult.
Assembler:
Assembler is a program which converts a assembly language program to machine language program.
These languages are just like our English like languages. These are easy to write programs and understand
the programs. Examples of High Level Languages are BASIC, COBOL, FORTRAN, PASCAL etc.
Compiler: Compiler is a program used to convert high level language to machine code at a time.
Interpreter: Interpreter is a program used to convert high level language to machine code line by line.
Now, Low level languages are used to develop system software where as high level languages are used to
develop application software. Then the part of C Language comes.
Introduction to C
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and
written by Dennis Ritchie on UNIX operating system. In the late seventies C began to replace the more
familiar languages of that time like PL/1, ALGOL etc. C is popular because it is reliable, simple and easy to
use.
360digrii
C-language hand book
Historical Development of C
In 1960 a horde of computer languages had come into existence, almost each for a specific purpose. For
example, COBOL was being used for commercial Applications and so on. So they thought of developing one
language which can program all possible applications. Therefore, an international committee was setup to
develop such a language. This committee came out with a language called ALGOL 60. However, ALGOL 60
never really became popular because it seeded too abstract, too general. To reduce this abstractions and
generality, a new language called Combined Programming Language (CPL) was developed at Cambridge
University. CPL was an attempt to bring ALGOL 60 down. However, CPL turned out to be so big, having so
many features, that it was hard to learn and difficult to implement.
Basic Combined Programming Language (BCPL), developed by Martin Richards at Cambridge University
aimed to solve this problem by bringing CPL down to its basic good features. But unfortunately it turned
out to be too less powerful and too specific. Around same time a language called B was written by Ken
Thompson at AT & T’s Bell Labs, as a farther simplification of CPL. But like BCPL, B too turned out to be
very specific. Ritchie inherited the features of B and BCPL, added some of his own and developed C.
Ritchie’s main achievement is the restoration of the lost generality in BCPL and B, and still keeping it
powerful.
Committee
Implement
Cambridge University
AT & T
Lost generality of BCPL and B
restored
1972 C Dennis Ritchie at
AT & T
Features of C Language
The C compiler combines the capabilities of an assembly language with the features of a high level
language and therefore it is well suited for writing both System Software as well as Application Software.
Therefore it is a middle level language.
Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators.
C language has only 32 keywords and its total strength lies in its built – in – functions. Several
standard functions are available which can be used for developing programs.
4. It is Portable:
360digrii
C-language hand book
C is highly portable. This means that C programs written for one computer can be run on another
with little or no modification. Portability is important if we plan to use a new computer with a different
operating system.
C language is well suited for structured programming, thus requiring the user to think of a problem
in terms of function modules or blocks. A proper collection of these modules would make a complete
program. This modular structure makes problem debugging, testing and maintenance easier.
C can extend itself. A C program is basically a collection of functions that are supported by the c
library. We can continuously add our own functions to the C library, with the availability of a large number
of functions, the programming task becomes simple.
STRUCTURE OF C PROGRAM
C program is a collection of building blocks called functions. A function is a subroutine that may include
one or more statements designed to perform a specific task. To write a C program, we first create
functions and then put them together. A c program may contain one or more functions shown below:
DOCUMENTATION SECTION
LINK SECTION
DEFINITION SECTION
Declaration Part
360digrii
C-language hand book
Executable Part
SUBPROGRAM SECTION
Function
1
Function 2
:
(User – defined functions)
:
Function n
The documentation section consists of a set of comment lines giving the name of the program, the author
and other details which the programmer would like to use later. The link section provides instructions to
the compiler to link functions from the system library. The definition section defines all symbolic
constants.
There are some variables that are used in more than one functions. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions.
Every C program must have one main() function section. This section contains two parts, declaration part
and executable part. The declaration part declares all the variables used in the executable part. There is at
least one statement in the executable part. These two parts must appear between the opening and the
closing braces. The program execution begins at the opening brace and ends at the closing brace. The
closing brace of the main function section is the logical end of the program. All statements in the
declaration and executable part end with a semicolon. The subprogram section contains all the user –
360digrii
C-language hand book
defined functions that are called in the main function. User – defined functions are generally placed
immediately after the main function, although they may appear in any order.
Variable: It is an identifier which creates some space in the memory and the value in that space changes
during program execution.
What is an identifier? It is some name to recognize. For example , how can I recognize you.. i.e. by your
name. in the same way, we have to give some name to the variable so that we can recognize it.
Variable creates some space in the memory. In which memory it creates space? Either in secondary
storage devices or RAM / ROM?
User can interact only to this memory. Whatever the variables we are creating it will be created in RAM.
Data Type:
C Language is rich in its data types. Storage representations and machine instructions to handle constants
differ from machine to machine. The variety of data types available allow the programmer to select the
type appropriate to the needs of the application as well as the machine. C supports the following data
types:
In int we can store only the integer values. In float data type we can store real values, and in char data type
we can store characters. Characters are enclosed in a single quote.
where type refers to an existing data type and identifier refers to the new name given to the data type. The
existing data type may belong to any class of type, including the user-defined ones.
Example:
typedef int i;
typedef float f;
Another user-defined data type is enumerated data type provided by C. It is defined as follows:
The identifier is a user defined enumerated data type which can be used to declare variables that can have
one of the values enclosed within the braces.
Example:
week = Monday;
Declaration of a Variable.
int a,b,c;
float p,q;
char s;
printf() is a statement used to display any messages on the standard output device such as
Monitor/screen.
1. printf(“message”);
What ever the message we are writing in the double quotes will be displayed as it is on to the screen.
2. printf(“<access specifiers>”,var-list);
this syntax is used when we want to display the values present in the variable on to the screen.
Access specifiers is used to inform the type of data of the variable to the compiler.
For int the access specifier is %d, for float %f, for char %c.
float b = 4.54;
360digrii
C-language hand book
char c = ‘a’;
if we want to print the values present in the variables a,b,c on to the screen we can use the following
statement.
a= 10 b = 4.54 c= a
printf(“ a = %d b= %f c= %c”,a,b,c);
The following program is used to find out the sum of two numbers.
#include <stdio.h>
main()
int a,b,s;
a=10;
b=20;
s=a+b;
printf(“sum = %d”,s);
}
360digrii
C-language hand book
The above program will display the following output.
sum = 30
when ever we are writing the program first we should think of the input, after that process the given
input and give the output.
In the above program compiler starts compiling the program starting from the main().
Now we will see one more program to find out the area of rectangle.
/* area of a rectangle */
#include <stdio.h>
main()
int l,b,a;
l = 10;
b = 5;
a = l * b;
printf(“area = %d “, l);
This function is used to take the input at run-time. i.e., we can enter the values to the variables while
running the program.
scanf(“<access specifiers>”,&var1,&var2,…….&varn);
Example:
int a;
float b;
char c;
Now if we want to enter the values into the variables a,b,c during runtime, we can use the following
statement.
scanf(“%d%f%c”,&a,&b,&c);
When we declare the variable, it allocates memory in the RAM and it gives some address to that variable.
If we want to get the address of that variable we can use “&” symbol.
Programs:
#include <stdio.h>
main()
int a,b,s;
scanf(“%d%d”,&a,&b);
360digrii
C-language hand book
s=a+b;
printf(“Sum = %d”,s);
Output:
Sum = 30
The above program will take the values into the variables into a and during runtime of the program.
It will take the 2 values and add the 2 values and stores it in the variable s.
si = (p * t * r) / 100
/* simple interest */
#include <stdio.h>
main()
int p,t,r;
float si;
si = (p*t*r)/100;
Operators in C Language
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator
5. Increment and Decrement Operators
6. Conditional Operator
7. Bit-wise Operators
8. Special Operators
1. Arithmetic Operators:
+, - , *, /, %
2. Relational Operators
Whenever you want to compare the values in the variables i.e., whenever we want to check the conditions
we use relational operators.
3. Logical Operators
Whenever we are using the && operator to join the conditions, if all conditions are true then the total
condition is true, if one of the condition is false then the condition is false.
Whenever we are using the || operator to join the conditions, if any one of the condition is true then the
entire condition is true. If all the conditions are false then the entire condition is false.
4. Assignment Operator.
For example.
X=5;
X++;
Printf(“x=%d”,x);
Output:
X=6
X=5;
Y= X++;
X=5;
Y=++x;
6. Conditional Operator:
Var = (cond)?exp1:exp2;
Eg:
360digrii
C-language hand book
X=5;
Y=10;
Big= (X>Y)?X:Y;
Big = 10.
About the Bit-wise Operators and Special Operators will be dealt later.
Conditional Statements:
Suppose if we want to execute the set of statements by checking the condition we use the conditional
statements.
if Statement:
Syntax:
if (condition)
statement – 1;
statement – 2;
statement – 3;
…
360digrii
C-language hand book
…
statement – n;
[else
statement – 1;
statement – 2;
statement – 3;
statement – n;
}]
For example:
a=10;
b=20;
if (a>b)
printf(“big = %d”,a);
else
printf(“big = %d”,b);
#include <stdio.h>
main()
int a,b;
scanf(“%d%d”,&a,&b);
if (a>b)
printf(“Biggest = %d”,a);
else
printf(“Biggest = %d”,b);
Output:
Biggest = 32
Biggest = 54
/* program to find whether the given age is major age or minor age */
#include <stdio.h>
main()
{
360digrii
C-language hand book
int age;
scanf(“%d”,&age);
printf(“Major age”);
else
printf(“Minor age”);
Output:
enter age 22
Major age
enter age 17
Minor age
We have see that if statement is used to select one of the given alternatives.
When the number of alternatives increases, the program becomes difficult to read and understand by
using if statement.
To solve this, C has a built-in multi way decision statement known as switch. The switch statement tests
the value of a given variable ( or expression) against a list of case values and when the match is found, a
block of statements associated with that case is executed.
switch (expression)
360digrii
C-language hand book
{
…..
…..
case value-n:statements;break;
default: statements;
Here break is used to come out of the switch statement when the expression matches with any one of the
case value.
If we are not using break statement in switch, it will execute all the statements present in all the case
vaules.
When the expression in the switch statement does not match with any one of the case values, it executes
the statements present in the default case.
For example, if we want to find the addition, subtraction, multiplication, division of two numbers we use
the following program.
#include <stdio.h>
main()
int a,b,ch,res;
clrscr();
scanf(“%d”,&ch);
switch(ch)
printf(“result = %d”,res);
Output:
enter 2 numbers 10 5
1. Addition
2. Subtraction
3. Multiplication
360digrii
C-language hand book
4. Diision
enter your choice 2
result = 5
#include <stdio.h>
main()
int day;
scanf(“%d”,&day);
switch(day)
case 2: printf(“Monday”);break;
case 3: printf(“Tuesday”);break;
case 4: printf(“Wednesday”);break;
case 5: printf(“Thursday”);break;
case 6: printf(“Friday”);break;
case 7: printf(“Saturday”);break;
}
360digrii
C-language hand book
/* program to find whether the given number is even or odd */
#include <stdio.h>
main()
int n;
scanf(“%d”,&n);
printf(“even number”);
else
printf(“odd number”);
Output:
enter a number 24
even number
enter a number 25
odd number
In the previous section we have seen that whenever we want to execute the set of statements by checking
the condition using if and switch. Here the blocks of statements are executed only once.
If we want to execute the blocks of statements repeatedly by checking the condition we use conditional
looping statements.
360digrii
C-language hand book
The Conditional Looping Statements in C Language are:
1. While Loop
2. do..while Loop
3. for Loop
While Loop
While loop is used to execute the set of statements repeatedly when the condition is true. When the
condition becomes false, it comes out of the loop and executes the next statement after the while loop.
Syntax:
while (condition)
statement – 1;
statement – 2;
…..
…..
…..
statement – n;
Here statement – 1 to statement –n will be executed continuously when the condition is true. When the
condition becomes false, it comes out of the while loop and executes the next statement after the while
loop.
Example:
i=1;
while (i<=10)
360digrii
C-language hand book
{
printf(“%d”,i);
i++;
The above example will display the natural numbers from 1 to 10.
Here first i is initialized to 1. Next we check the condition whether the value of i is less than or equal to 10
since we want to display the numbers from 1 to 10.
After that in the loop we will print the vale of i and increment the value of i and check the condition again.
#include <stdio.h>
main()
int i=1;
while(i<=10)
printf(“%d”,i);
i++;
#include <stdio.h>
360digrii
C-language hand book
main()
int i=2,n;
scanf(“%d”,&n);
while(i<=n)
printf(“%d”,i);
i = i + 2;
#include <stdio.>
main()
int i=1,n;
scanf(“%d”,&n);
while(i<=n)
if (i%2==0)
360digrii
C-language hand book
printf(“%d”,i);
i++;
In the first program the loop is executed n/2 times where as in the second program, the loop is executed n
times.
THE DO STATEMENT
The while loop construct makes 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 situations
it might be necessary to execute the body of the loop before the test is performed. Such situations can be
handled with the help of the do statement.
do
while(condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of
the loop, the condition in the while statement is evaluated. If the condition is true, the program continues
to evaluate the body of the loop once again. This process continues as long as the condition is true. When
the condition becomes false, the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
360digrii
C-language hand book
Since the test condition is evaluated at the bottom of the loop, the do..while construct provides an exit-
controlled loop and therefore the body of the loop is always executed atleasr once.
Example:
do
scanf(“%d”,&n);
....
....
while(n!=0);
This segment of a program reads a number from the keyboard until a zero number is keyed in.
for(initialization;test-condition;increment)
Example:
for(i=1;i<=10;i++)
printf(“%d”,i);
The above example will print the natural numbers from 1 to 10.
The for loop in C has several capabilities that are not found in other loop constructs. For example, more
than one variable can be initialized at a time in the for loop statement. The statements
p=1;
for(n=0;n<20;n++)
can be rewritten as
for(p=1,n=0;n<20;n++)
Like initialization section, the increment section may also have more than one part separated by commas
ARRAYS
360digrii
C-language hand book
Definition: An array is a collection of finite similar type of elements which share a common name and
stored in continuous memory locations.
A list of elements can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one-dimensional array.
Declaration of arrays
datatype arrayname[size];
The above declaration will create an array of size 5 which consists of integer elements and which are
stored in continuous memory locations.
The elements of the array can be accessed by using the subscripts of the array.
To access the values of the array n, we can access by using the n[0], n[1], n[2], n[3], n[4].
/* Creation of an array */
#include <stdio.h>
main()
int n[5],i;
scanf(“%d”,&n[i]);
for(i=4;i>=0;i--)
printf(“%d”,n[i]);
One dimensional arrays can store a list of values. In some situations where a table of values have to be
stored. This can be done by using a two-dimensional arrays.
The above example will create an arrays of size 3 rows and 3 columns i.e., totally we can store 9 elements.
WAP to create a two-dimensional array of size 3x3 and display in matrix form
#include <stdio.h>
main()
int n[3][3],i,,j;
clrscr();
for(j=0;j<3;j++)
scanf(“%d”,&n[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”,n[i][j]);
printf(“\n”);
A String is a collection of characters. A group of characters defined between double quotation marks is a
constant string.
Eg: “WELCOME”
Character strings are often used to build meaningful readable programs. The common operations
performed on character strings are:
char string-name[size];
The size determines the number of characters in the string-name. Some examples are:
char name[10];
char itemname[15];
putchar()
putchar (variable);
Eg: putchar(n);
getchar()
getchar() is a function which is used to read a single character from the keyboard.
variable = getchar();
Eg: n = getchar();
WAP to read a line of text containing a series of words from the terminal
#include <stdio.h>
main()
{
360digrii
C-language hand book
char line[80],ch;
int c = 0;
while((ch=getchar())!=’\n’)
line[c]=ch;
c++;
line[c]=’\0’;
printf(“%s”,line);
C library supports a large number of string-handling functions that can be used to carry out many of the
string manipulations. Following are the most commonly used string-handling functions:
strlen()
Eg: l = strlen(“Welcome”);
strcpy()
Strcpy(s1,s2);
strcat()
Strcat(s1,s2)
Here the string s2 and s1 is joined and copied into the string s1.
strcmp()
strcmp(s1,s2);
USER-DEFINED FUNCTIONS
360digrii
C-language hand book
C functions can be classified into two categories, namely, library or built-in-functions and user-defined
functions. main() is an example of user-defined function. printf(), scanf() are the examples of built-in
functions.
1. It facilitates top-down modular programming. In this programming style, the high level logic of the
overall problem is solved first while the details of each lower-level function are addressed later.
2. The length of a source program can be reduced by using functions at appropriate places. This factor
is particularly critical with microcomputers where memory space is limited.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs. This means that a C programmer can build on
what others have already done, instead of starting over, from scratch
main()
printline();
printf(“\nwelcome\n”);
printline();
printline()
int i;
for(i=1;i<=40;i++)
printf(“-“);
360digrii
C-language hand book
}
------------------------------------------------------------
welcome
------------------------------------------------------------
Hence whenever we require to draw a line we can call this function so that the program becomes shorter.
Structure of a C function
Function-name(arguments list)
argument declaration;
executable statement1;
executable statement2;
………..
………..
return(expression);
CATEGORY OF FUNCTIONS
A function, depending on whether arguments are present or not and whether a value is returned or not,
may belong to one of the following functions:
360digrii
C-language hand book
1. Functions with no arguments and no return values
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
RECURSION
For example:
main()
printf(“Welcome”);
main();
Will print Welcome infinite times. That’s why in a recursive function there must be some condition to
break the recursive function call.
The very good example of recursive function is to find the factorial of a given number.
main()
int n,f;
printf(“enter a number”);
scanf(“%d”,&n);
f = fact(n);
printf(“Factorial = %d”,f);
360digrii
C-language hand book
}
fact(int n)
if (n == 1)
return(1);
else
return(n*fact(n-1));
STORAGE CLASSES
The scope and life time of variables in functions can be defined by using the storage classes.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Automatic variables:
Automatic variables are declared inside a function in which they are to be utilized. They are created when
the function is called and destroyed automatically when the function is exited. Automatic variables are
therefore private or local to the function in which they are declared. Because of this property automatic
variables are also referred as local or internal variables.
Syntax:
Example Program
main()
int m =1000;
fun2();
printf(“%d\n”,m);
fun1()
int m = 10;
printf(“%d\n”,m);
fun2()
int m=100;
fun1();
360digrii
C-language hand book
printf(“%d\n”,m);
Output:
10
100
1000
External Variables:
Variables that are both alive and active throughout the entire program are known as external variables.
They are also known as global variables. Unlike local variables, global variables can be accessed by any
function in the program.
Lifetime : Global
int x;
main()
x = 10;
360digrii
C-language hand book
printf(“x = %d\n”,x);
printf(“x=%d\n”,fun1());
printf(“x=%d\n”,fun2());
printf(“x=%d\n”,fun3());
fun1()
x=x+10;
return(x);
fun2()
int x;
x = 1;
return(x);
fun3()
x = x+10;
return(x);
}
360digrii
C-language hand book
Output:
X=10
X=20
X=1
X=30
Static Variables
The value of static variables persists until the end of the program. A variable can be declared static using
the keyword static like
static int x;
static float y;
main()
int I;
for(i=1;i<=3;i++)
stat();
stat()
360digrii
C-language hand book
{
x=x+1;
printf(“x=%d\n”,x);
output:
x=1
x=2
x=3
X=1
X=1
X=1
Register variables
We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of keeping
in the memory. Since a register access is much faster than a memory access, keeping the frequently
accessed variables in the register will lead to faster execution of programs. This is done as follows:
register int c;
STRUCTURES
Structure is a user defined data type which is used to represent a collection of data items of different types
using a single name.
360digrii
C-language hand book
A structure is a convenient tool for handling a group of logically related data items. Structures help to
organize complex data in a more meaningful way. It is a powerful concept that is often need to use in
program design.
….
….
….
};
For example:
struct employee
int empno;
char ename[10];
float sal;
};
360digrii
C-language hand book
The keyword struct declares a structure to hold the details of the employee such as employee number,
employee name and his salary. These fields are called structure elements or members. Each member may
belong to a different type of data. employee is the name of the structure and is called the structure tag.
We can declare the structure variables using the tag name anywhere in the program.
For example:
The statement
We can assign the values to the members of the structure by using the dot operator (.) with the structure
variable.
For example if we want to assign value to employee number it can be done by the following statement:
e1.empno = 100;
The above statement will assign the value 100 to the empno.
WAP to create a structure employee with the fields empno, empname, and his salary.
/* creation of a structure */
#include <stdio.h>
main()
struct employee
int empno;
360digrii
C-language hand book
char ename[10];
float sal;
};
struct employee e;
scanf(“%d”,&e.empno);
scanf(“%s”,e.ename);
scanf(“%f”,&e.sal);
printf(“Employee No : %d\n”,e.empno);
UNIONS
Unions are a concept borrowed from structures and therefore follow the same syntax as structures.
However there is a major difference between them in terms of the storage. In structures 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 many members of different types, it can handle only one member at a time.
Like structure a union can be declared as follows:
….
….
….
};
In unions the compiler allocates a piece of storage that is large enough to hold the largest variable type in
the union.
union item
int m;
float n;
chat p;
};
In the declaration above, the member n requires 4 bytes which is the largest among the members. Hence
the union allocates 4 bytes of memory.
<--- p ------>
<------------ m ------------>
360digrii
C-language hand book
<------------------------------- n ------------------------>
POINTERS
Features of pointers:
Declaration of a pointer:
This tells the compiler three things about the variable ptr-name.
1. The asterisk (*) tells that the variable ptr-name is a pointer variable.
2. ptr-name needs a memory location.
3. ptr-name points to a variable of type data type.
For example:
int n;
int *p;
p = &n;
Once a pointer has been assigned the address of a variable, we can access the value present in the variable
by using indirection operator ( *) .
int n = 10;
int *p;
int m;
p = &n;
m = *p;
When the * is placed before a pointer returns the value of the variable of which the pointer value is the
address. In this case the value of m will become 10.
Example Program:
#include <stdio.h>
main()
int x,y;
int *p;
x = 10;
p = &x;
y = * p;
360digrii
C-language hand book
printf(“Value of x is %d\n”,x);
*p=25;
printf(“Now x = %d”,x);
Output:
Value of x is 10
Now x = 25
When an array is declared, the compiler allocates a base address and sufficient amount of storage to
contain all the elements of the array in contiguous memory locations. The base address is the location of
the first element of the array. The compiler also defines the array name as a constant pointer to the first
element. Suppose if we declare an array x as follows:
1 2 3 4 5
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value of x
is 100, the location where x[0] is stored. That
x = &x[0] = 100
If we declare p as an integer pointer, then we can make this pointer p to point to the array x by the
following statement:
p = x;
This is equivalent to
p = &x[0];
Now, we can access every value of x using p++ to move from one element to another.
#include <stdio.h>
main()
int *p,sum=0,i;
for(i=0;i<5;i++)
printf(“x[%d] %d %u\n”,i,*p,p);
p++;
printf(“Sum = %d\n”,sum);
Whenever we declare a variable as a local variable, it can be accessed in that function itself. Whenever if
we want to access a variable which is defined outside of that function, pointers can able to access a
variable which is defined outside of that function. This can be done by passing address of a variable to the
function.
main()
int x;
x = 20;
change(x);
360digrii
C-language hand book
printf(“%d\n”,x);
change(p)
int *p;
*p=*p+10;
In the above program we can change the value of x, which is declared as local variable to the function
main(), in the function change() by sending the address of x to the function change and which is collected
in the pointer p. Now by using indirection operator in the function change we can change the value of x.
We can access the members of a structure by using the pointer just by storing the address of a structure
variable in a pointer.
This can be done by using the arrow operator () with the pointer to the structure member.
struct employee
int empno;
char ename[10];
float sal;
};
struct employee e;
360digrii
C-language hand book
struct employee *p;
p = &e;
In the above example e is the structure variable and p is a pointer which cantains the address of the
structure variable e.
Now we can access the structure members by using arrow operator () with the pointer variable to the
structure member as follows:
pempno = 100;
#include <stdio.h>
main()
struct employee
int empno;
char ename[10];
float sal;
};
struct employee e;
p = &e;
scanf(“%s”,pename);
scanf(“%f”,&psal);
printf(“Employee no : %d\n”,pempno);
PREPROCESSOR
The preprocessor is a program that processes the source code before it passes through the
compiler. It operates under the control of preprocessor command lines or directives. Preprocessor
directives are placed in the source program before the main line. Before the source code passes through
the compiler, it is examined by the preprocessor for any preprocessor directives. If there are any,
appropriate actions are taken and then the source program is handed over to the compiler.
Preprocessor directives follow special syntax rules that are different from the normal C syntax.
They all begin with the symbol # in column one and do not require a semicolon at the end.
Examples:
#define PI 3.14
#define CUBE(X) X * X *X
FILE INCLUSION
This is used to include external files which contain some functions, macro definitions which can be used in
the program
#include <filename>
Where filename is the name of the file containing the required definitions or functions. At this point the
preprocessor inserts the entire contents of filename into the source code of the program.
For example, if we want to include the file stdio.h, it should be included using
#include <stdio.h>
These are used to switch on or off a particular line or group of lines in the program.
For example
360digrii
C-language hand book
#define “test.h”
#ifndef test
#define test1
#endif
test.h is the header file that contain the definition of test. #ifndef test searches for the definition of test in
the header file and if not defined, then all the lines between #ifndef and #endif are active in the program..
FILES
A file is the place on the disk where a group of related data is stored. C supports a number of functions that
have the ability to perform basic file operations, which include.
naming a file.
opening a file
reading data from a file.
writing data to a file
closing a file
fopen(): This function is used to create a new file for use or opens an existing file for use.
The general format for declaring and opening a file is
FILE *fp;
fp= fopen(“filename”, “mode”);
The first statement declares the variable fp as a “pointer to the data type FILE”. FILE is a structure that is
defined in the I/O library. The second statement opens file named filename and assigns an identifier to the
FILE type pointer fp. This pointer which contains all the information about the file is subsequently used as
a communication link between the system and the program.
360digrii
C-language hand book
The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be
one of the following:
r open the file for reading only
w open the file writing only
a open the file for appending data to it.
fclose(): A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from the buffers memory and all links to the
file are broken. It also prevents many accidental misuse of the file. In case, there is a limit to the number of
files that can be kept opens simultaneously, closing of unwanted files might help open the required files.
Another instance where we have to close the file is when we want to reopen the same file in a different
mode. The I/O library supports a function to do this takes the following form:
fclose(file_ptr);
getc(): It is a function which is used to read a single character from the data file.
Variable = getc(fp);
putc(): It is a function which is used to write a single character on to the data file.
putc(variable,fp);
What ever the character present the variable will be stored in the data file.
getw(): It is function which is used to read an integer data from the data file.
Variable = getw(fp);
360digrii
C-language hand book
putw(): It is a function which is used to write an integer data on to the data file.
putw(variable,fp);
fprintf(): This is function which is used to write mixed type of data on to the data file.
The general form of fprintf() function is:
fprintf(fp,”<access specifier>”,var_list);
For example:
fprintf(fp,”%d%f%c”,a,b,c);
Here the values present the variables a,b and c are stored in the data file.
fscanf(): It is a function used to read mixed type data from the data file.
The general form is:
fscanf(fp,”<access specifier>”, &var1,&var2,&var3,…….);
For example:
fscanf(fp,”%d%f%c”,&a,&b,&c);
The above statement will read data from the data and stores in the variables a, b and c.
ftell(): This is a function used to give the current position of the file pointer in the file, which can be used
later in the program. It takes the following form:
n = ftell(fp);
n should be long int data type.
360digrii
C-language hand book
fseek(): fseek function used to move the file position to a desired location within the file. It takes the
following form:
fseek(file_ptr, offset, position);
file_ptr is pointer to the file concerned, offset is a number or variable of type long, and position is an
integer number. The offset specifies the number of positions(bytes) to be moved from the location
specified by position. The position can take one of the following three values:
Value Meaning
0 Beginning of file
1 Current position
2 End of file
The offset may be positive, meaning move towards, or negative, meaning move backwards.
Example:
x = (int *)malloc(100*sizeof(int));
360digrii
C-language hand book
On execution of this statement, a memory space equivalent to “100 times the size of an int” bytes is
reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type of
int.
Example:
p = (int *) calloc(10,sizeof(int));
free(ptr);
ptr is a pointer to a memory block which has already been created by malloc or calloc.
360digrii
C-language hand book
Altering the size of a Block
It is some times necessary to alter the allocated space. This can be done with the help of the function
realloc. This process is called reallocation of memory. For example, if the original allocation is done by the
statement
ptr = malloc(size);
ptr = realloc(ptr,newsize);
Linked Lists
A linked list is a collection of nodes. A node consists of two parts : the data part and a link part.
NODE
DATA NEXT
The nodes in the linked list are not contiguous. Hence it is necessary in the linked list to keep track of the
nodes. This is done by using the link field. The address of the next node will be contained in the previous
node.
A linked list is represented as follows:
struct sll
{
int data;
struct sll *next;
};
switch(ch)
{
case 1: create();break;
case 2: display();break;
case 3: exit(1);
}
}
}
create()
360digrii
C-language hand book
{
struct sll *p;
int x;
p = (struct sll *)malloc(sizeof(struct sll));
printf(“Enter data “);
scanf(“%d”,&x);
pdata = x;
pnext = NULL;
if(start == NULL)
start = end = p;
else
{
endnext = p;
end = p;
}
}
display()
{
struct sll *p;
p=start;
while(p!=NULL)
{
printf(“%d”,pdata);
p=pnext;
}
}
360digrii
C-language hand book
BIT – LEVEL PROGRAMMING
One of the unique features of C language as compared to other high-level languages is that it allows direct
manipulation of individual bits within a word. Bit-level manipulations are used in setting a particular bit
or group of bits to 1 or 0. they are also used to perform certain numerical computations faster.
These are binary operators and require two integer-type operands. These operators work on their
operands bit by bit starting from the least significant (i.e. the rightmost) bit, setting each bit in the result as
shown in the following table:
Bitwise AND
The bitwise AND operator is represented by a single ampersand (&) and is surrounded on both sides by
integer expressions. The result of ANDing operation is 1 if both the bits have a value of 1; otherwise it is 0.
Let us consider two variables x and y whose values are 13 and 25. The binary representation of these two
variables are
The bitwise logical operators have lower precedence than the relational operators and therefore
additional parentheses are necessary as shown above.
The following program tests whether a given number is odd or even.
main()
{
int test = 1;
int number;
Output
Input a number
20
Number is even
Input a number
9
Number is odd
Input a number
-1
360digrii
C-language hand book
Bitwise OR
The bitwise OR is represented by the symbol | (vertical bar) and is surrounded by two integer operands.
The result of OR operation is 1 if at least one of the bits has a value of 1; otherwise it is zero. Consider the
following variables x and y
The bitwise inclusion Or operation is often used to set a particular bit to 1 in a flag. Example:
#define SET 8
main()
{
int flag;
....
....
Bitwise Exclusive OR
The bitwise exclusive OR is represented by the symbol ^. The result of exclusive OR is 1 if only one of the
bits is 1; otherwise it is 0. Consider the variables x and y.
vacated
positions
Shift operators are often used for multiplication and division by powers of two.
Consider the following statement:
x = y << 1;
This statement shifts one bit to the left in y and then the result is assigned to x. the decimal value of x will
be the value of y multiplied by 2. similarly, the statement
x = y >> 1;
shifts y one bit to the right and assigns the result to x. in this case, the value of x will be the value of y
divided by 2.
The shift operators, when combined with the logical bitwise operators, are useful for extracting data from
an integer field that holds multiple pieces of information. This process is known as masking.
BITWISE COMPLEMENT OPERATORS
The complement operator ~ (also called as one’s complement operator) is an unary operator and inverts
all the bits represented by its operand. That is, 0s becomes 1s and 1s become 0s.
Example:
This operator is often combined with the bitwise AND operator to turn off a particular bit. For example,
the statements