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

POP_Module 4 PPT.pptx

Uploaded by

deekshasn18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

POP_Module 4 PPT.pptx

Uploaded by

deekshasn18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Module 4

Introduction to String
• A string is a sequence of characters, terminated by a null character
‘\0’.
• ‘\0’ is automatically encountered at the end of the string.
Example: ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]
char ch[6] = “HELLO” ;
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’

STRING VARIABLE
•There is no separate data type 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 as arrays.
• Only difference is that, strings are of “char” type.

A character array or a string is declared with following syntax:


char variable_name[array_length];

Example:

char s[5] ;
Here, ch is a string which can store a maximum of 5 characters including a NULL
Character ‘\0’
Initialization of
• string character constants individually, use single quotes ' '
To initialize a string variable by assigning

Ex: ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]


char ch[6] = { 'P', 'r', 'e', 'm', '\0' } ;
‘P’ ‘r’ ‘e’ ‘m’ ‘\0’ ‘\0’

• To initialize a string variable by assigning all the characters collectively, use double quotes " "

Ex:
char ch[6] = {" Good "} ; ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]

OR ‘G’ ‘o’ ‘o’ ‘d’ ‘\0’ ‘\0’


char ch[6] = " Good " ;

Ex: ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]


char ch[6] = “Program” ; ‘P’ ‘r’ ‘o’ ‘g’ ‘r’ ‘\0’
Initialization of string

Invalid
Initialization char It is not possible to assign a
string to an array in this
str3[5]; way.

str3 = “GOOD”;

Instead, initialize the array at the time


Valid Initialization of declaration
char str3[5]= “GOOD”;
Program to illustrate the initialization of string
#include<stdio.h>
void main()
{
char s[6]={'G','o','o','d’}; //or char s[6]="Good";
printf("Value in array s[0] : %c \n", s[0]);
printf("Value in array s[1] : %c \n", s[1]);
printf("Value in array s[2] : %c \n", s[2]);
printf("Value in array s[3] : %c ", s[3]);

}
Reading & Writing Strings
1) Using Formatted input output function: (scanf and printf):
The strings can be read from the keyboard and can be displayed onto the monitor using
following two formatted functions:

• Formatted input function: scanf()


• Formatted output function: printf()
• The scanf( ) function reads strings from the keyboard and stores them in variables by using
%s format specifier.
→ %s is the format string/ control string for string.
→ %s removes all white spaces present before the string is removed.
Ex:
char a[10] ; Note: Using & operand with a string variable in the scanf statement is optional as
scanf(“%s”, a); string variable is a character array and denotes the address where the array begins.
• The printf( ) function along with the %s format specifier prints a string stored in character
array to the console.

• printf( ) function can be used to display the string data with the help of two ways.
1. Either we can pass the string data directly within the printf( ) function or
2. we can store the string data in a character array.

Example: printf(“Test string”);


OR
Example: char str[ ] = {“Test string”};
printf(%s”, str);
how much space is allocated here
char str[] = "Test string";

How Much Space is Allocated?


The space allocated for the array str includes the characters in the string plus one
extra byte for the null terminator (\0), which marks the end of the string in C.

"Test string" has 11 characters:


T, e, s, t, (space), s, t, r, i, n, g
The null terminator (\0) is automatically added at the end by the compiler.
So, the total space allocated is 12 bytes.
Program to illustrate the use of scanf() and printf()

#include<stdio.h>
void main()
{
char name[10];
printf("enter your name: \n");
scanf("%s", name);
printf("welcome: ");
printf("%s", name);
}
Output:
enter your name:
Radha welcome:
Radha
is it mandatory to mention array size in string?
Yes, in C, it is mandatory to specify the size of an array when declaring it, unless you initialize
it immediately. Here's why:
Why You Must Specify Array Size:
1.Memory Allocation: When you declare an array, the compiler needs to know how much memory
to allocate for it. Without a size, it cannot reserve memory.
2.Compiler Error: Declaring an array without a size or initialization (e.g., char name[];) will result in a
compilation error because the compiler doesn't know how much space is needed.

Situations Where Array Size Can Be Omitted:


You can omit the array size in specific cases where it can be inferred, such as during initialization:
Example 1: String Initialization
c
char name[] = "John"; // Compiler infers size as 5 (4 characters + null terminator)
Example 2: Array Initialization
c
int numbers[] = {1, 2, 3, 4, 5}; // Compiler infers size as 5
String Initialization
•Strings can be initialized as:
c
char str1[] = "Hello"; char str2[6] = "Hello"; // Includes null terminator '\0'
•But this is incorrect:
c
char str[5] = "Hello"; // ERROR: No space for '\0'
2) Using unformatted 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:

1. Unformatted input function: gets( )


2. Unformatted output function: puts( )
•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 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.

• 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 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);
printf("welcome: ");
puts(name); //same as printf(“%s”, name);
}

Output:
enter your name:
Radha
welcome: Radha
3) Using the getchar( ) and putchar( ) Functions

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

Output:
Enter a word
String
S
Usage of printf and putchar

#include<stdio.h #include<stdio.h
> void main() > void main()
{ {
char a[10]="GLOBAL" char a[10]="GLOBAL"
; ;
int i,j; int i,j;
for(i=0;i<6;i++ for(i=0;i<6;i++)
) {
{ for(j=0;j<=i;j++
for(j=0;j<=i;j++) ) putchar(a[j]);
printf("%c\t", printf("\n");
a[j]); printf("\n"); }
} }
}
STRING MANIPULATION FUNCTIONS FROM
THE BUILT-IN LIBRARY

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 handling functions.


• There are numerous functions defined in <string.h> header file.
String handling
Functions
Function Action
#include<string.h
>
strlen(s1) returns the length of a string s1
;
strcpy(s1,s2) copies string s2 string into string
; s1
strcmp(s1,s2) compares two strings, returns 0 if s1 and s2 are
; same
strcat(s1,s2) concatenates string s2 onto the end of string s1
;
strlwr() Converts the string to lowercase
letters
strupr() Converts the string to uppercase
letters
strlen() This function calculates the length of string. It takes only one
argument, i.e., string-name
The syntax is shown below:
temp_variable = strlen(string_name);

// Program to illustrate the use of strlen().


#include<stdio.h>
#include<string.h
> void main()
{
char a[21] ;
int len;
printf("Enter a string:\n");
gets(a);
len=strlen(a)
;
printf("The length of the string is: %d", len);
}
strcpy() • This function copies the content of one string to the content of another string. It
takes 2 arguments.
• The syntax is shown below:
strcpy(destination,source);
where source and destination are the name of the strings.
// Program to illustrate the use of strcpy().
#include<string.h>
#include<stdio.h>
void main()
{
char src[20],dest[20];
printf("Enter string: ");
gets(src);
strcpy(dest, src); //Content of string src is copied to string dest Output:
printf("Copied string: "); Enter string: cse
puts(dest); Copied string:
} cse
Program:
#include <stdio.h>
#include <string.h> // Include the string.h header for strcpy()

void main() {
char source[] = "Hello, World!"; // Source string
char destination[50]; // Destination string (make sure it's large enough to hold the
copied string)

// Using strcpy() to copy the content of source into destination


strcpy(destination, source);
Output:
Source string: Hello,World!
// Printing both the source and the destination strings Destination string: Hello,World!
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
}
strcmp() This function compares 2 string and returns value 0, if the 2 strings are equal.
It takes 2 arguments, i.e., name of two string to compare.
The syntax is shown below:
temp_variable=strcmp(string1,string2);
//Program to illustrate the use of strcmp().
#include<stdio.h> • Returns 0, if string1==string2
#include<string.h>
void main() • Returns value positive integer >
{ 0, if string1 > string2
char name1[21]="string", name2[21]="string"; • Returns value negative integer < 0,
int p1, p2, p3, p4; if string1 < string2
p1=strcmp(name1, name2);
p2=strcmp(name1, "String");
p3=strcmp(name1, "Lohit");
p4=strcmp("RAM", "ROM");
printf("p1=%d\np2=%d\np3=%d\np4=%d\n",p1,p2,p3
,p4);
}
Explanation:
1. p1 = 0
•strcmp(name1, name2) compares "string" with "string".
•Both strings are identical, so strcmp returns 0.
2. p2 = 32
•strcmp(name1, "String") compares "string" with "String".
•The comparison is case-sensitive, and ASCII values are used:
•The first character 's' (ASCII 115) is compared with 'S' (ASCII 83).
•Since 115 - 83 = 32, strcmp returns 32, indicating "string" is larger than "String".
3. p3 = 39
•strcmp(name1, "Lohit") compares "string" with "Lohit".
•The first character 's' (ASCII 115) is compared with 'L' (ASCII 76).
•Since 115 - 76 = 39, strcmp returns 39, indicating "string" is larger than "Lohit".
4. p4 = -1
•strcmp("RAM", "ROM") compares "RAM" with "ROM".
•The first character 'R' is identical in both strings.
•The second character 'A' (ASCII 65) is compared with 'O' (ASCII 79).
•Since 65 - 79 = -14, strcmp returns a negative value (in this case, -1).
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.
The syntax is shown below:
strcat(part1,part2);

strcat(part1,
part2);
strcat() // Example: Program to illustrate the use of strcat()
#include<stdio.h>
#include<string.h
>
void main()
{
char name1[10]="computer", name2[10]="
science"; printf("Before concatenation\n");
printf("name1= %s\n",name1);
printf("name2= %s\n",name2);
strcat(name1, name2);
printf(" \n After
concatenation\n"); printf("name1=
%s\n",name1);
printf("name2= %s\n",name2);
}
PROGRAMS ON STRINGS
WITHOUT USING BUILT IN FUNCTIONS
1. Write a C program, which reads your name from the keyboard and
outputs a list of ASCII codes, which represent your name.

#include<stdio.h>
#include<string.h
> void main()
{
char name[21]
; int i,len;
printf("Enter your name:\n");
gets(name);
len=strlen(name)
;
printf("The name is in ASCII form:\n");
for(i=0;i<len;i++)
printf("%d",name[i]);
}
2. Write a C program to find length of a string without
library using
function.
#include<stdio.h>
void main()
{
char a[21] ;
int len=0, i;
printf("Enter a string\n");
gets(a);
for(i=0;a[i]!='\0';i++
) len++;

printf("The length of the string is: %d",


len);

}
3. Write a C program to input a string, convert lowercase letters to uppercase and
vice versa without using library functions.

#include <stdio.h> for(i=0;i<len;i++)


#include<string.h> {
void main() if(a[i]>='A' && a[i]<='Z')
{ a[i]=a[i]+32;
char a[21]; else if(a[i]>='a' && a[i]<='z')
int i, len; a[i]=a[i]-32;
printf("Enter a string\n"); }
gets(a); printf("The modified string is %s",
a);
len=strlen(a); }
3. Program to concatenate two strings without using strcat( )
#include<stdio.h>
main()
{
char str1[25],str2[25];
int i=0,j=0;
printf(" Enter First String:");
gets(str1);
printf("\n Enter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0’)
{
str1[i]=str2[j];
j++; Output:
i++; Enter First String: Good
} Enter Second String: Morning
str1[i]='\0’; Concatenated String is GoodMorning
printf("\n Concatenated String is ");
puts(str1);
}
4. Program to copy one string into other without using strcpy( )

#include<stdio.h>
void main()
{
char src[100], dest[100];
int i;
printf("Enter string:");
gets(src);
i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++; Output:
} Enter string : Laptop
dest[i] = '\0'; Copied String : Laptop
printf("Copied String ; %s ", dest);
}
5. Program to compare 2 strings without using strcmp( ).
#include<stdio.h>
void main() if (flag==0 && str1[i]=='\0' && str2[i]=='\0’)
{ printf("Both strings are equal");
char str1[100],str2[100]; else
int i=0,flag=0; printf("Both strings are not equal");
printf("Enter first string: "); }
scanf("%s",str1);
printf("Enter second string: ");
scanf("%s",str2);

while(str1[i]!='\0' && str2[i]!='\0')


{
if(str1[i]!=str2[i])
{
Output:
flag=1;
Enter first string: Rama
break; Enter second string: Rama
} Both strings are equal
i++;
}
6. Write a C program Check for Palindrome string without using library function
#include <stdio.h> int main() {
#include <string.h> // Checking if the given strings are palindromes
printf("String 1: ");
void isPalindrome(char str[]) { isPalindrome("madam");
int len = strlen(str);
int i = 0, j = len - 1; printf("String 2: ");
isPalindrome("sir");
while (i < j) {
if (str[i] != str[j]) { return 0;
printf("not a palindrome.\n"); }
return; // Exit the function if characters don't match
}
i++;
j--;
}

printf("palindrome.\n");
}
7. Write a C program to find total number of alphabets, digits in a string without using
library functions.
#include <stdio.h> for(i=0;i<len;i++)
#include<string.h> {
void main() if((a[i]>='A' && a[i]<='Z') || (a[i]>='a' && a[i]<='z'))
{ alpha++;
char a[21]; else if(a[i]>='0' && a[i]<='9')
int i, len, alpha=0, digit=0; digit++;
printf("Enter a string\n"); }
gets(a); printf("No. of alphabets=%d\nNo. of digits=%d", alpha, digit);
len=strlen(a); }
8. Write a C program to count total number of vowels and consonants in a
string.
#include<stdio.h> for(i=0;i<len;i++)
#include<string.h> {
void main() if (isalpha(a[i]))
{ {
char a[21]; if(a[i]=='A' || a[i]=='E' || a[i]=='I' || a[i]== 'O' || a[i]=='U')
int i, len, vow=0, cons=0; vow++;
printf("Enter a string\n"); else cons++;
gets(a); }
strupr(a); }
len=strlen(a); printf("No. of vowels = %d\n", vow);
printf("No. of consonants = %d\n", cons);
}
Creating an Array of Strings
• An array of strings that is known as two-dimensional character array, which
consists of strings as its individual elements.
• The order of the subscripts in the array declaration is important. The first subscript
gives the number of strings in the array, while the second subscript gives the
length of each string in the array.
Syntax:
char arr_name[row][col];
→ col indicates maximum length of each string.
→ row indicates number of string

Example:
char alpha[3][5] = {“pawan”, “pooja”, “punya”} ;
The names would be stored in the memory as shown in the below Figure.
Note that each string ends with a “\0”. The arrangement is similar to that of a
two-dimensional numeric array.
C Program for Creating and Displaying an Array of String

#include<stdio.h>
void main()
{
int i;
char alpha[3][6] = {“Pawan”, “Pooja”, “Punya”} ;
for(i=0;i<3;i++)
{
printf("%s \t",alpha[i]);
}
}
POINTERS
INTRODUCTION TO POINTERS
• A pointer is a variable which stores the address of another variable.
• A pointer is a derive data type in ‘C’.
• Pointers can be used to access and manipulate data stored in
memory.

UNDERSTANDING POINTERS
• The computer memory is a sequential
collection of storage cells as shown in the
figure.
• The address is associated with a number
starting of ‘0’.
• The last address depends on memory size.
• If computer system as has 64KB memory
then, its last address is 655635
REPRESENATTION OF A VARIABLE
Ex: int quantity = 179;
In the above example quantity is integer variable and puts the value 179 in a specific location during the
execution of a program.
The system always associate the name “quantity” within the address chosen by system. (Ex: 5000)
Variabl Value Address
Pointer Variables: e

Quantit 113 7000


y

int *p;
p=&quantity;

Here, the variable P contains the address of the variable quantity. Hence, we can say that variable ‘P’
points to the variable quantity. Thus ‘P’ gets the name Pointer.
NOTE 1:

• Pointer Constant: Memory addresses within a computer are referred to as pointer


constants. We can’t change them but, we can store values in it.
• Pointer Values: Pointer values is the value obtained using address operator.
• Pointer Variables: The variable that contains pointer value.

NOTE 2:

Pointer uses two operators:


1. The address operator (&) - It gives the address of an object.
2. The indirection operator (*) - It is used to access object the pointer points to.
ACCESSING THE ADDRESS OF A VARIABLE

The actual location of a variable in the memory is system


dependent and therefore the address of a variable is not known
to us immediately.

• Therefore the operator (&) and immediately preceding


variable returns the address of the variable associated
with it.

Example:
int *p;
p = &quantity;
Declaring Pointer Variables
A 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.

Syntax:
data_type *ptrname;

Where,
data_type → It specifies the type of pointer variable that you want to declare
int,
float, char and double
etc.
*(Asterisk) → Tells the compiler that you are creating a pointer variable.
ptrname → Specifies the name of the pointer variable.
INITIALIZATION OF POINTER VARIABLE
The process of assigning address of a variable to a pointer variable is known
as Initialization.
Syntax:
data_type *ptrname= &expression
Where,
data_type → It can be any basic datatype.
ptrname → It is pointer variable
expression → It can be constant value or any variable containing value.

Ex: int a;
int *p = &a; // &a is stored in p variable
Null Pointers

We can initialize pointer variable to NULL or Zero.


int *p = NULL;

int *p = 0;
Generic Pointers
• 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.
• It is declared like a normal pointer variable but using the void keyword as the
pointer's data type.

• Syntax:
void *ptr;
Passing arguments to function using pointers

While using pointers to pass arguments to a function, the calling function


must pass addresses of the variables as arguments and the called function
must dereference the arguments to use them in the function body for
processing.

To use pointers for passing arguments to a function, the programmer must do the
following:

• Declare the function parameters as pointers

• Use the dereferenced pointers in the function body

• Pass the addresses as the actual argument when the function is called.
Programs that pass pointer variables as parameters to functions in C.

1. Write a C program to swap two integer values using pointers


#include<stdio.h>
void swap(int *,int *);
void main() {
int m,n;
printf("enter values for a and b:");
scanf("%d %d",&m,&n);
printf("the values before swapping are m=%d n=%d \n",m,n);
swap(&m,&n);
printf("the values after swapping are m=%d n=%d \n",m,n);
}

void swap(int *a, int *b){


int temp;
temp=*a;
*a=*b;
*b=temp;
}
2. To find the largest of three numbers using pointers
3. Write a program to add two integers using functions
#include <stdio.h>

int add(int num1, int num2) {


return num1 + num2;
}

int main() {
int a, b, sum;
printf("Enter the first integer: ");
scanf("%d", &a);
printf("Enter the second integer: ");
scanf("%d", &b);
sum = add(a, b); Output:
Enter the first integer: 10
printf("The sum of %d and %d is: %d\n", a, b, sum); Enter the second integer: 20
return 0; The sum of 10 and 20 is: 30
}
4. Using pointers perform add, subtract, multiply and divide two numbers with input and output.
#include <stdio.h> int main() {
int num1, num2, sum, diff, prod;
void add(int *a, int *b, int *result) { float quotient;
*result = *a + *b;
} printf("Enter first number: ");
scanf("%d", &num1);
void subtract(int *a, int *b, int *result) { printf("Enter second number: ");
*result = *a - *b; scanf("%d", &num2);
}
add(&num1, &num2, &sum);
void multiply(int *a, int *b, int *result) { subtract(&num1, &num2, &diff);
*result = *a * *b; multiply(&num1, &num2, &prod);
} divide(&num1, &num2, &quotient);
void divide(int *a, int *b, float *result) { printf("Sum: %d\n", sum); Output:
if (*b != 0) { printf("Difference: %d\n", diff); Enter first number: 10
*result = (float)*a / *b; printf("Product: %d\n", prod); Enter second number: 5
} else { printf("Quotient: %.2f\n", quotient); Sum: 15
printf("Error! Division by zero.\n");
Difference: 5
*result = 0; return 0; Product: 50
} } Quotient: 2.00
}
Thank You

You might also like