C LANGUAGE
‘C’ is a programming language developed at AT&T’s Bell laboratories of USA in 1972. It is designed and written by DENNIS
RITCHIE.
Development of C:-
year Language Developed By Remarks 1960 1963 1967 1970 1972 ALGOL CPL BCPL B C International committee Cambridge University Martine Richards at Cambridge university. Ken Thomson at AT&T’s Dennis Ritchie at AT&T’s
Too general, too abstract.
Hard to learn, difficult to implement.
Could deal with only specific problems. Could deal with only specific problems.
Lost generality of BCPL and B restricted.
Where C stands for:
All programming languages can be dividing into two major categories.
1) Problem oriented languages & High level Languages:
These languages have been designed to give a better programming efficiency, i.e. faster program development.
2) Machine oriented Languages & Low level Languages:
These languages have been designed to give a better machine efficiency i.e. faster program execution.
‘C’ language is between these two categories. So c is called as
‘middle level language’.
Steps in learning a language:
Steps in learning ‘C’:-
The character set:
A character denotes any alphabet, digit or special symbol used to represent information.
Alphabets: A……….Z, a………..z.
Digits: 0,1,2,3,4,5,6,7,8,9
Special symbols: ~`! @ # $ % ^ & * ( ) _ - + = | \ [ ] { } : ; ” ‘ , . ? / < >
Constants:
Constant is a quantity that does not change. This quantity can be stored at a location in the memory of the computer.
Variables:
A variable can be considered as a name given to the in the memory where this constant is stored.
Note: the constant of the variable can change. For ex: 5x+2y=100.
Here 5, 2 are cannot change. They are called constants.
TYPES OF CONSTANTS:
C constants can be divided in to two major categories. A. Primary constants. B. Secondary constants. C constants Primary Secondary Integer constants Real constants Character constants Array Pointers Structures Union...Etc.
Primary constants:
Rules for Integer constant:
9 Integer constants must have at least one digit. 9 It must not have decimal value.
9 It could be positive or negative.
9 If no sign is precedes integer constant it is assumed to be positive.
9 No comma or blanks are allowed with in an integer constant. 9 The integer specified by ‘int’ keyword.
9 The integer range is -32768 to +32767. Ex: 438, +4783, -2000, -32766.
Rules for real constant:
Real constants are often called floating point constants. The real constants can be written in two forms.
Fractional form Exponential form
Fractional form:
9 A real constant must have at least one digit. 9 It must have a decimal point.
9 It could be either positive or negative. 9 Default sign is positive.
9 No commas or blanks are allowed with in a real constant. Ex: +325.67.
+4875.2569 +245.00 -8745.2410.
In the exponent form of the representation, is represents two parts. The part appearing before ‘e’ is called Mantissa.
The part appearing after ‘e’ is called Exponent.
Rules for exponent values:
9 The mantissa part and exponent part should be separated by ‘e’.
9 The mantissa part may have positive or negative value. 9 Default sign of mantissa is positive.
9 The exponent must have at least one digit which must be positive or negative.
9 Default sign of exponential is negative value. 9 Range of real constants is -3.4e38 to 3.4e38.
Rules for constructing character constants:
9 A character constant is a single alphabet, a single digit or a single special symbol enclosed with in sign inverted commas.
9 The maximum length of a character constant can be 1 character.
Ex: ‘a’
‘A’ ‘5’ ‘+’
Rules for constructing Variable Names:
9 A variable name is any combination of 1 to 8 alphabets, digits or underscores. Some compilers allow variables names whose length could be up to 40 characters.
9 The first character in the variable name must be an alphabet. 9 No commas or blanks are allowed with in a variable name.
9 No special symbol other than an underscore (as tot_sal) can be used in a variable name.
Ex: si_int. m_hra.
Tot_da_23.
‘C’ keywords:
Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names. The keywords are also called “Reserved words”.
There are only 32 keywords available in C. Following is the list of keywords.
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 Instructions:
There are basically four types of instructions in C: A) Type declaration Instruction.
B) Input/Output Instructions. C) Arithmetic Instructions. D) Control Instructions.
The purpose of each of these instructions is given below:
Type declaration instruction - to declare the type of variables used in C program.
Input/Output Instructions: - Too perform the function of supplying input data to a program and obtaining the output results forms it.
Arithmetic Instructions - to perform arithmetic operations between constants and variables.
Control Instructions - To control the sequence of execution of various statements in a c program. Hierarchy of operations:
Priority operators description
1storder */% Multiplicaton, division, mod 2ndorder +- addition, substraction.
3rdorder = assignment.
Some tips about usage of operators in general.
A) In case of a tie between operators of same priority, the associatively of operators decides which operation would be performed first.
For ex: a*b/c
Here * and / the same priority. But a * b performed first.
B) We must remember to use pairs of parentheses. A careless imbalance of the right and left parenthesis is a common error.
Rules for the C programming:-
9 Blank space may be inserted between two words to improve the readability of the statement. However No blank spaces are allowed with in a variable, constant or keyword.
9 Usually all statements are entered in small case letters.
9 C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
9 Any c statement is always ends with a’;’
A few useful tips about the program:
9 Comment about the program should be enclosed with in /* */. 9 Any no of comments can be written at any place in the program. 9 Comments cannot be nested.
9 Any c program is nothing but a combination of functions. main () Is one such functions. Empty parenthesis after main is necessary. 9 Any variable used in the program must be declared before using it. For ex: int p, n, r;
CONTROLS instructions in C:
There are four types of control instructions in C. they are
A) Sequence Control Instruction: - it ensures that the instructions
are executed in the same order in which they appear in the program.
B) Decision and case control instructions: - it allows the computer
to take a Decision as to which instruction is to be executed next.
C) Loop control instructions: - these statements can help computer
to execute a group of statements repeatedly.
D) Case control Instructions: These statements are use to control
the case nature.
DISPLAY VARIABLES:
The function printf() statement is used to output simple string.
For ex: printf(“%d”,n); Printf(“%d%d”,m,n);
Printf(“\n the values are %d is m and %d is n”,m,n);
READING VARIABLES:
The function scanf() statement is used to input simple string or
variable.
For ex: scanf(“%d”,&n);
scanf(“%d%f%c”,&interger,&floatvalue,&character);
OPERATORS:
An operator is a symbol that operates on a certain data type.
An expression is a combination of variables, constant and operators
written according to the syntax of the language. In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable.
Types of operators:
In C, operators can be classified into various categories based on their utility and action. A list of operator types is given below:
• Arithmetic operators • Relational operators • Logical operators • Assignment operators
• Increment and decrement operators • Conditional operators
• Bitwise operators • Comma operators • Other operators
Arithmetic operators:
The arithmetic operators perform arithmetic operations and can be classified into unary and binary arithmetic operators. The arithmetic operators can operate on any built-in data type. A list of arithmetic operators and their meaning are given below:
Operator meaning
+ Addition or unary plus - subtraction or unary minus * Multiplication.
/ Division.
% modulo division (reminder after division).
Note:
 C has no operator for exponention. However, a function
pow(x,y) exists in math.h which returns xy.
 The unary minus operator has the effect of multiplying its operand is -1.
Relational operators:
R.O are used to compare arithmetic, logical and character expression. We often compare two similar quantities and depending on their relation, take some decisions. These comparisons can be done with the help of relational operators. Each operator compares their left hand side with their right hand side.
Operator meaning
< less than.
<= less than or equals to. > greater than.
>= greater than or equal to.
== equal to.
Logical operators:
A logical operator is used to compare to evaluate logical and relational expressions. These are three logical operators in C language. They are:
Operator meaning
&& logical AND || logical OR ! logical NOT
Bitwise operators:
A bitwise operator on each bit of data. These operators are used for testing, complementing or shifting bits to the right and left. Usually bitwise operators are not useful in cases of float and double variables. Lists of bitwise operators are given below:
Operator meaning
& bitwise AND
| bitwise OR
^ bitwise XOR
<< shift left >> shift right
~ bitwise complement
Arithmetic assignment operators:
The assignment operator is = (equal sign). This operator evaluates the expression on the right, and assigns the resulting value to the variable on the left.
The statement a+=5; will add the number 5 to the value of a. The other assignment operators are:
-= /= *= |= &= ^=
These have obvious meanings. They evaluate the expression on their right, and use the result performs the corresponding operation on the variable on the left.
Increment and decrement operators:
The increment and decrement operators are very useful in c language. They are extensively used in for and while loops. The syntax of the operators is given below.
++<variable name> --<variable name> <variable name>++ <variable name>--
The operator ++ adds 1 to the operand and – subtract 1 from the operand. These operators manifest in the two forms: prefix and postfix.
Conditional operator (ternary operator):
The conditional operator consists of two symbols: the question mark (?) and the colon (:). The syntax and the flowchart for the ternary operator are given in the following figures. This is the only operator in C that takes three operands.
larger = i > j? i : j;
Comma operator:
A set of expressions separated by commas is a valid construct in the c language. For ex: i, j are declared as followed nature.
int i, j;
Other operators:
The operator sizeof gives the size of the data type or the variable in
terms of bytes occupied in the memory. Another operator is the member
DATA TYPES REVISITED:
The primary data types in C were introduced. The primary types are again classified into several types.
Following table will summarize the data types:
s.no Data type Range Format Bytes
1 2. 3. 4. 5. 6. 7. 8. 9.
Short signed int Short unsigned int Long signed int Long unsigned int Float Double Long double Singed char Unsigned char -32768 to 32767 0 to 65535 -2147483648to2147483647 0 to 4294967295 -3.4e38 to 3.4e38 -1.7e308 to 1.7e304. -1.7e4932 to 1.7e4932. -128 to 127. 0 to 255. %d %u %ld %lu %f %lf %Lf %c %c 2 2 4 4 4 8 10 1 1
CONTROL STATEMENTS:
Many a times, we want a set of instructions to be executed in one situation and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction. A decision control instruction can be implemented in C using:
1) the if statement 2) the if-else statement 3) the nested if statement
The if statement:
In the C language the keywords if to implement the decision control instruction. The general form of if statement looks like this:
if (this condition is true) executes the statement;
The keyword if tells the compiler that what follows, is a decision control instruction. The condition following the keyword if is always enclosed with in a pair of parentheses. If the condition is not true then the statement is not executed, instead the program skips past it.
If we want to execute such multiple statements are to be executed then they must be placed within a pair of braces. The syntax is followed
if (this condition is true) { executable statement 1; executable statement 2; executable statement 3; ……. …… executable statement n; }
The if-else statement:
The if statement by itself will execute a single statement, or a group of statements, when the condition is false. Can we execute one group of statements if the condition is true and another group of statements if the condition is false? That is what is the purpose of the else statement. The syntax is followed:
if (this condition is true) { executable statement 1; executable statement 2; executable statement 3; ……. ……. …… executable statement n; }
else { executable statement 1; executable statement 2; executable statement 3; ……. …… executable statement n; }
In the above syntax weather the condition is true than the if blocks of statements are to be executes. If the condition is not true then the else block of the statements are to be executes.
Note:-
 The group of statements after the if up to and no including the else is called an ‘if block’. Similarly, the statements after the else form the ‘else block’.
 Notice that the else is written exactly below the if.
 Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces.
 As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope pair of braces is should be use.
Nested if-else:
It is perfectly all right if we write an entire if-else construct with in either the body of the if statement or the body of an else statement. This is called ‘nesting’ of ifs. This is shown in the following syntax.
if (this condition is true) { executable statement 1; ……. …… executable statement n; } else { if(condition) { executable statement n; } else { executable statement n; } }
Form of if:
The if statement can take any of the following forms: a) if (condition) do this; b) if(condition) { do this; and this; }
c) if(condition) do this; else do this; d) if(condition) { do this; and this; } else { do this; and this; } e) if(condition) do this; else { if (condition) do this; else { do this; and this; } } f) if(condition) { if( condition ) do this; else { do this; and this; } } else do this
The loop control structure:
The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times of until a particular condition is being satisfied. This repetitive operation is done through a loop control structure.
There are three methods by way of which we can repeat a part of a program. They are:
a) Using a for statement b) Using a while statement c) Using a do-while statement
While statement:
The while loop is most fundamental looping statement. It repeats a statement or block while its controlling is true. Here is the general form is follows: while(condition) { statement 1; statement 2; ………… ………… statement n; }
The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passed to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated. Since the condition is checked for while loop is called precheck loop.
Note:
 The statements with in the while loop would keep on getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
 The condition being tested may use relational or logical operations as shown in the following examples:
while(i<=10)
while(i<10&&j<=15)
while(j>10&&(b<15||C<20)) The flow chart of the while loop is can be follows:
do-while loop:
If the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, some times it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to being with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. C supplies a loop that does just that: do-while.
The do while loop always executes its body at least once, because its conditional expression is at the bottom of the loop its general form is.
do { statement 1; statement 2; …………. …………. statement n; } while (condition)
Each iteration of the do while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise the loop terminates. Hence do while is called
postcheck loop.
The do-while flow chart is follows:
FOR LOOP:
The for loop is useful while executing a statement a number of times.
The syntax of the for loop can be given below:
for(initial expression; test expression; update expression) { statement 1; statement 2; statement 3; …………. ………….. statement n; }
The for loop operation as follows:
While the loop first starts, the initial expression of the loop is executed. Generally, this is an expression that sets the value of the loop control variables, which acts as a counter that controls the loop. It is important to understand that the initialization expression is only executed once. Next, text expression is evaluated. It usually tests the loop control variable against a target value. If this expression is true, then the body of the lop is executed. This is usually an expression is that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.
CASE CONTROL STATEMENTS:
SWITCH STATEMENTS:
The control statement that allows us to make a decision form the number of choices is called switch. Or more correctly a
switch-case-default, since these three keywords go together to make up the control
statements.
The general form of the case is follows: switch (integer expression)
{ case constant1: do this; and this ; break; case constant 2: do this; and this ; break; case constant 3: do this; and this ; break; ……….. ……… ……….. ………. case constant n; do this; and this ; break; default: do this; and this ; }
The flow chart of the switch statement is follows:
The case statement is works like this:
The value of the expression is compared with each of the constant values in the case statement. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of expression, then the statement is optional. If no case matches and no default are present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statements. This has the effect of Jumping out of the switch.
JUMP STATEMENTS
:C supports three statements: break, continue and goto.
Using break statement:
We often come across situations where we want to jump out of a loop
instantly, without waiting to get back to the conditional test. The keyword
any c loop, control automatically passes to the first statement after the loop. A break is usually associated with an if.
The break flow chart is follows:
Using continue statement:
The keyword continue allows you to take the control to the beginning
of the loop, by passing the statements inside the loop, which have not been executed. The keyword continue associated with IF
Using goto statement:
A goto statement can cause C program control to end up almost any where in the program.FUNCTIONS
A function is a self contained block of statements that perform a coherent task of some kind. Every c program can be thought of as a collection of these functions.
The general form of the function is follows: main() { function1 (); function2 (); ………; function n(); }
function1 (arg1, arg2, arg3) type arg1,arg2,arg3; { statement 1; statement 2; statement 3; …………..; statement n; } Note:
 Any C program contains at least one function.
 If a program contains only one function, it must be main().  If a C program contains more than one function, then one of  These functions must be main(), because program execution
always begins with main().
 There are no limit on the number of functions that might be present in a C program.
 Each function in a program is called in the sequence specified by the function calls in the main();
 After each function has done its thing, control returns to main()  When main () runs out of function calls the program ends.  A function can be called any no of times.
 A function can be called form other functions, but a function cannot be defined in another function.
 There are basically two types of functions:
Library functions Ex: printf (), scanf ()……etc. User-defined functions Ex: India (), move ()…etc.
Use of the function:
There are mainly two reasons are there.
a) Writing function avoid rewriting the same code over and over. b) Using functions it becomes easier to write programs and keep track
of what they are doing.
Passing values between Functions:
#include<stdio.h> #include<conio.h> main()
{
int a,b,c,sum;
printf("\n enters the numberes"); scanf("%d%d%d",&a,&b,&c); sum=calsum(a,b,c);
printf("\n the sum= %d",sum); getch(); } calsum(x,y,z) int x,y,z; { int d; d = x+y+z; return(d); } Output:
Enters the numbers 10 30 30 The sum is 70.
 In this program, from the function main() the values of a,b,c are passed on to the function calsum(), by making a call to the function calsum() and mentioning a,b,c in the parentheses; In the calsum() function these values get collected in three
variables x,y,z.
calsum(x,y,z) int x,y,z;
 The variables a, b, c are called ‘actual arguments’ where as the variables x, y, z are called ‘formal arguments’.
 There are two methods of declaring the formal arguments. That one that we have to use in our program is known as Kernighan
and Ritchie (k&R) method.
calsum(x,y,z) int x,y,z; Another method is
calsum(int x, int y, int z)
This method is called ANSI method and is more commonly used these days.
 The return serves two purposes:
1) On executing the return statement it immediately transfers the control back to the calling statement.
2) It returns the value present in the parentheses after return to the calling program. In the above program the value of sum of three numbers is being returned.
3) There is no restriction on the number of return statements. Â All the following are valid return statements.
return(a); return(23); return(123.34); return;
 If we want that a called function should not return any value in that case, we must mention so by using the keyword void as shown below:
void display() {
printf(“\this is displayed block”); printf(“\n hallo”);
Advanced features of functions:
. With a sound basis of the preliminaries of c functions, let us now get into their intricacies. Following advanced topics would be considered here.
a) Calling functions by value and reference. b) Recursion.
Call by value and call by reference:
By now we are well familiar with how to call functions. But, if you observe carefully, when ever we called a function and passed something to it. we have always passed the ‘values’ of variable to the called function. Such function calls are called “call by value”. By this what we means is, on calling a function we are passing values of variables to it. The examples, call by value are shown below.
sum = calsum (a,b,c) f=fact (a);
We have also learnt that variable are stored somewhere in memory, so instead of passing the values of a variable, we can also pass the location number (also called address) of the variable to a function. It is called ‘call by
reference’. We will discuss it in pointers section.
Recursion:
Recursion is the process of defining something in the terms itself. As, it relates to C programming, recursion is the attribute that allows, a method to call it self. A method that calls itself is said to be recursive.
A example of recursion is the factorial of a number. main()
{
int fact(int); int result; result=fact(3);
printf(“\n the factorial of 3 is “,result); result=fact(4);
printf(“\n the factorial of 4 is “,result); result=fact(5);
printf(“\n the factorial of 5 is “,result); }
int fact(int n) { int r; if(n==1) return(1); r= fact(n-1)*n; return(r); } Output: The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120.
When fact () is called with the argument of 1, the function returns 1;
otherwise it returns the product of fact (n-1)*n. to evaluate this expression,
fact () is called with n-1. This process repeats until n equals I and calls to the
method beings returning.
STOTAGE CLASSES:
From C compiler’s point of view, a variable name identifies some physical location with in the computer were the string or bits representing variable value is stored. There are basically two kinds of locations in a computer where such a value may be kept: Memory and CPU registers. It is the variable’s storage class which determinates in which two locations the value is stored.
More ever. A variable’s storage class tells us: Where the variables would not be stored.
What will be initial value of the variable, if the initial value is not specifically assigned.(i.e. the default initial value).
What is the scope of the variable; i.e. in which functions the value of the variable would be available.
What is the life of the variable; i.e. how long would the variable exist. There are four storage classes in C:
¾ Automatic storage class ¾ Register storage class ¾ Static storage class
¾ External storage class. AUTOMATIC STORAGE CLASS:
The features of a variable defined to have an automatic storage call are as under:
a) Storage memory
b) Default initial value - An unpredictable value, which is often called a garbage value.. c) Scope - Local to the block in which the
variable is defined.
d) Life - Till the control remains with in the
block in which the variable is defined. Following program shows how an automatic storage class variable is declared and the fact that if the variable is not initialized it contains a garbage value.
#include<stdio.h> #include<conio.h> main()
{
auto int i,j;
printf(“\n %d%d”,I,j); getch(); } Output: 2345 78912
Where,2345 and 78912 are garbage value of I,j.
When you run this program you may get different values, since garbage values could be absolutely any values. So always make it a point that you initialize the automatic variables properly, other wise you are likely to get unexpected.
Scope and life of the automatic variable:
The following program shows the scope and life of an auto variable: #include<stdio.h>
#include<conio.h> main()
{
{
auto int i=2; {
auto int i=3;
printf(“\n i=%d”,i); } printf(“\n i=%d”,i); } printf(“i=%d”,i); } output: 3 2 1
STATIC STORAGE CLASS:
The features of a variable defined to a static storage class are as under: a) Storage - memory.
b) Default initial value - Zero.
c) Scope - local to the block in which the variable is defined.
d) Life - Value of the variable persists between different function calls.
Compare the two programs below to understand the difference between the automatic and static storage classes.
The programs consists of two functions main() and increment(). The function increment () gets called from main() thrice. Each time in it increments the value of I and prints it. The only difference in the two programs is that one used an auto storage class for variable I, whereas the other uses static storage class.
#include<stdio.h> #include<conio.h> main() { void increment; increment(); increment(); increment(); } void increment() {
auto int i=1; printf(“%d”,i); i=i+1; } output: 1 1 1 #include<stdio.h> #include<conio.h> main() { void increment; increment(); increment(); increment(); } void increment() {
static int i=1; printf(“%d”,i); i=i+1;
} output: 1 2 3
Like auto variables, static variables are also local to the block in which they are declare. The difference between them is that static variables don’t disappear when the function is no longer active. Their values persist. If the control come back to the same function again the static variables have the same value they had last time around.
REGESTER STORAGE CLASS:
The features of a variable defined to be register storage class are as under:
a) Storage - CPU registers b) Default initial value - Garbage value.
c) Scope - Local to the block in which the variable is defined.
d) Life - Till the control remains with in the block in which the variable is defined.
The program demonstrating register storage class: #include<stdio.h> #include<conio.h> main() { regester int i; for(i=0;i<10;i++) printf(“%d”,i); }
EXTERNAL STORAGE CLASS:
The features of a variable whose storage class has been defined as external are follows:
a) Storage - Memory. b) Default initial value - Zero.
c) Scope - global
d) Life - As long as the program’s execution doesn’t come to an end. Example: main() { void increment(); void decrement(); printf(“\n i=%d”,i); increment(); increment(); decrement(); decrement(); } void increment() { ini i=i+1;
printf(“\n on incrementing i=%d”,i); }
void decrement() {
int i=i-1;
printf(“\n on decrementing i=%d”,i); }
output: i=0; on incrementing i=1 on incrementing i=2 on decrementing i=1 on decrementing i=0
ARRAY & STRINGS
A array can be defined as a group of similar type variables which occupy
contiguous locations in memory and that are referred to by a common name. Arrays of any data type can be created and may have one or more
dimensions. Each member or element of an array is accessed or referred to by its position in the group, called index.
In c the elements of the array should be of the same data type.
ONE DIMEMTIAL ARRAY:
Array declaration:
To begin, like other variables an array needs to be declared, so that the compiler will know what kind of an array (i.e what data type it will be strong) and how large an array should be (size occupied by the array in the memory).
General form of array declaration is type var_name [size];
type: it denotes the data type the array will be strong. Var_name: name of the array.
Size: the maximum number of elements that can be stored in the array. EX:-
int var [10];
float number [20]; char ch[100];
This size is often called the dimension of the array.
Array initilisation:
Till the array elements are not given any specific values, they are supposed to contain garbage values, they are supposed to contain
garbage values if declared as auto. However can managed to store values in them during program execution.
Let us now see how to initialize an array while declaring it. Following are few examples that demonstrate this
int num[6] = { 2,3,4,5,6,7}; int n[] = {2,3,4,5,6,7};
float press[] = { 12.33,34.55,34.56,-98.78}; Note:
 Till the array elements are not given any specific values, they are supposed to contain garbage values.
 If the array is initialised where it is declared, mentioning the dimension of the array is important.
Accessing elements of an array:
Once an array is declared, then it can be referred. All the array elements are numbered, stating with 0 to n-1 elements.
Entering Data into an Array:
Here is the section of code that places data into an array: for(i=0;i<=10;i++)
{
printf(“\n enter the numner”); scanf(“%d”,&num[i]);
}
the for loop causes the process of asking for and receiving a number from the user to be repeated 10 times. The first time though the loop, i has a value 0, so the scanf() statement will cause the value typed to be stored in the array element num[0], the first element of the array. This process will repeat until i becomes 10. This is last time through the loop, which is a good thing, because there is no array element like num[10].
Reading data from an array:
The balance of the program read the data back out of the array and used it to calculate the average. The for loop is much the same, but now the body of the loop caused each number to be added to a running total stored in a variable called sum. When all the numbers have been added up, the result is divided by 10, to get the number’s average.
for(i=0;i<10;i++) {
sum=sum+num[i]; }
avg=sum/10;
Notes:
 An array is a collection of similar elements.
 The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
 An array is also known as a subscripted variable.
 Before using an array its type and dimension must be declared.  However big an array its element are always stored in
contiguous memory locations.
Array elements in memory:
int array[5];
What happens in memory what we make this declaration? 10 bytes get immediately reserved in memory. 10 because each of the 5 integers would be 2 bytes long. And since, the array is not being initilised; all eight values present in it would be garbage values. If the storage classed is declared to be static then all the array elements would have a default initial values as 0. What ever e the initial values all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is below shown:
Array bounding:
In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; probably on top of other data, or on the program itself. This will lead to unpredictable results, to say the least, and there will be no error message to warn that you are going beyond the array size. In some cases the computer may just hang.
Passing array elements to a Function:
Array elements can be passed to a function by calling the function by value, or by reference. In call by value we pass values of array elements to the function. The following example illustrates this:
#include<stdio.h> #include<conio.h> main()
int i; int marks[] = { 55, 35,45,65,75}; for(i=0;i<5;i++) { display(marks[i]); } } display(int m) { printf("\t %d",m); } OUTPUT: 55 35 45 65 75
TWO DIMENSIONAL ARRAYS:
A two dimensional array consists of both rows and columns of the elements as against one-dimensional array which has only column of elements.
For ex: 6 12 12 19
20 38 22 48
10 18 18 50
57 74 98 48
is a two dimensional array of integers.
Two dimensional array declaration:
General form: type var_name [rowsize] [column size] Type: denotes the data types the array will be strong. Var_name: denotes the array name.
Row size: denotes the max no of the rows. Column size: denotes the max no of the column. Examples:
int arr[3][5]; float var[5][6]; char name[10][10];
Initialising a two dimensional array:
Just like one dimensional array even two dimensional array can be initialized at the time of declaration.
For ex: int a[2][3] = { { 23,45,56}, {21,43,65} }; float f[][]= { { 1.53,4.63,6.92} { 2.34,5.87.95.23} }; int stud[2][2]={2,3,4,5}; Note:
It is important to remember that while initializing a array it is necessary to mention the second (column) dimension, where as the first dimension (row) is optional.
for(i=0;i<3;i++) {
for(j=0;j<4;j++) {
printf(“\n enter the number”); scanf(“%d”,&arr[i][j]);
} }
STRINGS:
The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character array are many a times also called strings. Character arrays or strings are used by programming languages to manipulate text such as word and sentences.
A string constant is a one dimensional array of characters terminated by a null (“\0”). For ex: char name = { ‘K’,’A’,’E’,’S’,’H’,’\0’ }
Each character in the array occupies one byte of memory and the last character is always ‘\0’. This is looks like two characters. But it is actually only one character, with the \ indicating that what follows it is something special. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same. ASCII value of ‘0’ is 48. The figure below shows the way a character array is stored in memory. That the elements of the character array is stored in contiguous memory locations.
The terminating null(‘\0’) is important, because it is the only way the function that work with a string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters.
B H A S K A R 1001 1002 1003 1004 1005 1006 1007
C considers the fact that you would use string very often and hence provides a shortcut for Initialising string. For ex: the string used above can also be initialised as,
char name[] =”Bhaskar”;
Note that in this declaration ‘\0’ is not necessary. C inserts the null character automatically.
Note:
 Character takes only a single byte to store a character.  String takes one extra character to store the null value. ex: char a[] = ‘a’;
Char string[10] = {’a’,’v’,’a’,’n’,’t’,’h’,’i, \0’}
String library functions:
There are some library functions are there. It is header by <string.h>
Functions use strlen strlwr strupr strcat strncat strcpy strncpy srtcmp strcmpi strnicmp strdup strchr strrchr strstr strset strrev
Finds length of a string.
Converts a string to lowercase. Converts a string to uppercase.
Appends one string at the end of another.
Appends first n char’s of a string at the end of another. Copies a string into another.
Copies first n characters of two strings. Compares two strings
Compares first n character of two strings.
Compares first n characters of two stings without regard to case Duplicates a string
Finds first occurrence of a given character in a string Finds last occurrence of a given character in a string Finds first occurrence of a given string in another string. Sets first n characters of a string to a given character Reverse string
Strlen():
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
main() {
char arr[] =”character”; int len1,len2;
len1 = strlen (arr);
len2 = strlen (“medicine”);
printf(“\n string = %s length = %d”,arr,len);
printf(“\n string = %s length = %d”,”medicine”,len2); }
The output would be:
string = character length = 9. String = medicine length =8.
Strcpy():
This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied to this function. Ex: #include<stdio.h> #include<conio.h> main() { char source[]="nayagara"; char target[20]; clrscr(); strcpy(target,source);
printf("\n the source string is:: %s",source);
printf ("\nTHE TARGET STRING IS:: %s",target); getch();
Two dimensional array of characters:
The following example is can be follows: #include<stdio.h> #include<conio.h> #define FOUND 1 #define NOTFOUND 0 main() { char masterlist[6][10]={"raman","surya","kumar","nagesh","gopal","rajesh"}; int i,flag,a; char yourname[10];
printf("\n enter your name:"); scanf("%s",yourname); flag = NOTFOUND; for(i=0;i<=5;i++) { a=strcmp(&masterlist[i][0],yourname); if(a==0) {
printf("\n Welcome, you can enter the palace"); flag =FOUND;
break; }
}
if(flag==NOTFOUND)
printf("\n sorry, you are a trespasser"); }
Output:
Enter the name Bhaskar Sorry, you are a trespasser. Enter your name surya
POINTERS
The address of data item is the address of its first storage location. This address can be stored in another data item and manipulated in a program. The address of a data item is called pointer to the data item and a variable that holds an address is called a pointer variable.
Address and dereferencing(& and *) operators: int C=5;
the compiler will automatically assign memory for this data item. The data item can be accessed of we know the location (i.e. the address) of the memory cell where the value of the data item is stored.
The address of c’s memory location can be determined by the
expression &C, where & is unary operator, called the ‘address of’ operator. It evaluates the address of its operand.
We can assign address of c to another variable. Pv as
Pv=&c;
This new variable pv is called a pointer to v, since it points to the location where v is stored in memory. Thus PV is referred to as a pointer
variable.
The data item is represented by v, can be accessed by the expression
*pv, where * unary operator, called the value at the address” operator. It
operates only on a pointer variable.
Access to an object through a pointer is called Dereferencing, and the operator asterisk (*) is called the “dereferencing or indirection operator” Ex1: determination of pointers.
#include<stdio.h> #include<conio.h> main() { int i =7; float f=10.5; char c='A';
printf("\n %d is stored at address %u",i,&i); printf("\n %d is stored at address %u",f,&f); printf("\n %d is stored at address %u",c,&c); getch();
OUTPUT:
7 is stored at address 65484
10.500000 is stored at address 65486 A is stored at address 65491
Pointers and function:
A function can take a pointer of any data type, as argument and can return a pointer to any data type. For ex: the function definition is
double *maxp(double *ap,double *bp) {
return(*ap<=*yp)?ap:bp; }
Call by reference:
In call by reference, address of the arguments are supplied to the called function and changes to the parameter values in the called function cause changes in the values of the argument.
Call by reference can be effected by passing pointers to the variables as arguments to the function. These pointers can then be used by the called function to access the arguments variables.
/* a program demonstrating Arguments as pointer */ #include<stdio.h> main() { int a=10,b=20; void swap(int*,int*); swap(&a,&b);
printf("\n a=%d,\t b=%d",a,b); getch();
}
void swap(int *a, int*b) { int temp; temp=*a; *a=*b; *b=temp; } a=20, b=10
Steps involved for using pointers in a function are:
1. Pass address of the variable( using the & or direct pointer variable). 2. Declare the variable as pointer with in the routine.
3.
Refer to the values contained in a memory location via *.Function returning pointers:
#include<stdio.h> #include<conio.h> main() { int a,b,*c; int * check(int,int);
printf("\n enter two numbers:"); scanf("%d%d",&a,&b);
c=check(a,b);
printf("\n greater no is %d",*c); getch();
}
int* check(int i,int j) { int *p,*q; p=&i; q=&j; if(*p>=*q) return(p); else return(q); } Output:
enter two numbers: 10 20 greater no is 20
POINTERS AND ARRAYS:
Pointers to array:
Arrays are internally stored as pointer. The elements of an array can be efficiently accessed by using a pointer.
#include<stdio.h> main()
{
static int ar[5]={10,20,30,40,50}; int i,*ptr; ptr=&[ar0); for(i=0;i<5;i++) { printf("\n %d - %d \n",ptr,*ptr); ptr++; } getch(); } Output: 404 – 10 406 – 20 408 – 30 410 – 40 412 - 50
Arrays as Function Arguments:
An array name, can be passed as argument to a function. The declaration is follows.
void fun_arr(double x[], int length) {
/* body of the length */ }
can be equivalently be written as
void fun_arr(double *x, int length) {
/* body of the function*/ }
When an array is passed as an argument to a function. We actually pass the starting address of the array. This address is accepted in a pointer variable declared in the function definition. Since arrays are stored in continuous memory location, we can perform indexing on the stating location on the array.
/* program to displau array element by passing array to a function */ #include<stdio.h>
#include<conio.h> main()
{
static int num[5]={25,49,17,90,11}; clrscr();
void display(int, *int); display(num,5);
getch(); }
void display(int *j,int n) {
int i=1;
printf("\n array elements are:"); while(i<=n) { printf("%d\t",*j); i++; j++; } } OUTPUT
array elements are:25 49 17 90 11
Pointers and character arrays:
All string manipulation use pointers. When a string is created, it is stored contiguously and a NULL(‘\0’) character is automatically appended to it at the end. This NULL signifies the end of the string.
A character-type pointer variable can be assigned to an entire string as a part of the variable declaration. Thus a string can conveniently be represented by an entire one dimensional character array or by a character pointer.
Shown below is c program in which two strings are represented as one_di. character array.
#include<stdio.h>
char z[]="this string is declared externally\n\n"; main()
{
clrscr();
printf("\n %s",z); printf("\n %s",x); }
Output:
this string is declared externally this string is declared with in main
/* Here is a different version of the same program. The string are now assigned to pointer variable rather than to conventional one_di array */
#include<stdio.h>
char *z="this string is declared externally\n\n"; main()
{
static char x="this string is declared with in main"; clrscr();
printf("\n %s",z); printf("\n %s",x); }
Output:
this string is declared externally this string is declared with in main
DYNAMIC MEMORY ALLOCATION:
In many programs the number of objects to the processed by the program and their sizes are not known.
C provides a collection of dynamic memory management functions that enable storage to be allocated as needed and released when no longer required. Their prototypes are declared in alloc.h header
file or malloc.h file.
The allocation of memory at run time, is known as “dynamic memory allocation”
1. malloc()
malloc() is used to obtain storage for an object. The allocation of
storage by calling malloc() yields a pointer to the beginning of the storage allocated and is suitable aligned and allocated, so that it may be assigned to a pointer variable.
Suppose that x is to be defined as a one dimensional, 10-elements array of integers. Our first step is to declare x as a pointer variable. At this movement, 2 bytes are stored in memory for this pointer variable.
int *x;
To assign sufficient memory for x(i.e. 10 integers), we can make use of the library function malloc () , as follows.
x=(int *)malloc(10 *sizeof (int));
Format:
Void *malloc(size);
Size: Is the number of bytes required.
Malloc returns a pointer to void it needs to be typecasted. Void* return type can be used to make general purpose function with out having to known the actual use of the function.
To be consistent with the definition of x as a pointer to integer, we want the pointer to be an integer. Hence, we include a type cast that is,
x= (int *) malloc (10 * sizeof (int));
calloc ():
calloc() function works exactly similar to malloc() except for the fact that it needs two arguments as against the one argument required by malloc().
void *calloc(n items, size);
nitems : the number of items to allocate. Size : Size of each item
For ex:
ar=(int*)calloc(10,sizeof(int));
Allocate the storage to hold an array of 10 integers and assigns the pointer to this storage to ar.
While allocating memory using calloc(), the number of items which are allocated, are initialised.
realloc()
general format for memory allocation using realloc() is
void *realloc (void *block, size);
Where
Block: points to a memory block previously obtained by calling malloc(), calloc() or realloc().
realloc() returns a pointer to the new storage and Null if it is not possible to resize the object, in which case the object(*block) remains unchanged. The new size is larger or smaller than the original size. If the
new size is larger, the original contents are preserved and the remaining space is uninitilised, if smaller, the contents are unchanged up to the new size.
The function realloc() works like malloc() for the specified size if block is a null pointer.
For ex:
cp=(char *)realloc(cp, sizeof(“computer”));
free():
The memory allocated malloc(), calloc() or realloc() function is not destroyed automatically. It has to be cleared by using the function free() free(ptr);
STRUCTURES
Ordinary variables can hold one piece of information and array can hold a number of pieces of information the same data type. These two data types can handle a great variety of situations. But quite often we deal with entities that are collection of dissimilar data types. C deals with this situation with use of structures.
a) Construct individual array, one for storing names, another for storing pieces and still another for storing number of pages.
b) Use structure variable. Declaring a structure:
The general form of a structure declaration statement is given below: Struct<structure name> { structure element1; structure element 2; ……… structure element n; };
once the new structure data type has been defined one or more variables can be declared to be of that type.
Ex: struct <structure name> variables; struct book { char name; float price; int pages; }; or struct bookb1,b2,b3; { char name; float price; int pages; }b1,b2,b3;
Note the following points while declaring a structure types:
a) The closing brace in the structure type declaration must be followed by
;
b) It is important to understand that a structure type declaration type does not tell the compiler in the space memory. Declaration all a structure declaration does is, it defines the “form of the structure”.
c) Usually structure type declaration appears on the top of the source code file, before any variables are functions are defined in very large programs they are usually put in a separate header file, and the file is included( using preprocessor direct to # include) in which ever program we want to use this structure type.
Accessing structure element:
Having declared the structure type on the structure type variables, we will shift our focus to how the elements of the structure can be accessed. In arrays we can access individual elements of an array using a subscript. Structure use a different scheme. They use a dot (.) operator. So to refer to pages of the structure defined in our simple program we have to used.
Ex: b1.works
Note: before the dot there must always a structure variable and after the dot
there must be always element
What ever be the elements of a structure they are always stored in contiguous memory locations. This can be illusstared by the following program.
\*Program demonstrating memory map of structure elements*\ #include<stdio.h> main() { struct book { char name; float price; int pages; }; struct book b1 = { ‘c’,150.00,230};
printf(“\n memory address of name = %u”,&b1.name); printf(“\n memory address of price = %u”,&b1.price); printf(“\n memory address of pages = %u”,&b1.pages); }
OUTPUT:
Memory address of name = 23456. Memory address of price = 23457 Memory address of pages = 23461.
Arrays of a structure:
The array of a structure is similar to a normal array declaration and follows down.
struct value b[10];
This provides the space in memory for 10 structures of the type struct book. The syntax we use to reference each element of the array b is similar to the syntax used for arrays in ints and chars.
In an array of structure all elements of the array are stored in adjacent memory locations. Since each element of this array is a structure, and since
all structure elements are always stored in adjacent location the arrangement of array of structure in memory is contiguous.
/* program demonstrating the usage of an array of structure*/ #include<stdio.h> #include<conio.h> main() { struct book { char name; float price; int pages; }; struct book b[10]; int i; clrscr(); for(i=0;i<10;i++) {
printf("\n enter the name::"); scanf("%c",&b[i].name); printf("\n enter the price"); scanf("%f",&b[i].price); printf("\n enter the pages::"); scanf("%d",&b[i].pages); } for(i=0;i<10;i++) { printf("\n %c%f%d",b[i].name,b[i].price,b[i].pages); } }
ASSIGNING A STRUCTURE VARIABLE TO ANOTHER
STRUCTURE VARIABLE:
The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator. This shown in the following program example:
/* program demonstration assigning a structure variable to another*/ #include<stdio.h> main() { struct employee { char name[10]; int age; float salary; };
struct employee e1= {"xyz",24,15000.00}; struct employee e2,e3;
clrscr(); strcpy(e2.name,e1.name); e2.age=e1.age; e2.salary=e1.salary; e3=e2; printf("\n %s%d%f",e1.name,e1.age,e1.salary); printf("\n %s%d%f",e2.name,e2.age,e2.salary); printf("\n %s%d%f",e3.name,e3.age,e3.salary); getch(); } OUTPUT: xyz 24 15000.00 xyz 24 15000.00 xyz 24 15000.00
NESTING OF STRUCTURES:
One structure can be bested with in another structure. Using this facility complex data types can be created.
#include<stdio.h> main() { struct address { char phone[15]; char city[30]; int pin; }; struct emp { char name[30]; struct address a; }
struct emp e{“xyz,”9885141414”,”Bombay”,32516); printf(“\n name = %s phone = %s”,e.name,e.a.phone); printf(“\n city = %s pin = %d”,e.a.city,e.a.pin); }
POINTERS AND STRUCTURES:
The way we can have a ointer pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to a struct. Such pointer are known as “structure pointer”
Ex: #include<stdio.h> main() { struct book { char name[30]; char author[30]; int callno; };
struct book b1={“wings of fire”, Abdul kalam ”, 23456); struct book *ptr;
prt = &b1;
printf(“\n %s%s%d”,b1.name,b1.author,b1.callno); printf(“\n %s%s%d”,ptr->name,ptr->author,ptr->callno);
printf(“\n %s%s%d”,*ptr.name,*ptr.author,*ptr.callno); }
output:
wings of fire Abdul kalam 23456 wings of fire Abdul kalam 23456 wings of fire Abdul kalam 23456