Masking

Masking implies transforming the desired bits of a variables by making use of logical operators. The operand which is used to perform masking is

called the mask. Masking is used to -
- copy a portion of a given bit pattern to a new variable and all fill the remainder bits of the variable with 0. (using &)
- copy a portion of a given bit pattern to a new variable and fill the remainder bits of the variables with 1. (using |)
- copy a portion of a given bit pattern to a new variable and invert the remainder bits of the variable. (using ^)
- to decide bit pattern of an integer variable.

Example: To use AND to check whether the third bit is ON or OFF
#define SETBIT 4
main()
{
int x,y;
printf("Enter value for y :");
scanf("%d", &y);
x = y & SETBIT;
if (x==0)
printf("\nThe third bit is OFF");
else
printf("\nThe third bit is ON");
}

Bitwise Complement (~) Operators

This operators is also called one's complement operator. This is an unary operator and inverts all the bits represented by the operand. i.e. if a bit

is 0 it becomes 1 and if it is 1 it becomes 0.
Example:
x = 1000 1100 0110 1010
~x=0111 0011 1001 0101
The use of this operator with AND is to turn of a particular bit.

Bitwise Shift Operators (<<,>>)

The bitwise shift operators are used to shift the bits either to the left or to the right. The shift operator are : Left Shift (<<) and right shift

(>>). The general form of bitwise shift operators is:
op << n for left shift
op >> n for right shift
Here op is an integer expression which is to be shifted by n bit positions to the left or right. The left shift operator causes all the bits in op to be

shifted left by n position. The n leftmost bits of the original bit pattern are lost, and the n rightmost bits are filled with 0s.

Bitwise Exclusive OR (^)

The result of exclusive OR is 1 only if either of the bits are 1 or 0 otherwise it is 0. In our above example the result of a

exclusive ORed with b is:
a ^ b = 0000 0000 0001 1010

Bitwise OR (|)

Considering the value of the a and b as given above, and making using of the table the result of bitwise OR on and b will be:
a | b = 0000 0000 0001 1110
Bitwise OR is used to set a particular bit to 1.

Bitwise AND (&)

The bitwise AND operand takes both values of operands as integers. if any of the bits is 0, or both the bits are 0 then the ANDing gives a 0. If both

the bits are 1, the result of bitwise AND is a 1. eg. 1=10 and b=20 then their binary representation is:
a = 0000 0000 0000 1010
b = 0000 0000 0001 0100
then a & b= 0000 0000 0000 0000
The resulting value represent the number 0. The use of bitwise AND is to determine whether a particular bit is a 1 or a 0 in programming situations.

Bitwise Logical Operators

There are three bitwise logical operators as we already know. They are:
bitwise AND (&)
bitwise OR (|)
bitwise exclusive OR (^)
These operators are known as binary operators. They can operate on two operands of type integer. The operators work on these integers bit by bit bit

starting from the rightmost (the least significant).
Bitwise operators have a lower precedence than relational operators.

Bitwise Operators

We known that C support what are called as bitwise operators. Let us revise these bitwise operators and see their operations in this section. C allow

direct manipulation of individual bits within a word. The bitwise operators in C are:
-Bitwise logical operators(&,|,^)
-Bitwise shift operator (<<,>>)
-One's complement operator(~)

Register Storage Class

The feature of a variable defined to be of register storage class are:
-The variable is stored in CPU registers
-The initial default value is unpredictable i.e. garbage
-The scope of the variable is local to the block in which it is defined.
-The life of the variable in only till the control remains within the block in which the variable is defined.
The variable stored in CPU register are accessed much faster than those stored in memory. Therefore we can tell the compiler to store the frequently

accessed variables to be kept in register instead of memory. The storage class of a variable can be declared registered as fallows:
register int count;
Example:
A small program to declare count to be of type register could be:
main()
{
register int count;
or(count=1;count<=10;count++)
printf("\n%d",count);
}

Static Storage Class

The feature of a variable whose storage class is static are:
-The variable is stored in memory
-Its default initial value is 0
-The scope of the variable is local to the block in which it is defined
-The value of the static variable persists until the end of the program.

Though the scope of static variable is local only to the block in which it is declared, the variable does not disappear but remains alive throughout

the program. The scope of auto variable as we have seen is also local and the value of these variables are no longer available once control goes out of the

block in which they are declared.Static variable are therefore useful when we wish to retain the value of the variables during function calls. A static

variable is initialised only once when the program is compiled. It is never initialised again. The following example illustrates the use of static variables:

Example:
main()
{
fn1();
fn1();
fn1();
}
fn1()
{
static int i=10;
printf("\ni=%d",i);
i=i+1;
}

The output of the program will be:
i=10
i=11
i=12

External Storage Class

When the storage class of the variable is declared extern it has the following features:
-The variable is stored in memory.
-The initial default value of the variable is zero.
-The scope of the variable is global (this means that the variable can be accessed by any function in the program).
-The variable is active and alive as long as the program execution does not come to an end i.e. its life is as long as the program is in execution.
External variable are declared outside all functions, but they are available to all the functions.
An example of declaring external variables is:
extern int a;
float b;
main()
{
:
:
}
fn1()
{
:
:
}
fn2()
{
:
:
}

The Automatic Storage Class

When the storage class of a variable is declared automatic(auto) it means:
-The variable is stored in memory
-The default value of the variable is auto which is unpredictable and often referred to as garbage.
-The scope of the variable is local only to the function in which it is declared
-The life of the variable is only till the control is in the block in which the variable is defined.

Example:
The following example shows how to declared the auto storage class of variables:
main()
{
auto int a,b;
printf("\na=%d\tb=%d",a,b);
}

A sample run of the program:
a=1140 b=249

Storage Classes in C

Variables in C not only have data types but also storage classes. The storage class provides information about the location of a variable. There are

basically two location where the variable value are stored: memory and CPU register. The variable's storage class decides in which of these location the

value is storage. The storage class of a variable tells us:
-where the variable would be stored
-the default initial value of the variable
(if the initial value has not been specifically assigned)
-the scope of the variable
(in which function the value of the variable would be variable)
-the life of the variable
The scope of the variable means over what part or parts of a program is the variable actually variable for use. The life of the variable is the

period during which the variable retain its value during the execution of the program.
Variables are also classified on the place of their declaration. Those variables which are declared within a particular function are local variable.

Those variables which are declared outside of any function are called global variables.
Storage classes explicitly declare the scope and life of the variables. These are useful mainly in multifunction and multiple file programs.
These are four storage classes in C:
-Automatic Storage Class
-External Storage Class
-Static Storage Class
-Register Storage Class

Type Casting

In some situations. it becomes necessary to force a type conversion which is different from the automatic conversion done by C. We are required to

explicitly convert a value of a particular expression to a specific data type. This is where, local conversion of a data type.This is where, local conversion

of a data type is done which is known as type casting. The general form of casting a value is:
(type-name) expression
type-name is one of the standard data types of C. The expression can be any valid C expression viz., a constant, variable or expression. The

parenthesis around the type name are essential. The value of the expression, undergoes the type conversion due to type casting. Some example of type casting:
a=(int)9.2
With type casting the fractional part will be truncated and the result will be 9.
int i=9, j=2;
float p;
{
p=(float) i/j;
}

Char Data Types

char data type occupies one byte in memory. By default char is signed. A signed char has a range of value between -128 to +127, unsigned char on the other hand has a range from 0 to 255.
Let us see the result of unsigned char and signed char with the following:
Example:
main()
{
unsigned char ch1;
char ch2;
ch1=224;
ch2=125;
printf("Character ch1=%c\t Ascii value=%d",ch1,ch1);
printf("Character ch2=%c\t Ascii value=%d",ch2,ch2);
}
The output of the program:
Character ch1=@ Ascii value=224
Character ch2=} Ascii value=125

Float Data Types

C offers a variation to float data types, which is double. double occupies 8 bytes in memory, and has a range of values between-1.7e308 to +3.4e38. A double data type uses 64 bits with a precision of 14 bits. Such number are known as double precision numbers.
A double type variable can be declared as:
double a;
double var1;
For even large real number C offers the long double data type. The long double occupies ten bytes in memory and falls in the range between -1.7e4932 to +1.7e4932. Declaring a long double data type yields still higher precision than the double data type.

Integer Data Types

Integer data types are further classified as: Signed and Unsigned.
In both the signed and unsigned we have the short int and long int.
int (signed integer) unsigned int(unsigned integer)
short int(Plain) unsigned short in(Plain)
long int(Plain) unsigned long int(Plain)
Thus, C has three classes of integer storage: short int, int and long int in both the signed and unsigned forms.

String Handling Functions

C Provides a number of useful function of these type of handling string. These function are in the common string library function which are supported by most C compilers. You can directly use these function in your programs.
Some of the most common string library function supported by most C compilers includes:

Function Use
strcat() Append one string at the end of other
strncat() Append first n character of a string at the end of another
strcpy() copies one string into another
strncpy() copies the first n characters of one string into another
strcmp() compare two strings
strncmp() compares the first n characters of two strings
strcmpi()/
stricmp() compare two strings ignoring the case
strnicmp() compares the first n characters of two strings without regard to case
strdup() duplicates a string
strchr() finds the first occurrence of a given character in a string
strrchr() find last occurrence of a given string in another string
strlen() Finds the length of a string
strlwr() convert a string into lowercase
strupr() convert a string into uppercase
strset() sets all the characters of a string to a given character
strnset() sets the first n characters of a string to a given character
strrev() reverse a string

Reading and Writing Strings

The scanf function can be used to read strings. The format specification used to read string as has already been introduced is %s. The scanf can be used as follows:
Example: To read string with the help of scanf
main()
{
char name[15];
printf("Enter your Name:");
scanf("%s",name);
printf("Good Morning %s",name);
}

A sample output of the above program:
Enter your name: Sushil
Good Morning
Sushil

Strings

Any group of characters within double quotation marks is a constant string. Thus a string constant is a one dimensional array of character
eg. "Programming Techniques Using C"
Since the string is enclosed in double quote if we wish to include double quotes in our string we can implement it in the following way with the use of the backslash(\):
"\"Programming Technology Using C\""
We use printf to print the above statement as follows:
printf("\"Programming Techniques Using C\"");
and the output will be:
"Programming Techniques Using C"

A string constant is an array of characters terminated by a null('\0'). A String constant can be initialized as follows:
char str1[]={'P','R','O','G','R','A','M','\0'};

Multidimensional Arrays

C allows of more than 2 dimensions.Such array are multidimensional arrays. The exact limit of the number of dimensions is dependent on the compiler. Multidimensional arrays are rarely required.
The following example declare multidimensional arrays:
int arr1[2][3][4];
float arr2[4][3][2][2];

Two Dimensional Arrays

It is also possible to declare arrays with two or more dimensions. A two dimensional array is also called a matrix. Such a matrix of a table can be stored in a two dimensional array.
The two dimensional array can be declared as follows:
type array_name[row_size][col_size];
The elements in a two dimensional array are stored row wise. Each dimension of the array is indexed from 0 onword to its maximum size minus one. The first index select the row and the second index selects the column.

Array Declaration

The array has to be declared before it can be used in a program. The general form of declaration or an array is:
type variable_name[size]
The type specifies the type of the element that are to be stored in the array like int,float etc. The variable_name is any valid variable name in C. The size indicates the maximum number of elements that can be stored in the array.
eg. float per[50];

One Dimensional Array

A one dimensional array has only one subscript. Thus a list of items which is given one variable name and uses only onesubscript is called a single subscripted variable or a one dimensional array.

What is an array ?

An array is a group of related data items which share a common name. For example, we can define an array name to represent percentages of 100 students, or salaries of 1000 employees etc. Here the quantities (data items) must be similar. The complete set of value of such similar quantities is called an array, whereas each individual value in the array is called an element. Array element could be int,float,char etc. In fact, array can be of any variable type. Array element are stored in contiguous memory locations.

The continue statement

The continue statement passes the control to the beginning of the loop. Thus when a continue is encountered in a loop, the following statements inside the body of the loop are skipped and control is transferred to the beginning of the loop for the next iteration.
Thus, the difference between the break and the continue is that break cause the loop to be terminated whereas continue causes the following statement to be skipped and continue with the next iteration.
The use of continue in loops is illustrated below:
in while
while(test condition)
{
------
-----
if(condition)
continue;
------
------
}

in the do-while
do
{
-----
-----
if(condition)
continue;
------
------
}while(test condition)

in the for loop
for(initialization;test condition;increment)
{
_______
_______
if(condition)
continue;
______
______
}

The break statement

In some situation it may be require to jump out of the loop without going back to the test conditions. For example, if you are checking a list of names and at the first occurance of a particular name you wish to exit the for loop or as soon as you encounter the first even number in a list you wish to exit the for loop. In such situation we make use of break. We have seen the use of the break keyword when we studied the case construct. break work in the same way in for and while loops as it works in the case construct.
When the break statement is encountered in a loop, the loop is exited and the control is transferred to the statement immediately follwoing the loop. The use of the break keyword for the various loop construct is illustrated below:

With the while statement as:
while(test condition)
{
-------
-------
if(condition)
break;
________
________
}
statement-a;

With a do statement as:
do
{
------
------
if(condition)
break;
______
_____
}while(------)
statement-a;

The for statement

The for statement is brobably the most frequently use loop construct. The for statement provides initialisation of counter, test condition and counter increment all in a single line. The general form of the for statement is:
for (initialisation; test-condition;increment)
{
body of the loop;
}

The do-while Statement

The while loop checks the test condition before executing the body of the loop i.e. it is an entry controlled loop. Hence, if the test condition is false for the first time itself the loop may not get executed at all. Another form of loop control is the do-while. This loop construct is an exit controlled loop i.e. it checks the test condition after executing the loop body. The body of the loop thus gets executed at least once in a do-while loop. This is only difference between the while and do-while.

The general form of the do-while is:
do
{
body of the loop
}
while(test condition);

The While Statement

The general form of the while statement is
while(test condition)
{
body of the loop
}
The while construct start with the while keyword followed by the test condition in the parenthesis. The body of the loop is included in the pair of braces. When the while keyword is encountered the test condition is checked.If it evaluates to true, the body of the loop is executed. Then the control again goes back to while. The condition is checked and again the body of the loop executed if true. Thus, the process repeates until the condition in the while loop evaluates to true. When the finally becomes false, the body of the loop is skipped and control is transferred to the statement which immediately follows the body of the loop.

The goto statement

C support the goto statement for unconditional branching from one point in the program to another. The syntax for the goto statement is:
goto label;
_______
______
label;
statement-1;
statement-2;

The Conditional (?:) Operator

The syntax of the conditional operator in C is:
exp1 ? exp2 : exp3;
where exp1,exp2 and exp3 are expression.Here, exp1 is evaluated first. If it is true(non zero), then exp2 is evaluated and it becomes the value of the expression. On the other hand if exp1 is false, then expression three is evaluated and its value becomes the value of the expression. The conditional operator need not be used only in arithmetic statement.

The if-else ladder

When multipath decisions are involved we make use of the if-else ladder. The if-else ladder is a chain of if where each has an associated if.The form of the if-else ladder is:
if(condition_1)
statement_2;
else if(condition_2)
statement_2;
else if(condition 3) statement_3;

Nested if-else statements

It is possible to nest if-else statement in an if or else statement. i.e. we can make use of more than one if-else statement by nesting them. There is not limit to the number of if-else nesting. The general form of nested if-else is:
if(test condition1)
{
if(test condition2)
{
statement-block-1;
}
else
{
statement block-2;
}
else
{
statement block-3;
}
}

if-else statement

There are situation where you may want to execute a statement(or a set of statements) when the if condition evaluates to true and another statement(or a set of statement) when the condition evaluates to false. In such cases we make of the if-else statement. The general form of the if-else statement is:
if(test condition)
{
statement-blick;
}
else
{
statement block;
}
statement a;
The test condition is evaluated. if it is true the statement block following if(called the if block) is executed, if it false the statement block following else(called the else block) is executed. The control is subsequently transferred to statement-a. In any cases only one statement block is executed.

The if Statement

The if statement is used to control the flow of the execution of statements in program. The general form of the if statement is
if (test condition)
The condition to be evaluated is placed in a pair of parenthesis immediately following the keywords if. First, the test condition is evaluated. If it is true then the statement (or set of statements) following if are executed. If the condition evaluates to false, the statement(or set of statements) following if are skipped.Thus there is a two way branching for the if statement: One for the true and the Other for the false condition.

Operator in C

An operator is a symbol which tells the computer to perform certain mathematical or logical manipulations. The operators are used in mathematical and logical expressions.
Operators in C are classified as under:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • Increment and Decrement Operators
  • Conditional Operators
  • Bitwise Operators
  • Special Operators

Primary Data Types

The four fundamental or primary data types are:
  • Integer(int)
  • Character(char)
  • Floating point(float)
  • double precision floating point(double)
These primary data types themselves are of many types. eg. integers could be long or short, signed or unsigned etc.

Variables

A variables is a data name used to store a data value. Variable names are names given to location in the memory where different constants are stored. Unlike a constant which remains unchanged during the execution of a program, a variable can take different values at different times during execution.
A variable name is a combination of alphabets,digits or underscores. The first character however must be an alphabet. No commas, or blank are allowed while constructing variable. The variable name should not be keyword. Variables are case sensitive i.e. sum and SUM are two distinct variables.
Some valid variable names are:
Max_length age xyz avg a1 T1

Constants

A constant in C is a fixed value which does not change during the execution of a program. C support several types of constants as under:
The basic classification of constant is:
Numeric Constants and Character Constants
These are further classified as:
Numeric Constants:
  • Integer
  • Real
Character Constants:
  • Single Character
  • String

Identifiers

Identifiers are names given to variables, functions and arrays. These are names which are user defined. They are made up by a combination of letters and digits. Normally an identifier should not be more than 8 characters long. The use of underscore is also permitted in identifiers.However, it is imperative that identifiers should begin with a letter.
Some example of identifiers are:
min1
max_temp
temp() etc.
C does not permit use of blank space, tabs, commas or special characters in identifiers.Thus:
min1
max*temp
12temp
are invalid identifier in C.

Keywords

Keywords are words whose meaning have already been defined and these meaning cannot be changed. Keywords are also called as reserved words. Keywords should not be used as used variable names (though some compilers allow you to construct variable names like keywords). All the keywords must be written in lowercase.

These are 32 Keywords in C as given below:

  • auto
  • double
  • if
  • static
  • break
  • else
  • int
  • struct
  • case
  • enum
  • long
  • switch
  • char
  • extern
  • near
  • typedef
  • const
  • float
  • register
  • union
  • continue
  • far
  • return
  • unsigned
  • default
  • for
  • short
  • void
  • do
  • goto
  • signed
  • while




C Tokens

The smallest individual units in a C program are called tokens. The alphabets,numbers and special symbols are combined to forms these tokens.
The types of tokens in C are:
-Keywords
-Identifiers
-Constants
-Strings
-Special Symbols
-Operators

What is a C program ?

C has only 32 keywords but a number of built in function. Thus a C program is basically a collection of function which are supported by the C library. We can make efficient use of these function in our programming task. One can also add new functions to the library.
Example: The first C program
main()
{
/* The First C Program */
printf("\nMy First C Program");
/* end of program */
}

The Output of this program will be:
My First C Program

Features of C

The C programming language was developed at AT &T's Bell Laboratories in USA in 1972. This language has been designed and written by Dennis Ritchie. C is a very Robust programming language and has a rich set of built in function. C is simple to learn and easy to use. C language is suitable for writing both system software and application programs and business packages. The Unix operating system was also developed at Bell Laboratories around the same time. Thus C is Strongly associated with Unix. In fact, Unix is coded almost entirely in C.