NAME :- SHUSHANT SONWANI
REGISTRATION NO.:- 2023CA95
WEEKLY ASSIGNMENT:- 5
1.
#include <stdio.h>
void moveZeroesToEnd(int arr[], int n) {
int nonZeroIndex = 0;
// Traverse the array and move non-zero elements to the beginning
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[nonZeroIndex] = arr[i];
nonZeroIndex++;
}
}
// Fill the remaining elements with zeroes
for (int i = nonZeroIndex; i < n; i++) {
arr[i] = 0;
}
}
int main() {
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0};
int n = sizeof(arr) / sizeof(arr[0]);
moveZeroesToEnd(arr, n);
printf("Array after moving zeroes to the end: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
2.
#include <stdio.h>
int countDistinctPairsWithDifference(int arr[], int n, int k) {
int count = 0;
for (int i = 0; i < n; i++) {
int element = arr[i];
int complement1 = element + k;
int complement2 = element - k;
// Check if complement1 exists in the array
for (int j = 0; j < n; j++) {
if (j != i && arr[j] == complement1) {
count++;
break;
}
}
// Check if complement2 exists in the array
for (int j = 0; j < n; j++) {
if (j != i && arr[j] == complement2) {
count++;
break;
}
}
}
// Divide by 2 to avoid counting duplicates
return count / 2;
}
int main() {
int arr[] = {1, 5, 3, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
int countPairs = countDistinctPairsWithDifference(arr, n, k);
printf("Distinct pairs with difference %d: %d\n", k, countPairs);
return 0;
}
3.
#include <stdio.h>
void reverseArray(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void rotateArray(int arr[], int n, int k) {
k = k % n; // In case k is greater than n
// Reverse the first part of the array (0 to k-1)
reverseArray(arr, 0, k - 1);
// Reverse the second part of the array (k to n-1)
reverseArray(arr, k, n - 1);
// Reverse the entire array
reverseArray(arr, 0, n - 1);
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
rotateArray(arr, n, k);
printf("Array after rotating by %d positions: ", k);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
4.
#include <stdio.h>
int main() {
int matrix[3][3];
int sum = 0;
printf("Enter a 3x3 matrix:\n");
// Input the 3x3 matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("Enter element at row %d, column %d: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
// Calculate the sum of the upper triangle
for (int i = 0; i < 3; i++) {
for (int j = i; j < 3; j++) {
sum += matrix[i][j];
}
}
// Print the matrix
printf("Entered matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("Sum of the upper triangle: %d\n", sum);
return 0;
}
6.
#include <stdio.h>
int main() {
int n;
// Get the size of the array (n > 5)
do {
printf("Enter the size of the array (n > 5): ");
scanf("%d", &n);
} while (n <= 5);
int arr[n];
// Input the array elements
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Initialize max and min with the first element
int max = arr[0];
int min = arr[0];
// Find the maximum and minimum elements
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// Print the maximum and minimum elements
printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);
return 0;
}
6.
#include <stdio.h>
int maxSubarraySum(int arr[], int n) {
int maxEndingHere = arr[0];
int maxSoFar = arr[0];
for (int i = 1; i < n; i++) {
// Find the maximum sum ending at the current element
maxEndingHere = (arr[i] > maxEndingHere + arr[i]) ? arr[i] :
maxEndingHere + arr[i];
// Update the maximum sum so far
maxSoFar = (maxEndingHere > maxSoFar) ? maxEndingHere : maxSoFar;
}
return maxSoFar;
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid array size.\n");
return 1;
}
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int maxSum = maxSubarraySum(arr, n);
printf("The maximum subarray sum is: %d\n", maxSum);
return 0;
}
7.
#include <stdio.h>
#include <stdlib.h>
double findMedianSortedArrays(int X[], int m, int Y[], int n) {
// Make sure array X is smaller or equal to array Y
if (m > n) {
int *tempArr = X;
X = Y;
Y = tempArr;
int temp = m;
m = n;
n = temp;
}
int i, j, min_index, max_index, mid_index, median;
min_index = 0;
max_index = m;
median = 0;
while (min_index <= max_index) {
i = (min_index + max_index) / 2;
j = (m + n + 1) / 2 - i;
if (i < m && j > 0 && Y[j - 1] > X[i]) {
min_index = i + 1;
} else if (i > 0 && j < n && Y[j] < X[i - 1]) {
max_index = i - 1;
} else {
if (i == 0) {
median = Y[j - 1];
} else if (j == 0) {
median = X[i - 1];
} else {
median = (X[i - 1] > Y[j - 1]) ? X[i - 1] : Y[j - 1];
}
break;
}
}
if ((m + n) % 2 == 0) {
if (i == m) {
return (median + Y[j]) / 2.0;
} else if (j == n) {
return (median + X[i]) / 2.0;
} else {
return (median + (X[i] < Y[j] ? X[i] : Y[j])) / 2.0;
}
} else {
return median;
}
}
int main() {
int X[] = {1, 3, 8};
int Y[] = {7, 9, 10};
int m = sizeof(X) / sizeof(X[0]);
int n = sizeof(Y) / sizeof(Y[0]);
double median = findMedianSortedArrays(X, m, Y, n);
printf("Median of the merged arrays is: %lf\n", median);
return 0;
}
8.
#include <stdio.h>
void printSpiralMatrix(int matrix[10][10], int n) {
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Print top row
for (int i = left; i <= right; i++) {
printf("%d ", matrix[top][i]);
}
top++;
// Print right column
for (int i = top; i <= bottom; i++) {
printf("%d ", matrix[i][right]);
}
right--;
// Check if there's a bottom row to print
if (top <= bottom) {
// Print bottom row
for (int i = right; i >= left; i--) {
printf("%d ", matrix[bottom][i]);
}
bottom--;
}
// Check if there's a left column to print
if (left <= right) {
// Print left column
for (int i = bottom; i >= top; i--) {
printf("%d ", matrix[i][left]);
}
left++;
}
}
}
int main() {
int matrix[10][10];
int n;
printf("Enter the size of the square matrix (n x n): ");
scanf("%d", &n);
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("Spiral Matrix:\n");
printSpiralMatrix(matrix, n);
return 0;
}
9.
#include <stdio.h>
#include <limits.h>
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
if (n < 2) {
printf("The array should have at least 2 elements.\n");
return 1;
}
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int firstHighest = INT_MIN, secondHighest = INT_MIN;
int firstLowest = INT_MAX, secondLowest = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = arr[i];
} else if (arr[i] > secondHighest && arr[i] != firstHighest) {
secondHighest = arr[i];
}
if (arr[i] < firstLowest) {
secondLowest = firstLowest;
firstLowest = arr[i];
} else if (arr[i] < secondLowest && arr[i] != firstLowest) {
secondLowest = arr[i];
}
}
printf("Second Highest: %d\n", secondHighest);
printf("Second Lowest: %d\n", secondLowest);
return 0;
}
10.
#include <stdio.h>
#include <string.h>
void reverseWord(char word[]) {
int len = strlen(word);
for (int i = 0; i < len / 2; i++) {
char temp = word[i];
word[i] = word[len - i - 1];
word[len - i - 1] = temp;
}
}
int main() {
char sentence[1000]; // Assuming the sentence is less than 1000 characters
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
char word[100]; // Assuming each word is less than 100 characters
int sentenceLength = strlen(sentence);
int wordIndex = 0;
printf("Reversed sentence: ");
for (int i = 0; i <= sentenceLength; i++) {
if (sentence[i] == ' ' || sentence[i] == '\0' || sentence[i] == '\n') {
word[wordIndex] = '\0';
reverseWord(word);
printf("%s", word);
if (sentence[i] == ' ') {
printf(" ");
}
wordIndex = 0;
} else {
word[wordIndex] = sentence[i];
wordIndex++;
}
}
printf("\n");
return 0;
}
11. #include <stdio.h>
#include <string.h>
void reverseWord(char *word) {
int start = 0;
int end = strlen(word) - 1;
while (start < end) {
char temp = word[start];
word[start] = word[end];
word[end] = temp;
start++;
end--;
}
}
int main() {
char sentence[1000];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
char *word = strtok(sentence, " ");
while (word != NULL) {
reverseWord(word);
printf("%s ", word);
word = strtok(NULL, " ");
}
return 0;
}
12.
#include <stdio.h>
#include <ctype.h>
void convertToUppercase(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = toupper((unsigned char)str[i]);
}
}
int main() {
char input[1000];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
// Call the function to convert the input to uppercase
convertToUppercase(input);
printf("Modified string: %s\n", input);
return 0;
}
13.
#include <stdio.h>
#include <stdbool.h>
// Function to check if there exist two elements with sum x
bool hasPairWithSum(int A[], int n, int x) {
bool hashTable[100000] = {false}; // Assuming the maximum value of
elements is less than 100000
for (int i = 0; i < n; i++) {
int complement = x - A[i];
// If the complement is already in the hash table, a pair with the sum x
exists
if (hashTable[complement]) {
return true;
}
// Add the current element to the hash table
hashTable[A[i]] = true;
}
// If no pair with the sum x is found, return false
return false;
}
int main() {
int n, x;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int A[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
printf("Enter the value of x: ");
scanf("%d", &x);
if (hasPairWithSum(A, n, x)) {
printf("There exist two elements in the array whose sum is %d.\n", x);
} else {
printf("No such pair exists.\n");
}
return 0;
}
16.
#include <stdio.h>
// Function to find the majority element
int findMajorityElement(int A[], int n) {
int candidate, count = 0;
// Find a potential candidate for the majority element
for (int i = 0; i < n; i++) {
if (count == 0) {
candidate = A[i];
count = 1;
} else {
if (A[i] == candidate) {
count++;
} else {
count--;
}
}
}
// Verify if the candidate is the majority element
count = 0;
for (int i = 0; i < n; i++) {
if (A[i] == candidate) {
count++;
}
}
if (count > n / 2) {
return candidate;
} else {
return -1; // No majority element exists
}
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int A[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
int majorityElement = findMajorityElement(A, n);
if (majorityElement != -1) {
printf("The majority element is: %d\n", majorityElement);
} else {
printf("No majority element exists.\n");
}
return 0;
}
17. #include <stdio.h>
// Function to print the union of two sorted arrays
void findUnion(int arr1[], int m, int arr2[], int n) {
int i = 0, j = 0;
printf("Union of the two arrays: ");
while (i < m && j < n) {
if (arr1[i] < arr2[j]) {
printf("%d ", arr1[i]);
i++;
} else if (arr1[i] > arr2[j]) {
printf("%d ", arr2[j]);
j++;
} else {
printf("%d ", arr1[i]);
i++;
j++;
}
}
// Print the remaining elements
while (i < m) {
printf("%d ", arr1[i]);
i++;
}
while (j < n) {
printf("%d ", arr2[j]);
j++;
}
printf("\n");
}
// Function to print the intersection of two sorted arrays
void findIntersection(int arr1[], int m, int arr2[], int n) {
int i = 0, j = 0;
printf("Intersection of the two arrays: ");
while (i < m && j < n) {
if (arr1[i] < arr2[j]) {
i++;
} else if (arr1[i] > arr2[j]) {
j++;
} else {
printf("%d ", arr1[i]);
i++;
j++;
}
}
printf("\n");
}
int main() {
int m, n;
printf("Enter the size of the first array: ");
scanf("%d", &m);
printf("Enter the elements of the first sorted array:\n");
int arr1[m];
for (int i = 0; i < m; i++) {
scanf("%d", &arr1[i]);
}
printf("Enter the size of the second array: ");
scanf("%d", &n);
printf("Enter the elements of the second sorted array:\n");
int arr2[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr2[i]);
}
findUnion(arr1, m, arr2, n);
findIntersection(arr1, m, arr2, n);
return 0;
}
18.
#include <stdio.h>
#include <math.h>
// Function to calculate the mean of an array
double calculateMean(int arr[], int n) {
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum / n;
}
// Function to calculate the standard deviation of an array
double calculateStandardDeviation(int arr[], int n, double mean) {
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += pow(arr[i] - mean, 2);
}
double variance = sum / n;
return sqrt(variance);
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
double mean = calculateMean(arr, n);
double standardDeviation = calculateStandardDeviation(arr, n, mean);
printf("Mean: %lf\n", mean);
printf("Standard Deviation: %lf\n", standardDeviation);
return 0;
}
19.
#include <stdio.h>
#include <ctype.h>
int main() {
char sentence[1000];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
int wordCount = 0;
int alphabetCount = 0;
int i = 0;
char currentChar;
while (sentence[i] != '\0') {
currentChar = sentence[i];
// Count alphabets
if (isalpha(currentChar)) {
alphabetCount++;
}
// Count words (assumes words are separated by spaces)
if (isspace(currentChar) && i > 0 && !isspace(sentence[i - 1])) {
wordCount++;
}
i++;
}
// Count the last word if the sentence doesn't end with a space
if (!isspace(sentence[i - 1]) && i > 0) {
wordCount++;
}
printf("Number of words: %d\n", wordCount);
printf("Number of alphabets: %d\n", alphabetCount);
return 0;
}
20.
#include <stdio.h>
int main() {
int n;
printf("Enter the size (n) of the matrices: ");
scanf("%d", &n);
int matrix1[n][n], matrix2[n][n], sumMatrix[n][n], diffMatrix[n][n];
printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Calculate the sum and difference matrices
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
diffMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
printf("Sum Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", sumMatrix[i][j]);
}
printf("\n");
}
printf("Difference Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", diffMatrix[i][j]);
}
printf("\n");
}
return 0;
}
21.
#include <stdio.h>
int stringLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
char inputString[100]; // You can change the size as needed
printf("Enter a string: ");
scanf("%s", inputString);
int length = stringLength(inputString);
printf("The length of the string is: %d\n", length);
return 0;
}
22.
#include <stdio.h>
int main() {
int originalArray[] = {22, 16, 17, 18, 16};
int n = 5; // Number of elements in the original array
int position, newValue;
printf("Original Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", originalArray[i]);
}
printf("\nEnter the position to insert a new element: ");
scanf("%d", &position);
if (position < 0 || position > n) {
printf("Invalid position for insertion.\n");
return 1;
}
printf("Enter the new value to insert: ");
scanf("%d", &newValue);
int newArray[n + 1]; // Create a new array with space for the new element
// Copy elements before the insertion point
for (int i = 0; i < position; i++) {
newArray[i] = originalArray[i];
}
// Insert the new element
newArray[position] = newValue;
// Copy elements after the insertion point
for (int i = position; i < n; i++) {
newArray[i + 1] = originalArray[i];
}
n++; // Increase the number of elements in the new array
printf("New Array after insertion: ");
for (int i = 0; i < n; i++) {
printf("%d ", newArray[i]);
}
return 0;
}
23.
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // It's not a prime number
}
}
return 1; // It's a prime number
}
int main() {
int n;
printf("Enter the value of n (greater than 20): ");
scanf("%d", &n);
if (n <= 20) {
printf("Please enter a value of n greater than 20.\n");
return 1;
}
int count = 0;
int number = 2; // Start with the first prime number
while (count < n) {
if (isPrime(number)) {
printf("%d ", number);
count++;
}
number++;
}
printf("\n");
return 0;
}
24.
#include <stdio.h>
double power(double base, int exponent) {
double result = 1.0;
if (exponent >= 0) {
for (int i = 0; i < exponent; i++) {
result *= base;
}
} else {
for (int i = 0; i > exponent; i--) {
result /= base;
}
}
return result;
}
int main() {
double base;
int exponent;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("%lf ^ %d = %lf\n", base, exponent, result);
return 0;
}
25.
#include <stdio.h>
void findFirstRepeating(int arr[], int size) {
int maxElement = 0; // Find the maximum element in the array
for (int i = 0; i < size; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
int *index = (int *)malloc((maxElement + 1) * sizeof(int));
for (int i = 0; i <= maxElement; i++) {
index[i] = -1; // Initialize the index array with -1
}
int minIndex = size; // Initialize the minimum index
for (int i = 0; i < size; i++) {
if (index[arr[i]] == -1) {
index[arr[i]] = i;
} else {
if (index[arr[i]] < minIndex) {
minIndex = index[arr[i]];
}
}
}
if (minIndex == size) {
printf("No repeating elements found.\n");
} else {
printf("The first repeating element is %d at index %d.\n", arr[minIndex],
minIndex);
}
free(index); // Free the dynamically allocated index array
}
int main() {
int arr[] = {10, 5, 3, 4, 3, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
findFirstRepeating(arr, size);
return 0;
}
26.
#include <stdio.h>
#include<stdlib.h>
void segregatePositive(int arr[], int n) {
int positiveIndex = 0;
for (int i = 0; i < n; i++) {
if (arr[i] <= 0) {
int temp = arr[i];
arr[i] = arr[positiveIndex];
arr[positiveIndex] = temp;
positiveIndex++;
}
}
}
int findSmallestPositive(int arr[], int n) {
for (int i = 0; i < n; i++) {
int index = abs(arr[i]) - 1;
if (index >= 0 && index < n && arr[index] > 0) {
arr[index] = -arr[index];
}
}
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
return i + 1;
}
}
return n + 1;
}
int main() {
int arr[] = {2, 3, 7, 6, 8, -1, -10, 15};
int n = sizeof(arr) / sizeof(arr[0]);
// Step 1: Segregate positive and non-positive numbers
segregatePositive(arr, n);
// Step 2: Find the smallest missing positive number
int smallestPositive = findSmallestPositive(arr, n);
printf("The smallest positive number missing is: %d\n", smallestPositive);
return 0;
}
27.
#include <stdio.h>
void segregateZerosAndOnes(int arr[], int n) {
int left = 0;
int right = n - 1;
while (left < right) {
// Move the left pointer to the right until it points to a 1
while (arr[left] == 0 && left < right) {
left++;
}
// Move the right pointer to the left until it points to a 0
while (arr[right] == 1 && left < right) {
right--;
}
// Swap the elements at the left and right pointers
if (left < right) {
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
int main() {
int arr[] = {0, 1, 0, 1, 1, 0, 0, 1};
int n = sizeof(arr) / sizeof(arr[0]);
segregateZerosAndOnes(arr, n);
printf("Segregated Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
28.
29.
#include <stdio.h>
int findOddOccurrence(int arr[], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
result ^= arr[i];
}
return result;
}
int main() {
int arr[] = {4, 4, 2, 2, 3, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int oddOccurrence = findOddOccurrence(arr, n);
printf("The number occurring an odd number of times is: %d\n",
oddOccurrence);
return 0;
}