0% found this document useful (0 votes)
32 views17 pages

UNIT3

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views17 pages

UNIT3

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT3 MSR

UNIT III
DERIVED DATA TYPES IN C
Arrays
An array is a group of data items of same data type that share a common name.
Different types of arrays
1. One dimensional array
2. Two dimensional array
3. Multi dimensional array

One dimensional arrays:


One dimensional array is a list of items of same type which can be given one
name and each item is referred using one subscript or index. The general form of
declaring it is
data-type array-name[size];
Where array name is user defined name and size indicates total number of
elements or data items that can be stored inside the array.The data type specifies
the type of the element contained in the array such as int,float or char.
For e.g. char name[10];
int a[5];
The computer reserves five locations as shown below
a[0]
a[1]
a[2]
a[3]
a[4]

The values to array elements can be assigned as follows:


a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
Initialization of one dimensional arrays:

1
UNIT3 MSR

The general form is


data-type array-name[size]={list of values};
The values in the list are separated by commas. For e.g.
int a[3]={1,2,3};
It will assign a[1]=1, a[2]=2 and a[3]=3
The size can be omitted. For e.g.
int a[ ]={1,2,3};
If the number of initializers less than the declared size, then the remaining
elements are initializes to 0.
int a[5]={1,2,3};
Character arrays may be initialized in a similar manner. For e.g.
char name[ ]={‘J’,’o’,’h’,’n’,’\0’};

Accessing two-dimensional array elements


Input the array elements:
Let A is an integer array of n elements.
int a[10];
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i];
}

Output the array elements:


for(i=0;i<n;i++)
{
printf (“%d\t”,a[i];
}

Two dimensional arrays:


Two dimensional array is a list of data items of same type arranged in the form of
rows and columns under a single name. In this each element is accessed by two
indices. The first index indicates row number and the second index column
number. The general form of two dimensional array declaration is
2
UNIT3 MSR

data-type array-name[rowsize][columnsize];
For e.g. int a[2][2];
In this, array a is having two rows and columns. Matrix is an example for two
dimensional array. The elements of the array a are a[1][1], a[1][2],a[2][1] and
a[2][2].

Initializing two dimensional arrays:


Like one dimensional arrays, two dimensional arrays may be initialized. The
different methods of initializing two dimensional array is:
int a[2][3]={1,2,3,4,5,6};
It can also be written as,
int a[2][3]={{1,2,3},{4,5,6}};
If values are missing in an initialize, they are automatically set to zero.
int a[2][3]={{1,2},{3}};
When the array is initialized with all values, explicitly need not to specify the
size of the first dimension.
int a[ ][3]={1,2,3,4,5,6};
When all the elements are initialized to zero, then
int a[2][3]={{0},{0}};

Accessing two-dimensional array elements


Input the array elements:
Let A is an integer array of elements of order m x n.
int a[10][10];
for(i=0; i<m;i++)
{
for(j=0; j<m; j++)
{
scanf(“%d”,&a[i][j];
}
}
Output the array elements:
Let A is an integer array of elements of order m x n.
for(i=0; i<m; i++)
3
UNIT3 MSR

{
for(j=0; j<m; j++)
{
printf(“%d”,a[i][j]\t;
}
printf(“\n”);
}
Programs using one dimensional and two dimensional arrays …..

Handling of character strings


A string is an array of characters. Any group of characters defined between
double quotation marks is a string constant.
Declaring and initializing string variables
A string variable is any valid C variable name and is always declared as an array.
The general form of declaration of a string variable is
char string_name[size];
The size determines the number of characters in the string. For e.g.
char city[10];
char name[20];
When the compiler assigns a string to a character array, it automatically supplies
a null character(‘\0’) at the end of the string.

Initializing a string variable


Character arrays may be initialized when they are declared. For e.g.
The string enclosed within double quotation is directly assigned to a string
variable. Here the null character is automatically appended to the end of the
string,
char city[8]=”NEWYORK”;

When individual characters are assigned to a string, then we must explicitly


append the null character to the end of string.
char city[8]={‘N’,’E’,’W’,’Y’,’O’,’R’,’K’,’\0’};

4
UNIT3 MSR

We can also initialize a string without specifying the size. The size of the array is
automatically determined based on the length of the string.
char city[ ]=”NEWYORK”;
A string with length zero is called Null string, Null string refers to an empty
string (“”).

Read a Single Character


The getchar() function is used to read a single character from the keyboard.
Syntax: variable = getchar();
Where the variable can be of character or integer type. The getchar() function
reads a single character and assign it to variable.
Example:
main()
{ char ch;
printf(“Enter a character : ”);
ch=getchar();
printf(“You have typed ed %c key”, ch);
}
Writing Single character to screen
putchar() function is used to display a single character at the current cursor
position on the standard output device.
Syntax: putchar(argument);
Example:
main()
{ char ch;
ch= ‘A’;
putchar(ch);
}

Reading strings from terminal


To read a string from the terminal we can use two input functions scanf() and
gets().
scanf():

5
UNIT3 MSR

 To read a set of characters using scanf() function, we need to use %s as


format specifier.
 The general format of format specifier is %ws, where w specifies the width
of the string.
o If the width w >= no. Of characters typed in. The entire string will be
stored in the string variable.
o If the width w < no. of characters in the string. The excess characters
will be truncated and left unread.
 We need not use ‘&’ before the variable name.
 The scanf() function automatically terminates the string with a null
character.
 However, the scanf() function has a drawback. When it encounters a white
space such as blank, tab or carriage return, it terminates the input.
Example:
char name[20];
printf(“Enter a String”);
scanf(“%s”, name);
 If the entered string is My India, the scanf function will read only My and
ignores India which comes after a blank space.
 Therefore, the value stored in name = “My”.
gets():
 gets() function is used to read a line of text.
 The gets() function reads the input characters until enter key is encountered.
 A null character is automatically appended to the end of the read characters
and are then stored in string variable that is specified as the argument of the
function.
Syntax: gets(variablename);
Example: char name[25];
gets(name);
Note: One should be very careful while using these functions. If the number of
characters that are entered exceeds the size of the variable, compiler will not
generate any error message. Extra characters simply overwrite the existing

6
UNIT3 MSR

content, without any warning. This may cause the program to unexpectedly crash
in the middle of execution.
Writing strings to screen
To output a string, we can use two standard output functions printf() and puts().
 The printf() function can be used along with %s as format specifier.
Example:
main()
{ char greet[25]=”Have a Nice Day”
printf(:%s”, greet);
}
The above code will display “Have a Nice Day” on the standard output device.
 The puts() function can also be used to display the string on the standard
output device.
Syntax: puts(expression);
Example:
main()
{ char greet25]=”Have a Nice Day”
puts( greet);
}

String handling functions


String functions are defined under the header file string.h. To use string
functions in the program we have to include string.h in our program. Some string
functions are listed below:
1. strlen(): This function returns the length of the string, that is, the number of
characters in the string. While calculating the length, it does not count the null
character.
Syntax: strlen(string variable / constant)
Example:
This program will
#include<stdio.h> produce output 5.
#include<string.h>
main()
{ char msg[10]= “Hello”;
7
UNIT3 MSR

printf(“Length of the string = %d”, strlen(msg));


}

2. strlwr(): This function is used to convert any uppercase letter in the given
string to its equivalent lowercase.
Syntax: strlwr(string);
Example:
#include<stdio.h> This program will produce
the output hello.
#include<string.h>
main()
{ char msg[10]= “Hello”;
strlwr(msg);
printf(“%s”,msg);
}

3. strupr():This function is used to convert any lowercase letter in the given


string to its equivalent uppercase.
Syntax: strupr(string);
Example: This program will produce
the output HELLO.
#include<stdio.h>
#include<string.h>
main()
{ char msg[10]= “Hello”;
strlwr(msg);
printf(“%s”,msg);
}

4. strrev(): This function is used to reverse a string. The converted string will be
stored in the source string itself.
Syntax: strupr(string);
Example:
#include<stdio.h>
#include<string.h>
This program will produce
main() the output olleH.
{ charmsg[10]= “Hello”;
strrev(msg);
printf(“%s”,msg);
8
UNIT3 MSR

5. strcpy(): This function is used to copy one string to another.


Syntax: strcpy(string1, string2);
Here contents of string2 will be assigned to string1. string2 may be a character
array variable or a string constant.
Example:
#include<stdio.h> This program will produce
#include<string.h> the output Hello.
main()
{ char msg[10]= “Hello”, str;
strcpy(str, msg);
printf(“%s”,str);
}
6. strncpy(): This function copies first n characters of the source string to the
destination string.
Syntax: strncpy(str1,str2,n);
Example: This program will produce
#include<stdio.h> the output Hell.
#include<string.h>
main()
{ charmsg[10]= “Hello”, str;
strncpy(str, msg, 4);
printf(“%s”,str);
}

7. strcmp(): This function is used to compare two strings that is to check


whether they are same or different. Here, two strings are compared character
by character until there is a mismatch or end of string is encountered.
Syntax: strcmp(str1,str2);
o If str1 and str2 are equal it returns 0.
o If str1>str2, it returns output greater than 0.
o If str1<str2, it returns output less than 0.
Example:
strcmp(“India”, “india”)

9
UNIT3 MSR

will return a negative value (-32) because the ASCII value of ‘I’ is less than the
ASCII value of “i”, which is the difference between the ASCII values of ‘I’ and
‘i’.

8. strncmp(): This function compares at most n characters of str1 with str2 and
return a negative, zero or positive value depending on whether str1< str2, str1
= str2, str1>str2.

9. strcat(): This function is used to concatenate two strings.


Syntax: strcat(str1,str2); Here str2 will be appended to str1.
Example
#include<stdio.h> This function produces
the output Hello World.
#include<string.h>
main()
{ char str1[]= “Hello ”, str2[]= “World”;
strcat(str1,str2);
printf(“%s”,str1);
}

10. strncat(): This function appends first ‘n’ characters of source string to the
end of destination string.
Syntax: strncat(str1,str2,n);
Example This function produces
#include<stdio.h> the output Hello Wor.

#include<string.h>
main()
{ char str1[]= “Hello ”, str2[]= “World”;
strcat(str1,str2,3);
printf(“%s”,str1);
}

11. strstr(): This functions returns the first occurrence of string str2 in str1,
Null if not present.

CHARACTER TYPE FUNCTIONS


10
UNIT3 MSR

C provides many character manipulation functions. These are included in the


standard library function ctype.h. Some of the character functions are listed in the
table below:

Function Description Example


It returns a non-zero value if C is isalpha(‘A’) returns 1
isalpha(c)
a letter (A-Z or a-z) isalpha(‘4’) returns 0
It returns a non-zero value if C is isdigit(‘5’) returns 1
isdigit(c)
a letter ( ‘0’ – ‘9’) isdigit(‘A’) returns 0
isupper(‘a’) returns 0
It returns a non-zero value if c is
isupper(c) isupper(‘A’) returns
an uppercase character.
1.
It returns a non-zero value if c is islower(‘a’) returns 1
islower(c)
a lowercase character. islower(‘A’) returns 0
tolower(c Translates the character to tolower(‘2’) returns 2
) lowercase tolower(‘A’) returns a
toupper(c Translates the character to toupper(‘2’) returns 2
) cppercase toupper(‘a’) returns A

Arithmetic operations on characters


C allows us to manipulate characters the same way we do with numbers.
Whenever a character constant or character variable is used in an expression, it is
automatically converted into an integer value(ASCII value) by the system. For
e.g.
char ch=’A’;
printf(“%d”,ch);
will display the ASCII value of ‘A’ as 65.
It is also possible to perform arithmetic operations on the character constants and
variables. For e.g.
ch=’B’-1; is valid.
The ASCII value of ‘B’ is 66 and therefore this will assign the value 65 to ch.
We can also use character constants in relational expressions. For e.g.
ch>=’A’&&ch<=’Z’
will check whether the character contained in the variable ch is an upper-case
letter.
11
UNIT3 MSR

atoi():
This function converts a string of digits into their integer values. The syntax is
x=atoi(string)
Where x is an integer variable and string is a string constant or string variable
which contains sequence of digits. atoi() function present under the header file
stdlib.h.
Ex: #include<stdio.h>
main()
{ int year;
char number[ ]=”2008”
year=atoi(number);
printf(“%d”, year);
}
Here, the function atoi() converts the string “2008” into numeric equivalent 2008
and assign it to the integer variable year.

POINTERS

A pointer is a variable that contains an address which is a location of another variable


in memory. Advantages of using pointers:
1. A pointer enables us to access a variable that is defined outside the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of storage space
in memory.
variable value address

x 10 5000

12
UNIT3 MSR

p 5000 5048

Consider int x=10; This will store the value of x in a memory location that is
having a unique memory address. Assume that the address is 5000 for x. Since
memory addresses are numbers, they can be assigned to some variables called as
pointer. Since pointer is a variable, its value is also stored in the memory in another
location. Suppose p is a pointer pointing to 5000, we can access the value of x using p.

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. How to determine the address of a variable? This
can be done with the help of & operator. The & operator immediately preceding a
variable returns the address of a variable. For e.g. p=&x; will assign the address 5000
to the variable p. The & operator can be referred as “address of”.
The & operator can be used only with a simple variable or an array element.

Declaring and initializing pointers

Since pointer variables contain addresses that belong to a separate data type, they must
be declared as pointers. The declaration of pointer variable takes the following form:
Data type *pointer-name;
This tells the compiler three things about the pointer-name.
1. * tells that the variable pointer-name is a pointer variable.
2. pointer-name needs a memory location.
3. pointer-name points to a variable of type data type.

For e.g. int *p;


declares p as a pointer points to an integer data type. Similarly float *p1; declares p1
as a pointer to a floating point variable.
Once a pointer variable has been declared, it can be made to point to a variable using
the statement such as
p=&x;

13
UNIT3 MSR

which causes p to point to x. Now p contains the address of x. This is known as pointer
initialization. Before a pointer is initialized, it should not be used.
For e.g. int x;
int *p;
p=&x;
This can also be written as int x,*p=&x;
But int *p=&x,x; is invalid because x is not declared first.

Accessing a variable through its pointer


This is done by using another operator * usually known as the indirection
operator. For e.g.
int x,*p,n;
x=10;
p=&x;
n=*p;
The last statement contains indirection operator * When the operator * is placed
before a pointer variable, the pointer returns the value of the variable to which it
points to. Indirection operator is referred as value at address.

Pointer expressions
Like other variables, pointer variables can be used in expressions. For e.g. if p1
and p2 are properly declared and initialized pointers then the following
statements are valid.
X= *p1 * *p2;
sum=sum+ *p1;
*p2=*p2+10;
Z=*p1/ *p2; Note that there is a space between / and * otherwise /* is considered
as the beginning of a comment.
C allows us to add integers to or subtract integers from pointers as well as to
subtract one pointer from another. p1+4,p2-2 and p1-p2 are all allowed.
We may also use short-hand operators with pointers. For e.g.
p1++;
--p2;
sum+=*p2;
Pointers can also be compared using relational operators. E.g.
p1>p2, p1==p2,p1!=p2 are allowed.
14
UNIT3 MSR

We cannot use pointers in multiplication, addition or division.


p1/p2,p1+p2,p1*p2 are not allowed.

Pointer increments and scale factor


Pointers can be incremented like p1++,p1=p1+2 and so on. However, the
expression like p1++; will cause the pointer p1 to point to the next value of its
type. For e.g. if p1 is an integer pointer with an initial value say 2000 then after
p1++; the value of p1 will be 2002 and not 2001. When we increment a pointer,
its value is increased by the length of the data type that it points to. This length is
called the scale factor.
char 1 byte
int 2 bytes
float 4 bytes
long int 4 bytes
double 8 bytes

Pointers and arrays


When an array is declared, the compiler allocates a base address and sufficient
amount of storage to hold all the elements of the array in sequential 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. For e.g. staticint x[5]={1,2,3,4,5};
Suppose the base address of x is 1000. Each integer requires 2 bytes. The 5
elements will be stored as follows:
Elements x[0] x[1] x[2] x[3] x[4]
Value 11 2 33 4 55
Address 1000 1002 1004 1006 1008
The name x is defined as a constant pointer pointing to the first element x[0] and
therefore x is 1000, where x[0] is stored.
x=&x[0]=1000
If we declare p as a pointer then we can make p to point to the array x by using
p=x; this is same as p=&x[0];
Every element of x can be accessed using p++ to move from one to another.

15
UNIT3 MSR

p+1=&x[1] (1002)
p+2=&x[2] (1004)
p+3=&x[3] (1006)
p+4=&x[4] (1008)

POINTERS AND STRINGS


A string is an array of characters which is terminated by the null character “\0'.
Thus the concept of pointers and one dimensional arrays can be extended to array of
characters. Let us write a program to determine the values of the elements of the
character array with the help of pointers.

Example : To access elements of a string with pointers


main()
{ charstr[25] = “Pointers”, *cp; Output:
int length; Character: P Address : 65472
Character: o Address : 65473
cp = &str[0]; Character: iAddress : 65474
Character: n Address : 65475
while(*cp != ‘\0’) Character: t Address : 65476
Character: e Address : 65477
{ printf(“\nCharacter :%c\tAddress : %u”, *cp, Character:
cp); r Address : 65478
cp++; Character: s Address : 65479
Length of the string : 8
}
length = cp –str;
printf(“Length of the string “%d”, length);
}
Since characters require one byte of storage in memory, incrementing pointer cp
will increment its value by 1 and it will point to the next character in the string. The
concept of single dimension array of characters i.e. string can be extended to the table
of strings. When we declare a two dimensional array of strings, each string will be
allocated equal length as specified in its declaration. However, in practice the all
strings of the table are rarely equal in length. Hence instead of making each row of a
fixed number of characters we can make each row a pointer to a string of varying
lengths.
Eg. char *name[3] = { “Jimmy”, “Jill”, “Joseph” };
The above declaration declares name to be an array of three pointers where each
pointer points to the particular name. This can be shown as follows :
name[0]----------> Jimmy
name[1]----------> Jill
name[2]----------> Joseph
16
UNIT3 MSR

Had we declared name to be a two dimensional array of strings as name[3][10] it


would have reserved 30 bytes for the array name, where each name would be allocated
10 bytes. But when we declare name to be an array of pointers, where each element
points to a name, the total memory allocated would be 18 bytes as follows:
In order to access the jth character of the ithrow : *(name[i] + j) would be useful.
[ Note that we first select the row, then the jth element of that particular row and then
determine value at address. We can print the names in the array as shown in the
following example ]
Example : To demonstrate an array of pointers to strings.
main()
{ inti;
char *name[3] = { “Jimmy”, “Jill”, “Joseph” };
printf(“\nNames in the array :”);
for(i=0; i<3; i++)
printf(“\n%s”, name[i]);
}

**************************

17

You might also like