November 20, 2024

Computer Programming Questions and Answers

Computer Programming
Share :

Computer Programming Questions and Answers


( Suggestion :  keep refreshing the page for updated content & Search Questions Using Find )


Q1.Write a C program to combine two one dimensional array into the first one dimensional array. [2Marks]
Answer : 

#include <stdio.h>

void combineArrays(int arr1[], int size1, int arr2[], int size2) {
// Resize arr1 to accommodate both arrays
int newSize = size1 + size2;
arr1 = realloc(arr1, newSize * sizeof(int));

// Copy elements from arr2 to arr1
for (int i = 0; i < size2; i++) {
arr1[size1 + i] = arr2[i];
}
}

int main() {
int size1, size2;

// Input size of the first array
printf(“Enter the size of the first array: “);
scanf(“%d”, &size1);

// Input elements of the first array
int arr1[size1];
printf(“Enter %d elements for the first array:\n”, size1);
for (int i = 0; i < size1; i++) {
scanf(“%d”, &arr1[i]);
}

// Input size of the second array
printf(“Enter the size of the second array: “);
scanf(“%d”, &size2);

// Input elements of the second array
int arr2[size2];
printf(“Enter %d elements for the second array:\n”, size2);
for (int i = 0; i < size2; i++) {
scanf(“%d”, &arr2[i]);
}

// Combine arrays
combineArrays(arr1, size1, arr2, size2);

// Display the combined array
printf(“Combined Array:\n”);
for (int i = 0; i < size1 + size2; i++) {
printf(“%d “, arr1[i]);
}

return 0;
}


Q2. There are 4 bytes in successive memory locations. Write a program to rotate the 4 bytes to the right by 2 bits. Assume the lower byte to be in the lower address. Example given below

Original value

Byte0 – 0xE6 (lower memory address)
Byte 1 – 0xCC
Byte2 – 0xFF
Byte30x88 (higher memory address)
After rotation
Byte0 – 0x39
Byte1 – 0xF3
Byte2 – 0x3F
Byte4 – 0xA2

Write a program to implement the above. You may use unions for data storage. Print the resulting array in hexadecimal units

Answer : 

#include <stdio.h>

union ByteUnion {
unsigned int value; // Assuming a 4-byte integer
unsigned char bytes[4];
};

void rotateRightByTwoBits(union ByteUnion *data) {
// Rotate the entire 4-byte integer to the right by 2 bits
data->value = (data->value >> 2) | (data->value << (32 – 2));
}

int main() {
union ByteUnion data;

// Initialize the bytes with the given values
data.bytes[0] = 0xE6;
data.bytes[1] = 0xCC;
data.bytes[2] = 0xFF;
data.bytes[3] = 0x88;

printf(“Original value:\n”);
for (int i = 0; i < 4; i++) {
printf(“Byte%d – 0x%02X\n”, i, data.bytes[i]);
}

// Rotate the bytes to the right by 2 bits
rotateRightByTwoBits(&data);

printf(“\nAfter rotation:\n”);
for (int i = 0; i < 4; i++) {
printf(“Byte%d – 0x%02X\n”, i, data.bytes[i]);
}

return 0;
}


Q3. Find a solution to count 1. uppercase, 2. lowercase and 3.special symbols separately present in “GO5600! 67* morning 7789” Input should be given as command line argument. Space and numbers should not be considered as special symbols. Check argument error condition also in solution. Use two dimension to read the input and to find the solution. Built in function can be used. [5. Marks]

Answer :

#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
// Check for the correct number of command line arguments
if (argc != 2) {
printf(“Usage: %s <input_string>\n”, argv[0]);
return 1; // Exit with an error code
}

// Initialize counters
int uppercaseCount = 0, lowercaseCount = 0, specialSymbolCount = 0;

// Loop through each character in the input string
for (int i = 0; argv[1][i] != ‘\0’; i++) {
// Check if the character is an uppercase letter
if (isupper(argv[1][i])) {
uppercaseCount++;
}
// Check if the character is a lowercase letter
else if (islower(argv[1][i])) {
lowercaseCount++;
}
// Check if the character is a special symbol (excluding space and numbers)
else if (!(isdigit(argv[1][i]) || isspace(argv[1][i]))) {
specialSymbolCount++;
}
}

// Print the results
printf(“Uppercase letters: %d\n”, uppercaseCount);
printf(“Lowercase letters: %d\n”, lowercaseCount);
printf(“Special symbols: %d\n”, specialSymbolCount);

return 0; // Exit successfully
}


Q4. Write a C program that removes duplicates from a one-dimensional integer array and finds the second smallest element in the array.

Answer :

#include <stdio.h>

void removeDuplicates(int arr[], int *n) {
int i, j, k;

for (i = 0; i < *n; i++) {
for (j = i + 1; j < *n;) {
if (arr[i] == arr[j]) {
for (k = j; k < *n – 1; k++) {
arr[k] = arr[k + 1];
}
(*n)–;
} else {
j++;
}
}
}
}

int findSecondSmallest(int arr[], int n) {
int smallest = arr[0];
int secondSmallest = arr[0];

for (int i = 1; i < n; i++) {
if (arr[i] < smallest) {
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest && arr[i] != smallest) {
secondSmallest = arr[i];
}
}

return secondSmallest;
}

int main() {
int n;

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

int arr[n];

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

// Remove duplicates
removeDuplicates(arr, &n);

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

// Find the second smallest element
if (n >= 2) {
int secondSmallest = findSecondSmallest(arr, n);
printf(“The second smallest element is: %d\n”, secondSmallest);
} else {
printf(“Not enough elements to find the second smallest element.\n”);
}

return 0;
}





Q5.Explain with a simple memory layout diagram union padding and why is it done in a union or structure? Sample union may be taken as union (char ss[7], int jj;} test; for a 32 bit controller. Many multi byte controllers access data at the data boundary. Taking the case of a 32 bit controller, The actual size of the above union is 7 bytes. However a 1 byte pad will be added to the union to make it 8 bytes which is a multiple of 4. The memory layout is shown below Memory X is the pad byte.

Answer :
union test {
char ss[7];
int jj;
};

Assuming a 32-bit controller, let’s analyze the memory layout:

  1. The union consists of two members: an array of 7 characters (ss[7]) and an integer (jj).
  2. The size of ss[7] is 7 bytes, and the size of int is typically 4 bytes on a 32-bit system.
  3. The size of the union is determined by the largest member, which is the integer (int jj) in this case. So, the size of the union will be 4 bytes.
  4. Since the array ss[7] is smaller than the integer, there will be padding added to make the size of the union a multiple of the largest member’s size. In this case, the largest member is an int (4 bytes), so the union size needs to be a multiple of 4.

Now, let’s represent the memory layout:

—————————————————–
| char ss[7] (7 bytes) | int jj (4 bytes) |
—————————————————–
| s[0] | s[1] | s[2] | s[3] | s[4] | s[5] | s[6] | Padding (X) |
—————————————————–

Q6. Write C program which can be used to merge two files into a single file using command line arguments ie the three files names are given as command line arguments.

Answer :
#include <stdio.h>int main(int argc, char *argv[]) {
// Check if the correct number of command line arguments are provided
if (argc != 4) {
printf(“Usage: %s <input_file1> <input_file2> <output_file>\n”, argv[0]);
return 1; // Return an error code
}// Open the first input file
FILE *inputFile1 = fopen(argv[1], “rb”);
if (inputFile1 == NULL) {
perror(“Error opening first input file”);
return 2; // Return an error code
}// Open the second input file
FILE *inputFile2 = fopen(argv[2], “rb”);
if (inputFile2 == NULL) {
perror(“Error opening second input file”);
fclose(inputFile1); // Close the first file
return 3; // Return an error code
}// Open the output file for writing
FILE *outputFile = fopen(argv[3], “wb”);
if (outputFile == NULL) {
perror(“Error opening output file”);
fclose(inputFile1); // Close the first file
fclose(inputFile2); // Close the second file
return 4; // Return an error code
}// Read and write the contents of the first input file
int ch;
while ((ch = fgetc(inputFile1)) != EOF) {
fputc(ch, outputFile);
}

// Read and write the contents of the second input file
while ((ch = fgetc(inputFile2)) != EOF) {
fputc(ch, outputFile);
}

// Close all the files
fclose(inputFile1);
fclose(inputFile2);
fclose(outputFile);

printf(“Files merged successfully!\n”);

return 0; // Return success code
}


Q7. Given two strings. The task is to check whether the given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.

Answer :

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

// Function to check if two strings are anagrams
int areAnagrams(char *str1, char *str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);

// If lengths are not equal, strings cannot be anagrams
if (len1 != len2) {
return 0;
}

// Sort both strings
for (int i = 0; i < len1 – 1; i++) {
for (int j = i + 1; j < len1; j++) {
if (str1[i] > str1[j]) {
// Swap characters
char temp = str1[i];
str1[i] = str1[j];
str1[j] = temp;
}
if (str2[i] > str2[j]) {
// Swap characters
char temp = str2[i];
str2[i] = str2[j];
str2[j] = temp;
}
}
}

// Compare sorted strings
for (int i = 0; i < len1; i++) {
if (str1[i] != str2[i]) {
return 0; // Not anagrams
}
}

return 1; // Anagrams
}

int main() {
char str1[100], str2[100];

// Input two strings from the user
printf(“Enter the first string: “);
scanf(“%s”, str1);

printf(“Enter the second string: “);
scanf(“%s”, str2);

// Check if the strings are anagrams
if (areAnagrams(str1, str2)) {
printf(“The strings are anagrams.\n”);
} else {
printf(“The strings are not anagrams.\n”);
}

return 0;
}


Q8. You are required to read a list of marks. Write a C program to create a linked list to store these marks. Use -1 to terminate the insertion operation in the list Then display the total number of marks you have read. Again, print the individual mark whether it is a pass mark or fail mark. (any mark less than 30 is a failed mark). Also, display the total number of passed mark and failed mark separately.

Answer:

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node in the linked list
struct Node {
int mark;
struct Node* next;
};

// Function to create a new node
struct Node* createNode(int mark) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->mark = mark;
newNode->next = NULL;
return newNode;
}

int main() {
struct Node* head = NULL;
int mark;

// Read marks and create linked list
printf(“Enter marks (enter -1 to terminate):\n”);
while (1) {
scanf(“%d”, &mark);
if (mark == -1) {
break;
}

// Create a new node with the entered mark
struct Node* newNode = createNode(mark);

// Insert the new node at the end of the linked list
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Display total number of marks
int totalMarks = 0;
struct Node* temp = head;
while (temp != NULL) {
totalMarks++;
temp = temp->next;
}
printf(“\nTotal number of marks: %d\n”, totalMarks);

// Display individual marks, pass/fail, and count of passed and failed marks
int passedCount = 0, failedCount = 0;
temp = head;
while (temp != NULL) {
printf(“Mark: %d – %s\n”, temp->mark, (temp->mark >= 30) ? “Pass” : “Fail”);
if (temp->mark >= 30) {
passedCount++;
} else {
failedCount++;
}
temp = temp->next;
}

// Display total number of passed and failed marks
printf(“\nTotal number of passed marks: %d\n”, passedCount);
printf(“Total number of failed marks: %d\n”, failedCount);

// Free the allocated memory for the linked list
temp = head;
while (temp != NULL) {
struct Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}

return 0;
}





Q9. Write an equivalent C program for the given command using command line arguments cp <source filename> <destination filename> copy only the alphabets from source file to destination file Possible error conditions should be checked. Display the copied contents from destination file.

Answer :

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX_BUFFER_SIZE 1024

void copyAlphabets(FILE *source, FILE *destination) {
char ch;

while ((ch = fgetc(source)) != EOF) {
if (isalpha(ch)) {
fputc(ch, destination);
}
}
}

int main(int argc, char *argv[]) {
if (argc != 3) {
printf(“Usage: %s <source filename> <destination filename>\n”, argv[0]);
return 1;
}

FILE *sourceFile = fopen(argv[1], “r”);
if (sourceFile == NULL) {
perror(“Error opening source file”);
return 2;
}

FILE *destinationFile = fopen(argv[2], “w”);
if (destinationFile == NULL) {
perror(“Error opening destination file”);
fclose(sourceFile);
return 3;
}

copyAlphabets(sourceFile, destinationFile);

fclose(sourceFile);
fclose(destinationFile);

// Display the copied contents from the destination file
destinationFile = fopen(argv[2], “r”);
if (destinationFile == NULL) {
perror(“Error opening destination file for display”);
return 4;
}

printf(“Copied contents from %s:\n”, argv[2]);
char buffer[MAX_BUFFER_SIZE];
while (fgets(buffer, sizeof(buffer), destinationFile) != NULL) {
printf(“%s”, buffer);
}

fclose(destinationFile);

return 0;
}


Q10. Write a C program to create a linked list and print the list in reverse order

Answer :

#include <stdio.h>
#include <stdlib.h>

// Define a Node structure for the linked list
struct Node {
int data;
struct Node* next;
};

// Function to insert a new node at the beginning of the linked list
struct Node* insertNode(struct Node* head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = head;
return newNode;
}

// Function to print the linked list in reverse order
void printReverse(struct Node* head) {
if (head == NULL) {
return;
}

// Recursively call the function for the next node
printReverse(head->next);

// Print the data of the current node
printf(“%d “, head->data);
}

// Function to free the memory allocated for the linked list
void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;

while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}

int main() {
struct Node* head = NULL;

// Insert elements into the linked list
head = insertNode(head, 1);
head = insertNode(head, 2);
head = insertNode(head, 3);
head = insertNode(head, 4);
head = insertNode(head, 5);

// Print the linked list in reverse order
printf(“Linked List in Reverse Order: “);
printReverse(head);

// Free the allocated memory for the linked list
freeList(head);

return 0;
}


Q11. Write a C program to implement insertion sort and write an algorithm for Binary Search

Answer :

 C program for insertion sort :

#include <stdio.h>

void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i – 1;

while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j – 1;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printf(“Sorted array: \n”);
for (int i = 0; i < n; i++)
printf(“%d “, arr[i]);

return 0;
}

Binary Search Algorithm :

BinarySearch(arr, x)
1. Set low to 0 and high to n-1, where n is the size of the array arr.
2. Repeat the following steps while low is less than or equal to high:
a. Set mid to the floor value of (low + high) / 2.
b. If arr[mid] is equal to x, return mid (element found).
c. If arr[mid] is less than x, set low to mid + 1.
d. If arr[mid] is greater than x, set high to mid – 1.
3. If the loop exits, the element x is not present in the array. Return -1.




Q12. Write a C Program to reverse string entered from command line arguments

Answer : 

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

int main(int argc, char *argv[]) {
if (argc != 2) {
printf(“Usage: %s <string>\n”, argv[0]);
return 1;
}

char *inputString = argv[1];
int length = strlen(inputString);

printf(“Original String: %s\n”, inputString);

printf(“Reversed String: “);
for (int i = length – 1; i >= 0; i–) {
printf(“%c”, inputString[i]);
}
printf(“\n”);

return 0;
}


For More Updates Join Our Channels :