0% found this document useful (0 votes)
8 views

C-Language Hand Out

C Lang

Uploaded by

Subbareddy GV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C-Language Hand Out

C Lang

Uploaded by

Subbareddy GV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

360digrii

C-language hand book


INTRODUCTION TO SOFTWARE
Before going to C language I would like to revise some concepts.

Software: It is a collection of interrelated programs.

Program: It is a set of sequential instructions given to the computer to solve a problem.

Now software is divided into two types.

1. System Software
2. Application Software.

Software

System Software Application 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:

Language is the media for communication.

If you want to communicate with the computer we require a language.


360digrii
C-language hand book
Languages are divided into two types

1. Low Level Languages.


2. High Level Languages
Languages

Low Level Lang. High Level Lang.

Machine Lang Assembly Lang Basic Cobol Fortran Pascal

Low Level Language:

Low level languages are not easily understood by the ordinary users. It is difficult to write the code and
understand the code.

Low Level Languages are

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.

Assembly Language Assembler Machine Code

High Level Languages:

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.

C is a language which is used to develop system software as well as application software.

Hence C is called as Middle Level Language.

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.

The following table shows the various stages in evolution of C language.

Year Language Developed by Remarks

1960 ALGOL International Too general, too abstract

Committee

1963 CPL Cambridge University Hard to learn, difficult to

Implement

Could deal with only specific


360digrii
C-language hand book
1967 BCPL Martin Richards at problems

Cambridge University

Could deal with only specific


problems
1970 B Ken Thompson at

AT & T
Lost generality of BCPL and B
restored
1972 C Dennis Ritchie at

AT & T

Features of C Language

1. It is a middle level 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.

2. It is fast and efficient:

Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators.

3. It has just 32 keywords:

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.

5. It is a structured programming language:

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.

6. It can extend itself:

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

GLOBAL DECLARATION SECTION

main() function 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?

The memory is created in RAM.

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:

1. Primary Data types


2. User-defined data types
3. Derived data types
Primary Data Types

C language supports the following primary data types

int, float, char.

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.

User Defined Data types


360digrii
C-language hand book
C supports a feature known as “type definition” that allows users to define an identifier that would
represent an existing data type. The user-defined data type identifier can later be used to declare
variables. It takes the general form:

typedef type identifier;

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:

enum identifier {value1, value2, …. Value n};

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:

enum day {Monday,Tuesday,…Sunday};

enum day week;

week = Monday;

Declaration of a Variable.

The syntax of declaring a variable is given below.

data type variable list;


360digrii
C-language hand book
Examples:

int a,b,c;

float p,q;

char s;

Memory allocation for the Data Types:

int will occupy 2 bytes of memory.

float will occupy 4 bytes of memory.

char will occupy 1 byte of memory.

Standard Output Function

The Standard output function in C language is printf().

printf() is a statement used to display any messages on the standard output device such as
Monitor/screen.

The syntax of printf() is :

1. printf(“message”);

eg. printf( “ Welcome “);

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.

Eg. int a = 10;

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.

printf (“%d %f %c”,a,b,c);

it will display 10 4.54 a on to the screen.

But this output is not readable to the user.

i.e. I want to display as following

a= 10 b = 4.54 c= a

we can use the following statement.

printf(“ a = %d b= %f c= %c”,a,b,c);

Now we will see some programs based on printf() statement.

The following program is used to find out the sum of two numbers.

/ * 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().

Next it goes to declaration part.

Here it allocates memory 2 bytes each for the variables a, b and s.

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);

Standard Input Function:

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() is the standard input function used in C Langugae.


360digrii
C-language hand book
This function is used to take the values into the variables during runtime.

The syntax of scanf() is:

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);

Here “ & “ symbol is called as address operator.

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:

/* program to find out the sum of two numbers */

#include <stdio.h>

main()

int a,b,s;

printf(“Enter two numbers “);

scanf(“%d%d”,&a,&b);
360digrii
C-language hand book
s=a+b;

printf(“Sum = %d”,s);

Output:

Enter two numbers 10 20

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.

Finally displaying the value present in the variable s.

WAP to find the simple interest.

To find the simple interest the formula is

si = (p * t * r) / 100

where p is principle, t is time , and r is rate.

/* simple interest */

#include <stdio.h>

main()

int p,t,r;

float si;

printf(“enter values of p,t,r”);


360digrii
C-language hand book
scanf(“%d%d%d”,&p,&t,&r);

si = (p*t*r)/100;

printf(“simple interest = %f”,si);

Operators in C Language

There are 8 types of operators are available 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:

The arithmetic operators available in C language are

+, - , *, /, %

2. Relational Operators

The relational operators are >, <, >=, <=, ==, !=

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 want to join the conditions we use the logical operators.

The logical operators are &&, || , !


360digrii
C-language hand book
&& operator is used to join the conditions.

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.

|| operator is also used to join the conditions.

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.

! Condition is the negation of the given condition.

Here we the condition is false the condition becomes true.

If the condition is true the condition becomes false.

4. Assignment Operator.

The assignment operator is used to assign a value or an expression to a variable.

We can also use assignment operator in the following way.

For example.

X= x+5 can be written as x+=5

X=x*10 can be written as x*=10.

5. Increment and Decrement Operators.

The increment and decrement operators are ++, --.

The increment and decrement operators are of two types.

Post increment and pre increment

Post decrement and pre decrement


360digrii
C-language hand book
Examples:

X=5;

X++;

Printf(“x=%d”,x);

Output:

X=6

The difference between post and pre is as follows

X=5;

Y= X++;

Here the value of x= 6 and y =5

Here first the value of x is assigned to y, then the value of x is incremented.

X=5;

Y=++x;

Here the value of x=6 and y=6.

Here first the of x is incremented , then it is assigned to y.

6. Conditional Operator:

The conditional operator is used to check the condition.

The syntax of conditional operator is

Var = (cond)?exp1:exp2;

If the condition is true it executes expression1 else it executes expression2.

Eg:
360digrii
C-language hand book
X=5;

Y=10;

Big= (X>Y)?X:Y;

printf (“Big = %d”,Big);

Here the condition is false hence it prints

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:

if statement is used to execute the set of statements if the condition is true.

If the condition is false it will execute the statements in else part.

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;

}]

Here the else part is optional.

For example:

a=10;

b=20;

if (a>b)

printf(“big = %d”,a);

else

printf(“big = %d”,b);

Programs Using if Statement


360digrii
C-language hand book
/* To find the biggest of 2 numbers */

#include <stdio.h>

main()

int a,b;

printf(“enter two numbers “);

scanf(“%d%d”,&a,&b);

if (a>b)

printf(“Biggest = %d”,a);

else

printf(“Biggest = %d”,b);

Output:

enter two numbers 32 25

Biggest = 32

enter two numbers 43 54

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;

printf(“enter age “);

scanf(“%d”,&age);

if (age > =18)

printf(“Major age”);

else

printf(“Minor age”);

Output:

enter age 22

Major age

enter age 17

Minor age

THE SWITCH STATEMENT

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.

The general format of switch statement is given below:

switch (expression)
360digrii
C-language hand book
{

case vaule-1: statements;break;

case value-2: statements;break;

…..

…..

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();

printf(“enter 2 numbers “);


360digrii
C-language hand book
scanf(“%d%d”,&a,&b);

printf(“1. Addition \n”);

printf(“2. Subtraction \n”);

printf(“3. Multiplication \n”);

printf(“4. Division \n”);

printf(“enter your choice “);

scanf(“%d”,&ch);

switch(ch)

case 1: res = a+b;break;

case 2: res = a-b;break;

case 3: res = a*b;break;

case 4: res = a/b;break;

default:printf(“Invalid Choice “);exit(1);

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

WAP to enter the day number and print it in words

#include <stdio.h>

main()

int day;

printf(“enter day no “);

scanf(“%d”,&day);

switch(day)

case 1: printf(“Sunday “);break;

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;

default: printf(“Invalid Choice”);

}
360digrii
C-language hand book
/* program to find whether the given number is even or odd */

#include <stdio.h>

main()

int n;

printf(“enter a number “);

scanf(“%d”,&n);

if (n % 2 == 0) /* if a no. is divisible by 2 then it is even else odd */

printf(“even number”);

else

printf(“odd number”);

Output:

enter a number 24

even number

enter a number 25

odd number

Conditional Looping Statements:

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.

This process will continue until the condition becomes false.

/* program to generate the natural numbers from 1 to 10 */

#include <stdio.h>

main()

int i=1;

while(i<=10)

printf(“%d”,i);

i++;

/* program to generate even numbers from 1 to n */

#include <stdio.h>
360digrii
C-language hand book
main()

int i=2,n;

printf(“enter the maximum even number “);

scanf(“%d”,&n);

while(i<=n)

printf(“%d”,i);

i = i + 2;

We can write the above program in another way..

#include <stdio.>

main()

int i=1,n;

printf(“enter the maximum even number “);

scanf(“%d”,&n);

while(i<=n)

if (i%2==0)
360digrii
C-language hand book
printf(“%d”,i);

i++;

The difference between the above two programs is :

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.

The general form of do statement is:

do

body of the loop

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

printf(“enter a number “);

scanf(“%d”,&n);

....

....

while(n!=0);

This segment of a program reads a number from the keyboard until a zero number is keyed in.

DIFFERECE BETWEEN WHILE LOOP AND DO..WHILE LOOP

While Loop Do.. While Loop

1. The condition is tested 1. The condition is tested


before the statements after the statements in do
in while loop while loop.
2. The statements are not 2. The statements are
executed not even once executed atleast once it
if the condition is false the condition is false for
for the first time. the first time

THE FOR STATEMENT


360digrii
C-language hand book
The for loop is another entry-controlled loop that provides a more concise loop control structure.

The general form of for loop is:

for(initialization;test-condition;increment)

body of the loop

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.

The starting of an array is called as base address.

ONE DIMENSIONAL ARRAYS

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

The general form of declaration of one dimensional arrays is:

datatype arrayname[size];

Example: int n[5];

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.

The subscript of an array in c language begins from 0.

To access the values of the array n, we can access by using the n[0], n[1], n[2], n[3], n[4].

WAP to create an array and display the elements in reverse order.

/* Creation of an array */

#include <stdio.h>

main()

int n[5],i;

printf(“Enter 5 elements \n”);


360digrii
C-language hand book
for(i=0;i<5;i++)

scanf(“%d”,&n[i]);

printd(“Elements in reverse order are:\n”);

for(i=4;i>=0;i--)

printf(“%d”,n[i]);

TWO DIMENSIONAL ARRAYS

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 two-dimensional array is a collection of rows and columns.

Declaration of Two-Dimensional Array

datatype arrayname[row size][column size];

Eg:. int n[3][3];

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

/* Creation of two-dimensional array */

#include <stdio.h>

main()

int n[3][3],i,,j;

clrscr();

printf(“Enter the elements of the matrix \n”);


360digrii
C-language hand book
for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf(“%d”,&n[i][j]);

printf(‘Elements in matrix form \n”);

for(i=0;i<3;i++)

for(j=0;j<3;j++)

printf(“%d”,n[i][j]);

printf(“\n”);

HANDLING OF CHARACTER STRINGS

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:

 Reading and Writing Strings


 Combining strings together
 Copying one string to another
 Comparing strings for equality
 Extracting a portion of a string

DECLARING AND INITIALIZING STRING VARIABLES


360digrii
C-language hand book
A string variable is any valid variable name and is always declared as an array. The general form of
declaration of a string variable is:

char string-name[size];

The size determines the number of characters in the string-name. Some examples are:

char name[10];

char itemname[15];

static char name[] = {‘W’,’E’,’L’,’C’,’O’,’M’,’E’};

putchar()

putchar() is a function which is used to write a single character on to the screen.

The general form:

putchar (variable);

Eg: putchar(n);

getchar()

getchar() is a function which is used to read a single character from the keyboard.

The general form:

variable = getchar();

Eg: n = getchar();

WAP to read a line of text containing a series of words from the terminal

/* Program to read a line of text from terminal */

#include <stdio.h>

main()

{
360digrii
C-language hand book
char line[80],ch;

int c = 0;

printf(“Enter a line of text \n”);

while((ch=getchar())!=’\n’)

line[c]=ch;

c++;

line[c]=’\0’;

printf(“Given line of text is\n”);

printf(“%s”,line);

STRING HANDLING FUNCTIONS

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()  finds the length of the string

strcpy()  Copies one string over another

strcat()  Concatenates two strings

strcmp()  compares two strings

strlen()

This function is used to find the length of the given string.

The general form:


360digrii
C-language hand book
Var = strlen(string variable);

Eg: l = strlen(“Welcome”);

The value of l is now 7.

strcpy()

This function is used to copy one string to another.

The general form:

Strcpy(s1,s2);

Where s1 and s2 are two strings

strcat()

This function is used to concatenate two strings

The general form is:

Strcat(s1,s2)

Here the string s2 and s1 is joined and copied into the string s1.

strcmp()

This function is used to compare the two strings

The general form is:

strcmp(s1,s2);

If s1 equals to s2 the function return a value equal to 0.

If s1 is greater than s2 the function return a value > 0

If s1 is less than s2 the function return a value < 0.

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.

Advantages of User-defined 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

Consider the following example program.

main()

printline();

printf(“\nwelcome\n”);

printline();

printline()

int i;

for(i=1;i<=40;i++)

printf(“-“);
360digrii
C-language hand book
}

The above program will generate the following output:

------------------------------------------------------------

welcome

------------------------------------------------------------

The printline() function is used to draw a line.

Hence whenever we require to draw a line we can call this function so that the program becomes shorter.

Structure of a C function

The structure of a C function is:

Function-name(arguments list)

argument declaration;

local variable declarations;

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

A function is called in itself is called as a 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.

A variable in C can have one of the four 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:

auto datatype variable list;


360digrii
C-language hand book
eg: auto int a,b,c;

Scope: Local to a function

Initial Value : Garbage

Life time: When the function is called

Example Program

/* Illustration of Working of auto variables */

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.

External variables are declared outside the function.

We can use the keyword extern to declare a external variable.

Scope : Through out the program

Initial Value : zero

Lifetime : Global

/* Illustration of Global variables */

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

Note: Preference is given to the local variable.

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;

Scope: To the function only

Initial Value: zero

Life time: Global

/* Illustration of Static Variables */.

main()

int I;

for(i=1;i<=3;i++)

stat();

stat()
360digrii
C-language hand book
{

static int x=0;

x=x+1;

printf(“x=%d\n”,x);

output:

x=1

x=2

x=3

If we declared x as an auto variable, the output would be:

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.

The general format of a structure is as follows:

struct <structure name>

data type – 1 variable list;

data type – 2 variable list;

….

….

….

Data type – n variable list;

};

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

struct employee e1,e2,e3;

declares e1, e2 and e3 as variables of type struct employee.

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;

printf(“enter employee number “);

scanf(“%d”,&e.empno);

printf(“enter employee name “);

scanf(“%s”,e.ename);

printf(“enter employee salary ‘);

scanf(“%f”,&e.sal);

printf(“Employee Details \n”);

printf(“Employee No : %d\n”,e.empno);

printf(“Employee Name :%s\n”,e.ename);

printf(“Employee Salary :%f\n”,e.sal);

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:

union <union name>


360digrii
C-language hand book
{

data type – 1 variable list;

data type – 2 variable list;

….

….

….

Data type – n variable list;

};

In unions the compiler allocates a piece of storage that is large enough to hold the largest variable type in
the union.

For example consider the following 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

A pointer is a variable which contains address of the some other variable.

Features of pointers:

1. A pointer enables us to access a variable that is defined outside the function.


2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of data storage space in memory.

Declaration of a pointer:

data type *ptr-name;

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;

The above statements declare a pointer variable p.

The statement p = &n can store the address of n in a pointer variable p.


360digrii
C-language hand book
Here & is called as a address operator.

Once a pointer has been assigned the address of a variable, we can access the value present in the variable
by using indirection operator ( *) .

This can be done as follows:

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:

/* ACCESSING VARIABLES USING POINTERS */

#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);

printf(“%d is stored at addr %u\n”,x,&x);

printf(“%d is stored at addr %u\n”,*p,p);

printf(“%d is stored at addr %u\n”,y,&y);

printf(“%d is stored at addr %u\n”,p,&p);

*p=25;

printf(“Now x = %d”,x);

Output:

Value of x is 10

10 is stored at addr 100

10 is stored at addr 100

10 is stored at addr 102

100 is stored at addr 104

Now x = 25

POINTERS AND ARRAYS

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:

static int x[5] = {1,2,3,4,5};


360digrii
C-language hand book
Suppose the base address of x is 100 and assuming that each integer requires two bytes, the five elements
will be stored as follows:

x[0] x[1] x[2] x[3] x[4]

1 2 3 4 5

100 102 104 106 108

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.

WAP using pointers to find the sum of elements in an array.

/* POINTERS IN ONE – DIMENSIONAL ARRAY */

#include <stdio.h>

main()

int *p,sum=0,i;

static int x[5] = {10,20,30,40,50};


360digrii
C-language hand book
p=x;

printf(“Element value Address \n”);

for(i=0;i<5;i++)

printf(“x[%d] %d %u\n”,i,*p,p);

sum = sum + *p;

p++;

printf(“Sum = %d\n”,sum);

POINTERS AND FUNCTIONS

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.

When an address is passed as an argument to a function then it is called as call by reference.

Consider the following example program:

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.

POINTERS AND STRUCTURES

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.

For example consider the following structure.

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:

pempno = 100;

/* ILLUSTRATION OF POINTERS AND STRUCTURES */

#include <stdio.h>

main()

struct employee

int empno;

char ename[10];

float sal;

};

struct employee e;

struct employee *p;

p = &e;

printf(“enter employee no “);


360digrii
C-language hand book
scanf(“%d”,&pempno);

printf(“enter employee name “);

scanf(“%s”,pename);

printf(“enter employee salary “);

scanf(“%f”,&psal);

printf(“Employee Details are \n”);

printf(“Employee no : %d\n”,pempno);

printf(“Employee Name :%s\n”,pename);

printf(“Employee Salary :%f\n”,psal);

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.

Preprocessor directives can be divided into three categories:

1. Macro substitution directives


2. File inclusion directives
3. Compiler control directives.
MACRO SUBSTITUTION
360digrii
C-language hand book
Macro substitution is a process where an identifier in a program is replaced by a predefined string
composed of one or more tokens. The preprocessor accomplishes this task under the direction of #define
statement. This statement, usually known as a macro definition takes the following general form:

#define identifier string

Examples:

#define COUNT 100

#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

The preprocessor directive for file inclusion is

#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>

COMPILER CONTROL DIRECTIVES

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

We use the following functions to implement the file operations

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.

The general format of getc() function is:

Variable = getc(fp);
putc(): It is a function which is used to write a single character on to the data file.

The general format of putc() function is:

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.

The general form of getw() function is:

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.

The general form of putw() is :

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.

Dynamic Memory Allocation


The process of allocating memory during runtime is known as dynamic memory allocation. There are four
library routines known as “memory management functions” that can be used for allocating and freeing
memory during program execution. These functions help us build complex application programs that use
the available memory intelligently.

Allocating a Block of Memory


A block of memory may be allocated using the function malloc. The malloc function reserves a block of
memory of specified size and returns a pointer of type void. This means that we can assign it to any type of
pointer. It takes the following form:
ptr = (cast-type *) malloc(byte-size);
ptr is a pointer of type cast-type. The malloc returns a pointer to an area of memory with size byte-size.

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.

Allocating Multiple Blocks of Memory


calloc is another memory allocation function that is normally used for requesting memory space at
runtime for storing derived data types such as arrays and structures. While malloc allocates a single block
of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all bytes to
zero. The general form of calloc is:

ptr = (cast-type *)calloc (n,elem-size);


The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are
initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough
space, a NULL pointer is returned.

Example:
p = (int *) calloc(10,sizeof(int));

Releasing the Used Space


Compile-time storage of a variable is allocated and released by the system in accordance with its storage
class. With the dynamic run-time allocation, it is our responsibility to release the space when it is not
required. The release of storage space becomes important when the storage is limited.
When we no longer need the data we stored in a block of memory, and we do not intend to use that
block for storing any other information, we may release that block of memory for future use, using the
free function:

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);

then reallocation of space may be done by the statement

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:

10 2000 20 3000 30 NULL

1000 2000 3000


360digrii
C-language hand book
Creation of a Linked List

struct sll
{
int data;
struct sll *next;
};

struct sll *start = NULL, *end = NULL;


main()
{
int ch;
while(1)
{
printf(“1. Create\n”);
printf(“2. Display\n”);
printf(“3. Exit \n”);
printf(“Enter your choice “);
scanf(“%d”,&ch);

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);
pdata = x;
pnext = NULL;
if(start == NULL)
start = end = p;
else
{
endnext = p;
end = p;
}
}
display()
{
struct sll *p;
p=start;
while(p!=NULL)
{
printf(“%d”,pdata);
p=pnext;
}
}
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.

C supports the following bit-wise operators;

1. Bitwise logical operators.


2. Bitwise shift operators.
3. One’s complement operator.

BITWISE LOGICAL OPERATORS

There are three logical bitwise operators. They are;

 Bitwise AND (&)


 Bitwise OR (|)
 Bitwise exclusive OR (^)

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:

op1 op2 op1 & op2 op1 | op2 op1 ^ op2


1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Table: Result of Logical Bitwise Operators


360digrii
C-language hand book

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

x - - - > 0000 0000 0000 1101


y - - - > 0000 0000 0001 1001
If we execute the statement
z = x & y;
then the result would be:

z - - - > 0000 0000 0000 1001


Bitwise ANDing is often used to test whether a particular bit is 1 or 0. For example, the following program
tests whether the fourth bit of the variable flag is 1 or 0.

#define TEST 8 /* represents 00…….01000*/


main()
{
int flag;
....
....

if((flag & TEST) != 0) /*test 4th bit*/


{
printf(“Fourth bit is set\n”);
}
....
....
}
360digrii
C-language hand book

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;

printf(“Input a number \n”);


while(number != -1)
{
if(number & test)
printf(“Number is odd\n”);
else
printf(“Number is even\n”);
printf(“Input a number \n”);
scanf(“%d”,&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

x---> 0000 0000 0000 1101


y---> 0000 0000 0001 1001

x|y - - - > 0000 0000 0001 1101

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;
....
....

flag = flag | SET;

if ((flag & SET) != 0)


{
printf(“flag is set \n”);
}
....
....
}
360digrii
C-language hand book
The statement
flag = flag | SET;
causes the fourth bit of flag to set 1 if it is 0 and does not change it if it is already 1.

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.

x---> 0000 0000 0000 1101


y---> 0000 0000 0001 1001

x^y - - - > 0000 0000 0001 0101

BITWISE SHIFT OPERATORS


The shift operators are used to move bit patterns either to the left or to the right. The shift operators are
represented by the symbols << and >> and are used in the following form:

Left shift : op << n


Right shift : op >> n
op is the integer expression that is to be shifted and n is the number of bit positions to be shifted.
The left-shift operation causes all the bits in the operand op to be shifted to the left by n positions. The
leftmost n bits in the original bit pattern will be lost and the rightmost n bit positions that are vacated will
be filled with 0s.
Similarly, the right-shift operation cause all the bits in the operand op to be shifted to the right by n
positions. The rightmost n bits will be lost. The leftmost n bit positions that are vacated will be filled with
zero, if the op is an unsigned integer. If the variable to be shifted is signed, then the operation is machine
dependent.
Both the operands op and n can be constants or variables. There are two restrictions on the value of n. it
may not be negative and it may not exceed the number of bits used to represent the left operand op.
Let us suppose x is an unsigned integer whose bit pattern is
0100 1001 1100 1011
360digrii
C-language hand book
then,
x << 3 = 0100 1110 0101 1000} vacated positions

x >> 3 = 0000 1001 0011 1001

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:

x = 1001 0110 1100 1011


~x = 0110 1001 0011 0100

This operator is often combined with the bitwise AND operator to turn off a particular bit. For example,
the statements

x = 8; /* 0000 0000 0000 1000 */


flag = flag & ~x;
would turn off the fourth bit in the variable flag.

You might also like