0% found this document useful (0 votes)
0 views47 pages

C Programming - QB Module 2

The document contains various C programming exercises focusing on arrays, including counting occurrences, displaying elements, calculating averages, and sorting. It also explains concepts like linear search, bubble sort, and matrix operations. Additionally, it provides examples of declaring and initializing single and two-dimensional arrays.

Uploaded by

Bhagya P S
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)
0 views47 pages

C Programming - QB Module 2

The document contains various C programming exercises focusing on arrays, including counting occurrences, displaying elements, calculating averages, and sorting. It also explains concepts like linear search, bubble sort, and matrix operations. Additionally, it provides examples of declaring and initializing single and two-dimensional arrays.

Uploaded by

Bhagya P S
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/ 47

C prgrogrammming -

QB module 2
1(a) C Program to Count the Number of Occurrences of a Given Number in
an Array
#include <stdio.h>

int main() {
int n, i, num, count = 0;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the number to count its occurrences: ");


scanf("%d", &num);

for(i = 0; i < n; i++) {


if(arr[i] == num) {
count++;
}
}

printf("The number %d occurs %d time(s) in the array.\n", num, count);

return 0;
}
1(b) C Program to Display All Elements from Odd Index Positions
#include <stdio.h>

int main() {
int n, i;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Elements at odd index positions are:\n");


for(i = 1; i < n; i += 2) {
printf("%d ", arr[i]);
}

printf("\n");

return 0;
}

2(a) C Program to Display All the Even Numbers from an Array


#include <stdio.h>

int main() {
int n, i;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);
int arr[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Even numbers in the array are:\n");


for(i = 0; i < n; i++) {
if(arr[i] % 2 == 0) {
printf("%d ", arr[i]);
}
}

printf("\n");

return 0;
}

2(b) C Program to Count and Display All the Odd Numbers in an Array
#include <stdio.h>

int main() {
int n, i, count = 0;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Odd numbers in the array are:\n");
for(i = 0; i < n; i++) {
if(arr[i] % 2 != 0) {
printf("%d ", arr[i]);
count++;
}
}

printf("\nTotal number of odd elements = %d\n", count);

return 0;
}

3. Write a C program to calculate the average of n numbers stored in an


array
#include <stdio.h>

int main() {
int n, i;
float sum = 0.0, average;

printf("Enter the number of elements: ");


scanf("%d", &n);

float arr[n];

printf("Enter %d numbers:\n", n);


for(i = 0; i < n; i++) {
scanf("%f", &arr[i]);
sum += arr[i];
}

average = sum / n;
printf("The average of the entered numbers is: %.2f\n", average);

return 0;
}

4. What is an array? Illustrate using an example how a single-dimensional


array is initialized. (3 Marks)

Definition:​
An array is a collection of elements of the same data type stored at contiguous
memory locations. It allows storing multiple values under a single variable name
using indexing.

Syntax (Declaration & Initialization):

int numbers[5] = {10, 20, 30, 40, 50};

In the above example:

●​ numbers is a single-dimensional array of size 5.​

●​ It stores 5 integers: 10, 20, 30, 40, and 50.​

●​ Indexing starts from 0. So, numbers[0] = 10, numbers[1] = 20, etc.

5. Write a C program to find average marks obtained by a class of 50 students


in a test using array. (3 Marks)
#include <stdio.h>

int main() {
int marks[50], i;
float sum = 0.0, average;

printf("Enter marks of 50 students:\n");


for(i = 0; i < 50; i++) {
scanf("%d", &marks[i]);
sum += marks[i];
}

average = sum / 50;

printf("Average marks of the class: %.2f\n", average);

return 0;
}

6. What are the different ways of declaring and initializing a


single-dimensional array? (3 Marks)

➤ Declaration Only:
int arr[5]; // Declares an array of 5 integers

➤ Declaration with Initialization:


int arr[5] = {1, 2, 3, 4, 5}; // Size is mentioned
int arr[] = {1, 2, 3, 4, 5}; // Size is automatically determined

➤ Partial Initialization:
int arr[5] = {1, 2}; // Remaining elements will be initialized to 0

7. Explain Linear Search with an Example (9 Marks)

✅ Definition:
Linear search (also known as sequential search) is a simple searching algorithm. It
checks each element of the array one by one until the desired element is found or
the array ends.

✅ Steps:
1.​ Start from the first element.​

2.​ Compare the target value with each element.​

3.​ If a match is found, return the index.​

4.​ If the end of the array is reached without a match, return -1 (not found).​

✅ Example Code:​
#include <stdio.h>

int main() {

int arr[5] = {10, 20, 30, 40, 50};

int key = 30, i, found = 0;

for(i = 0; i < 5; i++) {

if(arr[i] == key) {

printf("Element %d found at index %d.\n", key, i);

found = 1;

break;

if(!found) {
printf("Element %d not found in the array.\n", key);

return 0;

8. C Program to Sort an Array and Display Largest, Second Largest, and


Smallest Elements (9 Marks)​
#include <stdio.h>

int main() {

int n, i, j, temp;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);

for(i = 0; i < n; i++) {

scanf("%d", &arr[i]);

}
// Sorting in ascending order

for(i = 0; i < n - 1; i++) {

for(j = i + 1; j < n; j++) {

if(arr[i] > arr[j]) {

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

printf("Sorted array: ");

for(i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\nSmallest element: %d", arr[0]);

printf("\nSecond largest element: %d", arr[n - 2]);

printf("\nLargest element: %d\n", arr[n - 1]);


return 0;

9. C Program to Sort an Array Using Bubble Sort (9 Marks)​


#include <stdio.h>

int main() {

int n, i, j, temp;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);

for(i = 0; i < n; i++) {

scanf("%d", &arr[i]);

// Bubble Sort

for(i = 0; i < n - 1; i++) {

for(j = 0; j < n - i - 1; j++) {


if(arr[j] > arr[j + 1]) {

// Swap

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

printf("Sorted array in ascending order:\n");

for(i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

10. Write a C program to perform linear search on an array of numbers.


11. Explain the Concept of Bubble Sort with an Example (3 Marks)

✅ Definition:
Bubble Sort is a simple comparison-based sorting algorithm. It works by
repeatedly swapping adjacent elements if they are in the wrong order. This
process is repeated until the array is sorted.

✅ How It Works (Step-by-Step):


Suppose we have the array:​
[5, 3, 8, 4, 2]

Pass 1:

●​ Compare 5 and 3 → swap → [3, 5, 8, 4, 2]​

●​ Compare 5 and 8 → no swap​

●​ Compare 8 and 4 → swap → [3, 5, 4, 8, 2]​

●​ Compare 8 and 2 → swap → [3, 5, 4, 2, 8]​

Pass 2:

●​ Compare 3 and 5 → no swap​

●​ Compare 5 and 4 → swap → [3, 4, 5, 2, 8]​

●​ Compare 5 and 2 → swap → [3, 4, 2, 5, 8]​

●​ Compare 5 and 8 → no swap​



Continue this process until the array becomes fully sorted:​
Final Sorted Array: [2, 3, 4, 5, 8]

12. C Program to Find the Largest Element in an Array (3 Marks)


#include <stdio.h>

int main() {
int n, i, largest;

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

largest = arr[0]; // Assume first element is largest

for(i = 1; i < n; i++) {


if(arr[i] > largest) {
largest = arr[i];
}
}

printf("The largest element in the array is: %d\n", largest);

return 0;
}

13. C Program to Take a Matrix as Input and Print the Sum of Each Row and
Each Column (9 Marks)​
#include <stdio.h>
int main() {
int rows, cols, i, j;

printf("Enter number of rows: ");


scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

int matrix[rows][cols];

printf("Enter the elements of the matrix:\n");


for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Sum of each row


for(i = 0; i < rows; i++) {
int rowSum = 0;
for(j = 0; j < cols; j++) {
rowSum += matrix[i][j];
}
printf("Sum of row %d = %d\n", i + 1, rowSum);
}

// Sum of each column


for(j = 0; j < cols; j++) {
int colSum = 0;
for(i = 0; i < rows; i++) {
colSum += matrix[i][j];
}
printf("Sum of column %d = %d\n", j + 1, colSum);
}
return 0;
}

14. C Program to Take Two Matrices as Input and Perform Matrix


Subtraction (9 Marks)
#include <stdio.h>

int main() {
int rows, cols, i, j;

printf("Enter number of rows: ");


scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];

printf("Enter elements of first matrix:\n");


for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of second matrix:\n");


for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Matrix subtraction
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

printf("Resultant matrix after subtraction:\n");


for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

15. C Program to Display the Diagonal Values of a 10 × 10 Matrix (9 Marks)​


#include <stdio.h>

int main() {
int matrix[10][10];
int i, j;

printf("Enter elements of 10x10 matrix:\n");


for(i = 0; i < 10; i++) {
for(j = 0; j < 10; j++) {
scanf("%d", &matrix[i][j]);
}
}

printf("Diagonal elements are:\n");


for(i = 0; i < 10; i++) {
printf("%d ", matrix[i][i]);
}
printf("\n");
return 0;
}

16. Define a 3 × 4 two-dimensional integer array called n and assign values (9


Marks)​
#include <stdio.h>

int main() {
// Define and initialize the 3x4 array 'n'
int n[3][4] = {
{10, 12, 14, 16},
{20, 22, 24, 26},
{30, 32, 34, 36}
};

// Optional: Display the array elements to verify


printf("The 3x4 array elements are:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", n[i][j]);
}
printf("\n");
}

return 0;
}

17. Define a 3 × 4 two-dimensional integer array called n and assign the given
values (9 Marks)​
#include <stdio.h>

int main() {
// Define and initialize the 3x4 array 'n' with given values and zeros
int n[3][4] = {
{10, 12, 14, 16},
{20, 22, 0, 0},
{ 0, 0, 0, 0}
};

// Optional: Print the array elements to verify


printf("The 3x4 array elements are:\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 4; j++) {
printf("%d ", n[i][j]);
}
printf("\n");
}

return 0;
}

18. Different Ways of Initializing a 2D Array with Examples (3 Marks)

In C, a 2D array can be initialized in several ways. Here are some common


methods:

1. Full Initialization

You explicitly initialize every element of the 2D array.

int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

2. Partial Initialization
You can initialize only some elements; the rest are automatically set to zero.

int arr[2][3] = {
{1, 2}, // Third element is 0 by default
{4} // Second and third elements are 0 by default
};​

Resulting array:
1 2 0

4 0 0

3. Flat Initialization

You can initialize the 2D array as a flat list; the compiler fills the array row-wise.

int arr[2][3] = {1, 2, 3, 4, 5, 6};

19. Write a C program to check whether a given square matrix is an identity


matrix. (All diagonal elements must be 1 and all non-diagonal elements must
be 0. (9)

#include <stdio.h>

int main() {
int n, i, j, isIdentity = 1;

printf("Enter the size of the square matrix: ");


scanf("%d", &n);

int matrix[n][n];

printf("Enter the elements of the %dx%d matrix:\n", n, n);


for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Check identity matrix conditions


for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(i == j) {
// Diagonal elements must be 1
if(matrix[i][j] != 1) {
isIdentity = 0;
break;
}
} else {
// Non-diagonal elements must be 0
if(matrix[i][j] != 0) {
isIdentity = 0;
break;
}
}
}
if(!isIdentity) {
break;
}
}

if(isIdentity) {
printf("The matrix is an identity matrix.\n");
} else {
printf("The matrix is NOT an identity matrix.\n");
}

return 0;
}
20. C Program to Read a 2D Integer Matrix of Size m × n and Compute Its
Transpose (9 Marks)​
#include <stdio.h>

int main() {
int m, n, i, j;

printf("Enter number of rows (m): ");


scanf("%d", &m);
printf("Enter number of columns (n): ");
scanf("%d", &n);

int matrix[m][n], transpose[n][m];

printf("Enter elements of the %dx%d matrix:\n", m, n);


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Compute transpose
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Display transpose
printf("Transpose of the matrix is:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;
}

21. C Program to Read Two 2D Matrices, Perform Matrix Addition, and Print
the Sum Matrix​
#include <stdio.h>

int main() {
int m, n, i, j;

printf("Enter number of rows: ");


scanf("%d", &m);
printf("Enter number of columns: ");
scanf("%d", &n);

int matrix1[m][n], matrix2[m][n], sum[m][n];

printf("Enter elements of first matrix:\n");


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of second matrix:\n");


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Matrix addition
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Print sum matrix


printf("Sum of the two matrices is:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}

return 0;
}

22. C Program to Check Whether Two Matrices are Equal​


#include <stdio.h>

int main() {
int m, n, i, j, equal = 1;

printf("Enter number of rows: ");


scanf("%d", &m);
printf("Enter number of columns: ");
scanf("%d", &n);

int matrix1[m][n], matrix2[m][n];

printf("Enter elements of first matrix:\n");


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of second matrix:\n");


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Check equality
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
if(matrix1[i][j] != matrix2[i][j]) {
equal = 0;
break;
}
}
if(!equal) break;
}

if(equal)
printf("The matrices are equal.\n");
else
printf("The matrices are NOT equal.\n");

return 0;
}

23. C Statement to Access the Element in the Second Row and Third Column
of a Matrix​
matrix[1][2]

24. C Program to Read and Display a 3x3 Matrix


#include <stdio.h>
int main() {
int matrix[3][3], i, j;

printf("Enter elements of 3x3 matrix:\n");


for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}

printf("The 3x3 matrix is:\n");


for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

25. a) C Program Using Enum to Represent Days of the Week​


#include <stdio.h>

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main() {
enum Days today;

today = Wednesday;

printf("Day number %d\n", today); // Wednesday corresponds to 3

return 0;
}

25. b) Enum for Seasons and Switch Statement​


#include <stdio.h>

enum Seasons { Spring, Summer, Autumn, Winter };

int main() {
enum Seasons currentSeason;

currentSeason = Autumn;

switch(currentSeason) {
case Spring:
printf("It's Spring season.\n");
break;
case Summer:
printf("It's Summer season.\n");
break;
case Autumn:
printf("It's Autumn season.\n");
break;
case Winter:
printf("It's Winter season.\n");
break;
default:
printf("Invalid season.\n");
}
return 0;
}

26. What are Enumerated Data Types? Explain How Ordinal Values Are
Assigned to Their Members with Examples. Compare Enum with Typedef.

Enumerated Data Types (enum):


●​ enum is a user-defined data type in C that assigns names to integral
constants, making the code more readable.​

●​ Members of an enum are assigned ordinal (integer) values automatically,


starting from 0 by default. You can explicitly assign values to members as
well.​

Ordinal value assignment example:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

●​ Here, Sunday = 0, Monday = 1, Tuesday = 2, and so on.​

You can also assign custom values:

enum Status { Fail = 0, Pass = 1, Merit = 2, Distinction = 3 };

If you assign a value to one member, subsequent members increment by 1


automatically:

enum Colors { Red = 1, Blue, Green }; // Red=1, Blue=2, Green=3


27. Explain typedef and enum Data Types in Detail with Examples.

typedef:

●​ Used to create a new name (alias) for an existing data type.​

●​ Makes complex declarations easier to understand.​

Example:

typedef unsigned int UINT;


UINT age = 25; // Equivalent to: unsigned int age = 25;

You can also typedef structures:​


typedef struct {
int x, y;
} Point;

Point p1 = {10, 20};

enum:

●​ Defines a set of named integer constants.​

●​ Helps in representing related constants clearly.​

Example:

enum Weekday { Sun, Mon, Tue, Wed, Thu, Fri, Sat };


enum Weekday today = Wed;
printf("Today is day number %d\n", today); // Prints 3
28. Write a Simple C Program to Declare and Use an Enum.
#include <stdio.h>

enum Direction { North, East, South, West };

int main() {
enum Direction dir;
dir = South;

if(dir == South) {
printf("You are heading South.\n");
}

return 0;
}

29. Explain the Purpose of the typedef Construct in C.

●​ typedef is used to create new names (aliases) for existing data types.​

●​ It improves code readability and maintainability.​

●​ Useful when dealing with complex types like structures, pointers, or


function pointers.​

●​ Example: Instead of writing unsigned long int repeatedly, use typedef:

typedef unsigned long int ULONG;


ULONG number = 100000;
30. Explain enum Data Type in C with an Example.

●​ enum (enumeration) defines a set of named integral constants.​

●​ Helps group related constants with meaningful names.​

●​ Each enumerator has an integer value starting at 0 unless specified


otherwise.​

Example:

#include <stdio.h>

enum Month { January = 1, February, March, April, May, June, July, August,
September, October, November, December };

int main() {
enum Month currentMonth = April;
printf("Month number: %d\n", currentMonth); // Outputs 4
return 0;
}

31. What are String Handling Functions? Write a C Program to Determine


the Length of a String Using Both Built-in and Manual Method.

String Handling Functions are functions provided by C through the <string.h>


header for operations like copy, compare, concatenate, find length, etc.

Examples: strlen(), strcpy(), strcat(), strcmp(), etc.

#include <stdio.h>
#include <string.h>

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

printf("Enter a string: ");


gets(str);

// Built-in function
printf("Length using strlen(): %d\n", strlen(str));

// Manual method
for (i = 0; str[i] != '\0'; i++) {
length++;
}
printf("Length using manual method: %d\n", length);

return 0;
}

32. Write a C Program to Concatenate Two Strings Without Using Built-in


Functions​
#include <stdio.h>

int main() {
char str1[100], str2[50];
int i = 0, j = 0;

printf("Enter first string: ");


gets(str1);
printf("Enter second string: ");
gets(str2);

// Move to the end of str1


while (str1[i] != '\0') {
i++;
}
// Append str2 to str1
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';

printf("Concatenated string: %s\n", str1);


return 0;
}

33. Write a C Program to Reverse a String Without Using String Handling


Functions​
#include <stdio.h>

int main() {
char str[100];
int len = 0, i;
char temp;

printf("Enter a string: ");


gets(str);

// Find length manually


while (str[len] != '\0') {
len++;
}

// Reverse the string


for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("Reversed string: %s\n", str);
return 0;
}

34. Write a C Program to Print the Number of Vowels and Consonants in a


String​
#include <stdio.h>

int main() {
char str[100];
int i, vowels = 0, consonants = 0;

printf("Enter a string: ");


gets(str);

for (i = 0; str[i] != '\0'; i++) {


char ch = str[i];
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
ch = (ch >= 'A' && ch <= 'Z') ? ch + 32 : ch; // convert to lowercase
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}

printf("Vowels: %d\nConsonants: %d\n", vowels, consonants);


return 0;
}

35. Difference Between scanf("%s", str); and gets(str);


Example:​
char str[100];
scanf("%s", str); // Input: Hello World → Stores only "Hello"

gets(str); // Input: Hello World → Stores entire "Hello World"

36. Write a C Program to Read Your Name from the Console and Display It​
#include <stdio.h>

int main() {

char name[100];

printf("Enter your name: ");

gets(name); // You can also use fgets(name, sizeof(name), stdin);

printf("Hello, %s!\n", name);


return 0;

37. a) Write a C program to count the number of vowels in a given string. (5


Marks)
#include <stdio.h>

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

printf("Enter a string: ");


gets(str);

for (i = 0; str[i] != '\0'; i++) {


char ch = str[i];
if (ch >= 'A' && ch <= 'Z') ch += 32; // convert to lowercase
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
}

printf("Number of vowels: %d\n", vowels);


return 0;
}

38. Write a C program to check whether a string is palindrome or not without


using string handling functions​
#include <stdio.h>

int main() {
char str[100];
int i, len = 0, isPalindrome = 1;
printf("Enter a string: ");
gets(str);

// Calculate length manually


while (str[len] != '\0') {
len++;
}

for (i = 0; i < len / 2; i++) {


if (str[i] != str[len - i - 1]) {
isPalindrome = 0;
break;
}
}

if (isPalindrome)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");

return 0;
}

39. List any 4 string handling functions in C programming and explain with
examples

Here are four commonly used string handling functions from <string.h>:

1.​ strlen()​

○​ Use: Returns length of string (excluding \0)​

○​ Example:
int len = strlen("hello"); // len = 5

2. strcpy()

●​ Use: Copies one string into another​

●​ Example:

char str1[20], str2[] = "World";

strcpy(str1, str2); // str1 = "World"

3. strcat()

●​ Use: Appends one string to another​

●​ Example:

char str1[20] = "Hello ", str2[] = "World";

strcat(str1, str2); // str1 = "Hello World"

4. strcmp()

●​ Use: Compares two strings​

●​ Example:

int result = strcmp("abc", "abc"); // result = 0 (equal)


40. Write a C program to find the length of a string using a string handling
function

#include <stdio.h>

#include <string.h>

int main() {

char str[100];

printf("Enter a string: ");

gets(str);

printf("Length of string: %lu\n", strlen(str));

return 0;

41 & 42. Explain any three string handling functions in C with examples and
their syntax

43. a) C program to count the occurrence of a given character in a string (5


Marks)​
#include <stdio.h>

int main() {

char str[100], ch;

int i, count = 0;
printf("Enter a string: ");

gets(str);

printf("Enter the character to count: ");

scanf("%c", &ch);

for (i = 0; str[i] != '\0'; i++) {

if (str[i] == ch)

count++;

printf("Character '%c' occurs %d times.\n", ch, count);

return 0;

43. b) Program to count the number of spaces in a given string (4 Marks)​


#include <stdio.h>

int main() {

char str[100];

int i, spaceCount = 0;
printf("Enter a string: ");

gets(str);

for (i = 0; str[i] != '\0'; i++) {

if (str[i] == ' ')

spaceCount++;

printf("Number of spaces: %d\n", spaceCount);

return 0;

44. a) Program to find the length of a string without using string handling
functions (5 Marks)​
#include <stdio.h>

int main() {

char str[100];

int i = 0;

printf("Enter a string: ");


gets(str);

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

i++;

printf("Length of the string: %d\n", i);

return 0;

44. b) Program to replace all occurrences of a given character in a string with


another (4 Marks)​
#include <stdio.h>

int main() {

char str[100], ch1, ch2;

int i;

printf("Enter a string: ");

gets(str);

printf("Enter character to replace: ");


scanf("%c", &ch1);

getchar(); // clear newline from buffer

printf("Enter replacement character: ");

scanf("%c", &ch2);

for (i = 0; str[i] != '\0'; i++) {

if (str[i] == ch1)

str[i] = ch2;

printf("Modified string: %s\n", str);

return 0;

45. a) Program to compare two strings using the string handling function (5
Marks)​
#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];


printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

if (strcmp(str1, str2) == 0)

printf("Strings are equal.\n");

else

printf("Strings are not equal.\n");

return 0;

45. b) Program to read a string in uppercase and convert it into lowercase (4


Marks)​
#include <stdio.h>

int main() {

char str[100];

int i;

printf("Enter a string in uppercase: ");


gets(str);

for (i = 0; str[i] != '\0'; i++) {

if (str[i] >= 'A' && str[i] <= 'Z') {

str[i] = str[i] + 32;

printf("Lowercase string: %s\n", str);

return 0;

46. C program to copy content of one string into another using string handling
function

#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];

printf("Enter a string: ");

gets(str1);
strcpy(str2, str1);

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

return 0;

47. C program to concatenate two strings using the string handling function​
#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

return 0;
}

48. C program to compare two strings using the string handling function

#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

if (strcmp(str1, str2) == 0)

printf("Strings are equal.\n");

else

printf("Strings are not equal.\n");

return 0;

You might also like