0% found this document useful (0 votes)
49 views26 pages

C Language

Uploaded by

Mark 42
Strings in C are arrays of characters terminated by a null character. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings. Strings can be declared as character arrays and initialized either during or after declaration. Functions like scanf(), printf(), puts(), strcat(), strcmp(), strcpy() allow manipulating and working with strings in C.

Copyright:

© All Rights Reserved

Available Formats

Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
49 views26 pages

C Language

Uploaded by

Mark 42
Strings in C are arrays of characters terminated by a null character. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings. Strings can be declared as character arrays and initialized either during or after declaration. Functions like scanf(), printf(), puts(), strcat(), strcmp(), strcpy() allow manipulating and working with strings in C.

Copyright:

© All Rights Reserved

Available Formats

Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 26

UNIT-III

STRINGS IN C LANGUAGE
In C language, A group of or, One or more characters, digits, symbols, special
symbols enclosed with in double quotation (“,”) marks are called as String. In other words, A
character array is called a string. String are used to manipulate text such as words and
sentences. Every string is terminated with ‘\0’ (NULL) character. The NULL character is a
byte with all bits at logic is zero.
The common operations performed on character strings include:
1. Reading and Writing Strings
2. Combining Strings together.
3. Copying one string to another.
4. Comparing Strings for equality.
5. Extracting a portion of a string. And so on.

Declaring and Initializing String Variable: -C language does not support string as a data
type.It allows us to represent string as character array. The (Syntax) general form of
declaration of a string variable is as follows.
char stringname[size];
Here, stringname is a name of the string. The size determines the number of characters in the
stringname variable. For Example,
char city[20];
char student_name[30];
When the compiler assigns a character string to a character array, it automatically supplies a
NULL character (‘\0’) at the end of the string. Therefore, the size should be equal to the
maximum number of characters in the string plus one.
Character arrays (strings) may be initialized, when they are declared. C permits a string to be
initialized in either of the following two forms:
1. char city[9]= “NEW YORK”;
2. char city[9]= {‘N’,’E’,’W’,’ ‘, ‘Y’,’O’,’R’,’K’,’\0’};
The reason that, the string variable city had to be 9 elements(characters) long is that the string
NEW YORK contains 8 characters and one element space (location) is provided for the
NULL character.
C permits us to initialize a string without specifying the size of the string. For example, The
statement, char city[]=”NEW YORK”; defines a string variable city as 9 element array.
If The size of the string is much larger than the number of characters in the string,
then all unfilled locations can be filled with NULL characters.
For example,
char city[12]=”NEW YORK”;
Then, The storage will looks
like,
N E W Y O R K \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9 10 11
The following declaration is illegal
char city[2]=”HYD”; This will result in a compile time error.
We can not separate initialization form declaration. That is,
char city[10] ; /* declaration */
city=”HYD”; /* initialization */
Assignment of strings is not allowed. That is,
city1=city2; where, city1 and city2 are string variables.

1
Reading Strings from terminal (Input device): - We can read strings using scanf()
function with control string(format string) %s as follows.
Example: -
char city[10]; scanf(“%s”, &city);
The scanf() function determines its input on the first white space it finds.(White space
includes blanks, tabs, carriage returns, form feeds, new lines).Therefore, the scanf() function
reads first word as a string input and terminates the remaining words after the white spaces.
For example, the below line is typed from keyboard,
NEW YORK
The string NEW word is read into the variable city only, since the white space after the
NEW will terminate the remaining words.

In the case of reading strings, The ampersand(&) is not required before the string variable
name in scanf() function. For example:
char city[10];
scanf(“%s”, city);

We can read required number of characters from keyboard using scanf() with field width as
follows:
scanf(“%ws”, stringvariable);
example:
char city[12];
scanf( “%5s”, city);
The input string “HYD” will be stored as

H Y D \0 \0 \0 \0 \0 \0 \0 \0 \0

The input string “NEW YORK” will be stored as

N E W Y \0 \0 \0 \0 \0 \0 \0

Reading a line of text using scanf() function with edit set conversion code %[..] :

We can read a line of text including white spaces till the enter key is pressed.

For example:
char city[80];
scanf(“%[^\n]”,city);
It reads a line of input from keyboard and stores that input into the string variable city.
Displaying the Strings: -We can display Strings using printf() and puts() functions.
char city[20]=”hyd”;
printf(“%s”, city);
It displays the value of string city and cursor is placed at the same line.
puts(city);
It displays the value of string city and cursor is placed at the next line(\n).
.

2
STRING HANDLING FUNCTIONS
The string header file string.h provides many string handling functions useful for
manipulating strings (character arrays).
1 strcat():-It Appends the string pointed to by str2 to the end of the string pointed to by str1.
The terminating null character of str1 is overwritten. Copying stops once the terminating null
character of str2 is copied. If overlapping occurs, the result is undefined. The argument str1
is returned.
Syntax: char *strcat(char *str1 , const char *str2);
Example:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[60],str_two[30];
clrscr();
printf("Enter String One : ");
scanf("%s",&str_one);
printf("Enter String Two : ");
scanf("%s",&str_two);
strcat(str_one, str_two);
printf("Concatenated String : %s",str_one);
getch();
}
Output: -
Enter String One: VSM
Enter String Two: COLLEGE
Concatenated String: VSMCOLLEGE

2 strncat()-: It Appends the string pointed to by str2 to the end of the string pointed to by
str1 up to n characters long. The terminating null character of str1 is overwritten. Copying
stops once n characters are copied or the terminating null character of str2 is copied. A
terminating null character is always appended to str1. If overlapping occurs, the result is
undefined. The argument str1 is returned.
Syntax: char *strncat(char *str1, const char *str2, size_t n);

3.strcmp():- It Compares the string pointed to by str1 to the string pointed to by str2.
if str1 and str2 are equal based on ASCII value, then returns zero. If str1 is less than or greater
than str2 then it returns less than zero or greater than zero respectively.
Syntax: int strcmp(const char *str1, const char *str2);

Example:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30], str_two[30];
int n;
clrscr();
printf("Enter String One : ");
3
scanf("%s",&str_one);
printf("Enter String Two : ");
scanf("%s",&str_two);
n=strcmp(str_one,str_two);
if(n==0)
{
printf("Both the Strings are Equal");
}
else
{
printf("Strings are not Equal");
}
getch();
}

Output 1:
Enter String One : welcome
Enter String Two :
welcome Both the Strings
are Equal Output 2:
Enter String One : welcome
Enter String Two : WELCOME
Strings are not Equal
In the second output, the ASCII values of lower case ‘w’ letter and upper case ‘W’ letter are
different. Therefore, the two strings are not equal.

4.strncmp():-It Compares at most the first n bytes of str1 and str2. It stops comparing
after the null character.
It returns zero , if the first n bytes (or null terminated length) of str1 and str2 are equal based
on ASCII value, then returns zero. If str1 is less than or greater than str2 then it returns less
than zero or greater than zero respectively.
Syntax: int strncmp(const char *str1, const char *str2, size_t n);

5.stricmp():- It ignores the upper case and lower case sensitiveness of letters. It Compares
the string pointed to by str1 to the string pointed to by str2, but they are not case sensitive. if
str1 and str2 are equal, then returns zero. If str1 is less than or greater than str2 then it
returns less than zero or greater than zero respectively.
Syntax: int strcmp(const char *str1, const char *str2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30], str_two[30];
int n;
clrscr();
printf("Enter String One : ");
scanf("%s",&str_one);
printf("Enter String Two : ");

4
scanf("%s",&str_two);
n=strcimp(str_one,str_two);
if(n==0)
{
printf("Both the Strings are Equal");
}
else
{
printf("Strings are not Equal");
}
getch();
}
Output 1:
Enter String One : welcome
Enter String Two :
welcome Both the Strings
are Equal Output 2:
Enter String One : welcome
Enter String Two : WELCOME
Both the Strings are Equal
In the second output, the ASCII values of lower case ‘w’ letter and upper case ‘W’ letter are
ignored. Therefore, the two strings are equal.
Output 3:
Enter String One : welcomevsm
Enter String Two : WELCOME
Strings are not Equal
In the third output, The string are not matched. Therefore, the two strings are not equal.
6.strcpy():-It Copies the string pointed to by str2 to str1. It Copies up to and including the
null character of str2. If str1 and str2 overlap the behavior is undefined. The previous
content of str1 is overwritten.
Syntax: char *strcpy(char *str1, const char *str2);
Returns the argument str1. For example:
str_one = "abc";
str_two = "def";
strcpy(str_two , str_one); /* str_two becomes "abc" */
Example: Write a program to copy contents of one string into another
string#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30], str_two[30];
printf("Enter a String : ");
scanf("%s",&str_one);
strcpy(str_two,str_one);
printf("Contents of String One : %s",str_one); printf("\
nContents of String Two : %s",str_two); getch();
}

5
Output: -
Enter a String: abc
Contents of String One:
abc
Contents of String Two: abc
7. strncpy (): -It Copies up to n characters from the string pointed to by str2 to str1. It
Copying stops when n characters are copied or the terminating null character in str2 is
reached. If the null character is reached, the null characters are continually copied to str1
until n characters have been copied.
Returns the argument str1.
Syntax:char *strncpy(char *str1, const char *str2, size_t n);
For example,
str_one = "abc";
str_two = "def";
strcpy(str_two , str_one,2); /* str_two becomes "ab" */
Example: Write a program to copy contents of one string into another string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30], str_two[30];
printf("Enter a String : ");
scanf("%s",&str_one);
strcpy(str_two,str_one,2);
printf("Contents of String One : %s",str_one);
printf("\nContents of String Two : %s",str_two);
getch();
}
Output: -
Enter a String: abc
Contents of String One: abc
Contents of String Two: ab
8. strrev (): -It is used to reverse the characters in a given string. The contents(data) of
a given string are reversed. The previous data of a string can be overwritten.
Syntax: char *strrev(char *str1);
Example: -
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30];
printf("Enter String : ");
scanf("%s",&str_one);
strrev(str_one);
printf("Reversed String : %s",str_one);
}
Output: -
Enter String: VSM
Reversed String: MSV
6
9 strlen() It Computes the length of the string str up to but not including the terminating null
character. Returns the number of characters in the string.
Syntax: size_t strlen(const char *str);
Example:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str_one[30];
int len;
printf("Enter a String : ");
scanf("%s",&str_one);
len=strlen(str_one);
printf("\n Length of the Given String is : %d",len);
getch();
}
Output: -
Enter a String: welcome
Length of the Given String is
:7
Here, the variable len contains the value 7 , i.e the length of string “welcome”.

10. strstr():-It Finds the first occurrence of the entire string str2 (not including the
terminating null character) which appears in the string str1. It Returns a pointer to the first
occurrence of str2 in str1. If no match was found, then a null pointer is returned. If str2 points
to a string of zero length, then the argument str1 is returned.
Syntax: char *strstr(const char *str1, const char *str2);

11. strset():-It is one of many string functions available. For using string functions we need
to include string library.In this function we pass 2 parameters namely a string and a character.
When this function is called it will replace all the characters in the string by the specified
character. While counting it will take blank spaces also.
Syntax : char *strset( const char *str,char ch );
strset(str,ch) set all character in str to ch. quits when the first null character is
found. Returns a pointer to str.

7
ARRAYS & TYPES OF ARRAYS
To process large amount of similar type of data, C supports a derived data type
known as array that can be used for processing large amount of similar type of data.
Definition: -
An array is a fixed-sized consecutive memory location, having similar (same or
homogeneous) type of data elements (data items). All memory locations can be referenced
by a common name known as array name. Each memory location can be identified by a
unique number known as index or subscript. In array, the index number is always started from
0(zero). Each memory location can be referenced by array name and index number known as
subscripted variable. A set of pairs of index and a value is called as an array.
Advantages: -
1. Arrays use static memory allocation process to create memory locations for
array, it saves execution time.
2. Similar type of data elements can be stored only.
3. All elements can be processed in a sequential manner.
Disadvantages: -
1. Sometimes, Waste of memory, or shortage of memory
2. Unable to store different types of data elements.
3. There is no random-access facility to process individual data element.
Arrays can be used in the following examples:
1. List of student numbers in a college.
2. List of employees in an organization
3. List of products and their costs sold by a shop.
4. A Table of daily rainfall data. etc.,
Types of arrays: - Arrays can be classified into three types as follows.
1. One-dimensional Arrays
2. Two-dimensional Arrays
3. Multi-dimensional Arrays.
1.One-dimensional Arrays: An array, which use one subscript, is called One-dimensional
Array. A list of data elements referenced by one variable name using only one index or
subscript and such a variable is called a single-subscripted variable or a one-dimensional
array. It is a vector.
Declaring one-dimensional array:-
We can declare one dimensional array as follows:
Syntax:
datatype arrayname[size];
Example: int a[10];
The above statement create 10 memory locations of type integer with a common name. The
range of index is from 0 to 9. The array index position is always started from 0 (ZERO).

01 23 4 56 7 89
Initializing one-dimensional array: - An array can be initialized at either of the following
stages.
1.At compile time
2.At run time.
1. Compile time initialization: -
We can initialize an array, when it is declared with size.
Syntax:
datatype arrayname[size]={ list of values };

8
Example: -
int numbers[5]={10,20,30,40,50};
The above statement declares the array variable numbers with size 5 and will assign
10,20,30,40,50 values into each memory location of an array as follows:
10 20 30 40 50
0 1 2 3 4
When an array is being declared, we can initialize an array without specifying the size of
array as follows.
Syntax: -
Datatype arrayname[]={ list of values };
Example:
int numbers[]={10,20,30,40,50};
The above statement declares the array variable numbers with size 5 and will assign
10,20,30,40,50 values into each memory location of an array as follows:
10 20 30 40 50
0 1 2 3 4
2. Run-time initialization: -The memory locations of an array can be explicitly initialized
at run time as follows.
int a[100],i;
for( i=0; i<100;i++)
{
a[i]= 0;
}

In the above loop, the 100 locations of array ‘a’ are initialized with 0 (zero) at
run time.

Accessing Array Elements: -Given the declaration above of a 100 element array the
compiler reserves space for 100 consecutive floating-point values and accesses these values
using an index/subscript that takes values from 0 to 99. The first element in an array in C
always has the index 0, and if the array has n elements the last element will have the index n-
1.

An array element is accessed by writing the identifier of the array followed by the subscript
in square brackets. Thus to set the 15th element of the array above to 1.5 the following
assignment is used.
annual_temp[14] = 1.5;

Note that since the first element is at index 0, then the ith element is at index i-1. Hence in the
above the 15th element has index 14.

An array element can be used anywhere an identifier may be used. Here are some examples
assuming the following declarations:

2. Two-dimensional Array: An array, which use two subscripts , is called Two-dimensional


Array. A table of data elements referenced by one variable name using two indices or
subscripts and such a variable is called a two-dimensional array. The first index indicates
rows and the second index indicates columns. Two-dimensional arrays are used to manipulate
matrices. Two dimensional array elements are stored based on complier specification (either
row-major or column major order ).
9
Declaring two-dimensional array: -We can declare two-dimensional array as follows.
Syntax: -
datatype arrayname[rowsize][columnsize];
Example: - int a[3][4];
A 2-dimensional array a, which contains three rows and four columns can be shown
as below:
int a[3][4];

The above statement create 3*4 (12) memory locations of type integer with a common
name. The range of first index is from 0 to 2 and the range of second index is from 0 to 3.
Initializing a two-dimensional array: -An array can be initialized at either of the following
stages.
1. At compile time
2. At run time.
1. Compile time initialization: -We can initialize an array, when it is declared with size.
Syntax: - datatype arrayname[rowsize][columssize]={ list of values };
Example:-
int matrix[3][3]={10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90};
or
int matrix[3][3]={
{10 , 20 , 30},
{40 , 50 , 60},
{70 , 80 , 90}
};

The above statement declares the array variable matrix with size 3*3 and will assign
10,20,30,40,50,60,70,80,90 values into each memory location of an array as follows:
0 1 2 - Columns
10 20 30
40 50 60
70 80 90
We can initialize an array, when it is declared without size of array.
Syntax: -
datatype arrayname[][]={ list of values };
Example: -
int matrix[][]={
{10 , 20 , 30},
{40 , 50 , 60},
{70 , 80 , 90}
};

10
The above statement declares the array variable matrix with size 3*3 based on table of values
and will assign 10,20,30,40,50,60,70,80,90 values into each memory location of an array as
follows:
0 1 2
10 20 30
40 50 60
70 80 90
When the all locations are to be initialized to zero , then the following short-cut method can
be used as follows.
int matrix[3][3]= { {0}, {0},{0} };
The above statement initialize the first memory location of each row with zero, while other
locations of that row are automatically initialized to zero.
2. Run-time initialization: -The memory locations of an array can be explicitly initialized
at run time as follows.
int matrix[3][3], i , j;

for( i=0; i<3;i++)


{
for( j=0;j<3;j++)
matrix[i][j]= 0;
}
In the above nested loop, the 3*3=(9) locations of array matrix are initialized with 0 (zero)
at run time.
3. Multi-dimensional array: - An array, which use more than two subscripts, is called
Multi- dimensional array. C language allows arrays of three or more dimensions. The exact
limit is determined by the compiler. ANSI C does not specify any limit for array dimension.
Most compilers permit 7 to 10 dimensions. The general syntax of multi-dimensional array is
datatype arrayname[size_1][size_2]…[size_i]..[size_n];
where size_i is the size of ith dimension .
An example is as follows:
int survey[5][4][12]; where, survey is a three-dimensional array declared, it contain 240
integer type elements. The array survey may represent survey data of 12 months rainfall
during last 4 years in 5 cities.

Note1: The array index position is always started from 0 (ZERO), because
1. Zero-based numbering is numbering in which the initial element of a sequence is
assigned the index 0, rather than the index 1.
2. a[0] is actually *(a+0) - the element at the 0th distance from the start of the
memory region.
3. It is convenient to implement circular queue mechanism .and to apply
modulo division (%) operation.
4. The array index is the distance from the beginning. If the distance is 0, then you
are at the starting line. You can think of it as a number line:

Where, the 0 is the starting point.


5. Generally, in computers everything starts with 0. Address of memory can start with 0.
Numbers starts with 0. We can say, when the counting of number ends with 0 for
others, the counting of computers starts.
Note 2: If arrays are not initialized, then garbage values are stored.
If static arrays are not initialized, then zeroes (0) are stored.

Note3: In a multidimensional array with initialization, the left most dimension (rows in 2-D
array) may be omitted(optional).
Note 4:C language does not provide automatic bound(lowerbound(0) and upper bound(n-1) )
checking of array.
Note 5: The amount of storage required for holding elements of the array depends on data type
and size of array.
typedef in C
In C programming language, typedef is a keyword used to create alias name for the
existing datatypes. Using typedef keyword we can create a temporary name to the system
defined datatypes like int, float, char and double. we use that temporary name to create a
variable. The general syntax of typedef is as follows.
typedef <existing-datatype> <alias-name>
typedef with primitive datatypes: -Consider the following example of typedef
typedef int Number
In the above example, Number is defined as alias name for integer datatype. So, we can
use Number to declare integer variables.
Example:-
#include<stdio.h>
#include<conio.h>
typedef int Number;
void main(){
Number a,b,c; // Here a,b,&c are integer type of
variables. clrscr() ;
printf("Enter any two integer numbers: ")
; scanf("%d%d", &a,&b) ;
c = a + b;
printf("Sum = %d", c) ;
}
typedef with arrays: -In C programming language, typedef is also used with arrays.
Consider the following example program to understand how typedef is used with arrays.
Example Program to illustrate typedef with arrays in C.
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int Array[5]; // Here Array acts like an integer array type of size 5.
Array list = {10,20,30,40,50}; // List is an array of integer type with size 5.
int i;
clrscr() ;
printf("List elements are : \n") ;
for(i=0; i<5; i++) printf("%d\
t", list[i]) ;
}
In the above example program, Array is the alias name of integer array type of size 5.
We can use Array as datatype to create integer array of size 5. Here, list is an integer
array of size 5.
Enumerated data types
Enumeration is a user defined datatype in C language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword “enum” is
used to declare an enumeration. The syntax of enum in C language is

enum enum_name{const1, const2,.........};


The enum keyword is also used to define the variables of enum type. There are two ways to
define the variables of enum type as follows.

enum week{sunday, monday, tuesday, wednesday, thursday,


friday, saturday};
enum week day;

Example1: -

#include<stdio.h>

enum week{Mon, Tue, Wed, Thu, Fri, Sat, Sun};

enum day{Mond=10, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};

void main() {

printf("The value of enum week:


%d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thu, Fri, Sat,
Sun);

printf("The default value of enum day:


%d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid,
Satu, Sund);

}
Output:-
The value of enum week: 0 1 2 3 4 5 6
The default value of enum day:
10 11 12 13 18 11 12
In the above program, two enums are declared as week and day outside the main() function. In
the main() function, the values of enum elements are printed.
Example2: -
// An example program to demonstrate working
// of enum in C
#include<stdio.h>
enum week{Mon, Tue, Wed, Thu, Fri, Sat, Sun};
void main()
{
enum week day;
day = Wed;
printf("%d",day);

}
Output:-
2
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed.
Example3: -

// Another example program to demonstrate working


// of enum in C
#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,


Aug, Sep, Oct, Nov, Dec};

void main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is
Jan which is 0 and the value of Dec is 11.
Structures & Unions
Structure Definition: A Structure is a user-defined data type, which contains a collection of
one or more variables(fields/members) of different data types, grouped together under a
single name. By using structure declaration, we can make a group of structure variables,
arrays, pointers.
Declaration of Structures: -Structures can be declared as given below:
Syntax:-
struct struct_name
{
datatype1 field1 ;
datatype2 field2 ;
:
:
datatypeN fieldN ;
};
Structure declaration always start with struct keyword. struct_name is known as tag
or structure name. The struct declaration is enclosed with in a pair of curly braces { }.
The field1, field2.. fieldN are members of the structure.
After declaring a structure, We can define structure variables to create memory locations. The
structure declaration declares structures, but, this process does not allocate memory. The
memory locations can be allocated, whenever structure variables are defined.
Syntax: -
struct struct_name structvariable1, structvariable2,….structvariableN ;
Here, structvariable1, structvariable2,…..structvariableN are variables of struct struct_name.
Type-defined Structures: - We can use keyword “typedef” to define user-defined data types
such as structure, union or any other user defined data type as follows.
typedef struct
{
datatype1 field1 ;
datatype2 field2 ;
:
datatypeN fieldN ;
} typename ;
The typename represents structure definition associated with it and it can be used to
declare structure variables as shown below.
typename variable1, variable2,…. variableN;
Example: -
struct student
{
int sno;
char sname[20];
};
struct student stu[3] , *ptr;
Here, the variable stu is an array of struct student type. The pointer variable ptr is also struct
student type.

Accessing structure members:-We can access and assign values to the members of a
structure in number of ways. The link between member and structure variable is established
using the member operator . (dot operator)or period operator.
For example.
stu[0].sno=10;
strcpy (stu[0].sname,”raju”) ; Here, stu is a structure variable and sno, sname are
members of the strcture.
Initialization of Structures: -A structure variable can be initialized at compile time as follows.
struct student
{
int sno;
char sname[20];
} stu={10 , ”ramu”}; This assigns the value 10 to stu.sno and “ramu” to stu.sname

Coping (Assigning) and comparing structure variables: -Two variables of same structure
type can be copied the same way as ordinary variables. If stu1, and stu2 belong to the same
structure, then the following statements are valid.
stu2=stu1; /* the values of stu1 are assigned to stu2 structure. */
stu1=stu2; /* the values of stu2 are assigned to stu1 structure. */
Note: C language does not permit logical operations on structure variables. We have to
compare members individually.

Arrays of structures: -We use structures to define the format of a number of related
variables. For Example, to maintain three student’s details, we may declare array of
structures, each element of array representing a structure variable. For example,
struct student
{
int sno;
char sname[20];
};
struct student stu[3];
Here, the variable stu is an array of struct student type.

/* Example: Read and display 3 students data using Array of structures*/

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
};
struct student stu[3] ;
void main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
printf(“ \nStudent details are \n”);
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, stu[i].sno , stu[i].sname);
}
getch();
}

Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama

Student details are


Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name=
rama

Arrays with in structures: -C language permits the use of arrays as structure members. We
can declare single, or multi-dimensional arrays with in structures. For example,
struct student
{
int sno;
char sname[20];
int marks[3];
};
struct student stu[3];
Here, the variable stu is an array of struct student type, the member sname is an array of type
char and the member marks is an array of type int.
/* Example : Read and Display 3 students data using Arrays with in structures*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20]; /* char type Array with in structure */
int marks[3]; /* int type Array with in structure */
};
struct student stu[3] ;
main()
{
int i,j, tmarks;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
printf(“Enter marks of 3 subjects”); for(j=0;j<3;j+
+)
scanf(“%d”, &stu[i].marks[j]);
}
printf(“ \nStudent details are \n”);
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, stu[i].sno , stu[i].sname);
tmarks=0;
for (j=0; j<3;j++)
tmarks= tmarks + stu[i].marks[j];
printf(“ Total Marks = %d\n”, tmarks);
}

getch();
}
Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter marks of 3 subjects 50 60 70
Enter student number and name: 20 ravi
Enter marks of 3 subjects 70 80 90
Enter student number and name: 30 rama
Enter marks of 3 subjects 40 50 60
Student details are
Student number =10 and name= raju
Total Marks = 180
Student number =20 and name= ravi
Total Marks = 240
Student number =30 and name= rama
Total Marks = 150

Structure declarations with in structures (Nested structures):-We can declare structures


with in structures in C language. Structures with in structures are known as nesting of
structures. For example, We can declare dateofjoin structure with in student structure as
follows.
struct student
{
int sno;
char sname[20];

struct
{
int day;
int month;
int year;
}dateofjoin;
};
struct student stu;
Here, the student structure contains sno, sname, and a member dateofjoin which itself is a
structure with three members i.e., day, month, year are members of the inner structure. These
can referred to as
stu.dateofjoin.day
stu.dateofjoin.month
stu.dateofjoin.year

/* Example: Read and display one student data using structure declaration with in structures
or nesting of structures */
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
struct
{
int day;
int month;
int year;
}dateofjoin;
};
struct student stu;
main()
{
printf(“Enter One student data\n”);
printf(“ Enter student number and name:”);
scanf(“%d%s”, &stu.sno, &stu.sname);
printf(“ Enter Date of Joining:”);
scanf(“%d%d%d”, &stu.dateofjoin.day, &stu.dateofjoin.month, &stu.dateofjoin.year);
printf(“ \nGiven Student details are \n”);
printf(“ student number = %d and name:= %s\n”, stu.sno , stu.sname);
printf(“ Date of Join is =”);
printf(“%2d-%2d-%4d”,stu.dateofjoin.day, stu.dateofjoin.month, stu.dateofjoin.year);
getch();
}

Output:-
Enter One student data
Enter student number and name: 10 raju
Enter Date of Joining: 12 5 2010
Enter student number and name: 20 ravi
Enter Date of Joining: 13 5 2010
Enter student number and name: 30 rama
Enter Date of Joining: 14 5 2010
Given Student details are
Student number =10 and name= raju
Date of Join is = 12- 5-2010
Student number =20 and name= ravi
Date of Join is = 13- 5-2010
Student number =30 and name= rama
Date of Join is = 14- 5-2010
Structure Variables with in structures: -We can declare structure variables with in
structures in C language.For example, We can declare dateofjoin structure variable of date
structure with in a student structure as follows:
struct date
{
int day;
int month;
int year;
};

struct student
{
int sno;
char sname[20];
struct date dateofjoin;
};
struct student stu;
Here, the student structure contains sno, sname, and a member dateofjoin which is a member
of structure date with three members i.e., day, month, year are members of the structure date.
These can referred to as :
stu.dateofjoin.day
stu.dateofjoin.month
stu.dateofjoin.year
/* Example: Read and display one student data using structure variables with in structures */
#include<stdio.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
struct student
{
int sno;
char sname[20];
struct date
dateofjoin;
};
struct student stu;
main()
{
printf(“Enter One student data\n”);
printf(“ Enter student number and name:”);
scanf(“%d%s”, &stu.sno, &stu.sname);
printf(“ Enter Date of Joining:”);
scanf(“%d%d%d”, &stu.dateofjoin.day, &stu.dateofjoin.month, &stu.dateofjoin.year);
printf(“ \nGiven Student details are \n”);
printf(“ student number = %d and name:= %s\n”, stu.sno , stu.sname);
printf(“ Date of Join is =”);
printf(“%2d-%2d-%4d”,stu.dateofjoin.day, stu.dateofjoin.month, stu.dateofjoin.year);
getch();
}
Output: -
Enter One student data
Enter student number and name: 10 raju
Enter Date of Joining: 12 5 2010
Enter student number and name: 20 ravi
Enter Date of Joining: 13 5 2010
Enter student number and name: 30 rama
Enter Date of Joining: 14 5 2010
Given Student details are
Student number =10 and name= raju
Date of Join is = 12- 5-2010
Student number =20 and name= ravi
Date of Join is = 13- 5-2010
Student number =30 and name= rama
Date of Join is = 14- 5-2010

Pointers with structures: -We can use pointers during manipulation of structures. An
address of first element(field) of structure can be stored in to pointer variable of struct type.
For example,
struct student
{
int sno;
char sname[20];
};
struct student stu[3] , *ptr;
Here, the variable stu is an array of struct student type. The pointer variable ptr is also struct
student type.
The assignment ptr = stu; will assign the address of zeroth element(field) of stu structure to
pointer variable ptr; Now, Thr ptr will points to stu[0]. Its members (fields) can be accessed
using the following one of two notations.
1. ptr-> sno and ptr->sname
The symbol -> is called the arrow operator or memer selection operator.
2. (*ptr).sno and (*ptr).sname
Here, The parentheses () around *ptr are required because, member operator. has higher
precedence than * operator.
/* Example: Read and display 3 students data using structure and pointers*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
};
struct student stu[3] , *ptr;
main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
ptr = stu; /* ptr= &stu[0]; */
printf(“ \nStudent details are \n”);
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, ptr->sno , ptr->sname); ptr+
+;
}
getch();
}
Output: -
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama

Student details are


Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name=
rama

Functions with structures: -C language supports the passing of structure values as


arguments to functions There are three methods to pass values of structures to functions.
1. Pass each member of the structure as an actual argument of the function call.
2. Passing of a copy of entire structure to the called function ( Call by value method)
3. Passing of an address of a structure to a called function (Call by reference method).
This method is more efficient. For examples,
/* method 2 Example : Read and Display 3 students data using Functions with structure*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
};
struct student stu[3] ;
void display(struct student s[])
{
int i;
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, s[i].sno , s[i].sname);
}
}
void main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
printf(“ \nStudent details are \n”);
display(stu);
getch();
}
Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama
Student details are
Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name=
rama

Example: Read and display 3 students data using Functions, structure and pointers*/

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
};
struct student stu[3] ;

void display(struct student *ptr)


{
int i;
for( i=0;i<3; i++)
{
printf(“ student number = %d and name:= %s\n”, ptr->sno , ptr->sname); ptr+
+;
}
}
main()
{
int i;
printf(“Enter 3 students data\n”);
for( i=0;i<3; i++)
{
printf(“ Enter student number and name:”);
scanf(“%d%s”, & stu[i].sno, &stu[i].sname);
}
printf(“ \nStudent details are \n”);
display(&stu[0]);
getch();
}

Output:
Enter 3 students data
Enter student number and name: 10 raju
Enter student number and name: 20 ravi
Enter student number and name: 30 rama

Student details are


Student number =10 and name= raju
Student number =20 and name= ravi
Student number =30 and name=
rama

Unions
A union is a similar to a structure. A union is a user-defined data type. It contains a
collection of fields(members) with different data types. There is a major difference between
structure and union in terms of storage. In structures, each member has its own storage
location, whereas all the members of union use the same memory location. In union,
The compiler allocates storage that is large enough to hold the largest variable type in
the union. In structure, We can handle all members at a time , where as in union, we can handle
one member at a time. In structure, we can maintain values of all members simultaneously,
where in union, we can maintain only one value for one member at a time. Unions save storage,
but unions lost previous data of members(fields).The union can be declared using union
keyword as follows.
Syntax:-
union union_name
{
datatype1 field1;
datatype2 field2;
:
datatypeN fieldN;
};

Union declaration always start with union keyword. union_name is known as tag or
union name. The union declaration is enclosed with in a pair of curly braces { }.
The field1, field2,…. fieldN are members of the union.
After declaring a union, we can define union variables to create memory locations. The union
declaration declares unions, but, this process does not allocate memory. The memory
locations can be allocated, whenever union variables are defined.
Syntax: -
union union_name unionvariable1, unionvariable2,….unionvariableN;
Here, unionvariable1, unionvariable2,….unionvariableN are variables of union union_name.
/*Example for union */
#include<stdio.h>
#include<conio.h>
union tv
{
int cost;
float price;
};
union tv bpl ;
void main()
{
clrscr();
printf(“Enter BPL TV Cost:”);
scanf(“%d”, &bpl.cost);
printf(“ The size of bpl variable = %ld\n”, sizeof(bpl));
bpl.price= bpl.cost + 550.00;
printf(“ \nPrice of BPL TV is : %.2f”, bpl.price);
getch();
}
In the above program, the union variable bpl contains two fields.cost(2 bytes) and price(4
bytes).
The compiler allocates 4 bytes of storage for the union variable bpl. The first two bytes can
be used by cost field , the four bytes from first location can be used by price field. We can
use one field at a time, where as in structure, 6(2+4) bytes of storage can be allocated for two
fields(cost and price) separately.

Output:-
Enter BPL TV Cost: 5000
The size of bpl variable = 4
Price of BPL TV is: 5550.00
We can use unions in structures like nesting of structures. For example:
struct Employee
{
int empno;
char empname[20];
union
{
int basicsalary;
float netsalary;
}salary;
};
struct Employee e;
the size of variable e is (2+20+4) 26 bytes only.
Here, the netsalary can be calculated based on basecsalary + 500.00(HRA) +3000.00(TA)
At the time of input, basicsalary field is required, at the time output, netsalary field is required.
We can use structures in unions like nesting of structures. For example
union Employee
{
struct
{
int basicsalary;
int hra;
int ta;
int da;
}manager;
struct
{
int wages;
int da;
}worker;
};
union Employee e;
the size of variable e is 8 bytes only. The variable e contains two fields 1. manager 2. worker.
Therefore, we can use either manager structure or worker structure at a time based on choice
of input in the program.

You might also like