BPOPC MODULE 04

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

BPOPS203 Principles Of Programming Using C Module 04 Notes

MODULE 04
STRINGS AND POINTERS
4.1 STRINGS
• Array of characters are called strings.
• A string can also be defined as sequence of characters followed by a NULL ‘\0’ character.
• A string is terminated by NULL ‘\0’ character.
• Forex:
"C Programming"
• The above string can be pictorially represented as shown below:

C P r O g r a m m i n g \0

STRING VARIABLE
• There is no separate datatype for strings in C.
• They are treated as arrays of type char.
• So,a variable which is used to store an array of characters is called a string variable.

Declaration of String
• Strings are declared in C in similar manner asarrays.
Only difference is that, strings are of char type.
• Syntax:
char string_name[string_length];

example:

char str[5]; //string variable name can hold maximum of 5 characters including NULL character

• The above code can be pictorially represented as shown below:

0 1 2 3 4 5

H E L L O \0

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

Initialization of String

char str[5]=”hello”;
or
char str[5]={‘h’,’e’,’l’,’l’,’o’};

Both are same. If we specify characters separately we should use


Single quotes ‘ ‘ for each character.

Taxonomy of String

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

4.1.1 Reading & Printing Strings


The strings can be read from the keyboard and can be displayed onto the monitor using following 2 formatted
functions:

Formatted input function: scanf()


Formatted output function: printf()
Example: Program to illustrate the strings using scanf() and printf().
#include<stdio.h>
void main()
{
char name[10];
printf(“enter name:\n”);
scanf(“%s”,name);
printf(“name=%s”,name);
}

Output:

enter your name:


ram
Name=ram
4.1.2 STRING INPUT/OUTPUT FUNCTIONS: gets(), puts()
The strings can be read from the keyboard and can be displayed onto the monitor using following 2

Unformatted functions:

Unformatted input function: gets()


Unformatted output function: puts()

Example: Program to illustrate the use of gets() and puts().

#include<stdio.h>
void main()
{
char name[10];
printf(“enter your name:\n”);
gets(name); //same as scanf(“%s”,name);
puts(name); //same as printf(“%s”,name);
}

Output:

enter your name:


ram
welcome: ram

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

4.2STRING MANIPULATION FUNCTIONS /STRING HANDLING FUNCTIONS/STRING


OPERATIONS
• Strings are often needed to be manipulated by programmer according to the need of a problem.
All string manipulation can be done manually by the programmer but, this makes programming
complex and large.
• To solve this,the C supports a large number of string built-in functions.
• There are numerous functions defined in<string.h>headerfile.
• Various operations on string are:
• string length
• string copy
• string concatenation
• string compare
• string reverse
• Converting lowercase to uppercase string..
• Searching specific character in a string

1. strlen()
• This function calculates the length of string.It takes only one argument,i.e.,string-name.
• It returns the length of the string. It counts all the characters up to ‘\0’ except ‘\0’. So, an empty string has
length zero.
Syntax:
strlen(string_name);

char str[10]=”Pogram”;
len=strlen(str);

Example: Program to find length of a string using strlen()

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

#include<string.h>
#include<stdio.h>
void main()
{
char str[20];
intlen;
printf("Enter string:\n");
scanf(“%s”,str);
len=strlen(str);

printf("Length of the string= %d ",len);


}

Output:

Enter string:
program

Example: Program to find Length of a string without using built-in function strlen()

#include<stdio.h>
void main()
{
char str[20];
int i,len;
len=0;
for(i=0; strlen[i]!=’\0’; i++)
{
len++;
}
printf(“Length of a String=%d\n”,len);
}

2. strcpy()
• Thisfunctioncopiesthecontentofonestringtothecontentofanotherstring.Ittakes 2arguments.

Syntax:

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

strcpy(dest,src);
or
strcpy(str1,str2);

where source and destination are both the name of the string.

Example:Program to copy from one string to another string using built-in function strcpy().
#include<string.h>
#include<stdio.h>
void main()
{
char str1[20],str2[20];
printf("Enter string1: ");
scanf(“%s”,str1);
strcpy(str1,str2);
printf("Copied string:%s\n",str2);
}

Output:

Enter string:
CProgram
Copied string: CProgram

3. strcat()
This function joins 2 strings. It takes two arguments, i.e., 2 strings and resultant string is stored in

the first string specified in the argument.

Syntax:
strcat(first_string,second_string);

strcat(str1,str2);

Example: Program to illustrate the use of strcat().

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

#include <stdio.h>
#include <string.h>
void main()
{
char str1[10], str2[10];
printf("Enter FirstString:");
scanf(“%s”,str1);
printf("\n Enter SecondString:");
scanf(“%s”,str2);
strcat(str1,str2); //concatenates str1 and str2
printf("\n Concatenated String=%s\n”, str1);
}

Output:

Enter First String: programming


Enter Second String:
Language
Concatenated String= programminglanguage

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
BPOPS203 Principles Of Programming Using C Module 04 Notes

4. strcmp()
• This function compares two strings and returns value 0, if the two strings are equal.
• If string1 is greater than string2 then a positive value is returned.
• If string1 is less than string2 then the function returns a negative value.

Syntax:

strcmp(string1,string2);

Example: Program to illustrate the use of strcmp()

#include <string.h>
#include<stdio.h>
void main()
{
char str1[20],str2[20];
printf("Enter first string: ");
scanf(“%s”,str1);
printf("Enter second string: ");
scanf(“%s”,str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are not equal");
Output:
}
Enter first string:
Hello
Enter second string:
Hello
Both strings are equal

DEPT. OF CSE , KLEIT , HUBBALLI-27 Prepared by, Mrs. Shanta Kallur, CSE, KLEIT
[Type here]

5. strrev()
This function reverses all characters in the string str except the terminating NULL charcter ‘\0’
It reverses a string.The original string is lost.
Syntax:
strrev(string);
Ex: strrev(str);
Example: Program to reverse a string using strrev()
#include<string.h>
#include<stdio.h>
void main()
{
char str[20];
printf("Enter string:\n");
scanf(“%s”,str);
strrev(str);
printf(“string reverse=%s\n”,str);
}
Output:
Enter string:
Hello
String reverse:
olleH

6. strlwr() and strupr()


strlwr() function is used to convert uppercase string to lowercase.
strupr() function is used to convert lowercase string to uppercase.
#include<string.h>
#include<stdio.h>
void main()
{
char str[20];
printf("Enter string1:\n");
scanf(“%s”,str1);
printf("Enter string2:\n");
scanf(“%s”,str2);
strlwr(str1);
strupr(str2);
printf(“string lowercase=%s\n”,str1);
printf(“string uppercase=%s\n”,str2);
[Type here]

7. strchr()
It is used to search a specific character in a string.
Syntax:
strchr(string,searching_character);
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char *a;
a=strchr(“C Programming”, ‘P’);
printf(“%s”,a);
}

Output:
Programming

Array of Strings/Multidimensional Strings


Two dimensional array is an array of one dimensional character array, which consists of strings as its
individual elements.
Syntax:
char string_name[rows][columns];
Maximum length of each string
Number of strings
Example: char str[5][20]

From the above declaration it is observed that:

• 5 indicates that 5 names can be stored


• 20 indicates that each name can have at most 20 characters.
[Type here]

String Initialization:

char str[3][10]={

“RAM”,

“AMAN”,

“JOHN”

Pictorial Representation of Multi dimensional Strings

Example
[Type here]

#include<stdio.h>
void main()
{
char str[5][10];
int i;
1. Implements string copy operation STRCOPY (str1, str2) that copies a string str1 to
printf(“enter names”);
another string str2 without using library function.
for(i=0;i<5;i++)
{
scanf(“%s”,str[i]);
#include<stdio.h>
}
void STRCOPY(char str1[50], char str2[50]);
for(i=0;i<5;i++)
{ void main()
printf(“%s\n”,str[i]);
{
}
} char str1[50], str2[50];
printf("Enter the source string\n");
Write a C program to check given string is palindrome or not without using builtin functions.
scanf(“%s”,str1);
STRCOPY
#include<stdio.h> (str1, str2);
void main()printf(“copied string=%s”,str2);
{
}
char string[40];
void STRCOPY(char str1[50], char str2[50])
int length=0, flag=1,
{
printf("Enter string:\n");
int i;
scanf(“%s”,string);
for(i=0;string[i]!='\0';i++)
i=0;
{
while(str1[i]!='\0')
length++;
{
}
str2[i]=str1[i];
for(i=0;i< length/2;i++)
{ i++;
} != string[length-1-i] )
if( string[i]
{ str2[i]=’\0’;
flag=0;
}
break;
}
}
if(flag==1)
{
[Type here]

printf("PALINDROME");
}
else
{
printf("NOT PALINDROME");
}
}

Output 1

Enter String:
madam
PALINDROME

Output 2
------------
Enter String:
step on no pets
PALINDROME

Read a sentence and print frequency of vowels and total count of consonants.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
void main()
{
char str[50],ch;
int i, vcount=0, ccount=0;
printf("Enter the sentence\n");
scanf(“%s”,str);
for(i=0; i<strlen(str);i++)
{
if(isalpha(str[i]))
{
ch=tolower(str[i]);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
vcount++;
[Type here]

else
ccount++;
}
}
printf("Number of vowels=%d\n", vcount);
printf("Number of consonants=%d\n", ccount);
}

Write a C program to replace each constant in a string with the next one except letter ‘z’
‘Z’ and ‘a’ ‘A’ . Thus the string “Programming in C is fun” should be modified as
“Qsphsannjohjo D jtgvo”;
#include<stdio.h>
void main()
{
char str1[5], str2[50], ch;
int i;
printf(“enter the string:\n”);
scanf(“%s”, str1);
for(i=0; str1[i]!=’\0’; i++)
{
ch=str1[i];
if(ch==’a’||ch==’A’)
[Type here]

str2[i]=ch;
else if(ch==’z’||ch==’Z’)
str2[i]=ch;
else if(ch==’ ‘)
str2[i]=’ ‘;
else
str2[i]=++ch;
}
str2[i]=’\0’;
printf(“%s\n”,str2);
}

POINTERS
INTRODUCTION
• As you know, every variable is a memory-location and every memory-location has its address defined
which can be accessed using address (&) operator.
POINTER
• A pointer is a variable which holds address of another variable.

Operators used to represent pointers are:


1. Address Operator (&)
2. Indirection Operator (*)

 Declaration and Initialization of Pointers

Syntax:

data_type *ptr_variable_name;
ptr_variable_name=&variable_name;
[Type here]

where, variable_name is the variable whose address has to be stored in pointer.

Example:
int a=10;
int *ptr;
ptr=&a; // ptr holds the address of variable a
*ptr=a; // *ptr holds the value of variable a

Example program

#include<stdio.h>
void main()
{
int a=10;
int *ptr;
ptr=&a;
printf(“%d\n”, a); //10
printf(“%d\n”, &a); //2056
printf(“%d\n”, ptr); //2056
printf(“%d\n”, *ptr); //10
}
[Type here]
[Type here]

NULL POINTER
• A NULL pointer is defined as a special pointer value that points to '\0'(nowhere) in the memory. In other
words, NULL pointer does not point to any part of the memory.
• For ex:
int *ptr=NULL;

POINTERS AND FUNCTIONS


• When, argument is passed using pointer, address of the memory-location is passed instead of value.
• The function swap() is called by sending addresses of a and b.
• In the function header of function swap(), the formal parameters x and y declared using
* operator holds the address of a and b.
• In the function swap(), using *x and *y the values of a and b can be accessed and they
are changed.
• The values of actual parameters are exchanged (a=20 and b=10). If there are any changes in the formal
parameter then actual parameters also changes.

Program to swap two numbers using pointers/call by reference.

#include<stdio.h>
void swap(int *x, int *y);

void main()
{
int a,b;
a=10, b=20;
swap(&a,&b); //a and b are actual parameters

printf(“a=%d\n b=%d\n”,a,b);
}

void swap(int *x,int *y) // x and y are formal parameters


{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Output:
a=20
b=10
[Type here]

POINTERS AND ARRAYS


Pointers and arrays are very closely related to each other in terms of functionality. Both pointers and
arrays uses consecutive memory locations to store the data with one key difference in accessing the
data. Pointers uses addresses to access the data stored in memory. whereas array uses index value to
access the data stored in a memory location.
Syntax:
data_type ptr_name;
ptr_name=array_name;
Example:
int a[5];
int *ptr;
ptr=a;
• The name of the array always points to the first element of an array. Later which is incremented to get
other elements.
• Here, address of first element of an array is &a[0].
• Also, a represents the address of the pointer.
Example: Program to access elements of an array using pointer.
#include<stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
int *ptr;
ptr=a;
for(i=0;i<n;i++)
{
printf(“%d\n”, a[i]);
printf(“%d\n”, &a[i]);
printf(“%d\n”, ptr);
printf(“%d\n”, *ptr);
ptr++;
}
}

Page 67
[Type here]

Example: Program to find sum of all the elements of an array using pointers.
#include<stdio.h>
void main()
{
int i, a[10], n, sum=0,*ptr;
printf("Enter the size of the array:");
scanf("%d", &n);
printf("Enter the elements into the array: ");
for(i=0;i<n;i++)
scanf("%d ",&a[i]);
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+*ptr;
ptr++;
}
printf("sum= %d\n",sum);
}

CHARACTER POINTER AND POINTERS TO THE STRINGS:

Strings are array of characters instead of integer values of array, here pointer points to the character present
in a string represented as an array.

Syntax:

data_type *ptr_name;

ptr_name=string_name;

Example: char str[20]=”Hello”;

char *ptr;

ptr=str;

Here pointer points to all the character of a string, instead initially it points to the first element or first
character of a string later which is incremented to get other elements

Page 68
[Type here]

Example: Program to copy string from other string

#include<stdio.h>
void main()
{
char str1[20]=”Hello”;
char str2[20]
char *ptr;
ptr=str1;
for(i=0; str1[i]!=’\0’; i++)
{
str2[i]=*ptr;
ptr++;
}
str2[i]=’\0’;
printf(“copied string=%s\n”,str2);
}

Since character type occupies 1 byte for each element. If it reserves 2056 for first character element as
starting address, 2056+1=2057. 2057 as second character’s element as starting address, 2057+1=2058 for
third element and so on..

Page 69
[Type here]

POINTER ARITHMETIC/ADDRESS ARITHMETIC/POINTER


PROPERTIES
• As you know, pointer is an address, which is a numeric value.
• Therefore, you can perform arithmetic operations on a pointer just as you can a
numeric value.
• There are 4 arithmetic operators that can be used on pointers: ++, --, +, and –

1. Incrementing a Pointer and Decrementing a Pointer


An integer value can be added or subtracted from a pointer. It can be
incremented or decremented.

0 1 2 3 4

10 20 30 40 50
2056 2058 2060 2062 2064
address

Example: Program to increment and decrement pointers.


#include<stdio.h>
void main()
{
int a[5] = {10, 20,30,40,50};
int *ptr,i,n;
ptr = a;
for ( i = 0; i < n; i++)
{
printf("%d\n”,*ptr); //value is:10
printf(“%d\n”,ptr); //address is 2056
ptr++;

printf("%d\n”,*ptr); //value is:20


printf(“%d\n”,ptr); // address is 2058
ptr--;

printf("%d\n”,*ptr); //value is:10


printf(“%d\n”,ptr); //address is 2056

}
}

2.If two pointers pointing to the same type of data then one pointer value can be
assigned to another.
Example: int *ptr1,*ptr2;
ptr1=ptr2;

Page 70
[Type here]

3.Pointer can be assigned a NULL.


Example: int *ptr1;

ptr=NULL;

4. Two pointers cannot be multiplied or divided directly.

5. Relational operators can be used between the pointer. Comparing pointer variable
by relational

operators.

Example: int *ptr1, *ptr2;

ptr1>ptr2, ptr1<ptr2

Comparing pointer variable

#include<stdio.h>
void main()
{
int a=10,b=6;
int *ptr1,*ptr2;
ptr1=&a;
ptr2=&b;
if(*ptr1>*ptr2)
printf(“value stored in a is greater than b\n”);
else
printf(“value stored in b is greater than a\n”);
}

POINTERS TO POINTERS
• A pointer variable which contains address of another pointer-variable is called pointer
to a pointer.

• 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, following is the declaration to declare a pointer
to a pointer of type int: int **ptr;

Page 71
[Type here]

Example: Program to illustrate pointers to pointers.

#include<stdio.h>
void main()
{
int a=10;
*ptr1, **ptr2;
ptr1=&a;
ptr2=&ptr1;
printf(“%d\n”,a);
printf(“%d\n”,&a);
printf(“%d\n”,ptr1);
printf(“%d\n”,*ptr1);
printf(“%d\n”,&ptr1);
printf(“%d\n”,ptr2);
printf(“%d\n”,*ptr2);
printf(“%d\n”,**ptr2);
}

Page 72
[Type here]

TYPES OF POINTERS
There are eight different types of pointers which are as follows −
 Null pointer
 Void pointer
 Wild pointer
 Dangling pointer
 Complex pointer
 Near pointer
 Far pointer
 Huge pointer

NULL POINTER
You create a null pointer by assigning the null value at the time of
pointer declaration.
This method is useful when you do not assign any address to the
pointer. A null pointer always contains value 0.

Example
Following is the C program for the null pointer −
Live Demo

#include <stdio.h>
int main(){
int *ptr = NULL; //null pointer
printf("The value inside variable ptr is:
%d",ptr);
return 0;
}

Output
When the above program is executed, it produces the following result

The value inside variable ptr is:
0

VOID PONTER
Page 73
[Type here]

It is a pointer that has no associated data type with it. A void pointer
can hold addresses of any type and can be typecast to any type.
It is also called a generic pointer and does not have any standard data
type.
It is created by using the keyword void.

Example
Following is the C program for the void pointer −
Live Demo

#include <stdio.h>
int main(){
void *p = NULL; //void pointer
printf("The size of pointer is:%d
",sizeof(p)); //size of p depends on compiler
return 0;
}

Output
When the above program is executed, it produces the following result

The size of pointer is:8

WILD POINTER
Wild pointers are also called uninitialized pointers. Because they point
to some arbitrary memory location and may cause a program to crash
or behave badly.
This type of C pointer is not efficient. Because they may point to some
unknown memory location which may cause problems in our program.
This may lead to the crashing of the program.
It is advised to be cautious while working with wild pointers.

Example
Following is the C program for the wild pointer −
#include <stdio.h>
int main()
{
int *p; //wild pointer

Page 74
[Type here]

printf("
%d",*p);
return 0;
}
Process returned -1073741819 (0xC0000005) execution time : 1.206 s
Press any key to continue
i.e. you won’t get output, some compilers show error message at output

Page 75
[Type here]

Passing arguments to functions using pointers


PASS BY REFERENCE ( CALL BY REFERENCE )
• In pass by reference, the formal parameters are treated as aliases
(alternate names) for actual parameters. Any change in formal parameter
will also effect the actual parameter.
• In this technique, if formal parameters changes then actual parameters are
also changes.

Example: Program to exchange two numbers using call by reference

#include<stdio.h>
void exchange(int *x, int *y);

void main()
{
int a,b;
a=10, b=20;
exchange(&a,&b); //a and b are actual parameters

printf(“a=%d\n b=%d\n”,a,b);
}

void exchange(int *x,int *y) // x and y are formal parameters


{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Output:
a=20
b=10

• The function exchange() is called by sending addresses of a and b.


• In the function header of function exchange(), the formal parameters x and
y declared using
*operator holds the address of a and b.
• In the function exchange(), using *x and *y the values of a and b
can be accessed and they are changed.
• The values of actual parameters are exchanged (a=20 and b=10). If
there are any changes in the formal parameter, then actual parameters
also changes.

Page 76
[Type here]

QUESTION BANK
1. Mention various operations that can be performed on string using
built-in functions. Explain any two functions.
2. Develop a C program using pointer to compute the sum, mean and
standard deviation of all element stored in array of N real number.
3. Explain how strings are represented in main memory.
4. Write a program to compare two strings without using built-in
function.
5. What is pointer? Discuss pointer arithmetic with suitable C code
6. Explain gets()and puts() function with example
7. Illustrate string handling function any 4 with suitable examples.
8. Explain declaration and initialization of strings
9. Write a C program to find the length of string without using built of
functions.
10.Write a C program to concatenating and comparing two strings
without using built in function
11.Write a C program to check whether the given string is palindrome or
not without using built-in function.
12.Illustrate Passing arguments to functions using pointers
13.Write a C program to Read a sentence and print frequency of vowels
and total count of consonants.
14.Write a C program to replace each constant in a string with the next
one except letter ‘z’ ‘Z’ and ‘a’ ‘A’ . Thus the string “Programming
in C is fun” should be modified as “Qsphsannjoh jo D jt gvo”

Page 77

You might also like