0% found this document useful (0 votes)
12 views2 pages

C Programming Assignment Solutions

Uploaded by

samir241-15-361
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)
12 views2 pages

C Programming Assignment Solutions

Uploaded by

samir241-15-361
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

PPS Assignment Problems

Topics: Functions, Pointers, Strings, Structures

1. Write a function that will find the sum of as many numbers as the user wants
to.
2. Greatest Common Divisor (GCD): Write a function int gcd(int a, int b)

that finds the greatest common divisor of two integers a and b.

3. Palindrome Checker: Write a function int is_palindrome(char str[])

that checks if a given string str is a palindrome (reads the same backward as

forward).

4. Prime Number Checker: Write a function int is_prime(int num) that

determines if a given number num is prime.

5. String Length (without using strlen): Write a function int

string_length(char str[]) to find the length of a string str (without using

the built-in strlen function).

6. Swap Two Numbers: Write a function void swap(int *x, int *y) that

swaps the values of two integers pointed to by x and y.

7. Array Sum with Pointers: Write a function int sum_array(int arr[], int

size) that calculates the sum of elements in an array arr of size size using

pointers.

8. Reverse an Array: Write a function void reverse_array(int arr[], int

size) that reverses the elements of an array arr of size size in-place using

pointers.

9. Find Maximum in an Array: Write a function int find_max(int arr[], int

size) that finds the maximum element in an array arr of size size using

pointers.

10. String Copy (without using strcpy): Write a function void

string_copy(char dest[], char src[]) that copies a source string src to

a destination string dest (without using the built-in strcpy function).


11. Count Vowels and Consonants: Write a program that counts the number of

vowels and consonants in a given string.

12. Extract Words from a String: Write a program that extracts individual words

from a string separated by delimiters (e.g., spaces, commas).

13. Replace Substring: Write a function void replace_substring(char str[],

char old_sub[], char new_sub[]) that replaces occurrences of a substring

old_sub in a string str with a new substring new_sub.

14. Convert String to Uppercase/Lowercase: Write functions void

to_uppercase(char str[]) and void to_lowercase(char str[]) to

convert a string str to uppercase and lowercase, respectively.

15. Check if String is a Substring of Another: Write a function int

is_substring(char str[], char sub[]) that checks if a string sub is a

substring of another string str.

16. Write a c program to find the position of the first occurrence of a given

character in a string.

17. Write a program to find occurrences of each character in a string.

18. Date Structure: Define a structure Date to hold day, month, and year. Write

functions to check if a date is valid and calculate the difference between two

dates.

19. Student Record: Create a structure Student to store student information

(name, roll number, marks in various subjects). Write functions to create,

display, and calculate the total marks for a student.

20. Date Structure: Create a structure to represent a date (day, month, year)

and functions to compare two dates, calculate the difference between dates,

and perform other date-related operations.

Common questions

Powered by AI

Using pointers to reverse an array in-place is efficient regarding both time and space complexity. By using two pointers, one starting at the beginning and the other at the end, the elements are swapped and the pointers are moved towards each other until they meet. This results in an O(n) time complexity, where n is the number of elements. It does not use any additional space beyond a temporary variable for the swap, hence it's space-efficient. However, proper handling of pointers is essential to prevent issues such as accessing illegal memory locations.

Utilizing a structure to hold student data encapsulates the related attributes within a single entity, enhancing readability and maintainability by grouping logically related data. This approach supports encapsulation and allows for the scalability of adding new attributes without significant code changes. Moreover, structures lend themselves better to complex operations like sorting or searching through pointer manipulation. On the other hand, using individual variables for each student's attribute can lead to cumbersome and error-prone code, especially as the system scales. It hinders modular design and increases the risk of inconsistency, especially in large codebases with many student records.

To implement a function that finds the GCD of two integers using the Euclidean algorithm, the steps are: 1) Accept two integer inputs a and b. 2) Use a loop or recursion to repeatedly replace the larger number by its remainder when divided by the smaller number, until the remainder becomes zero. 3) When the remainder is zero, the other number in the pair at this step is the GCD. This leverages the property that GCD(a, b) = GCD(b, a % b), and reduces computation through division until a result is reached, ensuring efficient processing.

A function to find the sum of a dynamic number of integers can take advantage of variable-length argument lists and looping constructs. One approach is to use a loop that repeatedly accepts numbers from user input until a specific termination instruction (such as inputting a '0' or a non-numeric character) is given, and accumulates the total using a running sum. Alternatively, advanced techniques such as using the ellipsis (...) for variable-length parameters in a function prototype (e.g., int sum_numbers(int count, ...)) can be applied if variable arguments are permissible in the given context. This latter approach requires the use of <stdarg.h> for managing the arguments. The implications of each method include considerations of input validation and error handling to ensure robustness.

A palindrome check can be efficiently performed in-place by using two pointers: one starting at the beginning and the other at the end of the string, moving towards the center. The function compares characters pointed by them in each iteration. If all pairs match, the string is a palindrome. This approach, `int is_palindrome(char str[])`, is efficient as it requires O(n/2) comparisons for a string of length n, operating in O(n) time complexity overall. No additional data structures are required, as comparisons and checks are done on the original string, making it memory efficient.

Replacing a substring within a string manually involves scanning through the string for the occurrence of the target substring, copying preceding characters to a new string, appending the replacement substring, and then copying any following characters. The main loop continues until the entire string is traversed. Considerations include handling overlapping substrings, ensuring the source string has sufficient size to hold the expanded string, and reassessing buffer allocation dynamically. The algorithm's complexity is O(n * m), where n is the length of the string and m is the length or number of replacements, as each target substring location must be checked individually.

Finding the maximum element in an array using pointers involves iterating through the array with a pointer, starting from the first element. A variable is initialized to hold the maximum value, updated whenever a larger value is found: `int find_max(int arr[], int size) { int *ptr = arr; int max = *ptr; for(int i = 1; i < size; i++) { if (*(ptr + i) > max) max = *(ptr + i); } return max; }`. Pitfalls include pointer mismanagement leading to out-of-bounds access, and potential segfaults if the pointer is not appropriately initialized or if incorrect arithmetic is used. Additionally, the function does not handle edge cases such as empty arrays.

Designing a program to extract words from a string with various delimiters involves identifying and splitting the string at each delimiter occurrence. The common approach utilizes functions like strtok in C, which tokens the string iteratively based on the specified delimiters (e.g., " \t,."). The challenge lies in ensuring that consecutive delimiters, edge delimiters, and different whitespace characters are handled correctly without losing relevant data. Additionally, strtok alters the original string, which may not be desirable in all scenarios, demanding a need to preserve the original data format through alternative means like manual iteration and copying.

When writing a swap function using pointers, the primary consideration is ensuring both pointers are not null to avoid dereferencing issues, which can lead to segmentation faults. The function involves receiving pointer references to the integers, temporarily storing one value, and then exchanging them: `void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; }`. Additionally, careful memory handling must ensure that unexpected side-effects do not alter other parts of the program due to memory corruption. Such a function allows in-place swapping without the overhead of extra memory allocation.

A date structure should contain day, month, and year attributes. Key functional components include a method to validate the date—ensuring the day aligns with the month's length and accounts for leap years. The function to calculate differences must correctly handle varying month lengths and leap year adjustments. Considerations involve handling edge cases such as invalid date inputs, processing differences accurately over years and months, and upgrading functionality to include additional features like formatting. The complexity lies in balancing readability and ensuring exactness in the arithmetic operations handling period calculations and validations, ensuring wide adaptability and correctness.

You might also like