Module 4 Pop Notes
Module 4 Pop Notes
Declaration of a string:
Initialization of a string:
Example:
3. Char str[5]=”HELLO”;
Reading strings:
Char str[100];
Then str can be read from the user by using three ways:
Scanf(“%s”,str);
The main drawback with this function is that it terminates as soon as it finds a blank space.
Example: if the user enters “Hello world”, then str will contain only “Hello”. This is because the
moment a blank space is encountered, the string is terminated by the scanf() function.
Syntax: gets(str);
gets() is a simple function that overcomes the drawbacks of scanf().The gets() function takes the
starting address of the string which will hold the input .
Example:
Writing strings:
Printf(“%s”,str);
The next method of writing a string is by using the puts function.The string can be displayed by
writing
Puts(str);
Puts() is a simple function that overcomes the drawbacks of printf ().the puts() function writes a
line of output on the screen. It terminates the line with a newline character (‘\n’).it returns an
EOF(end of file)(-1)if an error occurs and returns a positive number on success.
Example program:
String taxonomy:
In c we can store a string either in fixed length format or in variable length format.
string
Fixed Variable
length length
Length Delimited
controlled
When storing a string in a fixed length format, you need to specify an appropriate size for the
string variable. If the size is too small, then you will not be able to store all the elements in the
string. On the other hand, if the string size is large, then unnecessarily memory space will be
wasted.
Example: Declare string variable to store the name of a student. If student has a long name of
say 20 characters, then the string can be expanded to accommodate 20 characters, on the other
hand, a student name has only 5 characters, then the string variable can be contracted to store
only 5 characters.
In length controlled string you need to specify the number of characters in the string. This count
is used by string manipulation function to determine the actual length of the string variable.
Delimited string:
In this format the string is ended with a delimiter. The delimiter is then used to identify the end
of the string.
For example in English language every sentence is ended with a full-stop, similarly in C we can
use any character such as comma, semicolon, colon, dash, null character etc. as the delimiter of a
string.However,the null character is the most commonly used string delimiter in the C language.
String operations:
1. Length:
The number of characters in the string constitutes the length of the string.
Example: Length (“C programming is fun”)
Output: return 20
Example program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],i=0,length;
Clrscr();
Printf(“\n enter the string:”);
gets(str);
while(str[i]!=’\0’)
i++;
length=I;
printf(“\\n the length of the string is:%d”,length);
getch();
}
We have already seen that in memory the ASCII codes are stored instead of the
real value. The ASCII code for A-Z varies from 65 to 91 and ASCII code for a-z
ranges from 97-123.
If we have to convert a lower case character to upper case then we just need to
subs tract 32 from the ASCII value of the character.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” && str[i]<=”z”)
upper_str[j]=str[i]-32;
else
upper_str[i]=str[i];
i++;
j++;
Upper_str[j]=”\0”;
Puts(upper_str);
return 0;
Output:
The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97-
123.
If we have to convert an upper case character into lower case, then we just need to add 32
to its ASCII value.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n 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[i]=str[i];
i++;
j++;
lower_str[j]=”\0”;
Puts(lower_str);
return 0;
Output:
If s1 and s2 are two strings, then concatenation operation produces a string which contains
characters of s1 followed by the characters of s2.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str1[100],str2[100],str3[100];
int i=0,j=0;
printf(“\n enter the first string :”);
gets(str1);
printf(“\n enter the second string:”);
gets(str2);
while(str1[i]!=’\0’)
{
Str3[j]=str1[i];
i++;
j++;
}
i=0;
while(str2[i] !=’\0’)
{
Str3[j]=str2[i];
i++;
j++;
Str3[j]=’\0’;
Puts(str3);
getch();
return 0;
Output:
Appending strings:
Appending one string to another involves copying the contents of the source string at the
end of the destination string.
Example: if s1 and s2 are two strings, then appending s1 to s2 means we have to add the
contents of s1 to s2.
Here s1 is the source string and s2 is the destination string. The appending operation
would leave the source string s1 unchanged and the destination string s2=s2+s1.
Example program:
#include <stdio.h>
#include<conio.h>
main()
Char Dest_str[100],source_str[50];
int i=0,j=0;
Dest_str[i]=source_str[j];
i++;
j++;
Dest_str[i]=’\0’;
Puts(Dest_str);
getch();
return 0;
Output:
If s1 and s2 are two strings then comparing two strings will give either of these results:
1. S1 and S2 are equal
2 . S1> S2,when in dictionary order s1 will come after s2.
3 S1<S2 ,when in dictionary order s1 precedes s2.
Example program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
Char str1[50],str2[50];
int i=0,len1=0,len2=0,same=0;
gets(str1);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
While(i=len1)
if(str1[i]==str2[i])
i++;
else
break;
if(i==len1)
Same=1;
if(len1!=len2)
if (same==0)
if(str1[i]>str2[i])
else if(str1[i]<str2[i]))
getch();
return 0;
Output:
Reversing a string:
If s1=“Hello”, then reverse of s1=”olleH”.To reverse a string we just need to swap the first
character with the last. Second character with the second last character and so on.
Note:
There is a library function strrev (s1) that reverses all the characters in the string except
the null character. It is defined in string.h.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
Char str[100],reverse_str[100],temp;
int i=0,j=0;
gets(str);
j=strlen(str)-1;
while(i<j)
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
Puts(str);
getch();
return 0;
Output:
In order to extract a substring from the main string we need to copy the content of the string
starting from the first position to the nth position where n is the number of characters to be
extracted.
Example:
In order to extract a substring from the right side of the main string we need to first calculate the
position.
Example:
To extract a substring from a given string requires information about three things.The main
string the position of the first character of the substring in the given string and maximum number
of characters/length of the substring.
Example:
Insertion:
The insertion operation insert a string S, in the main text T, at the Kth position.The
general syntax of this operation is : INSERT(text,position,string).
Example: INSERT(“xyzxyz”,3,”AAA”)=”xyzAAAxyz”.
Program:
#include<stdio.>
#include<conio.h>
main()
{
Char text[100], str[20], ins_text[100];
int i=0,j=0,k=0,pos;
Printf(“\n enter the main text:”);
gets (text);
printf(“\n enter the string to be inserted:”);
gets(str);
printf(“\n enter the position at which the string has to be inserted:””);
scanf(“%d”,&pos);
ehile(text[i]!=’\0’)
{
if(i==pos)
{
While(str[k]!=’\0’)
{
ins_text[j]=str[k];
j++;
k++;
}
}
else
{
ins_text[j]=text[i];
j++;
}
i++;
}
ins_text[j]=’\0’;
printf(“\n the new string is:”);
puts(ins_text);
getch();
return 0;
}
Output:
Indexing:
Index operation returns the position in the string where the string pattern first occurs.
Example:
Deletion:
Example:
DELETE(“ABCDXXXABCD”,5,3)=”ABCDABCD”
Program:
#include<stdio.h>
#include<conio.h>
main()
Char text[200],str[20],new_text[200];
int i=0,j=0,found=0,k,n=0,copy_loop=0;
gets(text);
fflush(stdin);
gets(str);
fflush9stdin);
while(text[i]!=’\0’)
j=0,found=0,k=i;
k++;
j++;
if(str[j]==’\0’)
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]=’\0’;
printf(“\n the new string is :”);
puts(new_text);
getch();
return 0;
Output:
Relpacement:
Replacement operation is used to replace the pattern p1 by another pattern t2 . This is done by
writing,REPLACE(text,pattern1,pattern2)
Example:
(“AAABBBCCC”,”BBB”,”X”)=AAAXCCC
The strcat() function appends the string pointed by str2 to the end of the string pointed to by str1.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[50]=””Programming”;
Strcat(str1,str2);
return 0;
Output:
Str1:Programming in c
2. strncat() function:
Syntax:
char *strncat(char *str1,const char *str2,size_t n);
This appends the string pointed to by str2 to the end of the string pointed to by str1 upto n
characters long.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[50]=”programming”;
Strncat(str1,str2,2);
Printf(“\n str1:%s”,str1);
return 0;
Output:
Str1:programming in
3. Strchr() function:
Syntax:
This function searches for the first occurrence of the character c in the string pointed to by the
argument str. The function returns a pointer pointing to the first matching character, or null if no
match was found.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
Pos=strchr(str,’n’);
if(pos)
else
return 0;
Output:
4. Strrchr()function:
Syntax:
The strchr() function searches for the first occurrence of the character c beginning at the rear end
and working towards the front in the string pointed to by the argument str.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
if(pos)
else
return 0;
Output:
5. strcmp() function:
Syntax:
the strcmp compares the string pointed to by str1 to the string pointed to by str2.The function
return zero if the strings are equal.Otherwise,it returns a value less than zero or greater than zero
if str1 is less than or greater than str2 .
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
if(strcmp(str1,str2)==0)
else
return 0;
Output:
6. Strcpy() function:
Syntax:
This function copies the string pointed to by str2 to str1 including the null character of str2.it
returns the argument str1.
Example:
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
strncpy(str1,str2,2)
printf(“\nstr1:%s”,str1);
return 0;
Output:
HE
7. strlen() function:
Syntax:
This function calculates the length of the string str upto but not including the null character, i.e
the function returns the number of characters in the string.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str[]=”HELLO”;
return 0;
Output:
Length of str is :5
8. strstr() function:
Syntax:
The function is used to find the first occurrence of string str2 in the string str1. It returns a
pointer to the first occurrence of str2 in str1.If no match is found then null pointer is returned.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str2[]=”DAY”;
Char *ptr;
Ptr=strstr(str1,str2));
if(ptr)
else
return 0;
Output:
Substring found
Array of string:
Char name[20][30];
Here the first index will specify how many strings are needed and the second index specifies the
length of every individual string.So here we allocate space for 20 names where each name can be
a maximum of 30 characters long.
Syntax:
Char name[5][10]={“Ram”,”Mohan”,”Shyam”,”Hari”,”Gopal”};
Name[0] R A M \0
M O H A N \0
Name[1]
S H Y A M \0
Name[2]
H A R I \0
Name[3]
G O P A L \0
Name[4]
POINTERS:
Pointer declaration:
Syntax:
Here data type is the data type of the value that the pointer will point to.
Example:
float *pch;
char *pfnum;
Example 1
#include<stdio.h>
int main()
return 0;
Output:
Example 2
#include<stdio.h>
Int main()
int num,*pnum;
Pnum=#
Scanf(“%d”,&num);
return 0;
Output:
POINTER FLEXIBILITY:
We can make the same pointer to point to different data variables in different statements.
p = &x;
p = &y;
p = &z;
We can also use different pointers to point to the same data variable.
Ex: p1 = &x;
P2 = &x;
C P3 = &x
The data type of the pointer variable and the variable whose address it will store must
both be of the same type.
int x=10;
float y=2.0;
int *px;
int *py;
Px=&y; //invalid
Py=&x; //invalid
Initialization:
Example:
int a=10;
int *p;
p=&a;
Memory representation: a
10
p 1000(memory address of a)
1000
2000(memory address of p)
int a=5;
int *p;
p=&a;
we access a value by *p
#include<stdio.h>
Void main()
printf(“a=%d\n”,a); // 10
printf(“&a=%d\n”,&a); //1000
printf(“p=%d\n”,p); //1000
printf(“*p=%d\n”,*p); //10
printf(“&p=%d\n”,&p); //2000
1000(memory
1000 address)
2000(memory address of p)
Types of pointers:
1. Typed pointer: Pointer which has been declared with specific type of data type.
syntax:
data type *variable;
Example:
int *p; float *p; double *p;
A generic pointer is a pointer variable that has void as its data type.
The void pointer or the generic pointer is a special type of pointer that can be used to
point to variables of any data type.
Syntax:
Void * variable;
Example:
Void *ptr;
The void pointer will not point to any data and thus,cannot be dereferenced.You need to
type cast a void pointer to another kind of pointer before using it.
Example: #include<stdio.h>int main()
int x=10;
Char ch=’A’;Void *gp; gp=&x;
3. Null pointer:
Null pointer which is a special pointer value that does not point anywhere. This means
that aNULL pointer does not point to any valid memory address.
To declare a null pointer you may use the predefined constant NULL,which is defined in
severalstandard header files including <stdio.h>,<stdlib.h> and <string.h>.
Syntax:
you can always check whether a given pointer variable stores address of some
variable orcontains a NULL by writing,
if(ptr==NULL)
Statement block;
follows:int ptr;
ptr=0;
Call by value method of passing parameters to a function. Using call by value method, it
is impossible to modify the actual parameters in call when you pass them to a function.
The incoming arguments to a function are treated as local variable in the function and
those local variables get a copy of the values passed from their caller.
The calling function sends the address of the variables and the called function must declare those
incoming arguments as pointers.
In order to modify the variables sent by the caller,the called function must dereference the
pointers that were passed to it.thus passing pointers to a function avoids the overhead of copying
data from one function to another.
To pass pointers for passing arguments to a function the programmer must do the following:
3. Pass the address as the actual argument when the function is called..
#include<stdio.h>
Void min()
{
Shruthi B S, Asst. prof , Dept of CSE,CEC Page 32
Module 4 Principles of programming using C
int a,b;
printf(“enter 2 numbers\n”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
int hold;
temp=*px;
*px=*py;
*py=temp;
Advantages of pointers:
Pointers provide a way to return more than one value to the functions
Pointers can be used to pass information back and forth between the calling function and
called function.
Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
Disadvantages of pointers:
If pointers are updated with incorrect values, it might lead to memory corruption.
Questions
1 Develop a C program to concatenate 2 strings without using built-in function.
2 Define String. Explain any 4 string manipulation function with suitable example.
3 Explain the difference between gets() and scanf() functions.
4 Develop a C program to find the largest of three numbers using pointer.
5 Define Pointer. Explain pointer variable declaration and initialization with suitable
example.
6 Explain the difference between a null pointer and a void pointer.
7 Mention various operations that can be performed on string using built-in functions.
Explain any two function.
8 Develop a program using pointer to compute the sum, mean and standard
deviation of all element stored in array of N real number .
9 Explain how strings are represented in main memory .
10 Write a program to compare two strings without using built-in function
11 What is pointer? Discuss pointer arithmetic with suitable C code
12 Explain gets()and puts() function with example
13 What are strings? Mention different operations that can be performed on strings?
Explain any two with an example?
14 Explain array of strings with an example?
15 Discuss the working of the following string manipulation functions with suitable
code: i) strchr ii) strspn iii) strcmp iv) strcpy
16 Write a program to add two integers by passing pointer variable as parameters to
functions?
17 Write a program to print all even numbers from m to n using pointers?
18 Write a program to find length of a string without using built in functions.
19 Write a program to check if a given string is palindrome or not without using built in
functions.
20 Write a program to replace each constant in a string with the text one except letter ‘z’ ,’Z’
and ‘a’ , ‘A’ for the string “corona virus” should be modified as “DpSpoa Wjsvt”.