0% found this document useful (0 votes)
7 views

Module-4 Even

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module-4 Even

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Module 4 Strings and Pointers

CAMBRIDGE INSTITUTE OF TECHNOLOGY-NORTH CAMPUS


Off International Airport Road, Kundana, Bengaluru – 562110
STUDY MATERIAL
Module-4 Strings and Pointers
Course Title: Principles of Programming using C Course Code: BPOPS203 Credit: 03
Faculty Name: SUNIL KUMAR B
Department: COMPUTER SCIENCE AND ENGINEERING

Name:________________________ USN:___________ /Branch:______

STRINGS
What are Strings?
Recall that an array is a collection of elements of similar data-type that are stored in
contiguous memory locations. When the elements of an array are integers or floating-points,
the arrays are called numerical arrays. However, when the elements of an array are
characters, the arrays are called strings.
In otherwords, a string is an array of characters in C language.
OR
A String in C is one-dimensional character array where each element is either a character
constant or a string constant.
OR
A String is a series of characters treated as a unit.
Consider an example of storing the word, VOLVO in a array variable name[5]. The word
VOLVO contains five characters. Fig.1. shows the storing of the VOLVO word, as a string in
C language:

V O L V O \0
name[0] name [1] name[2] name[3] name[4] name[5]

Fig.1. Displaying the storage of a String.


 As similar to a numerical array, the first element of the string is stored in 0th subscript
position; the second element is stored in 1st subscript position, and so on.
 The last character of the string is stored in n-1 subscript position, where n is the total
number of characters.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 1


Module 4 Strings and Pointers

 A character array or a string stores a null (\0) character at the nth subscript position,
while a numerical array does not store such a character.
Difference between Characters and Strings
A character, written within single quotes is treated as character in C language. For
example, „A‟ is a character. On the other hand, a single or multiple characters written within
double quotes are treated as strings. For example, “A” is a string.
In C language, all the string are terminated by a special invisible character \0. Thus when
you write „A‟ single character A gets written into computer‟s memory. But when you write
“A” two characters A and \0 get stored in memory.

Declaring and Initializing a String


As similar to a numerical array, a character array or a string is declared as follows:
char variable_name[array_length];
In the preceding syntax, variable_name stands for a user-defined string name, and
array_length stands for the size of the array or string.
A character array or a string variable is initialized by either assigning a character
constant individually or assigning all the characters collectively.
When you initialize a string variable by assigning character constants individually, you use
single quotes „ „, which is as shown in example 1.
Example 1.:- char name[10]={„S‟, „C‟, „A‟, „N‟, „I‟,‟A‟, „\0‟};
In the above example, the character array name is initialized with character
constants, since each character is quoted using single quotes „ „ individually, the elements are
called as character constants. Note the null (\0) character is also assigned manually for the 6th
subscript position of the array.
When we initialize a string variable by assigning all the characters collectively, we use
double quotes “ “, which is as shown in example 2.
Example 2.:- char name[10]={“SCANIA”};
In the above example, the character array name is initialized with string constants,
since all the characters are quoted using double quotes “ “ collectively, it is called string
constants(also called as String Literals). Note, the above declaration automatically adds the
null (\0) character at the end of the string.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 2


Module 4 Strings and Pointers

Printing and Reading Strings/Strings input and output functions


A string data can be read or displayed by using the input and output functions, such as
getchar( ), puts( ), printf( ), and scanf( ). These input and output functions are defined in
stdio.h header file to perform I/O operations.
1. Using the scanf( ) and printf( ) Functions
The scanf( ) function reads characters from the keyboard and stores them in variables
according to the specified formats, which are known as format specifiers. If we need to read
a string, we can use the %s format specifier.
scanf( ) function read strings which do not have any white spaces, that is, a white space or a
blank space in the string will terminate the reading of a string. To read a string with white
space gets( ) function is used.
Example:- scanf(“%s”, car);
When this statement is executed, the user has to enter the car name
(eg.”BHARATHBENZ”) without any white space (i.e not “BHARATH BENZ”).

The printf( ) function along with the %s format specifier prints a string stored in
character array to the console. We can use the printf( ) function to display the string data with
the help of two ways. Either we can pass the string data directly within the printf( ) function
or we can store the string data in a character array, for instance str, and then pass the str array
as a parameter in the printf( ) function.
Example:- printf(“Test string”);
Or
Example:-char str[ ] = {“Test string”};
printf(%s”, str);
2. Using the puts( ) and gets( ) Functions
The gets( ) function reads a string from keyboard. This function stops reading the
string only when we press the Enter key from the keyboard. The gets( ) function is similar to
the scanf( ) function. The difference between the gets( ) and scanf( ) functions is that the gets(
) function can read the whole sentence, which is a combination of multiple words; while the
scanf( ) function can read the characters until a space or a newline character is encountered.
Program displaying the limitations of scanf( ) Function.
#include<stdio.h>
int main( ) {
char msg[70];

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 3


Module 4 Strings and Pointers

printf(“Enter a message”);
scanf(“%s”, msg);
printf(“%s”, msg);
return 0;
}
Output:
Enter a message
Welcome to C language
Welcome
The puts( ) function, on the other hand, prints a string or a value stored in a variable to
the console in the next line.

/*Program to demonstrate the usage of gets( ) and puts( )*/


#include<stdio.h>
#define length 100
int main()
{
char vehicle_name [length] = "CORONA";
puts("Name of the vehicle:");
puts(vehicle_name);
puts("Enter a new name:");
gets(vehicle_name);
puts(vehicle_name);
getch();
return 0;
}
Output:-
Name of the vehicle: CORONA
Enter a new name: BHARATH BENZ
BHARATH BENZ
*Note:- For programming examples, refer text books and class notes.

3. Using the getchar( ) and putchar( ) Functions


The getchar( ) function, is used to read a single character from the standard input
device. getchar( ) returns the character it reads, or, the special value EOF (end of file), if there
are no more characters available.
The putchar( ) function writes a character to the standard output device. It returns the
character which is written.
/*Program using getchar( ) and putchar( ) Function.*/
#include<stdio.h>
int main( ) {
char ch;

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 4


Module 4 Strings and Pointers

printf(“Enter a word”);
ch=getchar( );
putchar(ch);
return 0;
}
Output:
Enter a word
String
S

STRING Taxonomy
In C, a string can be stored in either fixed-length format or in variable-
length format as shown in fig. below.

STRINGS

Fixed Variable
Length Length

Length Delimited
Controlled

Fig. String taxonomy


1. Fixed length strings: When storing a string in fixed-length format, we need to
specify an appropriate size for the string variable.
If the size is too small, we will not be able to store all the elements in the string. On the other
hand, if the string is large, then unnecessarily memory space will be wasted.
2. Variable-length strings: Here the string can be expanded or contracted to
accommodate the elements in it.
If a student has a long name of say 20 characters, then the string can be expanded to
accommodate 20 characters or fewer characters (5 if the student name has only 5
characters.
3. Length-controlled strings: In a length-controlled string, we need to specify the
number of characters in the string.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 5


Module 4 Strings and Pointers

4. Delimited strings: In this format, the string is ended with a delimiter. The delimiter is
then used to identify the end of the string.
For ex. Char name[8];

V O L V O \0

Creating an Array of Strings


Apart from creating a single string that is also called as one-dimensional character
array, we can also create an array of strings that is known as two-dimensional character
array, which consists of strings as its individual elements.
The following code shows an example of two-dimensional character array:
char alpha[3][3] = {“abc”,”def”,”xyz”};
alpha[ ][0] alpha[ ][1] alpha[ ][2]
alpha[0] a b c
alpha[ 1] d e f
alpha[ 2] x y z
Fig.2. shows the storage of an array of string, alphabets, in the main memory of a computer.
In the above fig., alpha[ ][ ] is a two dimensional array of characters, or an array of strings. It
stores 3 strings, where the maximum length of each string element is 0.
Program: Creating and Displaying an Array of String
#include<stdio.h>
#include<conio.h>
int main(){
int i;
char month_array[12][10]={"January","February","March","April",
"May","June","July","August","September",
"October","November","December"};
clrscr();
for(i=0;i<12;i++)
{
printf("%s \t",month_array[i]);
}
getch();
return 0;
}
Output:
January February March April May June July August September
October November December

*Note:- For more programming examples, refer text books and class notes.
Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 6
Module 4 Strings and Pointers

Operations on Strings
String Handling/Manipulation Functions
The C language provides a string library that contains various predefined string handling
functions, such as strcat and strlen. These string handling functions are stored in the string.h
header file.
Finding the length of the string.
1. strlen( )
The strlen( ) function is used to find out the length of a string. The syntax to use the
strlen( ) function is as follows:
strlen(string_data);
Example:-
int n;
char st[20] = “BENGALURU”;
n = strlen(st);
This will return the length of the string 9 which is assigned to an integer variable n.

Comparing two strings


2. strcmp( )
The strcmp( ) function is used to compare two character strings. It returns 0 when two
strings are identical; otherwise it returns a numerical value which is the difference in ASCII
values of the first mismatching characters of the strings being compared.
Its syntax is:
strcmp(string_data1, string_data2);
Example:-
char city[20] = “MYSURU”;
char town[20] = “MANGALURU”;
strcmp(city, town);
This will return an integer value 30 which is the difference in the ASCII values of the first
mismatching letters „Y‟ and „A‟.

Copying a String into a character variable.


3. strcpy( )
strcpy( ) function is used to copy a character string to a character variable. Consider the
following example.
char city[15];

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 7


Module 4 Strings and Pointers

strcpy(city, “BENGALURU”);
This will assign the string “BENGALURU” to the character variable city.

Concatenating Two Strings to form a New String.


4. strcat( )
strcat( ) function is used to join character strings. When two character strings are joined, it is
referred as concatenation of strings. Consider the following example.
char city[20] = “YELAHANKA”
char pin[8] = “-560064”;
strcat(city, pin);
This will join the two strings and store the result in city as “YELAHANK-560064”.
Note that the resultant string is always stored in the left side string variable.

Additional String Manipulation/Handling Functions


Some C compliers will accept the following string handling functions which are available in
header files string.h and ctype.h.
Function Purpose Example Result
strupr( ) To convert all alphabets in a strupr(“Delhi”) “DELHI”
string to upper case letters.
strlwr( ) To convert all alphabets in a strlwr(“CITY”) “city”
string to lower case letters.
strrev( ) To reverse a string strrev(“SACHIN”) “NIHCAS”
strncmp( ) To compare the first n m=strncmp(“DELHI”, m = -4
characters of two strings.
“DIDAR”,2)
strcmpi( ) To compare two strings with m = strcmpi(“DELHI”, m=0
case insensitive(neglecting
“Delhi”);
upper/lower case)
strncat( ) To join specific number of char s1[10] = “New”; S1 will be
letters to another string. char s2[10] = “Delhi”;
“Newdel”
strncat(s1,s2,3);

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 8


Module 4 Strings and Pointers

POINTERS
Possible questions:-1 What is a Pointer? Explain how pointer variables are declared and
initialized.
A pointer is a variable which points or represents a storage location in
memory(RAM). In other words, a pointer is a variable which holds/stores the address of
another variable. Pointers are used to access the values stored in the memory locations using
the memory addresses.
Pointer declaration
A pointer is declared like a variable with appropriate data type. The pointer variable in the
declaration is preceded by the * (asterisk) symbol. It has the following form:-
type *var1, *var2,…….*var n;
A pointer variable is declared as follows:-
int *ptr, *x; /*declared integer pointers*/
float *xptr, *y; /* declared float pointers*/
char *p, *a[10]; / declared character pointers*/

Pointer initialization.
A pointer variable is initialzed as follows:-
int a, b; /*normal variables*/
ptr = &a; /*assigning the address of a and b to pointer*/
xptr = &b;
The symbol & (ampersand) is an address operator which is used to access the address of a
variable and assign it to a pointer to initialize it.
The symbol * (asterisk) is an indirection operator which is used to access the value of a
variable through a pointer.
Ex:- int m = 15, *mptr;
mptr = &m;
printf(“Value of m = %d”, *mptr); /* output is m = 15 */
note:- Write a small program on pointers.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 9


Module 4 Strings and Pointers

Pointers as Function Arguments/Passing Arguments to functions using


pointers
Possible question:-1 Explain how a pointer is used as an argument in a function?
 A pointer can be used as an argument in function declaration. When a function with a
pointer argument is called, the calling program will pass the address (not the value) of
a variable to the argument.
 Any alterations to the value of pointer variables inside the function are automatically
accepted in the calling program.
 This method is referred as calling a function by reference.
Ex:- Call by Reference (address) method.
Example program:-
#include<stdio.h>
#include<conio.h>
void add10(int *x, int *y);
void main()
{
int a=25, b=10;
clrscr();
printf("Before function call a=%d b=%d",a,b);
add10(&a,&b); /*Function call*/
printf("\nAfter function call a=%d b=%d",a,b);
getch();
}
void add10(int *x, int *y)
{
*x = *x + 10;
*y = *y + 10;
printf("\nInside the function a=%d b=%d",*x,*y);
}

Comparison between Call by Value and Call by Reference.

Possible question:-2, Differentiate between call by Value and Call by Reference.


Call by Value Call by Reference
1. Here the value of the variable is 1. Here the address of the variable is
passed as an argument. passed as an argument.
2. Any alteration in the value of the 2. Any alteration in the value of the
argument passed is local to the argument passed is accepted in the
function and is not accepted in the calling program.
calling program.
3. Memory location occupied by formal 3. Memory location occupied by the
and actual arguments is different. formal and actual arguments is same
and there is a saving of memory

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 10


Module 4 Strings and Pointers

location.
4. Since a new location is created, this 4. Since the existing memory location is
method is slow. used through its address, this method
is fast.

Pointer/Address Arithmetic
Possible questions:-1 Explain with an example how pointers can also be used on
arithmetic operators.
Like how the arithmetic operations are possible on normal variables, it‟s also possible to
perform arithmetic operations on pointer variables.
Ex:-Incrementation pointers
#include<stdio.h>
void main( )
{
char a;
char *p = &a;
printf(“Value of pointer p before incrementation is %u\n”,p); /* p = 15000 */
p++;
printf(“Value of pointer p after incrementation is %u\n”,p); /* p = 15001 */
}

QUESTION BANK
Sl. Strings RBL
No.
1 What are Strings? Explain how strings are declared and initialized? L1
2 Explain how strings are read and displayed? L2
3 Explain the function which helps in reading any string and displaying any L2
string.
4 Explain the various functions available in C to manipulate the strings with L2
suitable examples.
5 Explain string handling or string manipulation functions in C? L2
6 What are sting input and output functions? L1
7 What are arrays of strings? Demonstrate with an example program? L1
8. Write a „C‟ program which accepts Student Name by the user as input, L1
i. Prints the length of the name entered along with the name.
ii. Copy Student Branch using string copy function.
Print Student name Branch concatenated.
9. Write a „C‟ program to read strings including blank character and output the L1
same.
10. Write a „C‟ program to check whether the entered string is Palindrome or not. L1
Pointers
11 Explain storage classes in C with suitable example. L2

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 11


Module 4 Strings and Pointers

12 What is a Pointer? Explain how pointer variables are declared and initialized. L1
13 Explain how a pointer is used as an argument in a function? L2
14 Differentiate between call by value and call by reference with suitable L2
example program.
15 Write a C program to find the bigger of 2 numbers using pointers. L1
16 Develop a function in C that will swap (exchange) the value of two integer L3
variables passed as arguments. Also write the main program.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 12

You might also like