Module 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

MODULE 5

STRING CONCEPTS
Definition: String is a variable length data stored in a character array.
Example: “hello”, “India”
I. C- strings
➢ In C a string is a data structure based on an array of char.
➢ A string is a sequence of elements of the char data type.
➢ There is no separate data-type called string in C language.
➢ As strings are variable-size data we have to represent them using character
Arrays.
Example string is:

L O K H E S H \0 Delimiter ‘\0’
indicates end
0 1 2 3 4 5 6 7 of string

Strings in C are classified into two types:


1. String literals
2. String variables

String literals are also known as string constants, is a sequence of characters enclosed by
double quotation marks is called string literals. A string literal is a constant its value cannot
be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.

String variables are nothing but character array. Following syntax and examples
illustrates declaring string variables.
Example: char array_name[ ]= “raj”

How string is stored?


➢ A string, even a literal one is very similar to an array of characters.
➢ The only difference between array of char and string is that, a string must end with
null character (\0).
➢ If you use a literal string in a program, it is stored in consecutive bytes in memory and
compiler places the null character at the end.
➢ Below fig shows storage for literal string “GCEM”
G C E M \0
Declaring string variables: A string is declared like an array of characters.
Syntax: char string_name[size];
Ex: char name[21];
Size 21 means it can store up to 20 characters plus the null character. Entire storage location
name is divided in to 21 boxes called bytes, each of which holds one character. Each
character is element of data type char.

Initializing the string in the declaration


char first[10]={‘t’,’a’,’b’,’l’,’e’,’\0’};
char second[10]=”table”;
Difference between a single character string and a single character array is:
Single character array takes 1 byte whereas single character string occupies two bytes as
shown below:

A \0 Single character string

‘A’ 25

Limitations of Strings: One string variable cannot be directly assigned to another string as
in the case of ordinary scalar variables.
Let us say int a=10, b;
b=a; /* is perfectly valid */

But take an example of string initialization: char name1[ ] = “hello”;


char name2[10 ];
name2=name1; /* This initialization is invalid */

But this initialization can be done using a loop and assigning individual characters of
name1 to name2 as shown below:
void main( )
{
int char name1[ ]= “hello”;
int char name2[5];
for (int i=0; i<4;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}

Printing and reading a string: Token oriented input/output function


Printing a string using printf: We can use printf function with %s format specifier to print
a string on to the monitor. The %s is used to display an array of characters that is terminated
by null character.
Example:
(1) char name[10]=”XYZ”;
printf(“the name is%s\n”,name);
o/p: the name is XYZ

(2) char name[ ]= “


BANGALORE”; printf(“%s”,
name);

printf (“%9.6s”, name);


printf(“%-10.3s”, name);

B A N G A L O R E %s prints entire string

%9.6s prints first 6 characters out


B A N G A L
of 9 characters

B A N
%-10.3 Prints first 3 characters but
in left justified manner because
of (- ) sign

Reading a string using scanf( )


It uses string conversion specifier %s to accept a string data. Following example illustrates
it:
char name[20];
scanf(“%s”, name);
Note: while reading strings we needn’t specify address of operator (&) as the character array
itself is an address (i.e name itself is base address of array in the above example)

Disadvantage of reading strings using scanf( ) function is multiple words strings cannot be
read. For example say we have to read NEW DELHI, following scanf( ) reads only NEW and
stops.

scanf(“%s”, name);

say input is
N E W D E L H I

Only part of a string (NEW) is read and second half (DELHI) is ignored.

N E W

Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion code
%[ ], which specifies the type of characters that can be accepted by scanf ( ) function.
For Example say we have to accept only 0-9 digits in a string then edit set code can be
used as follows:
char name[20];
scanf(“%[0123456789]”, name)

Example strings that will be read by above statement are:


12345, 123, 567, 7890 etc.

NOTE: Suppose we want to skip particular set of characters in a string, then we have to use:
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)
This function skips all Capital alphabets from a string.
Say string is APPLE, banana, Mango
Accepted words are: banana, ango
Example 2:
char name[20];
scanf(“%[^\n]”,name);

This function will read a line of characters including white space.

II. String manipulation function:

C library supports a large number of string handling functions that can be used to carry
out many of the string manipulations and are stored in header file “string.h”. Following are
the most commonly used string handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
3. strcmp( ) compare two strings
4. strcat( ) concatenates two strings
5. strcpy( ) copies left most n characters of source to destination
6. strncmp( ) compares left most of n characters of source to destination.

1. strcpy( ): It is possible to assign a value to a string variable using strcpy( ). It allows us


to copy a string from one location to another. The string to be copied can be literal or string
variable. The general form of call to strcpy is
strcpy(dest,source);
Strcpy() function has two parameters. The first is the dest, a string variable whose value is
going to be changed. The second is the source the string literal or variable which is going to
be copied to the destination.
Ex: char first[14];
char last[14];
strcpy(first,“AJAY KUMAR”);
strcpy(last,first);
After two calls to strcpy, first and last each has a value “AJAY KUMAR”
A call to strcpy can be used to copy just part of a string. Either or both of the parameters can
refer to addresses past the beginning of their strings.
Ex: char name[20]=”AJAY KUMAR”;

char newname[20]=”RAJ GOWDA”;

strcpy(name+5,newname+4);

name A J A Y G O W D A \0

0 1 2 3 4 5 6 7 8 9 10 11 12 13

Strcpy does not check to see whether there is room for the resulting string at the specified
location. If there is no room, it copies characters on top of whatever variables follow in
memory. This may destroy the contents of other variables.
2. strlen():the string length function can be used to find the length of the string in
bytes. It takes the form
length=strlen(str);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”GCEM”
lenth=strlen(str); //4
str=’\0’
length=strlen(str); //0

3. strcmp( ): A strcmp() is used to compare two strings. It takes the two strings as a
parameter and returns an integer value based on the relationship between two strings.
General form of call to strcmp()
result=strcmp(first,second);
result>0 if first> second
result=0 if first==second
result<0 if first<second

Ex: int res;


res=strcmp(“cat”,”car”); //res>0
res=strcmp(“pot”,”pot”);//res==0
res=strcmp(“big”,”little”); //res<0

4. strcat( ): often it is useful to concatenate or join two strings together. The strcat
function is used to join two strings together. The resulting string has only one null character
at the end.
General form of a call to strcat( )
strcat(first, second);
After the call, first contains all the characters from first, followed by the ones from second up
to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it doesn’t
find a null character, strcat continues copying bytes from memory until it finds null
character. The programmer must check to make sure that the resulting string fits in the
variable.

Ex: char dest[30]=”computer”;


char second[15]=” programming”;
strcat(dest,second); //computer programming

5. strncmp( ): The strncmp function compares up to specified number of characters from


the two string, starting at the address specified, and returns integer representing the
relationship between the compared string sections. It compares the character by character
until it finds a null character or characters that are different or until it has compared number
of characters.
General form of call to strncmp()
Result= strncmp(firstaddress, secondaddress, numchars);

Ex: char first[30]=”string”; char


second[10]=”stopper”; int n;
if(strncmp(first,second,4)==0) printf(“first
four characters are alike\n”); else
if(strncmp(first,second,4)<0)
printf(“first four characters of first string are less\n”);
else
printf(“first four characters of first string are greater\n”);

6. strncpy( ): The strncpy function allows us to extract a substring from one string and
copy it to another location.
General form of call to strncpy
strncpy(dest, source, numchars);
The strncpy function takes three parameters. Here this statement copies the numchars of the
source string in to dest string. Since numchar does not include null character , we have to
place it explicitly in the source string.
Ex: char source[20]= “computer world”;
char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com

Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: Char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
PROGRAMS
1. WACP to read N integers into an array A and to
i. Find the sum of odd numbers.
ii. Find the sum of even numbers.
iii. Find the average of all numbers.
Output the results compared with appropriate headings.
#include<stdio.h>
void main( )
{
int oddsum=0, evensum=0, i ,N, A[20];
float avg;
printf(“enter the size of an array\n”);
scanf(“%d”,&N)
printf(“Enter the array elements\n”);
for(i=0;i<N;i++)
{
scanf(“%d”, &A[i]); /* reading array values*/
}
for(i=0;i<N;i++)
{
if(A[i]%2==0);
{
evensum=evensum+A[i]; /* compute even sum */
}
else
{
oddsum=oddsum+A[i]; /* compute odd sum */
}
}
avg=(evensum+oddsum)/N; printf(“even
sum is = %d\n”, evensum); printf(“odd
sum is = %d\n”, oddsum);
printf(“Average of all is = %f\n”, avg);
}

2. Program to read and write the elements of one dimensional array


void main( )
{
int a[10],i,n;
printf(“enter the number of elements in an array\n”);
scanf(“%d”,&n)
printf(“enter the elements of an array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“the elements of an array are\n”);
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}

3. Program to read and write the elements of two dimensional arrays


void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”);
scanf(“%d”,&m,&n)
printf(“enter the elements of an array\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional array are\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
printf(“\n”);
}
}
4. Program to count number of odd numbers and even numbers in anarray:
void main( )
{
int odd_count=0, even_count=0, i , num[10];
printf(“Enter the array elements\n”);
for(i=0;i<10;i++)
{
scanf(“%d”, &num[i]); /* reading array values*/
}
for(i=0;i<10;i++)
{
rem=num[i]%2;
if(rem==0)
{
even_count++; /* increase even counter by1 */
}
else
{
odd_count++; /* increase odd counter by1 */
}
}
printf(“odd count is = %d\n”, odd_count);
printf(“even count is = %d\n”, even_count);
}

5. C program to find largest element in the two dimensional array.

#include<stdio.h>
void main()
{
int m,n,a[5][5],i,j,large;
printf("enter the size1 and size2 of 2D array\n");
scanf("%d%d",&m,&n);
printf("enter the elements of 2d array\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d"&a[i][j]);
large=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
printf("large=%d",large);
}

6. Write a C program to concatenate two strings without using build in


function strcat().
void main()
{
char str1[50],str2[25];
int i=0,j=0;
printf("enter the string1\n");
gets(str1);
printf("enter the string2\n");
gets(str2); while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}
7. Implement string copy operation STRCOPY(str1,str2) that copies astring
str1 to another string str2 without using library function.

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100],s2[100];
int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
S2[i]=s1[i];
i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}
MODULE - 5 Problem Solving through Programming

Module -5:
POINTER, STRUCTURES AND PREPROCESSORS

Pointers: A pointer is a variable that holds the address of another variable. The pointer variable
contains only the address of the referenced variable not the value stored at that address.

Some of the advantages of using pointers are as follows


1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in memory

Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memory
is not available at run time to store pointers.

Pointer uses two basic operators


1. The address operator (&): It gives address of an object
2. The indirection operator (*):It is used to accesses the object the pointer points to.

Declaring a pointer variable:


The general syntax of declaring pointer variable is

Datatype *ptrname;
Data type: It specifies the type of the pointer variable that you want to declare like (int, float,
char, double or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the
name of the pointer variable.

Example: int *p; // declares a pointer variable p of integer type


float *temp;// declares a pointer variable temp of float data type

Initialization of pointer variable: Similar to the initialization of other variables at the time of
their declaration, you can also initialize the pointer variable by assigning address of other
variables to them.
Syntax
Datatype *ptrname = expression;
Where
Datatype: It can be any basic data type,
ptrname is a pointer variable
expression can be any constant value or any variable containing value.

Page 1
MODULE - 5 Problem Solving through Programming

Example:
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable .
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp
program to illustrate declaration and initialization

#include<stdio.h>
void main()
{
int *ptr; / /declaration of pointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200

Using the address of (&) operator: A computer uses memory to store the instructions of
different programs and the values of different variables. Since memory is a sequential collection
of storage cells, each cell has an address. When you declare a variable, the operating system
allocates memory according to the size of the data type of that variable. In this memory location,
the value of the variable is stored.

Example : int a=100;

This statement request the operating system to allocate two bytes of space in memory and stores
100 in that location.
a ------------ variable name

100 ------------value of the variable

1500 ----------  the address of the memory location

By using the address of (&) operator, you can determine the address of a variable.

Page 2
MODULE - 5 Problem Solving through Programming

#include<stdio.h>
Void main()
{
int a=100,*ptr1;
float b=12.6, *ptr2;
ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f\n”,ptr2,*ptr2);
getch();
}
Output: the address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000

Pointers and functions (call by reference) arguments:


The call by reference method allows you to copy the addresses of actual arguments of the calling
function to the formal arguments of the called function. In this method the pointers are passed as
arguments to the functions. When you change the values in the functions, the original values of
the actual parameters are also changed. Following program illustrate use of call by reference.

#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int x,y;
x=100;
y=200;
printf(“before swap: x=%d\n y=%d\n”x,y);
swap(&x,&y);
printf(“after swap: x=%d\n,y=%d\n”,x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Output:
Before swap: x=100
y=200
After swap: x=200
y=100

Page 3
MODULE - 5 Problem Solving through Programming

Pointers and arrays: Arrays are closely related to pointers in C programming but the
important difference between them is that, a pointer variable can take different addresses
as value whereas, in case of array it is fixed. This can be demonstrated by an example:

#include <stdio.h>
void main()
{
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
}
Notice, that there is equal difference (difference of 1 byte) between any two consecutive
elements of array.

Note: You may get different address of an array.

Relation between Arrays and Pointers


Consider and array:

int arr[4];

In arrays of C programming, name of the array always points to the first element of an
array. Here, address of first element of an array is &arr[0]. Also, arr represents the
address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.

Address in arrays Address in pointes Value in arrays Value in pointers


&a[0] (a+0) a[0] *(a+0)
&a[1] (a+1) a[1] *(a+1)
&a[2] (a+2) a[2] *(a+2)
&a[3] (a+3) a[3] *(a+3)
&a[4] (a+4) a[4] *(a+4)
……. ………. …….. ………
&a[i] (a+i) a[i] *(a+i)

Page 4
MODULE - 5 Problem Solving through Programming

//C Program to find the sum of 10 marks with arrays and pointers.
#include <stdio.h>

void main()
{
int i,marks[10],sum=0;
printf("Enter 10 marks:\n");
for(i=0;i<10;++i)
scanf("%d",(marks+i));
for(i=0;i<10;++i){
sum += *(marks+i);
}
printf("Sum=%d",sum);
getch();
}
Output
Enter 10 marks:
2 3 4 5 3 5 7 10 21 28
Sum=88

Pointer Arithmetic
Pointer arithmetic is very important to understand, if you want to have complete knowledge of
pointer. In this topic we will study how the memory addresses change when you increment a
pointer.

16 bit Machine
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2
bytes. But when we perform any arithmetic function like increment on a pointer, changes occur
as per the size of their primitive data type.
Size of datatypes on 16-bit Machine :

Type Size(bytes)

int or signed int 2

Char 1

Long 4

Float 4

Double 8

long double 10

Page 5
MODULE - 5 Problem Solving through Programming

Examples for Pointer Arithmetic


Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment it, it will increment by 4
bytes because float is of 4 bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment it, it will
increment by 8 bytes because its data type is double.
Pointers to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains the
actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a pointer
to a pointer of type int −

int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example −

Page 6
MODULE - 5 Problem Solving through Programming

#include <stdio.h>
void main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
getch();
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Pointer and Character strings


Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points
to the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.
char *str;
str = "hello";
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *.
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.

Page 7
MODULE - 5 Problem Solving through Programming

Consider the following array of strings


char name[3][25]; //name is a table containing three names of maximum length 25(including null
character. Total storage is 75 bytes.
We may encounter rarely all the individual strings of length equal to 25. Therefore
instead of making each row fixed number of characters, we can make it a pointer to a string of
varying length. For example
char *name[3]={
"Bangalore",
"Chennai",
"Mangalore"
};
Declares name to be an array of three pointers to character, each pointer pointing to a particular
name as
Name[0] --------- Bangalore
Name[1] ---------Chennai
Name [2] -------- Mangalore
This declaration allocates only 28 bytes, sufficient to hold all characters. Whereas using array of
strings , same array without using pointer needs 75 bytes.
char name[3][25]= {
"Bangalore",
"Chennai",
"Mangalore"
};

Initialization of Pointer Arrays


Consider the problem of writing a function month_name(n), which returns a pointer to a
character string containing the name of the n-th month. This is an ideal application for an internal
static array. month_name contains a private array of character strings, and returns a pointer to the
proper one when called. This section shows how that array of names is initialized.
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
}

Page 8
MODULE - 5 Problem Solving through Programming

The declaration of name, which is an array of character pointers, The initializer is a list of
character strings; each is assigned to the corresponding position in the array. The characters of
the i-th string are placed somewhere, and a pointer to them is stored in name[i]. Since the size of
the array name is not specified, the compiler counts the initializers and fills in the correct
number.

Function returning Pointer


A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function, hence if you return a pointer
connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
int a=15;
int b=92;
int *p;
p=larger(&a, &b);
printf("%d is larger",*p);
}

int* larger(int *x, int *y)


{
if(*x > *y)
return x;
else
return y;
}

Page 9
MODULE - 5 Problem Solving through Programming

STRUCTURES

INTRODUCTION
C supports a constructed data type known as structures, a mechanism for packing data of
different data types. A structure is a convenient tool for handling a group of logically related data
items.
For example: it represents set of attributes such as student_name, roll_no, marks.

DEFINING A STRUCTURE
Structures must be defined first for their format that may be used later to declare structure
variables. Consider a book database consisting of book name, author, number of pages and price.
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structures to hold details of four fields, namely title, author,
Pages and price. These fields are called structure elements or structure members. book_bank is
called structure tag.
The general format of structure definition is as follows

struct tag_name
{
datatype member1;
datatype member2;
--------------
--------------
};

In defining structure you may note the following syntax


1. The template is terminated with a semicolon
2. while the entire definition is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag_name such as book_bank can be used to declare structure variables of its type.

ARRAYS VS STRUCTURES
Sl.no Arrays Structures
1 Array is a collection of related data elements Structure is collection of logically related data
of same data type elements of different data types.
2 Array is derived data type Structure is a programmer-defined one.
3 Array behaves like built in data type In case of Structures, first we have to design and
declare a data structure.
4 In Arrays we have to declare an array In structures after designing structure and
variables and use it. declaring then we can declare structure
variables and use it.

Page 10
MODULE - 5 Problem Solving through Programming

DECLARING STRUCTURE VARIABLES


After defining a structure format we have declare variables of that type. A Structure variable
declaration is similar to the declaration of variables of any other data types.
It includes the following elements.
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
For example
struct book_bank book1, book2, book3;

declares book1, book2 and book3 as variables of type struct book_bank.

The complete declaration look like

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;

OR it can also be done like given below

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1, book2, book3;

Type-defined structures
We can use the keyword typedef to define a structure as follows
typedef struct
{
--------------
type member1;
type member2;
--------------
--------------
}type_name;

Page 11
MODULE - 5 Problem Solving through Programming

The type_name represents structure definition associated with it and therefore, can be used
to declare structure variables as shown below:
type_name variable1, variable2, .................... ;
ACCESSING STRUCTURE MEMBERS
The members of structures can be in different ways. One way is by use of Dot operator or period
operator such as „ . ‟
For example
book1.price
the link between a member and variable is established using dot operator.
Examples:
1. book1.pages=250;
2. book1.price=120.00;

STRUCTURE INITIALIZATION
Like any other data type, a structure can be initialized at compile time.
main( )
{
struct st_record
{
int weight;
float height;
};
struct st_record student1={ 60, 180.75};
struct st_record student1={ 53, 170.60};
………….
………….
}

Another method is to initialize a structure variables outside the function as shown below:
struct st_record
{
int weight;
float height;
student1={ 60, 180.75};
}

main( )
{

struct st_record student 2={ 53, 170.60};


………….
………….
}

C language does not permit initialization of individual structure members within the template.
The initialization must be done only in the declaration of actual variables.

Page 12
MODULE - 5 Problem Solving through Programming

NOTE: The compile time initialization of a structure variable must have the following elements.
1. The keyword struct.
2. The structure tag name.
3. The name of the variable to be declared.
4. The assignment operator =.
5. The set of values for the members of the structure variables, separated by commas and
enclosed in braces.
6. A terminating semicolon.

Rules For Initializing Structures


There are few rules to be remembered while initializing structure variables at compile time
1. We cannot initialize individual members inside the structure template
2. The order of values enclosed in braces must match the order of members in the structure
definition.
3. It is permitted to have a partial initialization. We can initialize only the first few members and
leave the remaining blank. The uninitialized members should be only at the end of the list.
4. The uninitialized members will be assigned default values as follows
 Zero for integer and floating point numbers.
 „\0‟ for character and strings.

COPYING AND COMPARING STRUCTURE VARIABLES


Two variables of the same structure type can be copied the same way as ordinary variables. If
person1 and person2 belong to the same structure, then the following statements are valid:
person1=person2;
person2=person1;
However, the statements such as
person1 = = person2;
person2 != person1;
are not permitted(not valid or invalid) because C does not permit any logical operations on
structure variables. In case, we need to compare them, we may do so by comparing
members individually.

Page 13
MODULE - 5 Problem Solving through Programming

The following program illustrates how a structure variable can be copied into another of the
same type. It also performs member wise comparsion to decide whether two structure variables
are identical.
Program
struct class
{
int number;
char name[20];
float marks;
};

main( )
{
int x;
struct class student1={ 111, “Rao”, 72.50};
struct class student2={ 222, “Reddy”, 67.00};
struct class student3;

student3 = student2;
x=( (student3. number = = student2. number) &&
(student3.marks = = student2.marks) ) ? 1: 0 ;

if(x = = 1)
{
printf(“\n student2 and student3 are same\n\n”);
printf(“%d %s %f\n”, student3.number, student3.name, student3.marks);
}
else
printf(“\n student2 and student3 are different\n\n”);
}
Output
student2 and student3 are same

222 Reddy 67.000000

Figure Comparing and copying structure variables

OPERATIONS ON INDIVIDUAL MEMBERS

The individual members are identified using the member operator, the dot. A member
with the dot operator along with its structures variable can be treated like any other variables
name and therefore can be manipulated using expressions and operators.
Consider the above program, we can perform the following operations:
if(student1.number = = 111)
student1.marks = student1.marks + 10.00;
float sum = student1.marks + student2.marks;
student2.marks = student2.marks * 0.5;

Page 14
MODULE - 5 Problem Solving through Programming

we can also apply increment and decrement operators to numeric type members.
For example: student1.number ++;
++ student1.number;
The precedence of the member operator is higher than all arithmetic and relational
operators and therefore no parenthesis are required.

THREE WAYS TO ACCESS MEMBERS


We have used the dot operator to access the members of structures variables. In fact, there
are two other ways.
Consider the following structure:
typedef struct
{
int x;
int y;
} VECTOR;

VECTOR v, *ptr;
ptr = &v;
The identifier ptr is known as pointer that has been assigned the address of the structure
variable n.

Now, the members can be accessed in the following three ways:


 Using dot notation : v.x
 Using indirection notation : (*ptr).x
 Using selection notation: ptr-> x

ARRAYS OF STRUCTURES
We use structures to describe the format of a number of related variables. For example analyzing
the marks obtained by a class of students, we may use template to describe student name and
marks obtained in various subjects and then declare all the students as structure variables.
In such cases, we may declare an array of structures, each element of the array representing a
structure variable.
For example: struct class student[100];
defines an array called student, that consists of 100 elements. Each element is defined to be of
the type struct class.
Consider the following declaration:
struct marks
{
int sub1;
int sub2;
int sub3;
};
main( )
{
struct marks student[3] = { {45, 68, 81},{75, 53, 69},{57, 36, 71}};
}

Page 15
MODULE - 5 Problem Solving through Programming

This declares the student as an array of three elements student[0], student[1] and student[2]
and initialize their members as follows:
student[0].sub1=45;
student[0].sub2=68;
……..
……..
student[2].sub3=71;
Note: Each element of student array is a structure variable with three members.

An array of structures is stored inside the memory in the same way as a multi dimensional array.
The array student actually looks as shown below
student[0] .sub1 45
.sub2 68
.sub3 81
student[1] .sub1 75
.sub2 53
.sub3 69
student[2] .sub1 57
.sub2 36
.sub3 71
Figure: The array student inside memory

Page 16
MODULE - 5 Problem Solving through Programming

Program
struct marks
{
int sub1;
int sub2;
int sub3;
int T;
};
main( )
{
int i;
struct marks student[3] = {{45, 68, 81,0},{75, 53, 69,0},{57, 36, 71,0}};
struct marks total;
for( i = 0; i<=2; i++)
{
student[i].T= student[i].sub1+ student[i].sub2+ student[i].sub3;
total.sub1= total.sub1 + student[i].sub1;
total.sub2= total.sub2 + student[i].sub2;
total.sub3= total.sub3 + student[i].sub3;
total.T= total.T + student[i].T;
}
Printf(“STUDENT TOTAL\n\n ”);
for( i = 0; i<=2; i++)
printf(“student[%d] %d\n”,i+1, student[i].T );
printf(“\n SUBJECT\t\tTOTAL\n\n”);
printf(“%s\t\t%d\n”, “SUBJECT1”, total.sub1);
printf(“%s\t\t%d\n”, “SUBJECT2”, total.sub2);
printf(“%s\t\t%d\n”, “SUBJECT3”, total.sub3);

printf(“\n GRAND TOTAL = %d\n”, total.T);


}
OUTPUT
STUDENT TOTAL
student[1] 193
student[2] 197
student[3] 164

SUBJECT TOTAL
SUBJECT1 177
SUBJECT2 156
SUBJECT3 221

GRAND TOTAL = 554

Figure: Arrays of Structures: illustration of subscripted structure variables

Page 17
MODULE - 5 Problem Solving through Programming

C Preprocessor directives:

 Before a C program is compiled in a compiler, source code is processed by a program called


preprocessor. This process is called preprocessing.

 Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
 Below is the list of preprocessor directives that C language offers.

S.no Preprocessor Syntax Description


1 Macro #define This macro defines constant value and can be any of the
basic data types.
2 Header file #include <file_name> The source code of the file “file_name” is included in the
inclusion main program at the specified place
3 Conditional #ifdef, #endif, #if, Set of commands are included or excluded in source program
compilation #else, #ifndef before compilation with respect to the condition
4 Other directives #undef, #pragma #undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
function in a C program

The directives listed above are categorized into 3 types

1. The macro substitution directive


2. The file inclusion directives
3. Compiler control directives

Page 18
MODULE - 5 Problem Solving through Programming

Macro substitution: Macro substitution is a process where an identifier in a program is replaced


by a predefined string composed of one or more tokens. The preprocessor accomplishes this task
under the direction of #define statement. It takes the following form
#define identifier string
Here the preprocessor replaces every occurrence of the identifier in the source code by the
string.
Example: #define PI 3.14
#define COUNT 100
Macros with arguments: The preprocessor permits us to define more complex and more
useful form of replacements. It takes the form
#define identifier(f1,f2…fn) string
The identifier f1,f2..fn are the formal macro arguments. When macro is called, the
preprocessor substitutes the string replacing the formal parameters with the actual
parameters. Hence the string behaves like a template.
Example: #define CUBE(X) (x*x*x)
The following statement appears later in the program
Volume=CUBE(side);
Then the preprocessor would expand (side*side*side)

Nesting of macros: we can also use one macro in the another macro. That is macro definition
may be nested Example #define M 5
#define N M+1
#define SQUARE(x) ((x)*(x)) #deine
CUBE(X) SQUARE((x)*(x))
File inclusion: An external file containing functions or macro definition can be included as a
part of program so that we need not rewrite those functions or macro definition. This is achieved
by preprocessor directive.
#include “filename”

Page 19
MODULE - 5 Problem Solving through Programming

Where filename is the name of the file containing the required file. When the filename is
included within the double quotation marks, the search for the file is made in first in the
current directory and then in the standard directory.
Alternatively
#include<filename>
In this case file is searched only in the standard directories
Example:
#include<stdio.h>
Void main()
{
clrscr();
Printf(“this program demonstrates the use of file inclusion getch();
directive\n”);

Compiler control directives: the compiler control directives are used to conditionally include a
header file or define a macro under a specified condition. The compiler control directives are as
follows
1. #ifdef
2. #ifndef
3. #if
4. #ifelse
5 #ifelif
Conditional compilation: the compiler compiles selected porstion of the source codes based on
the condition.
Syntax of #ifdef directive is
#ifdef<identifier>
{
Statement 1;

Page 20
MODULE - 5 Problem Solving through Programming

Statement 2;
}
#else
{
Statement 3;
Statement 4;
}
#endif
The #ifdef preprocessor test whether the identifier has defined substitute text or not. If the
identifier is defined then #if block is compiler and executed. If the identifier is not defined, the
#else block is compiled and executed
Example program
#include<stdio.h>
#define LINE 1
VOID MAIN()
{
#ifdef LINE
printf(“this is line number 1\n”);
#else
Printf(“this is line number 2\n”);
#endif
}
Output : This is line number 1

The #ifndef Directive


Syntax of #ifndef directive is
#ifndef<identifier>
{
Statement 1;
Statement 2;

Page 21
MODULE - 5 Problem Solving through Programming

}
#else
{
Statement 3;
Statement 4;
}
#endif
The #ifndef preprocessor test whether the identifier has defined substitute text or not. If the
identifier is defined then #else block is compiler and executed. If the identifier is not defined,
the #if block is compiled and executed
Example program
#include<stdio.h>
#define LINE 1
VOID MAIN()
{
#ifndef LINE
printf(“this is line number 1\n”);
#else
Printf(“this is line number 2\n”);
#endif
}
Output : This is line number 2

Page 22

You might also like