Module 5
Module 5
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
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”
‘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 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’;
}
B A N
%-10.3 Prints first 3 characters but
in left justified manner because
of (- ) sign
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)
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);
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.
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
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.
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);
}
#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);
}
#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.
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.
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.
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.
This statement request the operating system to allocate two bytes of space in memory and stores
100 in that location.
a ------------ variable name
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
#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.
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.
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)
Char 1
Long 4
Float 4
Double 8
long double 10
Page 5
MODULE - 5 Problem Solving through Programming
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
Page 7
MODULE - 5 Problem Solving through Programming
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.
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;
--------------
--------------
};
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
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;
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( )
{
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.
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
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.
VECTOR v, *ptr;
ptr = &v;
The identifier ptr is known as pointer that has been assigned the address of the structure
variable n.
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);
SUBJECT TOTAL
SUBJECT1 177
SUBJECT2 156
SUBJECT3 221
Page 17
MODULE - 5 Problem Solving through Programming
C Preprocessor directives:
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
Below is the list of preprocessor directives that C language offers.
Page 18
MODULE - 5 Problem Solving through Programming
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
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