You are on page 1of 19

C short notes: -Module III

Structured Data Types


1. Arrays:
An array is a group of related data items that share a common name. It is a sequence of
data in memory, wherein all data are of the same type, and are placed in physically
adjacent locations.
Array Declaration:
Arrays must be declared before they are used. The general form of array
declaration is
type variable_name[size];
The type specifies the type of element that will be contained in the array, such that
int, float, or char and the size indicates the maximum number of elements that can
be stored inside the array.
Ex: int salary[10];// declares an array salary of type int that contains 10
elements.
Array salary represents a set of salaries of a group employees. The compiler
reserves 10 storage locations in adjacent memory locations.
Each individual values in an array is called elements. To access a particular
element in an array, the array index is used , which is the integer enclosed in the
square braces with the name of the array.
Ex: salary[0]- represents the salary of the first person in the array.
Array initialization:
An array can be initialized when they are declared.
type array_name[size]={ list of values};

Ex: int a[5]={12,33,23,43,45};


or
int a[ ]={12,23,33,43,45};// array size may be omitted during declaration.
The values into array ‘a’ can be read from the user.
for(i=0;i<5;i++)
{
scanf(“%d”, &a[i]);
}
The name of the array is ‘a’. If it is used without any subscript, then it refers to
the memory location of the first integer number in the array.
The statement
scanf(“%d”,&a[0]);
is equivalent to
scanf(“%d”,a);
Two-dimensional arrays
Two dimensional arrays are used to store and manipulate the two-dimensional data
structures such as matrices and tables. Here, the array has two subscripts. One subscript
denotes the row, and the other, the column.
Declaration of the two-dimensional array:
Two dimensional arrays are declared as follows:
type array_name[row_size][column_size];
where each dimension of the array is indexed from zero to its maximum size
minus one.
Ex: int m[10][10];
Initialization of two-dimensional arrays:
During the declaration the arrays can be declared by specifying the elements in
row major order.
int a[3][4]=
{
{1,2,3,4},
{2,3,4,5},
{4,5,6,7}
};
or
int a[ ][4]=
{
{1,2,3,4},
{2,3,4,5},
{5,4,3,4}
};// the first subscript can be omitted.
or
int a[ ][4]={1,2,3,4,2,3,4,5,5,4,3,4};//inner braces can be omitted.
C program to add two matrices:
#include<stdio.h>
int main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
printf("Input row and column of matrix a\n");
scanf("%d%d",&m,&n);
printf("Input row and column of matrix b\n");
scanf("%d%d",&p,&q);
if((m==p)&&(n==q))
{
printf("Input the elements in the matrix a\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);

}
}
printf("Input the elements in the matrix b\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
//adding two matrices
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
c[i][j]=a[i][j]+b[i][j];
}

}
//printing the resultant array
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}//if
else
{
printf("The matrices cannot be added\n");
}
return 0;
}
C program to find the trace of the matrix
#include<stdio.h>
int main()
{
int a[10][10], i,j,n,sum=0;
printf("enter the order of the matrix\n");
scanf("%d", &n);
printf("enter the elements of the matrix\n");
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
// to find the trace of the matrix
for (i=0;i<n;i++)
{
sum+=a[i][i];
}
printf("The trace of the matrix is %d",sum);
return 0;
}
C program to find the transpose of the matrix
#include<stdio.h>
int main()
{
int a[10][10], i,j,m,n;
printf("enter the order of the matrix\n");
scanf("%d%d", &m, &n);
printf("enter the elements of the matrix\n");
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
// to find the transpose of the matrix
printf("The transpose of the matrix is\n");
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
return 0;
}
Strings
Strings are array of characters that are arranged one after another in memory. To mark
the end of the string, C uses the null character. Strings in C are enclosed within the
double quotes. The string is stored in memory as ASCII codes of the characters that make
up the string, appended with 0(ASCII of the null).

String Initialization
The initialization of the string can be done as follows.
char month[ ]=”January”;
or
char month[ ]={‘J’,’a’,’n’,’u’,’a’,’r’,’y’,’\0’};
The compiler takes care of storing the ASCII codes of the characters of the string in
memory and also stores the null terminator in the end.
Ex:
#include<stdio.h>
void main( )
{
char month[15 ];
printf(“enter the string”);
gets(month);
printf(“The string entered is %s”,month);
}
String handling Functions(Functions in string.h)
The string.h header file contains the functions to manipulate strings.
1. strcat( )
This function concatenates two strings. i.e., it appends one string at the end of the
another. This function accepts two strings as parameters and stores the contents of the
second string at the end of the first.
Syntax:strcat(string1,string2)
When the function strcat( ) is executed, string2 is appended by removing the null
character at the end of the string1 and placing string2 from there.
Ex: #include<stdio.h>
#include<string.h>
int main( )
{
char oneString[10]=”Fish”;
char twoString[ ]=”face”;/*if the subscript is omitted, it is assumed to be the size
of the data with which the array is initialized*/
strcat(oneString,twoString);
printf(“%s”,oneString);
}
output:Fishface.
After concatenation, oneString contains 10 characters in length, including the null
character ‘\0’.
2. strcmp( )function
The strcmp( ) function compare two strings identified by the arguments and has a
value 0 if they are equal. If they are not, it has the numeric difference between the
first nonmatching characters in the strings.
Syntax:strcmp(string1,string2);
where string1 and string2 may be string variables and string constants.
strcmp(“their”,”there”);
will return a value of -9 which is the numeric difference between ASCII “i” and
ASCII “r”.
ASCII value of “r” is higher .
string1 is alphabetically above string2. (i. e. string2>string1.)
3. strcpy( )function
The strcpy( ) function copies one string to another.This function accepts two strings
as parameters and copies the second string character by character into the first
one,upto and including the null character of the second string.
Syntax:strcpy(string1,string2);
It assigns the contents of string2 to string1. String2 may be a character array
variable or a string constant.
Ex:
int main( )
{
char city[5];
strcpy(city,”DELHI”);
printf(“%s”,city);
return 0;
}
will assign the string constant “DELHI” to the string variable city.
4. strlen( )function
This function returns an integer which denotes the length of the string passed. The
length of a string is the number of characters present in it, excluding the terminating
null character.
Syntax : n=strlen(string);
where n is an integer variable which receives the value of the length of the string. The
argument may be a string constant.
Ex: void main( )
{
char str[ ]=”Hello”;
printf(“%d”, strlen(str));
}
will output 5.
5. strncpy( ) function
The strncpy() function is similar to the strcpy() function, except that it copies only the
specified number of characters from source string to destination string.
strncpy(str1, str2, n);
Ex:
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
strncpy ( target, source, 5 ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
Ans:
source string = fresh2refresh
target string after strncpy( ) = fresh
6. strncmp( )function
strncmp() comparison function is limited to the number of characters specified
during the function call.
For example strncmp(str1, str2, 4) would compare only the first four characters of
strings str1 and str2.
The return value of this function is
0, if both the strings str1 and str2 are equal.
>0, if the ASCII value of first unmatched character of str1 is greater than str2.
<0, if the ASCII value of first unmatched character of str1 is less than str2.
ex:
int main(void) {
char str1[10] ="THRISSUR";
char str2[20] ="THIRUVANTHAPURAM";
int n=4;
int result;
result=strncmp(str1,str2,n);
if(result==0)
printf("str1 is equal to str2 for 4 characters\n");
else if(result > 0)
printf("str1 is greater than str2 for 4 characters\n");
else
printf("str1 is less than str2 for 4 characters\n");
return 0;
}
Ans: str1 is greater than str2 for 4 charcters.
7. strncat( )function
strncat() appends only the specified number of characters to the destination string.
str1 – Destination string.
str2 – Source string which is appended at the end of destination string str1.
n – number of characters of source string str2 that needs to be appended.
int main(void) {
char str1[20]="THRISSUR";
char str2[20]="THIRUVANTHAPURAM";
int n=4;
strncat(str1,str2,n);
printf("String after concatenating 4 characters\n%s\n",str1);
return 0;
}
Ans: THRISSURTHIR
8. strstr( )function
The strstr() function searches the given string in the specified main string and returns
the pointer to the first occurrence of the given string.
Return value of strstr()-This function returns the pointer to the first occurrence of the
given string otherwise it returns a NULL pointer.
int main(void) {
char str1[20]="THRISSSUR POORAM";
char str2[10]="POORAM";
if(strstr(str1,str2)==NULL)
printf("str2 is not a substring of str1\n");
else
printf("str2 is a substring of str1\n");
return 0;
}
Ans: str2 is a substring of str1.
9. strchr( )function
The strchr() function finds the first occurrence of a specified character in a string.
The function strchr() searches str from left to right until the character ch . If ch is
found, a pointer to it is returned. If not, NULL is returned.
ex:
int main(void) {
char str1[20]="THRISSSUR POORAM";
char ch=’P’;
if(strchr(str1,ch)==NULL)
printf("P is not a character present in str1\n");
else
printf("P is a character present in str1\n");
return 0;
}
Ans: P is a character present in str1.
10. strrchr( )function

The strchr() function finds the last occurrence of a specified character in a string. If
character in the variable ch is found, a pointer to it is returned. If not, NULL is
returned.
ex:
int main(void) {
char str1[20]="THRISSSUR POORAM";
char ch=’O’;
if(strrchr(str1,ch)==NULL)
printf("O is not a character present in str1\n");
else
printf("O is a character present in str1\n");
return 0;
}
11. strrev( )function
strrev( ) function reverses a given string in C language.
ex:
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
String before strrev( ) : Hello
String after strrev( ) : olleH
12. strupr( )function
strupr( ) function converts a given string into uppercase.
#include<stdio.h>
#include<string.h>

int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n", strupr(str));
return 0;
}
13. strlwr( )function
strlwr( ) function converts a given string into lowercase.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Lower";
printf("%s\n",strlwr (str));
return 0;
}
Character functions
“ctype.h” header file support all the below functions in C language.
1.isalpha( )function
isalpha() function in C language checks whether given character is alphabetic or not.
Syntax for isalpha( ) function is given below.

int isalpha ( int x );

ex:
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalpha ( ch ) )
printf ( "\nEntered character is alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
}
2.isdigit( )function
isdigit( ) function in C language checks whether given character is digit or not.
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isdigit ( ch ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
}
3.islower( )function
islower( ) function in C language checks whether given character is lower case or
not.
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);

if ( islower ( ch ) )
printf ( "\nEntered character is lower case character") ;
else
printf("\nEntered character is not lower case character");
}
4.isupper( )function
isupper( ) function in C language checks whether given character is upper case or
not.
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isupper ( ch ) )
printf ("\nEntered character is uppercase character");
else
printf("\nEntered character is not uppercase character");
}
Character conversion functions
1. tolower( )function
tolower( ) function in C language checks whether given character is alphabetic
and converts to lowercase. Syntax for tolower( ) function is given below.
int tolower( int x );
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);

if(isalpha(ch))
printf ( "\nEntered character is converted into lower
character : %c\n",tolower ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}
2. toupper( )function
toupper( ) function in C language checks whether given character is alphabetic and
converts to uppercase. Syntax for toupper( ) function is given below.
int toupper( int x );
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);

if(isalpha(ch))
printf ( "\nEntered character is converted into
upper character : %c\n",toupper ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}

C program to check whether the string is a palindrome or not


#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, len, flag;
flag = 0;
printf("\n Please Enter any String : ");
gets(str);
len = strlen(str);
for(i = 0; i < len; i++)
{
if(str[i] != str[len - i - 1])
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("\n %s is a Palindrome String", str);
}
else
{
printf("\n %s is Not a Palindrome String", str);
}

return 0;
}
Structures
A structure in C is a heterogenous user defined data type. A structure may contain different data
types. It groups variables into a single entity.
The keyword structure declares a structure to hold 5 fields, these fields are called structure
elements or members. Each member may belong to a different type of data. The general format
of structure definition,
struct tag_name
{
data_type member1;
data_type member2;
};
An example of structure declaration is:
struct student
{
int rollno;
char subject[20];
float mark1,mark2,mark3,total;
};
Declaration of structure variables:
To use this structure in a program, we must define a structure variable as:
struct student stud1;
The members of a structure themselves are not variables. They do not occupy any memory until
they are associated with a structure variable such as stud1.
The structure declaration and variable declaration can be done in one statement.
structure student
{
int rollno;
char subject[12];
float mark1,mark2,mark2,total;
}stud1,stud2;
Initialization of structure variables:
To access the members of a structure, the member operator(.), is used. The link between a
member and a variable is established using this (.)dot operator or period operator. For example:
stud1.rollno;
where stud1 is a structure variable and rollno is the member of stud1.
Like any other variable we could initialize it as
stud1.rollno=1;
strcpy(stud1.subject,”computerscience”);
Array of Structures:
The array will have individual structures as its elements.
struct employee
{
char name[25];
char designation[25];
float salary;
}emp[10];
emp is an array of 10 structures of type employee.
C program using array of structures to enlist students in a class with their marks
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int i;
printf("Enter information of students:\n");
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}
Union
A union is a data type in C which allows the overlay of more than one variable in the same
memory area. In structures each member has its own storage location, whereas all the members
of a union use the same location. That union may contain many members of different types, it can
handle only one member at a time.
Declaration of a union
union employee
{
int empID;
char name[35];
char designation[12];
char department[12];
}emp;
The compiler allocates a piece of storage that is large enough to hold the largest variable type in
the union.
Difference between Structures and Unions
The amount of memory required to store a structure variable is the sum of sizes of all the
members . On the other hand, the amount of memory required is the same as that required by its
largest member.
struct employee
{
char name[12];
int empid;
char dept[12];
}emp;
union employee_dept
{
char name[12];
int empid;
char dept[12];
}empdep;
void main( )
{
printf(“The size of the structure is %d”,sizeof(emp);//12+2+12=26 bytes
printf(“The size of the union is %d”,sizeof(empdept);// 12 bytes.
}
Here individual values in a union occupy the same location in memory. Thus, writing into one
will overwrite the other.

You might also like