POP_Module 4 PPT.pptx
POP_Module 4 PPT.pptx
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.
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
• 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]
Invalid
Initialization char It is not possible to assign a
string to an array in this
str3[5]; way.
str3 = “GOOD”;
}
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:
• 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.
#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.
• 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
void main() {
char source[] = "Hello, World!"; // Source string
char destination[50]; // Destination string (make sure it's large enough to hold the
copied string)
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++;
}
3. Write a C program to input a string, convert lowercase letters to uppercase and
vice versa without using library functions.
#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);
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
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:
NOTE 2:
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
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
To use pointers for passing arguments to a function, the programmer must do the
following:
• Pass the addresses as the actual argument when the function is called.
Programs that pass pointer variables as parameters to functions in C.
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, "ient);
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