POP Module-4
POP Module-4
1
[Type here]
✓ ASCII code of a character is stored in the memory and not the character itself. So, at address 1000, 72
will be stored as the ASCII code for H is 72. The statement char str[] = "HELLO";
Syntax:
the general form of declaring a string is
char str[size];
✓ The other way to initialize a string is to initialize it as an array of characters. For example,
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};
Here, the compiler will automatically calculate the size based on the number of characters.
✓ We can also declare a string with size much larger than the number of elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it and finally terminates
the string with a null character. Rest of the elements in the array are automatically initialized to NULL
✓ Now consider the following statements:
char str[3];
str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-time error.
using scanf()
✓ Strings can be read using scanf() by writing scanf("%s", str);
✓ Unlike int, float, and char values, %s format does not require the ampersand before the variable str.
✓ The main pitfall of using this function is that the function terminates as soon as it finds a blank
space. Therefore we cannot read the complete sentence using scanf() function.
using gets()
✓ The string can be read by writing gets(str);
✓ gets() is a simple function that overcomes the drawbacks of the scanf() function.
✓ gets() function is used to read a sequence of characters (string) with spaces in between.
✓ The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
✓ The gets() function takes the starting address of the string which will hold the input.
✓ The string inputted using gets() is automatically terminated with a null character.
using getchar()
✓ Strings can also be read by calling the getchar() function repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a character
array as shown below:
i=0;
ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character
2
[Type here]
4.1.2 Writing Strings
✓ Strings can be displayed on the screen using the following three ways:
1. using printf() function
2. using puts() function, and
3. using putchar() function repeatedly.
using printf()
✓ Strings can be displayed using printf() by writing printf("%s", str);
✓ We use the format specifier %s to output a string. Observe carefully that there is no ‘&’ character
used with the string variable.
✓ We may also use width and precision specifications along with %s.
✓ The precision specifies the maximum number of characters to be displayed, after which the string is
truncated. For example, printf ("%5.3s", str); The above statement would print only the first three
characters in a total field of five characters. Also these characters would be right justified in the
allocated width.
✓ To make the string left justified, we must use a minus sign. For example, printf ("%–5.3s", str);
using puts()
✓ A string can be displayed by writing puts(str);
✓ puts() is a simple function that overcomes the drawbacks of the printf() function.
✓ The puts() function writes a line of output on the screen. It terminates the line with a newline
character (‘\n’).
using putchar()
✓ Strings can also be written by calling the putchar() function repeatedly to print a sequence of
single characters.
i=0;
while(str[i] != '\0')
{
putchar(str[i]);// Print the character on the screen
i++;
}
3
4.2.2 Variable-length strings
✓ A better option is to use a variable length format in which the string can be expanded or contracted
to accommodate the elements in it. For example, if you declare a string variable to store the name of
a student. If a 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. However, to use a variable-length string format
you 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.
1. Length-controlled strings: In a length-controlled string, you need to specify the number of
characters in the string.
2. Delimited strings: In this format, the string is ended with a delimiter such as comma, semicolon,
colon, dash, null character etc. The delimiter is then used to identify the end of the string.
void main()
{
char str1[10], str2[10]= “JAIN”;
strcpy(str1,str2);
printf(“The Source String=%s\n The Destination String=%s”, str1,str2);
}
Output:
The Source String= JAIN
The Destination String= JAIN
Output:
The concatenated String=GoodMorning.
Ex:
✓ “car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It returns
negative value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.
✓ “cat” and “car” are different strings. The characters ‘t’ and ‘r’ have different ASCII values. It returns
positive value since ASCII value of ‘t’ is greater than the ASCII value of ‘r’.
Ex: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10]=”Hello”;
char str2[10]=”Hey”;
if(strcmp(str1,str2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
}
Output:
The two strings are not identical
#include <stdio.h>
#include <string.h>
int main()
{
char str[50] = "information";
printf("The given string is =%s\n", str);
printf("After reversing string is =%s", strrev(str));
return 0;
}
4.4 Arrays of Strings
✓ An array of strings is declared as
<data_type> <array_name> [row_size][column_size];
Here, the first index row_size will specify how many strings are needed and the second index
column_size will specify the length of every individual string.
Ex: char names[20][30];
✓ So here, we will allocate space for 20 names where each name can be a maximum 30 characters long.
✓ Let us see the memory representation of an array of strings. If we have an array declared as char
name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};
Then in the memory, the array will be stored as shown in Fig. 4.13.
✓ By declaring the array names, we allocate 50 bytes. But the actual memory occupied is 27 bytes.
Thus, we see that about half of the memory allocated is wasted.
✓ Figure 4.14 shows an algorithm to process individual string from an array of strings. In Step 1, we
initialize the index variable I to zero. In Step 2, a while loop is executed until all the strings in the
array are accessed. In Step 3, each individual string is processed.
Ex: Write a C Program to Read and Print the Names of N Students of a Class.
#include<stdio.h>
void main()
{
char names[5][10];
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
printf(“\n Enter the names of students :”);
for(i=0;i<n;i++)
{
scanf(“%s”,names[i]);
}
printf(“\n Names of the students are : \n”);
for(i=0;i<n;i++)
puts(names[i]);
}
Disadvantages of pointers
One of the disadvantage of using pointer is that program may crash if sufficient memory is not
available at run time to store pointers.
Applications of pointer
• Arrays and Strings:
Pointers can be used to traverse and manipulate arrays and strings more efficiently.
• Function Pointers:
Pointers to functions allow you to create arrays of functions, pass functions as
arguments to other functions, or return functions from functions.
• Structures:
Pointers can be used to work with structures more efficiently, especially when dealing
with large structures.
• File Handling:
Pointers are used in file handling operations, enabling efficient reading and writing of
data to files.
• Efficient Parameter Passing:
Passing pointers to functions instead of passing large data structures can be more
efficient in terms of both time and space.
• Dynamic Data Structures:
Pointers are crucial in implementing dynamic data structures such as trees and
graphs.
• Callback Functions:
Pointers to functions are often used for implementing callback mechanisms, where a
function can be passed as an argument to another function.
4.7 Declaring Pointer Variables
✓ Pointer provides access to a variable by using the address of that variable.
✓ A pointer variable is therefore a variable that stores the address of another variable.
✓ The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
Here, data_type: is the data type of the value that the pointer will point to. It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.
Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.
Example:
int a=3;
int *ptr;
ptr=&a;
ptr a
Memory layout:
65530 3
Address: 65530
✓ ‘ptr = &a’ copies the address of ‘a’ to the pointer variable ‘ptr’.
Example Program: Write a C program to print value and address of the variable using pointers.
#include<stdio.h> Output:
void main () The address of a=65530 and value of a=20
{
int a=20, *ptr;
ptr = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of a=%d\n”,ptr,*ptr);
}
ptr1 a
Memory layout:
65530 20
Address: 65530
Syntax
data_type * ptr_name = address_of_variable;
where,
data_type:.It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
ptr_name: It is the name of the pointer variable.
address_of_variable: Itis the address of another variable.
Example:
int a;
int *ptr;
ptr=&a;
or
int a;
int *ptr=&a;
Both are equivalent.
✓ We can dereference a pointer, i.e., refer to the value of the variable to which it points, by using unary
'*' operator (also known as indirection operator) as *pnum, i.e., *pnum = 10, since 10 is value of x.
Therefore, * is equivalent to writing value at address. Look at the code below which shows the use of
pointer variable.
#include <stdio.h>
void main()
{
int num, *pnum;
pnum = #
printf(“Enter the number : ");
scanf("%d", &num);
printf("\n The number that was entered is : %d", *pnum);
}
Output:
Enter the number : 10
The number that was entered is : 10
What will be the value of *(&num)? It is equivalent to simply writing num.
Output:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A
void main()
{
Output:
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 4 5
scanf(“%d%d”,&a,&b); result =9
res = add(&a,&b);
printf(“result =%d\n”, res);
}
2. Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a,b;
printf(“Enter the values of a and b:”); Enter the values of a and b: 10 20
scanf(“%d%d”,&a,&b); Before swapping: a=10 b=20
printf(“Before swapping: a=%d\tb=%d”, a, b); After swapping: a=20 b=10
swap(&a,&b);
printf(“After swapping: a=%d\tb=%d”, a, b)
}
Output:
Enter the values of a and b: 10 20
Before swapping: a=10 b=20
After swapping: a=20 b=10