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

Modue 2

Uploaded by

stickman8068
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)
10 views

Modue 2

Uploaded by

stickman8068
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/ 35

Module 2

CHAPTER 11 Strings

Q1 Differentiate between fixed and variable length string


with example.

Fixed Length String Variable Length String

1. Fixed length strings 1. Variable length


always occupy the strings can change
same size regardless of in size based on the
the content. content they hold.

2. A fixed length string 2. A variable length


contains a set number string can contain
of characters. any number of
characters.
3. name - “John “
3. message = “Hello
world”

Q2. Define strings. Explain two ways of string declaration,


string initialisation. Give example for all.
A string is a sequence of characters terminated by a null character .
Null character is automatically encountered at the end of the string.
Ex: "Hello World";
String Declaration:
String declaration defines memory for a string when it is declared as
an array in local memory.
There are two different ways to declare and define a string. They are:
a. Memory is allocated for future characters:
The name of the string is a pointer constant. we don't need to worry
about allocating memory because the declaration is for an array and
memory allocation is automatic. we can read data into the string and
change data in the string as necessary.
Ex:char str[9];
b. Allocates memory for a pointer variable:
In this case however, no memory is allocated for the string itself.
Before we can use the string in any way we need to allocate memory
for it. Any attempt to use the string before memories allocated is a
logic error that may destroy memory contents and cause our
program to fail.
Ex:char* ptr;
Initialising strings:
We can initialize a string the same way that we initialize any storage
structure by assigning a value to it when it is defined. In this case the
value is a string literal.
Ex: to assign "Good Day" to a string, we would code
Char str[9]="Good Day";
The two ways to initialise the strings are:
a. A common method used to assign a string literal to a character
pointer, as shown below. This creates a string for the literal and then
stores its address in the string pointer variable, pStr.
Ex: pStr="Good Day";
b. We can also initialise a string as an array of characters.This method
is not used too often because it is so tedious to code.Note that in this
example, we must ensure that the null character is at the end of the
string.
Ex: char str[9]={'G','o','o','d', ' ', 'D','a','y','\0'};
Q3 Explain with example programs string input and output
functions.

The function gets() and puts( ) are called line oriented I/O functions
and can be used to process entire line. The gets() function can be
used to read entire line including white spaces. The puts() function
can be used to print the line.
 Reading a string using gets(): The general for of gets function is
as given below
gets(str);
 Printing a string using puts(): The general form of puts function
is as given below
puts(str);
PROGRAM :
#include <stdio.h>
void main()
{
char name[7];
printf("Enter your name \n");
gets(name);
printf("Your name is \n");
puts(name);
}
Output:
1)Enter your name: Sahil
Your name is: Sahil
2)Enter your name: Prasad
Your name is: Prasad

Q4 Explain string manipulation function with syntax and


example programs
The standard library string.h contains many function for string
manipulation. Some of string manipulation functions used in C are :
1. strlen()
2. strcpy()
3. strcmp()
4. strcat()
5. strupr()
6. strlwr()
1.strlen():
This function is used to find the length of the string in
bytes.
The general form of a call to strlen() is the following:
length = strlen(str);
PROGRAM:
#include <stdio.h>
#include <string.h>
void main()
{
char str[20];
int len;
printf("Enter a string \n");
scanf("%s",str);
len = strlen(str);
printf("Length of the given string is %d",len);
}
Output:
1.Enter a string
Vikas
Length of the given string is 5
2. Enter a string
PROGRAM
Length of the given string is 7
2.strcpy():
This function copies the string from one variable to another
variable. The strcpy() function will copy the entire string including
the terminating null character to the new location.
Syntax :
strcpy(dest,source);
PROGRAM:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20],str2[20];
printf("Enter a string \n");
scanf("%s",str1);
strcpy(str2,str1);
printf("The String of str1: %s\n",str1);
printf("The string of str2 : %s\n",str2);
}
Output:
1.Enter a string
Revanth
The String of str1: Revanth
The string of str2 : Revanth
2. Enter a string
KKR
The String of str1: KKR
The string of str2 : KKR
3.strcmp():
It is used to compare one string with another and it is case
sensitive.
Syntax:
result = strcmp(first,second);
PROGRAM:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20] = "appa",str2[20] = "amma";
int n;
printf("The string are %s and %s\n",str1,str2);
n = strcmp(str1,str2);
if(n==0)
{
printf("Both the string are equal.");
}
else
{
printf("String are not equal.");
}
}
Output:
The string are appa and amma
String are not equal.
4.strcat():
This function is used to concatenate two strings. The resulting
string has only one null character at the end.
Syntax:
strcat(first,second);
PROGRAM:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20] = "Shakthi",str2[20] = "vel";
printf("The string are %s and %s\n",str1,str2);
strcat(str1,str2);
printf("The concatenated string is %s\n",str1);
}
Output:
The string are Shakthi and vel
The concatenated string is Shakthivel
5.strupr():
This function converts lowercase character to uppercase.
Syntax:
strupr(str);
PROGRAM:
#include <stdio.h>
#include <string.h>

void main()
{
char lwr[30];
printf("Enter a string of lower case characters : ");
scanf("%s",lwr);
strupr(lwr);
printf("The Entered string in upper case character is :%s",lwr);
}
Output:
1.Enter a string of lower case characters : prashanth
The Entered string in upper case character is :PRASHANTH
2.Enter a string of lower case characters : sai
The Entered string in upper case character is :SAI
6.strlwr():
This function coverts uppercase characters to lowercase.
Syntax:
strlwr(str);
PROGRAM:
#include <stdio.h>
#include <string.h>
void main()
{
char upr[30];
printf("Enter a string of upper case characters : ");
scanf("%s",upr);
strlwr(upr);
printf("The Entered string in lower case character is :%s",upr);
}
Output:
1.Enter a string of upper case characters : RCB
The Entered string in lower case character is :rcb
2.Enter a string of upper case characters : CSK
The Entered string in lower case character is :csk

Q5. Explain array of strings with example.


In C programming ,an array of string is essentially an array of
characters, where each element in the array represent the string:
1.DECLERATION: you can declare the strings using the below syntax:
char array_name[size][max_length];
 array_name is the name of the array
 size is the number of strings in the array
 max_length is the maximum length of each string(including the
null character)
2.INTIALIZATION: after declaring the array, you can initialize it by
assigning strings to each element
For example: char fruits[3][20]={“apple”, “orange” ,”papaya”};
Here, fruits is an array of 3 strings ,each of 20 characters
3.ACCESSING ELEMENTS: you can access individual strings using
array indexing.
For example: fruit[0]refers to the first string(“apple”)
EXAMPLAR PROGRAM FOR THE ABOVE:
#include<stdio.h>
#include<string.h>
int main()
{
char fruits[3][20]={“apple”, “orange, “papaya”};
for(int i=0;i<3;i++)
{
printf(“string%d:%s\n”,i,fruits[i]);
}
return 0;
}
Output :
string apple ,orange ,papaya

Q6. Explain sscanf and sprint with example programs.


Sscanf( )
 sscanf() is a function in the C programming language used to
read formatted input from a string.
 It stands for "String Scan Formatted".
 It is part of the C Standard Library and is declared in the
<stdio.h> header file.
Syntax:
The function prototype of sscanf() is:
int sscanf(const char *str, const char *format, ...);
 str is the string from which data is to be read.
 format is a format string that specifies how to interpret the data
in the string str.
 The ellipsis ... indicates that sscanf() can accept a variable
number of arguments. These arguments are pointers to the
variables where the extracted data will be stored.
NOTE:
 Sscanf() is one-to-many function.
 It splits one string into many variables.

EXAMPLE:
#include <stdio.h>

int main() {

char str[] = "John 25 123.45";

char name[20];
int age;
float salary;

sscanf(str, "%s %d %f", name, &age, &salary);

printf("Name: %s\n", name);


printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);

return 0;
}

OUTPUT:
Name: John
Age: 25
Salary: 123.45
sprintf( )
 sprintf() is a function in the C programming language used to
write formatted data to a string.
 It stands for "String Print Formatted".
 It is part of the C Standard Library and is declared in the
<stdio.h> header file.
Syntax:
The function prototype of sprintf() is:

int sprintf(char *str, const char *format, ...);

 str is the character array (string) where the formatted data will
be stored.

 format is a format string that specifies how the data should be


formatted.

 The ellipsis ... indicates that sprintf() can accept a variable


number of arguments. These arguments are the values to be
formatted and inserted into the string according to the format
string.

EXAMPLE:
#include <stdio.h>
int main() {
char str[100];
int age = 25;
float salary = 123.45;
sprintf(str, "My age is %d and my salary is %.2f", age, salary);
printf("%s\n", str);
return 0;
}
OUTPUT:
My age is 25 and my salary is 123.45

Q7 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>
int main()
{
char name[21];
int i,len;
printf("Enter your name : \n");
gets(name);
len = strlen(name);
printf("The name is ASCII form : \n");
for(i=0;i<len;i++)
{
printf("%d\t",name[i]);
}
return 0;
}
OUTPUT:
1.Enter your name :
Veeru
The name is ASCII form :
86 101 101 114 117
2. Enter your name :
Abi
The name is ASCII form :
65 98 105

Q8. Write a C program to find length of a string without


using library function.

#include <stdio.h>
void main() {
char a[21];
int length = 0;
printf("Enter a string: ");
gets(a);
for (int i = 0; a[i] != '\0'; i++) {
length++;
}
printf("The length of the string is: %d\n", length);
}

Output :
1.Enter a string : Helloworld
The length of the string is: 10

2. Enter a string : Global


The length of the string is : 6

Q9 Write a C program to input a string, convert lowercase


letters to uppercase and vice versa without using library
functions.
#include <stdio.h > .
#include<string.h>
void main()
{
char a[21];
int i, len;
printf("Enter a string\n");
gets(a);
len=strlen(a);
for(i=0;i<len;i++)
{
if(a[i]>='A' && a[i]<='Z')
a[i]=a[i]+32;
else if(a[i]>='a' && a[i]<='z')
a[i]=a[i]-32;
}
printf("The modified string is %s", a);
}
OUTPUT-1
Enter a string: global .
The modified string is GLOBAL.
OUTPUT-2
Enter a string: TECHNOLOGY.
The modified string is: technology.

Q10 Write a C program to find total number of alphabets,


digits in a string without using library functions.

#include <stdio.h>

int main() {
char str[100];
int alphabets = 0, digits = 0, i = 0;

printf("Enter a string: ");


scanf("%[^\n]", str);

while (str[i] != '\0') {


if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
alphabets++;
}
else if (str[i] >= '0' && str[i] <= '9') {
digits++;
}
i++;
}

printf("Total number of alphabets: %d\n", alphabets);


printf("Total number of digits: %d\n", digits);
return 0;
}

Outputs:
1) Enter a string: 4 6 8
Total number of alphabets: 0
Total number of digits: 3

2) Enter a string: T 8 H K 9 R 0 0
Total number of alphabets: 4
Total number of digits: 4

Q11 Write a c program to count total number of vowels and


consonants in a string.
#include<stdio.h>
#include<string.h>
void main()
{
char a[21];
int i,len,vow=0,cons=0;
printf(“Enter a string : \n”);
gets(a);
strupr(a);
len=strlrn(a);
for(i=0;i<len;i++)
{
if(isalpha(a[i]))
{
if(a[i]==’A’||a[i]==’E’||a[i]==’I’||a[i]==’O’||a[i]==’U’)
vow++;
else
cons++;
}
}
printf(“Number of vowels = %d\n”,vow);
printf(“Number of consonants = %d\n”,cons);
}

OUTPUT 1 : Enter a string : TajMahal


Number of vowels : 3
Number of consonants : 5
OUTPUT 2 : Enter a string : Employee
Number of vowels : 4
Number of consonants : 4

Q12.Write a C program to Sort String Characters.

#include<stdio.h>
#include<string.h>
int main (void)
{
char string = ”welcometocprogramming”;
char temp;
int i,j;
int n = strlen(string);
printf(“String before sorting - %s \n”,string);
for (i = 0 ; i < n-1 ; i++)
{
for (j = i+1 ; j<n ; j++)
{
if (string[i] > string[j])
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
printf(“String after sorting - %s \n”,string);
return 0;
}
OUTPUT:
String before sorting – welcometocprogramming
String after sorting – acceeggilmmmnoooprrtw

Q13. Write a C Program to Reverse String .

#include <stdio.h>
int main()
{
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to store reverse string
int length = 0;
int loop = 0;
while(s1[length] != ‘\0’)
{
length++;
}
printf("\n Printing in reverse - ");
for(loop = --length; loop>=0; loop--)
printf("%c", s1[loop]);
return 0;
}

OUTPUT:
1. Printing in reverse - lahaMjaT

Q14. Write a C program to copy a string without using


library function.

#include <stdio.h>

void stringCopy(char *a, char *b) {


int i = 0;
while (a[i] != '\0') {
b[i] = a[i];
i++;
}
b[i] = '\0';
}

int main() {
char a[20];
printf("Enter the string :");
gets(a);
char b[20];

stringCopy(a, b);

printf("Copied string: %s\n", b);


return 0;
}

Output:
1.
Enter the string :Hello
Copied string: Hello
2.
Enter the string :World
Copied string: World

Q15 Write a c program to compare two strings without


using library function.

#include<stdio.h>
Int main()
{
Char s1[ ]=”advise”;
Char s2[ ]=”advice”;
Int n=0;
Int flag=1;
while(s1[n]!=’\o’)
{
If(s1[n]!=s2[n])
{
flag=0;
break;
}
n++;
}
If(flag==1)
{
Printf(“%s and %s are identical\n”,s1,s2);
}
else
{
Printf(“%s and %s are NOT identical\n”,s1,s2);
}
return 0;
}
OUTPUT:
advise and advice are NOT identical

Q16. CONCATENATE OF STRINGS WITH USING A C


PROGRAM
#include<stdio.h>
#include<string.h>
Int main()
{
char s1[10]= “Taj”;
char s2[]= “Mahal”;
int i,j,n1,n2,n;
n1=strlen(s1);
n2=strlen(s2);
n=n1+n2;
j=0;
for(i=n1;i<n;i++)
{
s1[i]=s2[j];
j++;
}
s1[i]= ‘\0’;
printf(“%s”,s1);
return 0;
}
OUTPUT :
Taj Mahal

Q17 Write a c program to find total number of alphabets ,


digits in a string.
Ans) #include <stdio.h>
#include <ctype.h>
void main()
{

int i=0,alphabets=0,digits=0;

char str[100];

printf("Enter a string: \n");

gets(str);

while(str[i] != '\0')

if(isalpha(str[i]) != 0) alphabets++;

else if(isdigit(str[i]) != 0) digits++;

i++;

printf("Number of alphabets = %d \n",alphabets);

printf("Number of digits = %d\n",digits);

OUTPUT 1 : Enter a string : Global 2024


Number of alphabets : 6
Number of digits : 4
OUTPUT 2 : Enter a string : Independence 1947
Number of alphabets = 12

Number of digits = 4
Q18. Write a c program to write vowels and consonants in a
string.
#include<stdio.h>
#include<string.h>
Void main()
{
Char a[21];
Int I,len,vow=0,cons=0;
Printf(“enter the string\n”);
Gets(a);
Strupr(a);
Len=strlen(a);
For(i=0;i<len;i++)
{
If(isalpha(a[i]))
{
If(a[i]==’A’||a[i]==’E’||a[i]==’I’||a[i]==’O’||a[i]==’U’)vow++;
Else cons++;
}
}
Printf(“no. of vowels = %d\n”,vow);
Printf(“no. of consonants = %d\n”,cons);
}
Output:
1.Enter the string: Hello world
No of vowels: 3
No of consonants: 7
Q19. Write a C program that uses a function to reverse the
elements of an array in place. The function must accept
only one pointer value and return void.
Logic: The revArray function accepts a pointer to the array and its size
as arguments. It iterates through the first half of the array and swaps
the elements with their corresponding elements from the second
half, effectively reversing the array in place.
In the main function, the user inputs the size of the array and its
elements. The original array is printed. The revArray function is called
to reverse the array. The reversed array is printed.
Program:
#include <stdio.h>
void revArray(int *array, int size) {
int temp;
for (int i = 0; i < size / 2; i++) {
temp = array[i];
array[i] = array[size - i - 1];
array[size - i - 1] = temp;
}
}
int main() {
int size, array[100], i;
printf("c ");
scanf("%d", &size);
printf("Enter %d elements for the array:\n", size);
for (i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
printf("Original array: ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
revArray(array, size);
printf("Reversed array: ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
Output: 1. Enter the size of the array: 3
Enter 3 elements for the array: 2 5 7
Original array: 2 5 7
Reversed array: 7 5 2
2. Enter the size of the array: 5
Enter 3 elements for the array: 2 4 6 8
Original array: 2 4 6 8
Reversed array: 8 6 4 2
Q20. Write a C program using functions to read values
from keyboard into a two-dimensional array, create two
one-dimensional arrays that contain row and column
averages.
Logic: The data structure for calculating row average and column
average is as shown:
The program begins by requesting the user to provide data for a two
dimensional array. For a twodimensional array, a function reading
values from keyboard usually requires nested for loops. If the array is
an n by m array, the first loop varies the row from zero to n — 1. The
second loop varies the column from zero to m – 1.
Once the array has been filled, the program calculates the average of
each row and places it in a parallel array of row averages. It then
calculates the average for each column and places it in an array of
column averages. Although we have represented the column average
array horizontally and the row average array vertically, they are both
one-dimensional arrays.
When all the calculations are complete, the program calls a function
to print the array with the row averages at the end of each row and
the column averages at the bottom of each column.
Program:
#include <stdio.h>
#define MAX_ROWS 3
#define MAX_COLS 4
void getData(int table[][MAX_COLS]);
void rowAverage(int table[][MAX_COLS],float rowAvrg[]);
void colAverage(int table[][MAX_COLS], float colAvrg[]);
void printTables(int table[][MAX_COLS],float rowAvrg[],
float colAvrg[]);
int main (void){
int table[MAX_ROWS][MAX_COLS];
float rowAve[MAX_ROWS] = {0};
float colAve[MAX_COLS] = {0};
getData(table);
rowAverage(table, rowAve);
colAverage(table, colAve);
printf( "\n" );
printTables(table, rowAve, colAve);
return 0;
}
void getData(int table[][MAX_COLS]){
int row, col;
for (row = 0; row < MAX_ROWS; row++)
for (col = 0; col < MAX_COLS; col++){
printf("\nEnter integer and press Enter key: ");
scanf("%d",&table[row][col]);
}
return;
}
void rowAverage ( int table[][MAX_COLS],float rowAvrg []){
for ( int row = 0; row < MAX_ROWS; row++){
for ( int col = 0; col < MAX_COLS; col++)
rowAvrg[row] += table [row][col];
rowAvrg[row] /= MAX_COLS;
}
return;
}
void colAverage ( int table[][MAX_COLS],float colAvrg []){
for ( int col = 0; col < MAX_COLS; col++) {
for ( int row = 0; row < MAX_ROWS; row++)
colAvrg[col] += table [row][col];
colAvrg[col] /= MAX_ROWS;
}
return;
}
void printTables (int table[ ][MAX_COLS], float rowAvrg[],
float colAvrg[]){
for (int row = 0; row<MAX_ROWS; row++)
{
for (int col=0; col< MAX_COLS; col++)
printf("%6d", table[row][col]);
printf("%6.2f\n", rowAvrg[row]);
}
printf("_________________________________\n");

for (int col = 0; col < MAX_COLS; col++)


printf("%6.2f", colAvrg[col]);
return;
}
Output:
28 43 72
79 23 70
55 39 69
1 41 40
Average of rows are:
Row 1=47
Row 2=57
Row 3=54
Row 4=27
Average of columns are:
Column 1=40
Column 2=36
Column 3=62
Q21. Write a C program that uses a function that inserts a
string into another string at a specified position. It should
return a positive number if it is successful or zero if it has
any problems, such as an insertion location greater than the
length of the receiving string. The first parameter is the
receiving string, the second parameter is the string to be
inserted, and the third parameter is the insertion (index)
position in the first string.
Logic: The function myInsertString inserts a string into another string
at a specified position. This function takes three parameters: receiver
(the receiving string), insertion (the string to be inserted), and
position (the insertion position in the receiving string). It first
calculates the lengths of the receiver and insertion strings using
function strlen. Then it checks if the insertion position is valid. If it is
not (i.e., less than 0 or greater than the length of the receiver string),
it returns 0 to indicate failure. If the insertion position is valid, it shifts
the characters in the receiver string to make space for the insertion.
Finally, it copies the insertion string into the receiver at the specified
position and returns 1 to indicate success.
The main function prompts the user to enter the receiving string, the
string to be inserted, and the insertion position. It then calls the
myInsertString function and outputs an appropriate message based
on the result. If the insertion is successful, it also outputs the
resulting string.
Program:
#include <stdio.h>
#include <string.h>
int myInsertString(char *receiver, const char *insertion, int
position) {
int i;
int receiverLength = strlen(receiver);
int insertionLength = strlen(insertion);
if (position < 0 || position > receiverLength) {
return 0;
}
for (i = receiverLength; i >= position; i--) {
receiver[i + insertionLength] = receiver[i];
}
for (i = 0; i < insertionLength; i++) {
receiver[position + i] = insertion[i];
}
return 1;
}
int main() {
char receiver[100];
char insertion[100];
int position;
printf("Enter the receiving string: ");
scanf("%s", receiver);
printf("Enter the string to be inserted: ");
scanf("%s", insertion);
printf("Enter the insertion position: ");
scanf("%d", &position);
if (myInsertString(receiver, insertion, position)) {
printf("After insertion: %s\n", receiver);
} else {
printf("Invalid insertion position!\n");
}
return 0;
}
Output: 1 Enter the receiving string: TAJ
Enter the string to be inserted: MAHAL
Enter the insertion position: 1
After insertion: TMAHALAJ

2 Enter the receiving string: QUTUB


Enter the string to be inserted: MINAR
Enter the insertion position: 5
After insertion: QUTUBMINAR

You might also like