2014 C Notes (Repaired)-3(1)
2014 C Notes (Repaired)-3(1)
UNIT – I
OVERVIEW OF C:
HISTORY OF C
‘C’ seems a strange name for a programming language. ‘C’is a structured, high-level,
machine independent language. It allows software developers to develop programs without
worrying about the hardware platforms where they will be implemented.
The root of all modem languages is ALGOL, introduced in the early 1960s. ALGOL
was the first computer language to use a block structure.
In 1970,Ken Thompson created a language using many features of BCPL and called it
simply B. B was used to create early versions of UNIX operating system at Bell Laboratories.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories
in 1972. C uses many concepts from these languages and added the concept or data type and
other powerful features. Since it was developed along with the UNIX operating system, it is
strongly associated wilh UNIX.
B
1970 Ken Thompson
K&R C
1978 Kernighan and Ritchie
ANSI C
1989 ANSI Committee
ANSI/ISO C
1990 ISO Committee
C99
1999 Standardization Committee
2
IMPORTANCE OF C
C has all the advantages of assembly Language and all the significant features of modern high
level ‘Language. So it is called middle Level Language.
Documentation section
link section
definition section
}
subprogram section
(user defined function)
subprogram section
(user defined function)
3
1) Documentation section – It gives the name of the program, the author and any other details
about the program.
2) Link section – It provides instruction to the compiler to link functions from the system
library.
4) Main( ) function section – Every C program must have one main() function. The program
execution begins at the opening brace and ends at the closing brace of main function section.
5) Subprogram section – It contains all the user-defined functions that are called in the main
function.
CHARACTER SET
1. Letters
2. Digits
3. Special characters
4. White spaces
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters:
, -comma ‘ -apostrophe
\ -backslash ~ -tilde
_ -underscore . –period
4
; -semicolon : -colon
^-caret *-asterisk
#-number sign
TRIGRAPH CHARACTERS
Each trigraph sequence consists of three characters (two question marks followed by another
character)
?? ( [ left bracket
?? / \ back slash
??- ~ tilde
C TOKENS
In an individual words and punctuation marks are called tokens. Similarly , In a C program
the smallest individual units are known as C tokens. C has fixed type of tokens as
follows.
1. Keywords ( float, while )
5
2. Identifiers ( amount )
3. Constants ( 100 , 200)
4. Strings (“hello”)
5. Operators ( + - * % )
6. Special symbols { } []
KEYWORDS
Every c word is classified as either a keyword or an identifier. All key words have
fixed meanings cannot be changed. A keyword may not be used as a variable name. All
keywords must be written in lowercasae.
IDENTIFIERS
Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of a sequence of letters and digits, with a letter as a first character.
Both lowercase and uppercase letters are permitted. Rules for Identifiers
1. First character must be an alphabet or underscore.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.
Example: name, area, amount.
A constant is fixed values that do not change any value during the execution of a
program.
There are mainly two types of constants namely: Numeric and character constants.
CONSTANTS
Integer Constants
Character constants have integer values known as ASCII values. For example, the
statement
Printf(“%d” , ‘a’);
Would print the number 97, the ASCII value of the letter a. Similarly, the statement
Printf(“%d” , ‘97’);
Constants Meaning
‘\a’ Audible alert(bell)
‘\b’ Back space
‘\f’ Form feed
‘\n’ Newline
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\v’ Vertical tab
‘\’ Single quote
‘\”’ Double quote
‘\?’ Question mark
‘\\’ Backslash
‘\0’ null
String Constants:
A combination of characters enclosed within a part of double inverted commas is called
as “String Constant”.
Example :
“Salem” “35.675” ,
VARIABLES
Variable names are names given to locations in the memory. These locations can
contain integer, real or character constants.
An integer variable can hold only an integer constant, a real variable can hold only a
real constant and a character variable can hold only a character constant. Rules for
Constructing Variable Names
DATA TYPES
All c compilers support five fundamental data types namely integer (int), character
(char), floating point (float), double precision floating point (double) and void. The basic four
types are
i) Integer types
a) Integer
b) character
c) Floating type
d) void
9
Integer types:
Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest
15bits for number.
To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned forms.
A short int requires half the amount of storage than normal integer. Unlike signed
integer, unsigned integers are always positive and use all the bits for the magnitude of the
number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers
are used to declare a longer range of values and it occupies 4 bytes of storage space.
The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The double is
same as float but with longer precision and takes double space (8 bytes) than float. To extend
the precision further we can use long double which occupies 10 bytes of memory space.
Character Type:
Character type variable can hold a single character. As there are singed and unsigned int
(either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte
each, but having different ranges. Unsigned characters have values between 0 and 255, signed
characters have values from –128 to 127.
Void Type:
The void type has no values therefore we cannot declare it as variable as we did in case
of integer and float.
The void data type is usually used with function to specify its type. Like in our first C
program we declared “main()” as void type because it does not return any value. The concept of
returning values will be discussed in detail in the C function hub.
Array in C programming
An array in C language is a collection of similar data-type, means an array can hold
value of a particular data type for which it has been declared. Arrays can be created from
any of the C data-types int,
Pointers in C Programming
A pointer is derived data type in c. Pointers contain memory addresses as their values.
11
Structure in C Programming
We used variable in our C program to store value but one variable can store only single
piece information (an integer can hold only one integer value) and to store similar type of
values we had to declare...
C language supports a feature where user can define an identifier that characterizes an
existing data type. In short its purpose is to redefine the name of an existing data type.
Syntax: typedef <type> <identifier>; like
typedef int number;
In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables.
The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n
Example:
enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;
DECLARATION OF VARIABLES
A variable can be used to store value of any data type. The general format of any declaration is
datatype v1, v2, v3, ……….. vn;
Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Example:
int sum;
int number, salary;
double average, mean;
Character char
Signed Short Integer signed short int (or) short int (or) short
Signed Long Integer signed long int (or) long int (or) long
13
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.
Example:
The second type of user defined datatype is enumerated data type which is defined as
follows.
The identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the definition we can
declare variables to be of this ‘new’ type as below.
The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n
Example:
Another way of giving values to variables is to input data through keyboard using the scanf
function.
The general format of scanf is as follow:
scanf(“control string”, & variable1,&variable2,…….)
The const data type qualifier tells the compiler that the value of the int variable class_size may
not be modified in the program.
When we declare a variable as volatile, the compiler will examine the value of the
variable each time it is encountered to see whether any external alteration has changed the
value.
The value of the variable declared as volatile can be modified by its own program as
well. The value must not be modified by the program while it may be altered by some other
process, then we declare the variable as both const and volatile
Volatile const int location =100;
OPERATORS:
Operators are the symbol which operates on value or a variable. For example: + is a operator to
perform addition. C programming language has wide range of operators to perform various
operations. For better understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Assignment Operators
Relational Operators
16
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
* Multiplication
/ Division
OUTPUT:
a+b=13
a-b=5
a*b=36
17
a/b=2
Remainder when a divided by b=1
Explanation
Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4
equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So,
the output is also integer and the compiler neglects the term after decimal point and shows
answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.
In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts
1 to operand respectively. For example:
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return
it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and
then only increment it. This can be demonstrated by an example:
#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}
Output
2 4
18
Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to the
left side. For example:
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Relational Operator
Relational operator’s checks relationship between two operands. If the relation is true, it returns
value 1 and if the relation is false, it returns value 0. For example:
a>b. Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it
returns 0.
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are
3 logical operators:
Meaning of
Operator Example
Operator
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c= =5) || (d>5)) to
be true, either the expression should be true. Since, (c= =5) is true. So, the expression is
true. Since, expression (c= =5) is true! (c= =5) is false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols? and: . Conditional
operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level
programming.
| Bitwise OR
20
Operators Meaning of operators
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
It is a unary operator which is used in finding the size of data type, constant, arrays, structure
etc. For example:
#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}
Output
Conditional operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.
21
Syntax of conditional operators
conditional_expression? expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.
Output
UNIT II
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. In C, decision making can be performed with following two
statements.
1. IF STATEMENT:
if statement syntax
if (test expression){
Statement/s to be executed if test expression is true;
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis
are executed. But, if the test expression is false, the execution of the statements for the body of
if statements are skipped.
Flowchart of if statement
23
2. IF...ELSE STATEMENT:
The if...else statement is used, if the programmer wants to execute some code, if the test
expression is true and execute some other code if the test expression is false.
Syntax of if...else
if (test expression)
Statements to be executed if test expression is true;
else
Statements to be executed if test expression is false;
#include <stdio.h>
int main(){
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
24
Output
The if...else statement can be used in nested form when a serious decision are involved.
if (test expression)
statements to be executed if test expression is true;
else
if(test expression 1)
statements to be executed if test expressions 1 is true;
else
if (test expression 2)
.
.
.
else
statements to be executed if all test expressions are false;
If the test expression is true, it will execute the code before else part but, if it is false, the control
of the program jumps to the else part and check test expression 1 and the process continues. If
all the test expression are false then, the last statement is executed.
#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check".\n);
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d=%d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d>%d",numb1,numb2);
else
25
printf("Result: %d>%d",numb2,numb1);
return 0;
}
Output 1
ELSE IF LADDER
There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of it’s in which the statement associated with each else is an if. It
takes the following general form:
if (condition 1)
statement 1 ;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;
This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default
statement will be executed.
4. SWITCH....CASE STATEMENT
26
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one among many alternatives
if...else can be used but, this makes programming logic complex. This type of problem can be
handled in C programming using switch...case statement.
Syntax of switch...case
switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant3;
break;
.
.
.
default:
codes to be executed if expression doesn't match to any cases;
}
Flow chart:
Output
Enter operator +, -, * or /:
/
Enter two operators:
34
3
Num2/num1=11.33
GOTO STATEMENT
In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax of goto statement
goto label;
.............
.............
.............
label:
28
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code/s after it.
Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement is
considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmers should try to avoid goto statement as possible as they can.
Loops causes program to execute the certain block of code repeatedly until some conditions are
satisfied, i.e., loops are used in performing repetitive work in programming.
Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s
only one time and repeat the execution 10 times using loop.
for loop
while loop
do...while loop
WHILE LOOP:
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
Output
Enter a number.
5
Factorial=120
DO...WHILE LOOP:
In C, do...while loop is very similar to while loop. Only difference between these two loops is
that, in while loops, test expression is checked at first but, in do...while loop code is executed at
first then the condition is checked. So, the code are executed at least once in do...while loops.
do {
some code/s;
30
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true,
code/s inside body of do are executed again and the process continues until test expression
becomes false (zero).
#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
31
In this C program, user is asked a number and it is added with sum. Then, only the test condition
in the do...while loop is checked. If the test condition is true, i.e, num is not equal to 0, the body
of do...while loop is again executed until num equals to zero.
FOR LOOP
The initial expression is initialized only once at the beginning of the for loop. Then, the test
expression is checked by the program. If the test expression is false, for loop is terminated. But,
if test expression is true then, the codes are executed and update expression is updated. Again,
the test expression is checked. If it is false, loop is terminated and if it is true, the same process
repeats until test expression is false.
Flow chart:
Example Program:
#include <stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
32
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
JUMPS IN LOOPS:
Loops perform a set of operations repeatedly until the control variables fails to
satisfy the test conditions.
The number of times the loop is repeated is decided in advance and the test
conditions is returned to achieve this.
Some times, when executing a loop it becomes desirable to skip a part of the loop
or to leave the loop as soon as a certain conditions occurs.
C permits a jump form one statement to another within a loop as well as jump out of a
loop.
Jumping Out of a Loop:
Exit from a loop can be accomplished by using the break statement or the goto
statement.
These statements can also be used within while, do or for loops.
When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
When the loops are nested the break would only exit from the loop containing it. i.e the
break will exit only a single loop.
while (------) do for (-------)
{ { {
if (condition) if (condition)
if(error)
33
break; break; break;
} } from }
UNIT - III
ARRAYS
An array is a fixed-size sequenced collection of elements of the same data type. It
is simply a grouping of like-type data. In its simplest form, an array can be used to
represent a list of numbers or a list of items.
An array is a group of related data items that share a common name.
An array is a collection of similar quantities. It is referenced by a common
name.
Each element of an array is stored in successive locations of memory.
Arrays to represent not only simple list of values but also tables of data tin two,
three or more dimensions.
There are three types of arrays. They are
1. One-dimensional arrays.
2. Two-dimensional arrays.
3. Multidimensional arrays.
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or one-dimensional array.
Declaration of arrays:
Like any other variable arrays must be declared before they are used.
34
The general form of declaration is:
Where
The type specifies the type of the elements that will be contained in the array, such as
int, float or char
the size indicates the maximum number of elements that can be stored inside the array .
a is the name of the array with 5 subscripts of integer data types 0 to 4 and the computer
reserves five storage location as shown below.
a[0]
a[1]
a[2]
a[3]
a[4]
A value stored into an element in the array simply by specifying the array element on the
left hand side of the equals sign. In the statement
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array.
The ability to represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the elements
in the array by varying the value of the variable that is used as a subscript into the array. So the
for loop
Will sequence through the first 100 elements of the array grades (elements 0 to 99) and
will add the values of each grade into sum. When the for loop is finished, the variable sum will
35
then contain the total of first 100 values of the grades array (Assuming sum were set to zero
before the loop was entered)
Initialization of arrays:
At compile time
At run time
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element if the
number of values in the list is less than the number of elements, then only that many elements
are initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler allocates
enough space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. This approach works
fine as long as we initialize every element in the array.
------
-------
For(i=0;i<100; i=i+1)
{ if i<50
Sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to zero while the remaining 50
elements are initialized to 2.0 at run time.
Two-Dimensional Arrays
Two dimensional arrays are used in situation where a table of values needs to be stored
in an array.
Example:
int a[3][3];
37
Two-dimensional arrays are stored in memory. The first index selects the row and the second
index selects the column within that row.
Column0 Column1 Column2
The two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces.
Example:
int table[2][3] = { 0, 0, 0, 1, 1, 1};
initializes the elements of the first two row to zero and the second row to one. The
initialization is done row by row.
int table[2][3] = {{ 0, 0, 0}, {1, 1, 1}};
int table[2][3] = {
{0, 0, 0}, Matrix form
{1, 1, 1}
};
int table[ ][3] = {
{0, 0, 0}, is permitted
{1, 1, 1}
};
If the values are missing in an initializer, they are automatically set to zero.
int table[2][3] = {
{1, 1}, is permitted
{2}
};
DYNAMIC ARRAYS:
The process of allocating memory at compile time is known as static allocation and the
arrays that receive static memory allocation are called static arrays.
The process of allocate memory to arrays at run-time is known as dynamic memory
allocation.
The arrays created at run time are called Dynamic arrays.
The functions used in the dynamic memory management are :
1. malloc()
2. calloc()
3. realloc()
These functions are included in the header file <stdlib.h>.
The concept of dynamic arrays is used in creating and manipulating data structures
such as linked lists, stacks and queues.
39
/* Program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrixn”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be addedn”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{
for(j=0;j < n;j++)
printf(“%dt”,&a[i][j]);
printf(“n”);
}
}
#include<stdio.h>
void main()
{
int a[20];
int i,n,max,min;
print f("enter no of elements:");
scan f("%d",&n);
print f("reading array elements:");
for(i=0;i<n;i++)
{
print f("enter a[%d]elements:");
scan f("%d",&a[i]);
}
print f("array elements:");
for(i=0;i<n;i++)
{
print f("%dt",a[i]);
}
max=a[0];
min=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
40
}
if(min>a[i])
{
min=a[i];
}
}
print f("n max=%dt min=%d",max,min);
}
How to write a 'C' program to read an array of 10 numbers and print the prime numbers?
#include <stdio.h>
void main ()
{
int arr[10], i, j, flag;
for (i=0;i<10;i++)
for (i=0;i<10;i++)
{
flag=1;
}
}
}
for (i=0;i<10;i++)
{
if (flag=1)
#include<stdio.h>
main()
{
int a[10][10] b[10][10] c[10][10]:
int i j k;
printf("enter the elements in A matrix");
for(i 0;i< 5;i++)
41
for(j 0;j<+5;j++)
{
scanf(" d" &a[i][j]); }
printf("enter b matrix");
for(i 0;i< 5;i++)
for(j 0;j<+5;j++)
{
scanf(" d" &b[i][j]);
}
c[0][0] 0;
for(i 0;i< 5;i++)
{ [ this is main logic ]
for(j 0;j< 5;j++)
{
for(k 0;k< 5;k++)
{
c[i][j] c[i][j] c[k][j]+a[i][k]*b[k][j];
}
}
printf("multiplication matrix is");
for(i 0;i< 5;i++)
for(j 0;j< 5;j++)
printf(" d" c[i][j]):
}
UNIT-IV
42
USER DEFINED FUNCTIONS
INTRODUCTION
We have mentioned earlier that one of the strengths of C language is that C functions are
easy to define and use. C functions can be classified into two categories, namely, library
functions and user-defined functions. main is an example of user defined function. printf and
scanf belong to the category of library functions. The main distinction between user-defined and
library function is that the former are not required to be written by user while the latter have to
be developed by the user at the time of writing a program. However the user defined function
can become a part of the C program library.
A function in C language is a block of code that performs a specific task. It has a name
and it is reusable i.e. it can be executed from as many different parts in a C Program as required.
It also optionally returns a value to the calling program
Every function has a unique name. This name is used to call function from “main()”
function. A function can be called from within another function.
A function is independent and it can perform its task without intervention from or
interfering with other parts of the program.
A function performs a specific task. A task is a distinct job that your program must perform
as a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.
A function returns a value to the calling program. This is optional and depends upon the
task your function is going to accomplish. Suppose you want to just show few lines
through function then it is not necessary to return a value. But if you are calculating area of
rectangle and wanted to use result somewhere in program then you have to send back
(return) value to the calling function.
1. It facilitates top-down modular programming. In this programming style, the high level
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 a appropriate
places.
It is easy to locate and isolate a faulty function for further investigations.
3. 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 from scratch.
A MULTI-FUNCTION PROGRAM
A function in simple terms can be viewed as a black box which takes in some value (if
required) and outputs some result. The internal details of the function are hidden from rest of the
program. Every C program can be designed using a collection of these black boxes.
Consider an example as follows:
displayname()
{
printf("\nResult of displayname function call");
}
Above function can be used as follows
main()
{
printf("\nThis demonstrates user-defined functions");
displayname();
}
In order to make use of a user-defined function, we need to establish three elements that
are related to functions.
1. Function definition
2. Function call
3. Function declaration
1. FUNCTION DEFINITION
Function name
Function type
List of parameters
Local variable declaration
Function statements and
a return statement.
All the six elements are grouped into two parts
Function header( first three elements) and
Function body(second three elements)
We begin here, the general format of a function definition is
Function –type function-name(argument list)
{
local variable declarations;
executable statement1;
executable statement2;
----------
45
----------
return (expression);
}
All parts are not essential. Some may be absent. For example, the argument list and its
associated argument declaration parts are optional. The declaration of local variables is required
only when any local variables are used in the function.
Function header-> it consists of three parts: function type, the function name and the formal
parameter list
Name and type-> The function name is any valid c identifier. The function type specifies the
type value that the function is expected to return to the program calling the function.
Formal parameter list-> The parameter list declares the variables that will receive the data sent
by the calling program. They serve as input data to the function to carry out the specified task.
The parameters are also known as arguments.
The parameter list separated by commas and surrounded by parentheses. And there is
no semicolon after the closing parentheses. The declaration of parameter variables cannot be
combined. Ex( int a,b) is illegal.
A function need not always receive values from the calling program. In such cases
function have no formal parameters. It is empty, so we can use the keyword void between the
parentheses.
Function body-> The function body contains the declarations and statements. The body
enclosed in braces, contains three parts.
1. Local declarations that specify the variables needed by the function
2. Function statements that perform the task of the function
3. A return statement that return the value evaluated by the function
A function does not return any value we can omit the return statement.
Return Values and Their Types ->A function may or may not send back any value to the
calling function. If it does, it is done through the return statement. While it is possible to pass to
the called function any number of values, the called function can only return one value per call,
at the most we can have
return
or
return(expression)
46
The first, the 'plain' return does not return any value; it acts much as the closing brace of the
function. When a return is encountered, the control is immediately passed back to the calling
function. An example of the use of a simple return is as follows:
if(error)
return;
The second form of return with an expression returns the value of the expression. For example,
mul(x,y)
int x,y;
{
int p;
p = x*y;
return(p);
}
return(x*y);
Now by default all functions return int type data. If a function wants to return some other type of
value (can be float, character, string, structure, pointer, etc) whether it is user-defined or inbuilt
data type, it can be achieved by giving a type specifier in the function header.
Example:
double sum(w,r)
char rait(c)
When a value is returned it is automatically cast to the function's type. In functions that do
computations using double, yet return int, the returned value will be truncated to an integer.
FUNCTION CALLS-> A function can be called by simply using the function name followed
by a list of actual parameters, if any, enclosed parentheses.
Note:
If the actual parameters are more than the formal parameters, the extra actual arguments
will be discarded.
On the other hand, if the actual are less than the formals, the unmatched formal
arguments will be initialized to some garbage.
47
Any mismatch in data types may also result in some garbage values.
FUNCTION DECLARATION-> All functions in c program must be declared, before they are
invoked. A function declaration consists of four parts
Function type(return type)
Function name
Parameter list
Terminating semicolon
Its general form is
Function type function name(parameter list);
Note:
The parameter list must be separated by commas
The parameter names do not need to be the same in the prototype declaration and the
function definition
The types must match the types of parameters in the function definition, in number and
order
Use of parameter names in the declaration is optional
If the function has no formal parameters, the list is written as(void)
When the declared types do not match with the types in the function definition, compiler
will produce an error.
TYPES OF FUNCTIONS
A function may belong to any one of the following categories:
1. #include<stdio.h>
2. #include<conio.h>
3. void add(int x,int y)
4. {
5. int result;
6. result = x+y;
7. printf("Sum of %d and %d is %d.\n\n",x,y,result);
8. }
48
9. void main()
10. {
11. clrscr();
12. add(10,15);
13. add(55,64);
14. add(168,325);
15. getch();
16. }
Program Output
1. #include<stdio.h>
2. #include<conio.h>
3. void printline()
4. {
5. int i;
6. printf("\n");
7. for(i=0;i<30;i++)
8. {
9. printf("-");
10. }
11. printf("\n");
12. }
13. void main()
14. {
15. clrscr();
16. printf("Welcome to function in C");
17. printline();
18. printf("Function easy to learn.");
19. printline();
20. getch();
21. }
Output
A C function with arguments can perform much better than previous function type. This type of
function can accept data from calling function. In other words, you send data to the called
function from calling function but you cannot send result data back to the calling function.
Rather, it displays the result on the terminal. But we can control the output of function by
providing various values as arguments. Let’s have an example to get it better.
#include<stdio.h>
#include<conio.h>
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}
51
Output
This type of function can send arguments (data) from the calling function to the called
function and wait for the result to be returned back from the called function back to the calling
function. And this type of function is mostly used in programming world because it can do two
way communications; it can accept data as arguments as well as can send back data as return
value. The data returned by the function can be used later in our program for further
calculations.
#include<stdio.h>
#include<conio.h>
52
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}
void main()
{
int z;
clrscr();
z = add(952,321);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}
We may need a function which does not take any argument but only returns values to the
calling function then this type of function is useful. The best example of this type of function is
“getchar()” library function which is declared in the header file “stdio.h”. We can declare a
similar library function of own. Take a look.
1. #include<stdio.h>
2. #include<conio.h>
3. int send()
4. {
53
5. int no1;
6. printf("Enter a no : ");
7. scanf("%d",&no1);
8. return(no1);
9. }
10. void main()
11. {
12. int z;
13. clrscr();
14. z = send();
15. printf("\nYou entered : %d.", z);
16. getch();
17. }
We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters. It is a bit difficult for novice because this type
of function uses pointer. Let’s see an example:
1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
54
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
14. getch();
15. }
We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters.It is a bit difficult for novice because this type of
function uses pointer. Let’s see an example:
1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
14. getch();
15. }
55
NESTING OF FUNCTIONS
C permits nesting of functions freely. Main can call function1, which calls functions2,
which calls function3 etc…. and so on. Consider the following program.
Void main()
{
void add();
add()
}
void add ()
{
printf(“ PROGRAMMING”);
add1();
}
void add1()
{
printf(“LANGUAGE”);
}
RECURSION
UNIT V
POINTERS
INTRODUCTION
In c a pointer is a variable that points to or references a memory location in which data is stored.
Each memory cell in the computer has an address that can be used to access that location so a
pointer variable points to a memory location we can access and change the contents of this
memory location via the pointer. It is a derived data type.
Benefits of pointers:
UNDERSTANDING POINTERS
57
Definition: A pointer is a variable; it may contain the memory address of another variable.
Pointer can have any name that is legal for other variable. It is declared in the same manner like
other variables. It always denoted by *
A pointer is a variable whose value is also an address. Each variable has two attributes:
address and value. A variable can take any value specified by its data type. A pointer to an
integer is a variable that can store the address of that integer.
Assigning values directly to variables, we can indirectly manipulate a variable by
creating a variable called a pointer, which contain the memory address of another variable.
Value at address 30 4567-> address of the variable
The second variable contains the address of the first variable. 30 is the value at the address,
4567 is the address of the first variable.
ACCESSING THE ADDRESS OF A VARIABLE
The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us. It can be done with the help of & operator. The
operator & immediately preceding a variable returns the address of the variable associated with
it.
For ex:
S=&quality;
This would assign the address 5000(the location of quality) to the variable s. The & operator can
be named as ‘address of’.
Note: the & operator can be used only with a simple variable or an array element.
For defining a pointer variable ‘*’ symbol is used. A pointer variable must be declared
with * preceding the variable name. The general structure for declaring a pointer variable is
data_type*ptr_name;
For example
int*p
This declares the variable p as a pointer variable that points to an integer data type.
For example:
58
main()
{
int*p;
int i=30;
p=&i;
}
p 30
We can also use different pointers to point to the same data variable. Example
int x P1 P2 P3
int *p1=&x;
int *p2=&y;
int *p3=&z;
x
59
----
-------
Once the pointer is declared and assigned to the address of another variable. The variable
can be accessed through its pointers. This is done by using another unary operator * (asterisk),
usually known as the indirection operator. Another name for the indirection operator is the
dereferencing operator.
Example:
int *p;
x=15;
p=&x;
#include<stdio.h>
main()
{
/* local definition */
int a=22, *a;
float b=2.25, *b;
/* statements */
a=&a; /* ‘&’ is a address of letter and it represents the address of the variable */
b=&b;
printf(“\n Value of a =%d”,*a);
printf(“\n value of b=%d”,*b);
}
Output
Value of a=22
Value of b=2.25
CHAIN OF POINTERS
Any pointer variable points to another pointer variable to access the content of other
memory location of variable is called chain of pointers.
Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the
location that contains the desired value. This is known as multiple directions
For example:
Main()
{
int x, *p1,**p2;
X=100;
P1=&x; /* address of x*/
P2=&p1; /* address of p1 */
Printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an integer and p2 as a
pointer to a pointer to an integer.
Like other variables pointer variables can be used in expressions. For example if p1 and
p2 are properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract one
pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2;
etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 ,
p1==p2 and p1!=p2 are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
61
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}
POINTER TO ARRAYS
When an array is declared, the compile 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 (index 0) of the array. The compiler also defines the
array name as a constant pointer to the first element. Suppose we declare an array x as follows
int x[5]=1,2,3,4,5}
Suppose the base address of x is 1000 and assuming that each integer requires two bytes,
the five elements will be stored as
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the
value of x is 1000, the location where x[0] is stored. That is x=&x[0]=1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array x by
the following assignment: p=x; This will be equivalent to p=&x[0];
Strings are treated like character arrays and therefore, they are declared and initialized as
follows:
Char str[5]=”good”;
62
The compiler automatically inserts the null character’\0’ at the end of the strings. C
supports an alternative method to create strings pointer variables of type char.
This creates a string for the literal and then stores its address in the pointer variable str.
The pointer str now points to the first character of the string “good” as shown in fig.
g o o d \0 str
ARRAY OF POINTERS
Pointer arithmetic
Array notation is form of relative addressing. The compiler treats the subscripts as a relative
offset from the beginning of the array. When a pointer variable set to the start of an array and is
incremented to find the next element, absolute addressing is being implemented.
Accessing arrays through pointers is marginally faster than using array notation.
Pointer allows us to perform certain functions that are externally difficult with array notation.
Program:
#include<stdio.h>
main()
{
int *a[3];
int b=10,c=20,d=30,i;
a[0] =&b;
a[1] =&c;
a[2] =&d;
63
for(i=0;i<3;i++)
{
Printf(“address=%u”,a[i]);
Printf(“value=%d”,*(a[i]));
}
}
b c d
10 20 30
a[0] a[1] a[2]
400 500 600
0 0 0
Output
Address=4000 value=10
Address=5000 value=20
Address=6000 value=30
POINTERS AS FUNCTION ARGUMENTS
When we pass addresses to function, the parameters receiving the addresses should be
pointers. The process of calling a function using pointers to pass the addresses of variable is
known as call by reference. (You know, the process of passing the actual value of variables is
known as call by value.) The function which is called by ‘reference’ can change the value of
the variable used in the call. Consider the following code:
Main()
{
int x;
x = 20;
change(&x);
printf(“%d \n”,x);
}
change(p);
int *p;
{
*p = *p + 10;
}
The statement *p=*p+10 to the value stored at the address p. Since p represents the address of x,
the value of x is changed from 20 to 30. Therefore, the output of the program will be 30, not 20.
The function large receives the address of the variables a and b, decides which one is
lager using the pointers x and y and then returns the address f its location. The returned value is
then assigned to the pointer variable p in the calling function. In this case, the address of b is
returned and assigned p and therefore the output will be the value of b, namely 20.
POINTERS TO FUNCTIONS
A function has a type and an address location in the memory. It is therefore possible to
declare a pointer to a function , which can be used as an argument in another function.
A pointer to a function is described as follows.
Type (* fptr) ();
This tells the compiler that fptr is a pointer to a function, which returns type value. The
parentheses around *fptr are necessary.
We can make a function pointer to point to a specific function b simply assigning the name of
the function to the pointer.
For example
double mul (int, int);
65
double (*p1) ();
p1=mul;
Here p1 as a pointer to a function and mul is a function to which p1 points. To call the
function mul, we may now use the pointer p1 with the list of parameters, i.e.,
(*p1) (x,y) /* function call*/
We know the name of an array stands for the address of its zeroth element the same
concept applies for names of arrays of structures. Suppose item is an array variable of struct
type. Consider the following declaration:
struct products
{
char name[30];
int manufac;
float net;
}
item[2],*ptr;
this statement declares item as array of two elements, each type struct products and ptr as a
pointer data objects of type struct products, the following assignment statement is
ptr=item;
would assign the address of zeroth element of product to ptr. The pointer ptr will now point to
item[0]. Its members can be accessed by using the following notation.
ptr- >name;
ptr- >manufac;
ptr- >net;
The symbol - > is called arrow pointer and is made up of minus sign and a greater than
sign. Note that ptr- > is simple another way of writing product[0].
When the pointer is incremented by one it is made to pint to next record ie item[1]. The
following statement will print the values of members of all the elements of the product array.
66
for(ptr=item; ptr< item+2;ptr++)
printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);
We could also use the notation (*ptr).number to access the number. The parenthesis around
*ptr are necessary because the member operator ‘.’ has a higher precedence than the operator *.