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

Array - Practice Problems

The document discusses different ways to manipulate and analyze data stored in arrays in C programming language. It provides code snippets to perform operations like replacing an element, counting occurrences, finding maximum/minimum elements, their indices, 2nd/3rd maximum/minimum, indices of a given element and counting its occurrences.

Uploaded by

niloypandit.1408
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Array - Practice Problems

The document discusses different ways to manipulate and analyze data stored in arrays in C programming language. It provides code snippets to perform operations like replacing an element, counting occurrences, finding maximum/minimum elements, their indices, 2nd/3rd maximum/minimum, indices of a given element and counting its occurrences.

Uploaded by

niloypandit.1408
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1D Array:

1. Write a C program to replace the value at a given index.


#include <stdio.h>

int main()
{
// Declare an array of 5 integers and initialize it
int array[5] = {10, 20, 30, 40, 50};
int size = 5; // Size of the array
int index, value; // Index and value to be replaced

// Print the original array


printf("The original array is: ");
for(int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");

// Input the index and the value from the user


printf("Enter the index to be replaced: ");
scanf("%d", &index);
printf("Enter the new value: ");
scanf("%d", &value);

// Check if the index is valid


if(index >= 0 && index < size)
{
// Replace the value at the given index
array[index] = value;

// Print the updated array


printf("The updated array is: ");
for(int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
else
{
// Invalid index
printf("Invalid index.\n");
}
return 0;
}
2. Write a C program to count the occurrences of a number in an array.
#include <stdio.h>

int main() {
// Declare and initialize an array of integers
int arr[] = {1, 4, 1, 2, 7, 1, 2, 5, 3, 6};
int n = sizeof(arr) / sizeof(arr[0]); // Get the size of the array

// Initialize variables to track the mode and its frequency


int mode = arr[0];
int max_freq = 1;

// Loop through the original array


for (int i = 0; i < n; i++) {
int current_element = arr[i];
int current_freq = 1;

// Check for duplicates in the remaining part of the array


for (int j = i + 1; j < n; j++) {
if (arr[j] == current_element) {
current_freq++;
}
}

// Update mode and frequency if a new mode is found


if (current_freq > max_freq) {
mode = current_element;
max_freq = current_freq;
}
}

// Print the mode and its frequency


printf("Mode: %d\n", mode);
printf("%d occurs %d times\n", mode, max_freq);

return 0;
}
#include <stdio.h>

int main() {
// Declare and initialize an array of integers
int arr[] = {1, 4, 1, 2, 7, 1, 2, 5, 3, 6};
int n = sizeof(arr) / sizeof(arr[0]); // Get the size of the array

// Find the maximum element in the original array


int max_element = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}

// Declare and initialize another array to store the frequency of each element
int freq[max_element + 1]; // Make sure the frequency array covers the range of
elements
for (int i = 0; i <= max_element; i++) {
freq[i] = 0;
}

// Loop through the original array


for (int i = 0; i < n; i++) {
// Increment the frequency of the current element by one
freq[arr[i]]++;
}

// Find the maximum frequency


int max_freq = freq[0];
for (int i = 1; i <= max_element; i++) {
if (freq[i] > max_freq) {
max_freq = freq[i];
}
}

// Print the mode(s) and the frequency of each number


printf("Mode(s): ");
for (int i = 0; i <= max_element; i++) {
if (freq[i] == max_freq) {
printf("%d ", i);
}
printf("\n%d occurs %d times\n", i, freq[i]);
}
return 0;
}
3. Write a C program to find the maximum/minimum element and it’s index in an array of
integers.
#include <stdio.h>

int main()
{
// Declare an array of 10 integers and initialize it
int array[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int size = 10; // Size of the array
int max, min, max_index, min_index; // Maximum, minimum, and their indices

// Initialize maximum, minimum, and their indices with the first element and index
max = min = array[0];
max_index = min_index = 0;

// Loop through the array elements, starting from the second element
for(int i = 1; i < size; i++)
{
// Compare the current element with the maximum element
if(array[i] > max)
{
// Update the maximum element and its index
max = array[i];
max_index = i;
}

// Compare the current element with the minimum element


if(array[i] < min)
{
// Update the minimum element and its index
min = array[i];
min_index = i;
}
}

// Print the maximum element and its index


printf("The maximum element is %d and its index is %d\n", max, max_index);

// Print the minimum element and its index


printf("The minimum element is %d and its index is %d\n", min, min_index);
return 0;
}
4. Write a C program to find the 2nd/3rd maximum/minimum element and it’s index in an array
of integers.
#include <stdio.h>

int main() {
int size;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &size);

// Input the array elements


int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

int firstMax = arr[0], secondMax = arr[0], thirdMax = arr[0];


int firstMin = arr[0], secondMin = arr[0], thirdMin = arr[0];
int firstMaxIndex = 0, secondMaxIndex = 0, thirdMaxIndex = 0;
int firstMinIndex = 0, secondMinIndex = 0, thirdMinIndex = 0;

// Iterate through the array to find 2nd and 3rd maximum/minimum


for (int i = 1; i < size; i++) {
// Finding 2nd and 3rd maximum
if (arr[i] > firstMax) {
thirdMax = secondMax;
thirdMaxIndex = secondMaxIndex;

secondMax = firstMax;
secondMaxIndex = firstMaxIndex;

firstMax = arr[i];
firstMaxIndex = i;
} else if (arr[i] > secondMax && arr[i] < firstMax) {
thirdMax = secondMax;
thirdMaxIndex = secondMaxIndex;

secondMax = arr[i];
secondMaxIndex = i;
} else if (arr[i] > thirdMax && arr[i] < secondMax) {
thirdMax = arr[i];
thirdMaxIndex = i;
}

// Finding 2nd and 3rd minimum


if (arr[i] < firstMin) {
thirdMin = secondMin;
thirdMinIndex = secondMinIndex;

secondMin = firstMin;
secondMinIndex = firstMinIndex;

firstMin = arr[i];
firstMinIndex = i;
} else if (arr[i] < secondMin && arr[i] > firstMin) {
thirdMin = secondMin;
thirdMinIndex = secondMinIndex;

secondMin = arr[i];
secondMinIndex = i;
} else if (arr[i] < thirdMin && arr[i] > secondMin) {
thirdMin = arr[i];
thirdMinIndex = i;
}
}

// Display the results


printf("2nd Maximum: %d\n", secondMax);
printf("Index of 2nd Maximum: %d\n", secondMaxIndex);
printf("3rd Maximum: %d\n", thirdMax);
printf("Index of 3rd Maximum: %d\n", thirdMaxIndex);
printf("2nd Minimum: %d\n", secondMin);
printf("Index of 2nd Minimum: %d\n", secondMinIndex);
printf("3rd Minimum: %d\n", thirdMin);
printf("Index of 3rd Minimum: %d\n", thirdMinIndex);

return 0;
}
5. Write a C program that takes an array of integers A, another integer t and finds the first/last
index of t in the array A. If t does not exist in the array, it should print -1.
#include <stdio.h>

int main() {
int size;
// Input the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);

// Input the array elements


int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

int target;

// Input the target integer to find


printf("Enter the target integer to find: ");
scanf("%d", &target);

// Find the first index of the target


int firstIndex = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
firstIndex = i;
break;
}
}

// Find the last index of the target


int lastIndex = -1;
for (int i = size - 1; i >= 0; i--) {
if (arr[i] == target) {
lastIndex = i;
break;
}
}

// Display the results


if (firstIndex != -1) {
printf("First occurrence of %d at index: %d\n", target, firstIndex);
} else {
printf("%d not found in the array.\n", target);
}

if (lastIndex != -1) {
printf("Last occurrence of %d at index: %d\n", target, lastIndex);
} else {
printf("%d not found in the array.\n", target);
}

return 0;
}
6. Write a C program that takes an array of integers A, another integer t and count the
occurrences of t in the array A.
#include <stdio.h>

int main()
{
// Declare an array of 10 integers and initialize it
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = 10; // Size of the array
int number, count = 0; // Number to be searched and count of occurrences

// Input the number from the user


printf("Enter the number to be searched: ");
scanf("%d", &number);

// Loop through the array elements


for(int i = 0; i < size; i++)
{
// Compare the element with the number
if(array[i] == number)
{
// Increment the count
count++;
}
}

// Print the count


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

return 0;
}

7. Write a C program that takes an array of positive integers A, another integer t, removes it
from the array A if it exists and shifts every element at right to the left placing -1 at the end of
the array.
#include <stdio.h>
void removeAndShift(int arr[], int size, int target) {
int i, j;

// Find the index of the target element in the array


for (i = 0; i < size; i++) {
if (arr[i] == target) {
// Remove the target element by shifting elements to the left
for (j = i; j < size - 1; j++) {
arr[j] = arr[j + 1];
}

// Place -1 at the end of the array


arr[size - 1] = -1;

// Reduce the size of the array


size--;

// Break the loop once the target is found and removed


break;
}
}
}

int main() {
int size, target;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &size);

int arr[size];

// Input array elements


printf("Enter %d positive integers:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Input the integer to be removed


printf("Enter the integer to be removed: ");
scanf("%d", &target);

// Call the function to remove the target and shift elements


removeAndShift(arr, size, target);
// Display the modified array
printf("Modified array after removing %d and shifting elements:\n", target);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
8. Write a C program to find the mode (the number repeated most often) of an array.
# #include <stdio.h>

// A function to return the mode of an array or -1 if there is no mode


int mode(int arr[], int n) {
int max_value = 0; // To store the mode value
int max_count = 0; // To store the frequency of the mode value
int i, j; // Loop variables

// Loop through the array elements


for (i = 0; i < n; i++) {
int count = 0; // To store the frequency of the current element
// Loop through the array again to compare the elements
for (j = 0; j < n; j++) {
// If the elements are equal, increment the count
if (arr[j] == arr[i]) count++;
}
// If the count is greater than the max_count, update the max_value and max_count
if (count > max_count) {
max_count = count;
max_value = arr[i];
}
}
// If the maximum frequency is one, there is no mode
if (max_count == 1) return -1;
// Otherwise, return the mode value
return max_value;
}

int main() {
int n; // To store the size of the array
int i; // Loop variable

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare an array of size n


int arr[n];

// Input the elements of the array


printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Get the mode of the array


int m = mode(arr, n);

// If the mode is -1, print that there is no mode


if (m == -1) {
printf("There is no mode in the array.\n");
}
// Otherwise, print the mode of the array
else {
printf("The mode of the array is: %d\n", m);
}

return 0;
}
## #include <stdio.h>

int main() {
int size;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &size);

int arr[size];

// Input array elements


printf("Enter %d integers:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Repetition count for each number:\n");


int maxCount = 0; // to store the count of the mode
int mode = -1; // to store the mode value

for (int i = 0; i < size; i++) {


// Skip if the number has already been considered
if (arr[i] == -1) {
continue;
}

int currentNumber = arr[i];


int currentCount = 1; // count for the current number

// Check for repetition and mark repeated occurrences as -1


for (int j = i + 1; j < size; j++) {
if (arr[j] == currentNumber) {
currentCount++;
arr[j] = -1; // Mark repeated occurrences
}
}

printf("%d is repeated %d times\n", currentNumber, currentCount);

// Check if the current number has a higher count than the current mode
if (currentCount > maxCount) {
maxCount = currentCount;
mode = currentNumber;
}
}

// Check if every number is repeated only once


if (maxCount == 1) {
printf("No mode found (every number is repeated only once).\n");
} else if (mode != -1) {
printf("Mode: %d (Repeated %d times)\n", mode, maxCount);
} else {
printf("No mode found.\n");
}

return 0;
}
9. Write a C program that takes N integer numbers in an array, N different integer numbers in a
second array and puts the sum of the same indexed numbers from the two arrays in a third
array.
#include <stdio.h>

int main()
{
// Declare the variables
int N, i;
int arr1 [N], arr2 [N], arr3 [N];

// Get the value of N from the user


printf("Enter the value of N: ");
scanf("%d", &N);

// Get the elements of the first array from the user


printf("Enter %d elements for the first array: \n", N);
for (i = 0; i < N; i++)
{
scanf("%d", &arr1 [i]);
}

// Get the elements of the second array from the user


printf("Enter %d elements for the second array: \n", N);
for (i = 0; i < N; i++)
{
scanf("%d", &arr2 [i]);
}

// Add the corresponding elements of the two arrays and store them in the third array
for (i = 0; i < N; i++)
{
arr3 [i] = arr1 [i] + arr2 [i];
}

// Display the result


printf("The sum of the two arrays is: \n");
for (i = 0; i < N; i++)
{
printf("%d ", arr3 [i]);
}
printf("\n");

return 0;
}
10. Write a C program to reverse an array.
#include <stdio.h>

int main()
{
// Declare the variables
int N, i, temp;
int arr [N];

// Get the value of N from the user


printf("Enter the size of the array: ");
scanf("%d", &N);

// Get the elements of the array from the user


printf("Enter %d elements for the array: \n", N);
for (i = 0; i < N; i++)
{
scanf("%d", &arr [i]);
}

// Reverse the array by swapping the elements from both ends


for (i = 0; i < N/2; i++)
{
temp = arr [i];
arr [i] = arr [N-i-1];
arr [N-i-1] = temp;
}

// Display the result


printf("The reversed array is: \n");
for (i = 0; i < N; i++)
{
printf("%d ", arr [i]);
}
printf("\n");

return 0;
}
11. Write a C program to reverse an array (in place).
12. Write a C program to sort an array in ascending/descending order.?
#include <stdio.h>

int main()
{
// Declare the variables
int N, i, j, temp;

char order;

// Get the value of N from the user


printf("Enter the size of the array: ");
scanf("%d", &N);
int arr [N];

for (i = 0; i < N; i++)


{
// Get the elements of the array from the user
printf("Enter %d elements for the array: ", i+1);
scanf("%d", &arr [i]);
printf("\n");
}

// Get the order of sorting from the user


printf("Enter A for ascending order or D for descending order: ");
scanf(" %c", &order);

// Sort the array according to the order


for (i = 0; i < N; i++)
{
for (j = i + 1; j < N; j++)
{
if (order == 'A' || order == 'a')
{
// Swap the elements if they are not in ascending order
if (arr [i] > arr [j])
{
temp = arr [i];
arr [i] = arr [j];
arr [j] = temp;
}
}
else if (order == 'D' || order == 'd')
{
// Swap the elements if they are not in descending order
if (arr [i] < arr [j])
{
temp = arr [i];
arr [i] = arr [j];
arr [j] = temp;
}
}
else
{
// Invalid order input
printf("Invalid order. Please enter A or D.\n");
return 0;
}
}
}

// Display the result


printf("The sorted array is: \n");
for (i = 0; i < N; i++)
{
printf("%d ", arr [i]);
}
printf("\n");

return 0;
}

13. Write a C program to remove all the duplicate elements in an array.?


#include <stdio.h>

int main() {
// Declare variables
int N, i, j, k;

// Get the size of the array from the user


printf("Enter the size of the array: ");
scanf("%d", &N);

// Declare an array of size N


int arr[N];

// Get elements of the array from the user


printf("Enter %d elements for the array: \n", N);
for (i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
// Remove duplicate elements
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; ) {
if (arr[i] == arr[j]) {
// Shift elements to the left to overwrite duplicate
for (k = j; k < N - 1; k++) {
arr[k] = arr[k + 1];
}
N--; // Reduce the size of the array
} else {
j++; // Move to the next element
}
}
}

// Display the array after removing duplicates


printf("Array after removing duplicates: \n");
for (i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
14. Write a C program to print true if an input array of integers contains a pair with a given sum,
false otherwise.
#include <stdio.h>

int main() {
// Declare variables
int N, sum, found = 0;

// Get the size of the array from the user


printf("Enter the size of the array: ");
scanf("%d", &N);

// Declare an array of size N


int arr[N];

// Get elements of the array from the user


printf("Enter %d integers for the array: \n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
// Get the sum to check for
printf("Enter the sum to check for: ");
scanf("%d", &sum);

// Check for a pair with the given sum


for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (arr[i] + arr[j] == sum) {
found = 1; // Set found to true
break;
}
}
if (found) {
break;
}
}

// Display the result


if (found) {
printf("True, the array contains a pair with the given sum.\n");
} else {
printf("False, the array does not contain a pair with the given sum.\n");
}

return 0;
}
15. Write a C program to find the union (set operation) of two arrays.
#include <stdio.h>

int main() {
// Declare variables
int N1, N2;

// Get the size of the first array from the user


printf("Enter the size of the first array: ");
scanf("%d", &N1);

// Declare the first array of size N1


int arr1[N1];

// Get elements of the first array from the user


printf("Enter %d integers for the first array:\n", N1);
for (int i = 0; i < N1; i++) {
scanf("%d", &arr1[i]);
}

// Get the size of the second array from the user


printf("Enter the size of the second array: ");
scanf("%d", &N2);

// Declare the second array of size N2


int arr2[N2];

// Get elements of the second array from the user


printf("Enter %d integers for the second array:\n", N2);
for (int i = 0; i < N2; i++) {
scanf("%d", &arr2[i]);
}

// Declare an array for the union with maximum possible size (sum of sizes of both
arrays)
int unionArr[N1 + N2];
int unionSize = 0; // Variable to keep track of the size of the union

// Find the union of two arrays


for (int i = 0; i < N1; i++) {
// Add elements from the first array to the union
int isDuplicate = 0;
for (int j = 0; j < unionSize; j++) {
if (unionArr[j] == arr1[i]) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
unionArr[unionSize++] = arr1[i];
}
}

for (int i = 0; i < N2; i++) {


// Add elements from the second array to the union
int isDuplicate = 0;
for (int j = 0; j < unionSize; j++) {
if (unionArr[j] == arr2[i]) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
unionArr[unionSize++] = arr2[i];
}
}

// Display the union of the two arrays


printf("Union of the two arrays:\n");
for (int i = 0; i < unionSize; i++) {
printf("%d ", unionArr[i]);
}
printf("\n");

return 0;
}
16. Write a C program to find the intersection (set operation) of two arrays.
#include <stdio.h>

int main() {
// Declare variables
int N1, N2;

// Get the size of the first array from the user


printf("Enter the size of the first array: ");
scanf("%d", &N1);

// Declare the first array of size N1


int arr1[N1];

// Get elements of the first array from the user


printf("Enter %d integers for the first array:\n", N1);
for (int i = 0; i < N1; i++) {
scanf("%d", &arr1[i]);
}

// Get the size of the second array from the user


printf("Enter the size of the second array: ");
scanf("%d", &N2);

// Declare the second array of size N2


int arr2[N2];

// Get elements of the second array from the user


printf("Enter %d integers for the second array:\n", N2);
for (int i = 0; i < N2; i++) {
scanf("%d", &arr2[i]);
}

// Declare an array for the intersection with maximum possible size (minimum of sizes of
both arrays)
int intersectionArr[N1 < N2 ? N1 : N2];
int intersectionSize = 0; // Variable to keep track of the size of the intersection

// Find the intersection of two arrays


for (int i = 0; i < N1; i++) {
for (int j = 0; j < N2; j++) {
// Check if the current element of the first array is in the second array
if (arr1[i] == arr2[j]) {
// Check if the element is already in the intersection
int isDuplicate = 0;
for (int k = 0; k < intersectionSize; k++) {
if (intersectionArr[k] == arr1[i]) {
isDuplicate = 1;
break;
}
}
// Add the element to the intersection if not a duplicate
if (!isDuplicate) {
intersectionArr[intersectionSize++] = arr1[i];
}
break; // Move to the next element in the first array
}
}
}

// Display the intersection of the two arrays


printf("Intersection of the two arrays:\n");
for (int i = 0; i < intersectionSize; i++) {
printf("%d ", intersectionArr[i]);
}
printf("\n");

return 0;
}
17. -

String:
18. Write a C program to find the number of lowercase characters in a string without using any
library function.
#include <stdio.h>

int main() {
// Declare variables
char str[100];
int lowercaseCount = 0;

// Get a string input from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Iterate through each character in the string


for (int i = 0; str[i] != '\0'; i++) {
// Check if the current character is a lowercase letter
if (str[i] >= 'a' && str[i] <= 'z') {
lowercaseCount++;
}
}

// Display the number of lowercase characters in the string


printf("Number of lowercase characters: %d\n", lowercaseCount);

return 0;
}
19. Write a C program to Capitalize a given string.
Sample Input Sample Output

hello Hello

WORLD World

AfTer After
#include <stdio.h>

// Function to capitalize the first letter of each word in a string


void capitalizeString(char str[])
{
int i;

// Capitalize the first character


if (str[0] >= 'a' && str[0] <= 'z')
{
str[0] = str[0] - 'a' + 'A';
}

// Capitalize the first character after each space


for (i = 1; str[i] != '\0'; i++)
{
// Check if the current character is a space

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


{
// Convert the rest of the characters to lowercase
str[i] = str[i] - 'A' + 'a';
}
}
}

int main()
{
// Declare variables
char str[100];

// Get a string input from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Capitalize the given string


capitalizeString(str);

// Display the capitalized string


printf("Capitalized string: %s", str);

return 0;
}
20. Write a C program to count the occurrences of a character in a string irrespective of its case.
#include <stdio.h>

int main() {
// Declare variables
char str[100], ch;
int count = 0;

// Get a string input from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Get the character to count
printf("Enter the character to count: ");
scanf(" %c", &ch);

// Iterate through each character in the string


for (int i = 0; str[i] != '\0'; i++) {
// Check if the current character matches the specified character (case-insensitive)
if (str[i] == ch || (str[i] >= 'a' && str[i] <= 'z' && str[i] - 'a' + 'A' == ch) ||
(str[i] >= 'A' && str[i] <= 'Z' && str[i] - 'A' + 'a' == ch)) {
count++;
}
}

// Display the count of occurrences


printf("Occurrences of '%c' in the string: %d\n", ch, count);

return 0;
}
21. Write a C program to count the occurrences of every character of a string.
#include <stdio.h>

int main()
{
// Declare the variables
char str[100];
int i, j, count;
int freq[256] = {0}; // An array to store the frequency of each character

// Get the string from the user


printf("Enter a string: ");
scanf("%s", str);

// Loop through the string and increment the frequency of each character
for (i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}

// Loop through the frequency array and print the count of each character
for (i = 0; i < 256; i++)
{
if (freq[i] != 0)
{
printf("The character '%c' occurs %d times in the string.\n", i, freq[i]);
}
}

return 0;
}

#include <stdio.h>

int main() {
// Declare variables
char str[100];
int charCount[128] = {0}; // Assuming ASCII characters

// Get a string input from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Iterate through each character in the string


for (int i = 0; str[i] != '\0'; i++) {
// Increment the count for the current character
charCount[str[i]]++;
}

// Display the occurrences of each character


printf("Occurrences of each character in the string:\n");
for (int i = 0; i < 128; i++) {
if (charCount[i] > 0) {
printf("'%c': %d\n", i, charCount[i]);
}
}

return 0;
}
22. Write a C program to count the occurrences of every character of a string irrespective of
their cases.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
char str[MAX_SIZE];
int i, len;
int freq[26];

/* Input string from user */


printf("Enter any string: ");
gets(str);

len = strlen(str);

/* Initialize frequency of each character to 0 */


for(i=0; i<26; i++)
{
freq[i] = 0;
}

/* Find total number of occurrences of each character */


for(i=0; i<len; i++)
{
/* If the current character is lowercase alphabet */
if(str[i]>='a' && str[i]<='z')
{
freq[str[i] - 97]++;
}
else if(str[i]>='A' && str[i]<='Z')
{
freq[str[i] - 65]++;
}
}

/* Print the frequency of all characters in the string */


printf("\nFrequency of all characters in the given string: \n");
for(i=0; i<26; i++)
{
/* If current character exists in given string */
if(freq[i] != 0)
{
printf("'%c' = %d\n", (i + 97), freq[i]);
}
}

return 0;
}
23. Write a C program to remove the last k characters from a string without using any loops.
#include <stdio.h>
#include <string.h>

int main() {
char inputString[100]; // Adjust the size as needed
int k;

// Input string
printf("Enter a string: ");
gets(inputString);

// Input k
printf("Enter the value of k: ");
scanf("%d", &k);

// Calculate the length of the string


int len = strlen(inputString);

// Ensure k is valid
if (k > 0 && k <= len) {
// Set the (len - k)th character to null terminator
inputString[len - k] = '\0';

// Output modified string


printf("String after removing last %d characters: %s\n", k, inputString);
} else {
// Invalid k value
printf("Invalid value of k.\n");
}

return 0;
}
24. Write a C program to check whether a given string is a palindrome or not.
#include <stdio.h>
#include <string.h>

int main() {
char inputString[100]; // Adjust the size as needed
int isPalindrome = 1; // Assume the string is a palindrome by default

// Input string
printf("Enter a string: ");
scanf("%s", inputString);

int len = strlen(inputString);

// Check if the string is a palindrome


for (int i = 0; i < len / 2; i++) {
if (inputString[i] != inputString[len - i - 1]) {
isPalindrome = 0; // Set to 0 if characters don't match
break;
}
}

// Print the result


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

return 0;
}

25. Write a C program to find the length of a string without using any library function.
#include <stdio.h>

int main() {
char inputString[100]; // Adjust the size as needed
int length = 0;

// Input string
printf("Enter a string: ");
scanf("%s", inputString);

// Calculate the length of the string without using library function


while (inputString[length] != '\0') {
length++;
}

// Print the length of the string


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

return 0;
}
26. Write a C program to concatenate two strings without using any library function.
#include <stdio.h>

int main() {
char firstString[100], secondString[100]; // Adjust the size as needed
int i, j;

// Input first string


printf("Enter the first string: ");
scanf("%s", firstString);

// Input second string


printf("Enter the second string: ");
scanf("%s", secondString);

// Find the length of the first string


i = 0;
while (firstString[i] != '\0') {
i++;
}

// Concatenate the second string to the end of the first string


j = 0;
while (secondString[j] != '\0') {
firstString[i] = secondString[j];
i++;
j++;
}

// Add null terminator to the end of the concatenated string


firstString[i] = '\0';

// Print the concatenated string


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

return 0;
}
27. Write a C program to find the number of words in a string without using any library function.
#include <stdio.h>

int main()
{
// Declare a string
char str[100];
// Input a string from the user
printf("Enter a string: ");
scanf("%[^\n]s", str); // Read until newline

// Initialize a variable to store the word count


int count = 0;

// Initialize a variable to store the index of the string


int i = 0;

// Loop until the end of the string is reached


while (str[i] != '\0')
{
// If the current character is a whitespace and the next character is not
if ((str[i] == ' ' || str[i] == '\t' || str[i] == '\n') && (str[i+1] != ' ' && str[i+1] != '\t' && str[i+1] !=
'\n'))
{
// Increment the word count
count++;
}

// Increment the index


i++;
}

// If the last character is not a whitespace, increment the word count


if (str[i-1] != ' ' && str[i-1] != '\t' && str[i-1] != '\n')
{
count++;
}

// Print the result


printf("The number of words in the string is %d\n", count);

return 0;
}

28. -

2D Array:
29. Write a C program to print a 2D matrix both row-wise and column-wise.
#include <stdio.h>

int main() {
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);

int matrix[rows][cols];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the matrix row-wise


printf("\nMatrix row-wise:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Print the matrix column-wise


printf("\nMatrix column-wise:\n");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}
30. Write a C program to transpose a 2D square matrix and store the transposed matrix in a
new 2d array. Can you do it into the original 2d array that means without taking any new
array?
Sample Input Sample Output
147
123 258
456 369
789
#include <stdio.h>

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

int matrix[n][n];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Transpose the matrix in-place


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Swap elements across the main diagonal
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}

// Print the transposed matrix


printf("\nTransposed Matrix (in-place):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}
31. Write a C program to check if a 2D square matrix is symmetric not.
#include <stdio.h>

#define MAX_SIZE 100

int isSymmetric(int matrix[MAX_SIZE][MAX_SIZE], int n) {


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the matrix is symmetric
if (matrix[i][j] != matrix[j][i]) {
return 0; // Not symmetric
}
}
}
return 1; // Symmetric
}

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Check if the matrix is symmetric


if (isSymmetric(matrix, n)) {
printf("\nThe matrix is symmetric.\n");
} else {
printf("\nThe matrix is not symmetric.\n");
}

return 0;
}
32. Write a C program to check if a 2D square matrix is symmetric or not w.r.t. the right
diagonal.
#include <stdio.h>

#define MAX_SIZE 100

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Check if the matrix is symmetric with respect to the right diagonal


int isSymmetric = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
// Compare elements mirrored across the right diagonal
if (matrix[i][j] != matrix[j][i]) {
isSymmetric = 0; // Not symmetric
break;
}
}
if (!isSymmetric) {
break;
}
}

// Print the result


if (isSymmetric) {
printf("\nThe matrix is symmetric with respect to the right diagonal.\n");
} else {
printf("\nThe matrix is not symmetric with respect to the right diagonal.\n");
}

return 0;
}
33. Write a C program to generate the 2D identity matrix of a given size.
#include <stdio.h>

#define MAX_SIZE 10

int main() {
int n; // Size of the identity matrix
printf("Enter the size of the identity matrix: ");
scanf("%d", &n);

if (n <= 0 || n > MAX_SIZE) {


printf("Invalid size. Please enter a positive integer less than or equal to %d.\n",
MAX_SIZE);
return 1;
}

int identityMatrix[MAX_SIZE][MAX_SIZE];
// Generate the identity matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Set diagonal elements to 1, others to 0
identityMatrix[i][j] = (i == j) ? 1 : 0;
}
}

// Print the identity matrix


printf("\nIdentity Matrix of size %d:\n", n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", identityMatrix[i][j]);
}
printf("\n");
}

return 0;
}
34. Write a C program to print both the diagonals (major, minor) of a 2D square matrix.
#include <stdio.h>

#define MAX_SIZE 10

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

if (n <= 0 || n > MAX_SIZE) {


printf("Invalid size. Please enter a positive integer less than or equal to %d.\n",
MAX_SIZE);
return 1;
}

int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Print the major diagonal


printf("\nMajor Diagonal:\n");
for (int i = 0; i < n; i++) {
printf("%d\t", matrix[i][i]);
}
printf("\n");

// Print the minor diagonal


printf("\nMinor Diagonal:\n");
for (int i = 0; i < n; i++) {
printf("%d\t", matrix[i][n - i - 1]);
}
printf("\n");

return 0;
}
35. Write a C program to print the trace of a 2D square matrix.
#include <stdio.h>

#define MAX_SIZE 10

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

if (n <= 0 || n > MAX_SIZE) {


printf("Invalid size. Please enter a positive integer less than or equal to %d.\n",
MAX_SIZE);
return 1;
}

int matrix[MAX_SIZE][MAX_SIZE];
// Input elements of the matrix
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Calculate and print the trace of the matrix


int trace = 0;
for (int i = 0; i < n; i++) {
trace += matrix[i][i];
}

printf("\nTrace of the matrix: %d\n", trace);

return 0;
}
36. Write a C program to check if a 2D square matrix is a diagonal matrix or not.?
#include <stdio.h>

#define MAX_SIZE 10

int isDiagonalMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if elements outside the main diagonal are zero
if (i != j && matrix[i][j] != 0) {
return 0; // Not a diagonal matrix
}
}
}
return 1; // Diagonal matrix
}

int main() {
int n; // Size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);

if (n <= 0 || n > MAX_SIZE) {


printf("Invalid size. Please enter a positive integer less than or equal to %d.\n",
MAX_SIZE);
return 1;
}

int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Check if the matrix is a diagonal matrix


if (isDiagonalMatrix(matrix, n)) {
printf("\nThe matrix is a diagonal matrix.\n");
} else {
printf("\nThe matrix is not a diagonal matrix.\n");
}

return 0;
}
37. Write a C program to check if a 2D square matrix is a diagonal matrix or not w.r.t. the right
diagonal.?
38. Write a C program to multiply two 2D matrices.?
#include <stdio.h>

#define MAX_SIZE 10

int main() {
int rows1, cols1, rows2, cols2;

// Input dimensions of the first matrix


printf("Enter the number of rows for the first matrix: ");
scanf("%d", &rows1);
printf("Enter the number of columns for the first matrix: ");
scanf("%d", &cols1);

// Input dimensions of the second matrix


printf("Enter the number of rows for the second matrix: ");
scanf("%d", &rows2);
printf("Enter the number of columns for the second matrix: ");
scanf("%d", &cols2);

if (cols1 != rows2) {
printf("Matrix multiplication is not possible. Number of columns in the first matrix should
be equal to the number of rows in the second matrix.\n");
return 1;
}

int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];

// Input elements of the first matrix


printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix1[i][j]);
}
}

// Input elements of the second matrix


printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix2[i][j]);
}
}

// Initialize result matrix elements to 0


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
}
}

// Multiply matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Print the matrices


printf("\nMatrix 1:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
printf("%d\t", matrix1[i][j]);
}
printf("\n");
}

printf("\nMatrix 2:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d\t", matrix2[i][j]);
}
printf("\n");
}

// Print the result matrix


printf("\nResult Matrix (Matrix 1 * Matrix 2):\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}
39. Write a C program to swap any two given rows/columns of a 2D matrix.
#include <stdio.h>

#define MAX_SIZE 10

int main() {
int rows, cols;

// Input dimensions of the matrix


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

if (rows <= 0 || cols <= 0 || rows > MAX_SIZE || cols > MAX_SIZE) {
printf("Invalid dimensions. Please enter positive integers less than or equal to %d.\n",
MAX_SIZE);
return 1;
}

int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
int choice;
printf("\nEnter 1 to swap rows, 2 to swap columns: ");
scanf("%d", &choice);

if (choice == 1) {
int row1, row2;
printf("Enter the row numbers to swap (1 to %d): ", rows);
scanf("%d %d", &row1, &row2);

if (row1 < 1 || row1 > rows || row2 < 1 || row2 > rows) {
printf("Invalid row numbers. Please enter valid row numbers.\n");
return 1;
}

// Swap the rows


for (int j = 0; j < cols; j++) {
int temp = matrix[row1 - 1][j];
matrix[row1 - 1][j] = matrix[row2 - 1][j];
matrix[row2 - 1][j] = temp;
}
} else if (choice == 2) {
int col1, col2;
printf("Enter the column numbers to swap (1 to %d): ", cols);
scanf("%d %d", &col1, &col2);

if (col1 < 1 || col1 > cols || col2 < 1 || col2 > cols) {
printf("Invalid column numbers. Please enter valid column numbers.\n");
return 1;
}

// Swap the columns


for (int i = 0; i < rows; i++) {
int temp = matrix[i][col1 - 1];
matrix[i][col1 - 1] = matrix[i][col2 - 1];
matrix[i][col2 - 1] = temp;
}
} else {
printf("Invalid choice. Please enter either 1 or 2.\n");
return 1;
}

// Print the matrix after swapping


printf("\nMatrix after swapping:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}

You might also like