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

module 3 important questions

The document covers various topics related to arrays and strings in C programming, including string handling functions, sorting algorithms, searching techniques, and matrix operations. It provides explanations, examples, and C program implementations for tasks like bubble sort, linear search, string concatenation, and checking for diagonal matrices. Additionally, it discusses string initialization, the significance of null characters, and methods to count vowels and consonants in a string.

Uploaded by

Arnav Rajesh
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)
1 views

module 3 important questions

The document covers various topics related to arrays and strings in C programming, including string handling functions, sorting algorithms, searching techniques, and matrix operations. It provides explanations, examples, and C program implementations for tasks like bubble sort, linear search, string concatenation, and checking for diagonal matrices. Additionally, it discusses string initialization, the significance of null characters, and methods to count vowels and consonants in a string.

Uploaded by

Arnav Rajesh
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/ 12

MODULE -3

ARRAYS AND STRINGS

⭐⭐1. Explain the String handling functions in C with examples.(3 marks and above)
Ans: 1. `strlen`:

Definition: `strlen` is used to calculate the length of a given string, excluding the null terminator '\0'.
Example: `int length = strlen("Hello"); // Returns 5`
2. `strcpy`:
Definition: `strcpy` copies the contents of one string to another, including the null terminator '\0'.
Example: `char destination[20]; strcpy(destination, "Hello"); // destination contains "Hello"`
3. `strcat`:
Definition: `strcat` appends the characters of the second string to the end of the first string and adds a null
terminator.
Example: `char str1[30] = "Hello"; strcat(str1, ", world!"); // str1 contains "Hello, world!"`
4. `strcmp`:
Definition: `strcmp` compares two strings lexicographically and returns an integer indicating their
relationship.
Example: `int result = strcmp("apple", "banana"); // Returns a value less than 0`
5. `puts`:
Definition: `puts` writes a string to the standard output followed by a newline character.
Example: `puts("Hello, world!"); // Outputs "Hello, world!"`
6. `gets` (Deprecated and Unsafe):
Definition: `gets` reads a line from the standard input and stores it in the provided buffer.
Example: `char name[30]; gets(name); // Reads user input into 'name' (unsafe, avoid using)`

⭐⭐2. Write a C program to perform bubble sort. (7 marks)


Ans: #include <stdio.h>
int main()
{
int n, i, j, temp;
// Input the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble sort algorithm
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
// Swap adjacent elements if they are in the wrong order
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display the sorted array
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
This program first takes the number of elements and then the array elements as input from the user. It uses
the bubble sort algorithm to sort the elements in ascending order. Finally, it prints the sorted array.

⭐⭐3. Write a C program to perform linear search on an array of numbers.(7 marks)


Ans: #include <stdio.h>
int main() {
int n, searchKey, i, found = 0;
// Input the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input the element to be searched
printf("Enter the element to search for: ");
scanf("%d", &searchKey);
// Linear search algorithm
for (i = 0; i < n; i++) {
// If the element is found, mark 'found' as 1 and break the loop
if (arr[i] == searchKey) {
found = 1;
break;
}
}
// Display the result
if (found) {
printf("Element %d found at index %d.\n", searchKey, i);
}
else {
printf("Element not found in the array.\n");
}
return 0;
}
This program first takes the number of elements and the array elements as input from the user. Then it
takes the element to be searched for. It uses a linear search algorithm to find the element in the array.
Finally, it prints whether the element is found along with its index or indicates that the element is not
present in the array.

4. Differentiate between strlen() function and sizeof() operator. (3 marks)


Ans: 1. `strlen`:
- Function: `strlen` calculates the length of a string by counting the characters until the null terminator `\0`
is encountered.
- Example:
char str[] = "Hello";
length = strlen(str); // length = 5
2. `sizeof`:
- Operator: `sizeof` is used to determine the size (in bytes) of a data type or an object.
- Example:
char str[] = "Hello";
sizeOfString = sizeof(str); // sizeOfString = 6 (including '\0')
In summary, `strlen` calculates the length of a string by counting characters, excluding the null terminator,
while `sizeof` determines the size in bytes of a data type or an object, including any padding and the null
terminator.

⭐5. How to initialise a 1-D array in C? (3 marks)

⭐6. How to initialise a 2-D array in C? (3 marks)


7. Is it preferable to use scanf() while reading a string? Why? How to overcome the issue? (3 marks)
Ans: When using `scanf("%s", str)`, it reads characters until it encounters a space, tab, or newline. After that
reading is terminated. Also, If the input string is longer than the allocated buffer size, it can overwrite
adjacent memory, leading to unpredictable behaviour or crashes.
To overcome this issue, you can use `fgets` to read strings and specify the maximum number of characters
to read. .Also 'gets' could be used.

8. What is a null character in C? Explain its significance.(3 marks)


Ans: A null character in C is represented as `'\0'` and has a value of 0. It marks the end of a string or
character array. Its significance lies in indicating to C functions that the string's content ends at that point.
It's used to determine the length of strings, making them compatible with various string manipulation
functions.

⭐⭐9. Without using any built in string processing function like strlen, strcat etc., write a program to
concatenate two strings. (7 marks)
Ans: #include <stdio.h>

int main() {
// Define two arrays to store the strings
char str1[100], str2[100];
// Input the first string
printf("Enter the first string: ");
scanf("%s", str1);
// Input the second string
printf("Enter the second string: ");
scanf("%s", str2);
// Find the length of the first string
int len1 = 0;
while (str1[len1] != '\0')
len1++;
// Concatenate the second string to the end of the first string
int i, j = 0;
for (i = len1; str2[j] != '\0'; i++, j++)
str1[i] = str2[j];
str1[i] = '\0';
// Print the concatenated string
printf("Concatenated string: %s\n", str1);
return 0;
}
This program first reads two strings from the user, then iterates through the first string to find its length.
After that, it uses a loop to concatenate the characters of the second string onto the end of the first string.
Finally, it prints the concatenated string.

10. Write a C program to check whether a given matrix is a diagonal matrix. (7 marks)
Ans: #include <stdio.h>

int main() {
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int matrix[rows][cols];
// Input the matrix elements
printf("Enter the matrix elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Check if the matrix is diagonal
int isDiagonal = 1; // Assume the matrix is diagonal
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// If an off-diagonal element is non-zero, it's not diagonal
if (i != j && matrix[i][j] != 0) {
isDiagonal = 0; // Mark the matrix as not diagonal
break; // Exit the inner loop
}
}
if (!isDiagonal) {
break; // Exit the outer loop
}
}
// Print the result
if (isDiagonal) {
printf("The matrix is a diagonal matrix.\n");
} else {
printf("The matrix is not a diagonal matrix.\n");
}
return 0;
}
This program first takes the dimensions of the matrix as input, then reads the matrix elements from the
user. It checks whether the matrix is diagonal by iterating through its elements and checking if any off-
diagonal element is non-zero. If it finds such an element, it concludes that the matrix is not diagonal.
Otherwise, it considers the matrix as diagonal and prints the appropriate result.

⭐11. Write a C program to find the transpose of a matrix.(7 marks)

Ans: #include <stdio.h>

int main() {
// Define variables for matrix dimensions
int rows, cols;
// Input number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare the matrix
int matrix[rows][cols];
// Input matrix elements
printf("Enter matrix elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Display original matrix
printf("Original matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Transpose the matrix
int transpose[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
transpose[i][j] = matrix[j][i];
}
}
// Display transposed matrix
printf("Transposed matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
This program finds the transpose of a matrix. This program takes user input for matrix dimensions and
elements, displays the original matrix, calculates the transpose, and then displays the transposed matrix.

⭐12. Write a C program to reverse a string without using string handling functions. (7 marks)

Ans: #include <stdio.h>


int main() {
// Declare a character array to store the input string
char input[100];
// Input the string from the user
printf("Enter a string: ");
scanf("%s", input);
// Calculate the length of the string
int length = 0;
while (input[length] != '\0') {
length++;
}
// Reverse the string
int start = 0;
int end = length - 1;
while (start < end) {
// Swap characters at start and end positions
char temp = input[start];
input[start] = input[end];
input[end] = temp;
// Move the start and end positions towards each other
start++;
end--;
}
// Display the reversed string
printf("Reversed string: %s\n", input);
return 0;
}
This C program reverses a string without using string handling functions. This program takes user input for
a string, calculates the length of the string, reverses the string using a two-pointer approach, and then
displays the reversed string.

⭐13. Write a C program to print number of vowels and consonants in a string. (7 marks)
Ans: #include <stdio.h>
#include <ctype.h> // Include the header for 'toupper' function
int main() {
// Declare a character array to store the input string
char input[100];
// Input the string from the user
printf("Enter a string: ");
scanf("%[^\n]", input);
// Initialize variables to count vowels and consonants
int vowels = 0, consonants = 0;
// Iterate through each character in the string
for (int i = 0; input[i] != '\0'; i++) {
// Convert the character to uppercase using 'toupper' function
char ch = toupper(input[i]);
// Check if the character is an alphabet letter
if ((ch >= 'A' && ch <= 'Z')) {
// Check if the character is a vowel
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
vowels++;
} else {
consonants++;
}
}
}
// Display the counts of vowels and consonants
printf("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants);

return 0;
}
The program takes user input for a string, iterates through each character, converts it to uppercase using
`toupper`, checks if it's an alphabet letter, and then counts vowels and consonants accordingly. Finally, it
displays the counts of vowels and consonants in the string.

14. Write a C program to find the sum and average of elements of a matrix. (7 marks)
Ans: #include <stdio.h>
int main() {
// Define variables for matrix dimensions
int rows, cols;
// Input number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare the matrix
int matrix[rows][cols];
// Input matrix elements
printf("Enter matrix elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate the sum of elements
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += matrix[i][j];
}
}
// Calculate the average of elements
float average = (float)sum / (rows * cols);
// Display the sum and average
printf("Sum of elements: %d\n", sum);
printf("Average of elements: %f\n", average);
return 0;
}
This C program calculates the sum and average of elements in a matrix. The program takes user input for
matrix dimensions and elements, calculates the sum of elements, calculates the average by dividing the
sum by the total number of elements, and then displays the sum and average.

⭐15. Write a C program that reads a string from keyboard and determines whether the string is
palindrome or not. (7 marks)
Ans: #include <stdio.h>
int main() {
// Declare a character array to store the input string
char input[100];
// Input the string from the user
printf("Enter a string: ");
scanf("%s", input);
// Calculate the length of the string
int length = 0;
while (input[length] != '\0') {
length++;
}
// Initialize a flag for palindrome check
int isPalindrome = 1; // 1 indicates palindrome, 0 indicates not palindrome
// Check if the string is a palindrome
for (int i = 0, j = length - 1; i < j; i++, j--) {
if (input[i] != input[j]) {
isPalindrome = 0;
break;
}
}
// Display whether the string is palindrome or not
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
This C program checks whether a given string is a palindrome or not. The program takes user input for a
string, calculates the length of the string, initializes a flag for palindrome check (1 for palindrome, 0 for not
palindrome), iterates through the string to compare characters from both ends using a `for` loop, and finally
displays whether the string is a palindrome or not.

You might also like