C Programming
C Programming
MODULE 5
STRING TAXONOMY
When storing fixed – length strings we need to specify an appropriate size for the string
variable. If the size is too small, then we will not able to store all the elements in the string. If
the string size is large, then unnecessarily memory space will be wasted.
To use a variable length string format we need a technique to indicate the end of
elements that are a part of the string. This can be done either by using length controlled string
or a delimiter.
Here, we need to specify the number of characters in the string. This count is used by
string manipulation functions to determine the actual length of the string variable.
Delimited Strings
In this format, the string is ended with a delimiter. The delimiter is then used to identify
the end of the string.
OPERATIONS ON STRINGS
The number of characters in the string is the length of the string. Even blank spaces will
be counted. The size of string “ C PROGRAMMING IS FUN “ is 20.
#include<stdio.h>
void main()
{
char str[100];
int i , length;
clrscr();
printf(“enter the string : ”);
gets(str);
while( str[i] ! = ‘\0’ )
i++;
length = i;
printf(“length of string is “ %d”, length);
}
Output
enter the string : hello
length of string is 5
The ASCII code for A – Z varies from 65 to 91 and for a –z is from 97 to 123. So to
convert a lower case character to upper case, we just need to subtract 32 from ASCII value of
the character.
#include<stdio.h>
void main()
{
char str[100], upper_str[100];
int i=0,j=0;
printf("enter the string");
gets(str);
while( str[i]!='\0' )
{
To convert a upper case character to lower case, we just need to add 32 from ASCII value of
the character.
#include<stdio.h>
void main()
{
char str[100], lower_str[100];
int i=0,j=0;
printf("enter the string: ");
gets(str);
while( str[i]!='\0' )
{
if(str[i]>='A' && str[i]<='Z')
lower_str[j] = str[i] + 32;
else
lower_str[j] = str[i];
i++;
j++;
}
str[i]= '\0';
printf("\n Sting converted into upper case is: ");
puts(lower_str);
}
Output:
enter the string: HAI
Sting converted into upper case is: hai
i++;
j++;
}
str3[j]= '\0';
printf("\n Concatenated string is: ");
puts(str3);
}
Output:
enter the first string: hai
enter the second string: hello
Concatenated string is: haihello
dest_str[i]= '\0';
printf("\n After appending , the destination string is: ");
puts(dest_str);
}
Output:
enter the source string: hello
enter the destination string: hai
After appending , the destination string is: haihello
If S1 and S2 are two strings then comparing two strings will give either of these results:
else
printf("str1 is equal to str2");
return (0);
}
Output
Enter string1:hai
Enter string2:hello
REVERSING A STRING
To reverse a string we just need to swap the first character with the last, second
character with the last second character and so on.
#include<stdio.h>
#include<string.h>
void main()
{
char str[30], reverse_str[30],temp;
int i=0, j=0;
printf("\nEnter string:");
gets(str);
j=strlen(str)-1;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}
while(str[j]!= '\0')
{
substr[i]=str[j];
i++;
j++;
}
substr[i]='\0';
printf("the substring is: ");
puts(substr);
}
Output:
Enter string:hi there
enter the number of characters to be copied:5
the substring is: there
Output:
Enter string:Hi there
enter the position from where substring should start:1
i++;
}
ins_text[j]='\0';
printf("the new string is: ");
puts(ins_text);
}
Output:
nter main text:How you?
enter the string to be inserted:are
enter the position at which string has to be inserted:3
the new string is: Howareyou?
INDEXING
Index operation return the position in the string where the string pattern first occurs.
For example:
INDEX(“Welcome to the world of programming”, “world”) = 15
If the pattern is not found it returns 0.
DELETING A STRING FROM THE MAIN STRING
The deletion operation deletes a substring from a given text.
DELETE(text, position, length)
DELETE(“ABCDXXXABCD”,4,3) = “ABCDABCD”
{
j=0;k=i;
while(text[k]==str[j] && str[j]!='\0')
{
k++;
j++;
}
if(str[j]== '\0')
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_text[n]='\0';
printf("the new string is:");
puts(new_text);
}
Output:
Enter main text:Hai, how are you?
enter the string to be deleted:, how are you?
the new string is:Hai
gets(str);
printf("enter the pattern to be replaced:");
gets(pat);
printf("enter the replacing pattern:");
gets(rep_pat);
while(str[i]!= '\0' )
{
j=0;k=i;
while(str[k]==pat[j] && pat[j]!='\0')
{
k++;
j++;
}
if(pat[j]== '\0')
{
copy_loop=k;
while(rep_pat[rep_index]!='\0')
{
new_str[n]= rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n]=str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("the new string is:");
puts(new_str);
}
Output
This function 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. The process stops when the terminating
null character of str2 is copied.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[]= "In C";
strcat(str1,str2);
printf("\n str1: %s",str1);
}
Output:
str1: ProgrammingIn C
strncat Function
Syntax: char *strncat(char *str1, const char *str2, size_t n);
This function appends the string pointed to by str2 to the end of the string pointed to by str1
upto n characters long. The terminating null character of str1 is overwritten. The process stops
when the n characters are copied or null character of str2 is copied.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[]= "In C";
strncat(str1,str2,2);
printf("\n str1: %s",str1);
}
Output:
str1: ProgrammingIn
strchr Function
Syntax: char *strchr(const char *str, int c);
This function searches for the first occurrence of the character in the string pointed to by the
argument str. It returns a pointer pointing to the first matching character or NULL if no match
is found.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Programming In C";
char *pos;
pos=strchr(str,'n');
if(pos)
printf("\n string after n is %s",pos);
else
printf("\n char not found in the string");
}
Output:
string after n is ng In C
strrchr Function
Syntax: char *strrchr(const char *str, int c);
This function searches for the first occurrence of the character in the string beginning at the
rear end and working towards the front. It returns a pointer pointing to the last matching
character or NULL if no match is found.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Programming In C Lab";
char *pos;
pos=strrchr(str,'n');
if(pos)
printf("\n string after last position of n %s",pos);
else
printf("\n char not found in the string");
}
Output
string after last position of n n C Lab
strcmp Function
Syntax: int *strcmp(const char *str1, const char *str2);
This function compares the string pointed to by str1 to the string pointed by str2. The function
returns zero if the strings are equal, less than zero if str1 is less than str2, greater than zero if
str1 is greater than str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Hello";
char str2[50]="Bye";
int n;
n=strcmp(str1,str2);
if(n==0)
printf("\n Strings are identical");
else if(n>0)
printf("\n string 1 is greater than str2");
else
printf("\n string 1 is lesser than str2");
}
Output
string 1 is greater than str2
strncmp Function
Syntax: int *strcmp(const char *str1, const char *str2, size_t n);
This function compares the string at most the first n bytes of str1 and str2. The function returns
zero if the strings are equal, less than zero if str1 is less than str2, greater than zero if str1 is
greater than str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Hello";
char str2[50]="Hai";
int n;
n=strncmp(str1,str2,1);
if(n==0)
printf("\n Strings are identical");
else if(n>0)
printf("\n string 1 is greater than str2");
else
printf("\n string 1 is lesser than str2");
}
Output
Strings are identical
Strcpy Function
Syntax: char *strcpy(char *str1, const char *str2);
This function copies the string pointed by str2 to str1 including the null character of str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50],str2[50]="Hai";
strcpy(str1,str2);
printf("string 1 is %s",str1);
}
Output:
string 1 is Hai
Strncpy Function
Syntax: char *strncpy(char *str1, const char *str2, size_t n);
This function copies up to n characters from the string pointed by str2 to str1 including the null
character of str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50],str2[50]="Hello";
strncpy(str1,str2,2);
printf("string 1 is %s",str1);
}
Output:
string 1 is He
strlen Function
Syntax: size_t strlen(const char *str);
This function calculates the length of the string str up to but not including the null character
i.e, it returns the number of characters in the string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Hello";
printf("length of the string is %d",strlen(str));
}
Output:
length of the string is 5
strcspn Function
Syntax: size_t strcspn(const char *str1, const char *str2);
This function returns the index of the first character in str1 that matches any of the characters
in str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[50]="ro";
printf("Position of first character in str1 that matches with that in str2 is
%d",strcspn(str1,str2));
}
Output:
Position of first character in str1 that matches with that in str2 is 1
strpbrk Function
Syntax: char *strpbrk(const char *str1, const char *str2);
This function returns a pointer to the first occurrence in str1 of any character in str2, or NULL
if none are present. The only difference between strpbrk() and strcspn() is that strcspn() returns
the index of the character and strpbrk() returns a pointer to the first occurrence of a character
in str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming in C";
char str2[50]="Program";
char *ptr=strpbrk(str1,str2);
if(ptr==NULL)
printf("No character mathces in two strings");
else
printf("character in str2 matches with that in str1");
}
Output:
character in str2 matches with that in str1
strtok Function
Syntax: char *strtok(const char *str1, const char *delimiter);
This function is used to isolate sequential tokens in a null-terminated string
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Hello, to, the, world of, programming";
char result[50];
char delim[]=",";
result=strtok(str1,delim);
while(result!=NULL)
{
printf("\n %s",result);
result=strtok(NULL,delim);
}
}
Output:
Hello
to
the
world
of
programming
strtol Function
Syntax: long strtol(const char *str, char **end, int base);
This function converts the string pointed by str to a long value. The function skips leading
white space characters and stops when it encounters the first non-numeric character.
#include<stdio.h>
#include<string.h>
void main()
{
long num;
num=strtol("12345 decimal value",NULL,10);
printf("%ld \n",num);
num=strtol("65432 octal value",NULL,8);
printf("%ld \n",num);
num=strtol("10110101 binary value",NULL,2);
printf("%ld \n",num);
num=strtol("A7CB4 hexadecimal value",NULL,16);
printf("%ld \n",num);
}
Output
12345
27418
181
687284
strtod Function
Result: x=12.39
atol() function
Syntax: long atol(const char *str);
This function converts a given string passed to it as an argument into a long int value.
Example: x=atol(“12345.6789”);
Result: x=12345L
POINTERS
Every computer has a primary memory. All data and programs need to be placed in the
primary memory for execution. RAM (Random Access Memory) is a part of primary memory.
It is a collection of memory locations and each location has a specific address. The computer
has 3 areas of memory each of which is used for a specific task. They are stack, heap and global
memory.
Stack
A fixed size of memory called system stack is allocated by the system and is filled as
needed from the bottom to the top, one element at a time. These elements are removed from
the top to the bottom by removing one element at a time i.e., last element added to the stack is
removed first. When a program has used the variables or data stored in the stack, it can be
discarded to enable the stack to be used by other programs to store their data. It is a section of
memory that is allocated for automatic variables within functions.
Heap
It is a contiguous block of memory that is available for use by programs when the need
arises. A fixed size heap is allocated by the system and is used by the system in random fashion.
The addresses of the memory locations in heap that are not currently allocated to any program
for use are stored in a free list. When a program requests a block of memory, the dynamic
allocation technique takes a block from heap and assigns it to the program. When the program
has finished using the block, it returns the memory block to the heap and address are added to
the free list. Compared to heaps, stacks are faster but smaller and expensive.
Global Memory
The block of code that is the main() program is stored in the global memory. The
memory in the global area is allocated randomly to store the code of different functions in the
program in such a way that one function is not contiguous to another function. All global
variables declared in the program are stored in the global area.
INTRODUCTION TO POINTERS
A Pointer is a variable that contains the memory location of another variable. A pointer
is a variable that represents the location of a data item, such as variable or an array element.
Pointer are useful for the following applications:
To pass information back and forth between a function and its reference point
Enable programmers to return multiple data items rom a function via function
arguments.
Provide an alternate way to access individual elements of the array.
To pass arrays and strings as function arguments
Enable references to functions.
To create complex data structures such as trees, linked lists, linked stacks, linked queues
and graphs.
For dynamic memory allocations of a variable.
Write a program to find the size of various data types on your system.
#include<stdio.h>
int main()
{
printf("Size of short int: %d \n", sizeof(short int));
printf("Size of unsigned int: %d \n", sizeof(unsigned int));
printf("Size of signed int: %d \n", sizeof(signed int));
printf("Size of int: %d \n", sizeof(int));
printf("Size of long int: %d \n", sizeof(long int));
printf("Size of char: %d \n", sizeof(char));
printf("Size of char: %d \n", sizeof(char));
Ouput
Size of short int: 2
Size of unsigned int: 2
Size of signed int: 2
Size of int: 2
Size of long int: 4
Size of char: 1
Size of char: 1
Size of unsigned char: 1
Size of signed char: 1
Size of floating point number: 4
Size of double number: 8
int *pnum;
char *pch;
float *pfnum;
double *pdnum;
long *plnum;
printf("Size of integer pointer: %d \n", sizeof(pnum));
printf("Size of character pointer: %d \n", sizeof(pch));
printf("Size of float pointer: %d \n", sizeof(pfnum));
printf("Size of double pointer: %d \n", sizeof(pdnum));
printf("Size of long pointer: %d \n", sizeof(plnum));
return 0;
}
Output:
Size of integer pointer: 2
Size of character pointer: 2
Size of float pointer: 2
Size of double pointer: 2
Size of long pointer: 2
In the above statement, ptr is the name of pointer variable. The ‘*’ informs the compiler that
ptr is a pointer variable and the int specifies that it will store the address of an integer variable.
We can deference a pointer i.e., refer to the value of the variable to which it points, by using
unary * pointer ( also known as indirection operator) as *ptr. %p prints the argument as a
memory address in hexadecimal form.
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
printf(“enter the number:”);
scanf(“%d”, &num);
printf(“ \n The number that was entered is: %d”, *pnum);
printf(“ \n The address of number in memory is : %p”, &num);
return 0;
}
Ouput:
Enter the number: 10
The number that was entered is: 10
The address of number in memory is : FFDC
We can also assign values to variables using pointer variables and modify their values. The
code given below shows this.
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
*pnum=10;
printf(“\n *pnum=%d”,*pnum);
printf(“\n num = %d”, num);
*pnum= *pnum +1;
printf(“\n after increment *pnum=%d”,*pnum);
printf(“\n after increment num = %d”,num);
return 0;
}
Output:
*pnum=10
num = 10
after increment *pnum=11
after increment num = 11
STRUCTURES
A Structure is a collection of variable under a single name. The variables within a
structure are of different data types and each has a name that is used to select it from the
structure. Structure is a user defined data type.
Structure Declaration
A structure is declared using the keyword struct followed by the structure name. All the
variables of the structure are declared within the structure.
Syntax:
struct structure_name
{
data_type var_name;
data_type var_name;
……
};
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Here, we have declared two variable stud1 and stud2 of the type student.
Typedef Declarations
The typedef keyword enables the programmer to create a new data type name from an
existing data type. By using typedef, no new data is created, rather an alternate name is given
to a known data type.
General syntax:
typedef existing data_type new data_type
Example:
typedef int INTEGER;
now, INTEGER is the new name of the data type. To declare variable using the new data type
name, following code should will be used.
INTEGER num=5;
When we precede a struct name with typedef keyword, then the struct becomes a new type.
typedef struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
To declare a variable of structure student we have to write
student stud1,stud2;
INITIALIZATION OF STRUCTURE
Initializing a structure means assigning some constants to the members of the structure.
When the user does not explicitly initialize the structure, then C automatically does that. For
int and float the value is initialized to zero and character and string are initialized to ‘\0’.
General Syntax:
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…….
} struct_var = {constant1, constnat2,…..};
Or
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…….
};
struct sturct_name struct_var = {constant1, constnat2,…..};
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
} stud1 = {01, “Rahul”, “BCA”, 45000};
OR
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}
struct student stud1 = {01, “Rahul”, “BCA”, 45000};
ACCESSING THE MEMBER OF STRUCTURE
A structure member variable is generally accessed using a ‘.’ (dot) operator. The syntax
of accessing a structure or a member of a structure can be given as follows:
struct_var.member_name
Example:
stud1.r_no = 01;
stud1.name= “RAHUL”;
stud1.course= “BCA”;
stud1.fees= 45000;
To input the values and print the values, we may write
scanf(“%d”,stud1.r_no);
scanf(“%f”,stud1.fees);
printf(“%s”,stud1.name);
printf(“%f”,stud1.fees);
C does not allow two structures to be compared. But, we can compare individual members of
one structure with individual members of another structure.
There are three different ways through which we can find the member of bytes of
structure will occupy in the memory.
Simple Addition
In this method, list of all data types are made and memory required by each of the items will
be added.
struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};
SIZE = size of emp_ID + size of name + size of salary + size of designation + size of experience
size of emp_ID = 2
size of name = 20 X size of character
size of salary = 8
size of designation = 20 X size of character
size of experience = 4
= 2 + 20 (1) + 8 + 20 (1) + 4
= 54 bytes
char designation[20];
float experience;
};
void main()
{
struct Employee e;
printf(“ %d”, sizeof(e));
}
Ouput:
54
Ouput:
size of structure= 54
Programs
Write a program using structures to read and display the information about a student
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("Enter The Information of Students :\n\n");
printf("Enter Name : ");
scanf("%s",s.name);
printf("Enter Roll No. : ");
scanf("%d",&s.roll);
printf("Enter marks : ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output:
Enter The Information of Students :
Enter Name : Rahul
Enter Roll No. : 01
Enter marks : 45
Displaying Information
Name : Rahul
Roll No. : 01
marks : 45
Salary :76543
Entered detail is:
Name: Mike
Id: 1120
Salary: 76543.000000