Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Subject: Programming Fundamentals

Subject code: EE-133

Submitted to: Dr. Salman Arain

Submitted by: Muhammad Akmal

Reg no.: 2022-UET-NFC-FD- EE-59

Section: B

Semester: 2nd

Department: Electrical Engineering


CQI Assignment
Question no.1:
Write a simple algorithm to find the maximum element in an array of integers.
Additionally, discuss the time complexity of your algorithm. If you were to optimize this
further, what approach you will use?

Solution:
#include <stdio.h>

int findMax(int arr[], int size) {

int max = arr[0];

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

if (arr[i] > max) {

max = arr[i];

return max;

int main() {

int arr[] = { 3, 7, 2, 9, 5 };

int size = sizeof(arr) / sizeof(arr[0]);

int max = findMax(arr, size);

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

return 0;

To optimize this further, you might consider:

 Divide and Conquer (Binary Search):


If the array is sorted, you could use binary search to find the maximum element in
O(log n) time. Sorting the array initially might take O(n log n) time, but subsequent searches
for the maximum value would be faster.
 Parallelization:
For very large arrays, using parallel processing techniques could help divide the
workload among multiple processors/cores, potentially reducing the time required to find the
maximum element.

 Maintaining a Max Heap:


You can build a max heap from the array elements in O(n) time and then extract the
maximum element in O(log n) time, achieving O(n) for finding the maximum.

Question no.2:
Implement a function to check if a given string is a palindrome. A palindrome is a word,
phrase, or sequence of characters that reads the same backward as forward.

Solution:
#include <stdio.h>

#include <string.h>

#include <stdbool.h>

#include <ctype.h>

bool isPalindrome(const char *str) {

int left = 0;

int right = strlen(str) - 1;

while (left < right) {

while (!isalnum(str[left]) && left < right) {

left++;

while (!isalnum(str[right]) && left < right) {

right--;

char leftChar = tolower(str[left]);

char rightChar = tolower(str[right]);

if (leftChar != rightChar) {

return false; // Characters don't match, not a palindrome

}
left++;

right--;

return true; // All characters matched, it's a palindrome

int main() {

const char *str1 = "A man, a plan, a canal, Panama";

const char *str2 = "hello";

if (isPalindrome(str1)) {

printf("\"%s\" is a palindrome.\n", str1);

} else {

printf("\"%s\" is not a palindrome.\n", str1);

if (isPalindrome(str2)) {

printf("\"%s\" is a palindrome.\n", str2);

} else {

printf("\"%s\" is not a palindrome.\n", str2);

return 0;

You might also like