UNIT 3
UNIT 3
Definition :
An Array is a collection of similar data items that are stored under a common name. A
value in array is identified by index or subscript enclosed in square brackets with array
name.
The individual data items can be integers, floating point, characters and so on, but
they must be the same type and same storage class. Each element is referred by specifying
the array name with subscript, each subscript enclosed in square brackets andit must be a
non-negative integer.
If ‘n’ elements in the array ‘a’ then the elements are
a[0],a[1],a[2],a[3],…..a[n-1].
Arrays can be classified into
Single Dimensional arrays
Multi – Dimensional arrays
Single dimensional array:
A single dimensional or one-dimensional array consists of a fixed number of elements of
the same data type organized as a simple linear sequence.
The elements of a single dimensional array can be accessed by using a single subscript.
Eg: X[1],X[2]….X[n]
The subscript can begin with number Zero.
Declarations of arrays:
The general form of array declaration is
Initialization of arrays:
We can initialize the elements of arrays in the same way as the ordinary variable when
they are declared.
The general form:
data-type array-name[size] = {list of values};
Will declare the variable number as an array of size 3 and will assign Zero to each
element.
Eg: int number[5] = {3,4,5};
will initialize the first three elements and the remaining two elements to ZERO.
The size may be omitted. In such cases the compiler allocates enough space for all
initialized elements
printf("%d\t", a[i]);
}
Output:
Enter the number n: 5
Enter the numbers: 3 2 8 1 4
1 2 3 4 8
Eg:
int a[3][4];
3-rowsize; 4-column size;
initializes the elements of the first row to ZERO and second row to ONE.
The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}};
If the values are missing in an initializer they are automatically set to ZERO.
#include <stdio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
printf("\n\t Enter First Matrix : ");
for(i=0;i<3;i++)
{
Page 77
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\t Enter Second Matrix : ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\n\t Matrix Multiplication is : \n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",c[i][j]);
}
printf("\n");
}
}
Output:
Enter First Matrix :
1 2 1
3 2 1
1 2 1
Arrays can have more than one dimension, these arrays-of-arrays are called
multidimensional arrays
The general form:
type array-name[s1][s2]…[sn];
Eg:
int a[3][5][12];
float b[5][4][5][3];
It allows us to enter only fixed number of elements into it. We cannot alter
the size of the array once array is declared.
Inserting and deleting the records from the array would be costly since we
add / delete the elements from the array, we need to manage memory
space too.
STRINGS
Strings
A string is sequence of characters enclosed within double quotes.
Eg: “Make hay while the sun shines”
Important points about string literal constants are as follows:
Every string literal constant is automatically terminated by null
character ie ‘\0’.
String literals are enclosed within double quotes(“A”) whereas
character literals are enclosed within single quotes(‘A’).
The length of a string is defined as the number of characters
present in it.
In C language string type is not separately available and character
Page 79
In the above syntax str_name is any name given to the string variable and size is used
to define the length of the string, i.e the number of characters strings will store.
Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays.
Initializing a String
A string can be initialized in different ways.
2 Ways to Initialize a String in C
1. Assigning a string literal : String literals can be assigned without size. Here, the
name of the string str acts as a pointer because it is an array.
char str[] = "hello";
or
char str[6] = "hello";
2. Assigning character by character : We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null
character.
char str[] = { 'h','e','l','l','o','\0'};
or
char str[6] = { 'h','e','l','l','o','\0'};
The problem with scanf() is that it terminates its input on the first white space it finds.
Therefore, if the input is typed as,
Page 80
“NEW YORK”
then only the string “NEW” will be stored in array add.
2. Reading a line of text using gets():
It is possible to read a line of text with the help of gets() function.
Example :
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name,); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Syntax
char * strcat ( char * destination, const char * source );
Eg:
void main()
{
char src[]="c", dest[]="programming";
strcat(src,dest);
printf("concatenated string is %s",src);
}
Output:
concatenated string is c programming
2. strcpy() function
Definition:
strcpy( ) function copies contents of one string into another string.
Syntax
char * strcpy ( char * destination, const char * source );
Eg:
void main()
{
char src[]="spark",dest[15];
strcpy(dest,src);
printf("%s is copied to dest string\t",dest);
}
Output:
spark is copied to dest string.
3. strlen() function
Definition
strlen( ) function in C gives the length of the given string.
Syntax
int strlen ( const char * str );
Eg:
void main()
{
char string[]="spark";
Page 82
int len;
len=strlen(string);
printf("length of %s is %d\t",string,len);
}
Output: length of spark is 5.
4. strcmp() function
Definition
This function compares two strings passed as parameters and returns either
+ve number,0,-ve number.
+ve value indicates string1 > string2.
0 indicates string1 and string2 are equal.
-ve value indicates string1 < string2.
Syntax
Eg:
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="spark",string2[]="programming";
int cmp;
cmp=strcmp(string1,string2);
if(cmp>0)
printf("%s > %s",string1,string2);
else
{
if(cmp<0)
printf("%s < %s",string1,string2);
else
printf("%s = %s",string1,string2);
}
}
Output:
spark > programming.
This is because alphabetically p comes first then s.so the string compare function returns
difference between ascii of s and p which would be +ve.
5. strrev() function
Definition
This function accepts single string as parameter and reverses that string.
Syntax
char * strrev(char *s)
Eg:
Page 83
#include <stdio.h>
#include <string.h>
void main(void)
{
char string[]="spark";
strrev(string);
printf("reverse string is %s",string);
}
Output
reverse string is kraps.
6. strlwr() function
Definition
strlwr( ) function converts a given string into lowercase.
Syntax
char *strlwr(char *string);
Eg:
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="SPArk";
strlwr(string1);
printf("%s is in lower case",string1);
}
Output
spark is in lower case.
7. strupr() function
Definition
strupr( ) function converts a given string into uppercase.
Syntax
}
Output
SPARK is in upper case.
Page 84
8. atoi()
converts the string argument to an integer .
#include <stdio.h>
#include <string.h>
void main () {
int val;
char str[20]=”989”;
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
}
Example :1 Program to reverse a given string
#include <stdio.h>
main()
{
char s[80], c;
int i=0,k;
c = getchar();
while( c != ‘\n’)
{
s[i] = c;
i++;
c= getchar();
}
s[i] = ‘\0’;
printf(“Length = %d\n”, i);
printf(“%s”, s);
for(k=i-1; k >=0; k--)
printf(“%c”, s[k]);
}
Output:
Input: shar
Output: rahs
Example :2 : Program to Check a Given String is Palindrome or not
#include <stdio.h>
#include <string.h>
void main()
{
char s1[25],s2[25];
printf("Enter the string: ");
gets(s1);
strcpy(s2,s1);
strrev(s2);
if(!strcmp(s1,s2))
printf("string is palindrome");
else
Page 85
Definition of Function:
A Function is a self contained block or a sub-program of one or more statements that
performs a special task when it is called.
Types of Functions:
1. Library or Built-in Functions
Built in Functions are pre defined functions.
e.g., scanf( ),printf( ),getch(),exit(),etc.
2. User defined Functions
User-Defined Functions
Functions defined by the users according to their requirements are called user-defined
functions. These functions are used to break down a large program into small functions.
Defining a Function:
Two principal components exists in defining a function
(i) First line (includes the name of the function and argument declaration)
(ii) Second line (body of the function)
First line contains the type specification of the value returned by the function followed
by function name and set of arguments separated by commas. Each argument is preceded
by its associated type declaration.
Format:
Page 86
data type function name (type1 arg1, type2 arg 2,………, typeN arg n)
{
<Local declaration>
………………………
< statement block >
………………………
………………………
return(variable or expression);
}
Note:
data type is the value return by the function and arguments expected.
arg 1,arg 2,….,arg n are the arguments which are variable that will receive the values from
the calling program. name is the name of the function by which the function is called by
the calling program.
Local declaration: Referred to as local variables and are used only inside the function.
Statement block: Consists of a set of statements and built-in functions which are
executed as the function is called.
Return: The result is returned to the calling program through a return statement that
normally appears at the end of a function block. Note that the function block starts and
ends with braces { }
The arguments appearing in the function call are referred to as actual arguments
main()
{
………..
add(a,b); // function calling. a and b are Actual arguments.
………..
}
Page 87
add function_name
a,b actual arguments
Function Prototype:
Function prototypes are usually written at the beginning of the main ( )
program.
The general form of function prototype:
Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function]. The arguments in the function declaration and definition
are called formal parameters.
Actual arguments:
These are the parameters transferred from the calling function [main
function] to the called function [user defined function]. The arguments in function calling
in main ( ) is called Actual arguments.
Note:
o Actual Argument – This is the argument which is used in function call.
o Formal parameter – This is the parameter which is used in function
definition.
Categories of Functions:
1. Function with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and with return values.
4. Function with no arguments and with return values.
Category 1: Functions with no arguments and no return values:
When a function has no arguments, it does not receive any data from the calling
Page 88
function. In effect there is no data transfer between the calling function and the called
function.
Calling Function Analysis Called Function
main() fun1()
{ {
-------- ----
--------- No arguments passed ----
fun1(); ----
----- }
----- No values Sent back
}
Eg:
#include<stdio.h>
main()
{
void add(void);
add( ); // Calling function without passing any argument
}
void add ( )
{
int a,b,c;
printf(“Enter two numbers “);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“ Sum is …%d”,c);
}
Output:
Enter two numbers
10
20
Sum is … 30
Category 2: Functions with arguments and no return values:
Calling Function Analysis Called Function
main() fun1(x,y)
{ {
-------- ----
--------- arguments passed ----
fun1(a,b); ----
----- }
----- No values Sent bank
}
When a single value is passed to a function via an actual argument the value of actual
argument is copied into the function. Therefore the value of the corresponding formal
parameter can to alter within the function but the value of the actual argument within the
calling routine will not change. This procedure for passing the value of an argument to a
function to is known as passing by value.
Example Program:
#include<stdio.h>
Page 89
main()
{
void add (int,int );
int a,b;
printf ("Enter two values:”);
scanf(“%d%d”,&a,&b);
add (a,b);
}
void add (int x, int y)
{
int z;
z=x+y;
printf ("Sum is ….%d”,z);
}
Output:
Enter two values :
10
20
Sum is …. 30
main ( )
{
int add(int,int );
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“ Sum is …%d”,c);
}
int add( int x,int y)
{
int z;
z=x+y;
return(z);
}
Output:
Enter two values : 10 20
Sum is … 30
Category 4: Functions without arguments and with return values:
Eg:
#include<stdio.h>
main()
{
int sum();
c=add();
printf(“sum is …%d”,c);
}
int add ( )
{
int a,b,c;
printf(“Enter two numbers”);
Page 91
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Output:
Enter two numbers
10
20
Sum is …30
In call by value method the formal parameters are sent as a photocopy of the actual
Page 92
argument. Hence, changes made in the called function will not be reflected in the calling
function.
2. CALL BY REFERENCE:-
The method of passing arguments by address or reference is also known as Call by
address or Call by reference.
In this method, the address of the actual arguments is passed to the formal
parameters of the function.
If the arguments are passed by reference, the changes made in the values pointed
to by the formal parameters in the called function are reflected back to the calling
function.
Eg: Swapping two variables using pointers
#include <stdio.h>
//swap(int ,int );
void main()
{
int a,b;
printf("Enter the values of a and b" );
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("\n In main() After Swapping a=%d\tb=%d\n",a,b);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Enter the values of a and b
100
200
In main() After Swapping a=200 b=100
In call by reference address of the actual arguments are passed to the called
function and stored in formal parameters. Therefore any changes made using the formal
parameters will be reflected in the calling function.
argument passed is local to the function and argument passed is accepted in the calling
is not accepted in the calling program. program.
5. Here is no possibility of wrong data 5. There is a possibility of wrong data
manipulation since the arguments are manipulation since the addresses are used
directly used in an application. in an expression. A good skill of
programming is required here.
RECURSION
A function that calls itself is known as a recursive function. And, this technique
is known as recursion.
Applications of Recursion :-
Towers of Hanoi (Binary recursion)
Printing Backwards
Finding Factorial
Advantages of Recursion in C
Makes the program elegant.
Page 95
It adds clarity to the program code and also reduces the time to write the
code.
It is best for solving problems based on tree structures.
Disadvantages of Recursion in C
It is slower than non recursive programs due to the overhead of maintaining
the stack.
It requires more memory for the stack.
For better performance, use loops instead of recursion. Because recursion is
slower.
STRUCTURES
Definition:
A structure is a collection of variables under a single name. These variables can be of
different types. A structure is a convenient way of grouping several pieces of related
information together.
A structure type is defined by,
Syntax 1:
struct tag-name/structure_name
{
datatype member1;
datatype member2;
...
datatype membern;
};
Eg:
struct student
{
char name[20];
int ID;
};
Declare a structure variable
Method 1 :
We can declare structure variables using the tag name anywhere in the program.
Eg:
struct student s1,s2,s3;
declares s1,s2,s3 as variables of type struct student. Each one of these variables has 2
members as specified by the template.
Method 2 :
Struct student
{
char name[64];
char course[30];
int age;
int year;
} s1,s2;
In this case ,the variables are declared immediately.
Page 96
Structure initialization:
Like any other data type, a structure variable can be initialized. For ex,
struct {
char name[64];
char course[30];
int age;
int year;
} student = { “arthi”, “B.SC”, 23, 2008};
C does not permit the initialization of individual structure members within the
template. The initialization must be done only outside the structure using variables.
Eg:
s1.name
s1.id
We would assign the values to the members as,
strcpy(s1.name, “ram”);
s1.id = 1;
We can also get values from users using scanf( );
Eg:
scanf(“%s”, s1.name);
scanf(“%d”, &s1.id);
Arrays of structures
Eg:
struct marks
{
int sub1;
int sub2;
int sub3;
};
struct marks stud[3];
Page 97
The above creates an array of 3 structures. The members can be accessed as follows,
stud[0].sub1 = 45;
stud[0].sub2 = 68;
stud[0].sub3 = 71;
stud[2].sub1 = 60;
stud[2].sub2 = 75;
stud[2].sub3 = 71;
}
Example 2 : Program for Employee Details using structure
#include <stdio.h>
struct employee
{
char name[100];
int age;
float salary;
char department[50];
};
int main(){
struct employee emp;
return 0;
}
Output
Enter Name, Age, Salary and Department of Employee
Jack 30 1234.5 Sales
Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
Dept : Sales
Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
Dept : Sales
Unions
Unions follow the same syntax as structures. The major difference is in terms of storage.
In structures, each member has its own storage location, whereas all members of a union
use the same location.
Syntax:
union tag-name
Page 99
{
datatype member1;
Eg:
union student
{datatype member2;
...
datatype membern;
char name[20];int
ID;
};
The union contains 2 elements each of different data type. However, we can use only one of
them at a time. The compiler allocates space that is large enough to hold the largest variable type
in union. In the above ex, name uses 20 byes and id used 2 bytes and union takes the bigger one
as its size. So it is 20 bytes and represents the size of the union.
POINTERS:
Definition:
A pointer is a variable that represents the location (rather than the value) of a data item,
such as a variable or an array.
Pointer Declaration:
A Pointer is a numeric variable and, like all variables, must be declared before it can be
used. Pointer variable name should follow the same rules as that of ordinary variable name
Page 100
Typename is any of C’s data types and indicates the type of the variable that the pointer
points to. The asterisk(*) is the indirection operator, and it indicates that ptrname is pointer
to type name and not a variable of type name. Pointers can be declared along with non
pointer variables.
--Where, * is used to denote that “p” is pointer variable and not a normal variable.
Pointer –Initialization:
int x; *p;
p = &x;
Page 75
This is nothing but a pointer variable p is assigned the address of the variable x. The
address of the variables will be different every time the program is executed.
Reading/Accessing value through pointer:
Example:
#include<stdio.h>
void main()
{
int a=10, *ptr;
ptr=&a;
printf(”\n The value of a is ”,a);
*ptr=(*ptr)/2;
printf(”The value of a is.”,(*ptr));
}
Output:
The value of a is: 10
The value of a is: 5
Page 76
Declaration of void pointer:
void * pointer_name;
Eg:
void *ptr; // ptr is declared as void pointer
char cnum;
int inum;
float fnum;
ptr=&cnum; // ptr has address of character data
ptr=&inum; // ptr has address of integer data
ptr=&fnum; // ptr has address of float data
Null Pointer
NULL pointer is a pointer which is pointing to nothing.
NULL pointer points the base address of segment
int *nptr=0;
NULL is micro constant which has been defined in the header file stdio.h
Elements of the array are stored in contiguous memory locations. They can be efficiently
accessed by using pointers.
Pointer variable can be assigned to an array. The address of each element is
increased by one factor depending upon the type of data type. The factor depends on the
type of pointer variable defined. If it is integer the factor is increased by 2. Consider the
following example:
int x[5]={11,22,33,44,55}, *p;
p = x; //p=&x; // p = &x[0];
Page 77
Assume the address on x[0] is 1000 then the address of other elements will be as follows
x[1] = 1002
x[2] = 1004
x[3] = 1006
x[4] = 1008
Example:
#include<stdio.h>
main()
{
int i;
int a[5]={1,2,3,4,5};
int *p=a; /* same as int*p= &a[0]
for(i=0;i<5;i++)
{
printf(“%d”,*p);
p++;
}
Array of Pointers
An array of pointers is a collection of addresses. The addresses in array ofpointers
could be the addresses of isolated variables or the addresses of array elements or any other
addresses. The only constraint is that all the pointers in an array must be of the same type.
Eg:
#include<stdio.h>
main()
{
int a=10,b=20,c=30;
int *arr[3]={&a,&b,&c};
printf(“%d\t%d\t%d”,*arr[0],*arr[1],*arr[2]);
}
Output:
10 20 30
Function pointers
Example:
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
In an array of function pointers, array takes the addresses of different functions, and the
appropriate function will be called based on the index number.
Example.:
#include <stdio.h>
float add(float,int);
float sub(float,int);
int main()
{
float x; // variable declaration.
int y;
float (*fp[2]) (float,int); // function pointer declaration.
Page 79
struct
{
member 1;
member 2;
}variable,*ptr;
Here the variable represents structure type variable and *ptr represents the name of the
pointer.
Example:
#include<stdio.h>
void main()
{
struct account
{
char name[20];
char place[25];
int accno;
};
static struct account m4={“aaa”, “Chennai”,23142};
struct account *ptr;
ptr=&m4;
printf(“%s%s%d”,m4.name,m4.place,m4.accno);
Page 80
printf(“%s%s%d”,ptr->name,ptr->place,ptr->accno);
}
Output:
aaa chennai 23142
aaa Chennai 23142.