0% found this document useful (0 votes)
16 views14 pages

C Programming: Arrays and Functions

The document provides a comprehensive overview of various programming concepts in C, including the definition and use of arrays, nested structures, and multiple programming tasks such as summing natural numbers, reversing strings, matrix operations, and string manipulation functions. It includes example code snippets for each task, demonstrating practical applications of these concepts. Additionally, it explains five string functions in C and provides a program to analyze characters in a string.

Uploaded by

parekhurvi340
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)
16 views14 pages

C Programming: Arrays and Functions

The document provides a comprehensive overview of various programming concepts in C, including the definition and use of arrays, nested structures, and multiple programming tasks such as summing natural numbers, reversing strings, matrix operations, and string manipulation functions. It includes example code snippets for each task, demonstrating practical applications of these concepts. Additionally, it explains five string functions in C and provides a program to analyze characters in a string.

Uploaded by

parekhurvi340
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

Module 4

· Define Array. Apply nested structure.


Definition of Array in C:
An array in C is a collection of elements of the same data type,
stored in contiguous memory locations. Arrays are used to store
multiple values in a single variable.
Syntax:
data_type array_name[size];
Nested Structure with Array Example:
A nested structure means a structure inside another structure. We
can use arrays within such structures.
Example:
#include <stdio.h>
struct Student {
char name[50];
int marks[3]; // Array inside structure
};
int main() {
struct Student s1 = {"John", {85, 90, 78}};
printf("Name: %s\n", [Link]);
printf("Marks: %d, %d, %d\n", [Link][0], [Link][1],
[Link][2]);
return 0;
}

· Write a program to print the sum of any 10 natural


numbers entered using the keyboard.
#include <stdio.h>
int main() {
int numbers[10], sum = 0;
printf("Enter 10 natural numbers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &numbers[i]);
sum += numbers[i];
}
printf("Sum of the entered numbers = %d\n", sum);
return 0;
}

· W.A.P. (Write A Program) to find the reverse of a


string without using standard library functions.
#include <stdio.h>
int main() {
char str[100], temp;
int i, length = 0;
printf("Enter a string: ");
gets(str); // Note: gets() is unsafe, use fgets() in real projects
// Find the length of the string manually
while (str[length] != '\0') {
length++;
}
// Reverse the string in-place
for (i = 0; i < length / 2; i++) {
temp = str[i];
str[i] = str[length - 1 - i];
str[length - 1 - i] = temp;
}
printf("Reversed string: %s\n", str);
return 0;
}

· W.A.P. for the transpose of a matrix.


#include <stdio.h>
int main() {
int matrix[10][10], transpose[10][10];
int rows, cols;
// Input rows and columns
printf("Enter number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Input matrix elements
printf("Enter elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Find transpose
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Print transpose
printf("Transpose of the matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}

· W.A.P. for the addition of two matrices.


#include <stdio.h>
int main() {
int matrix1[10][10], matrix2[10][10], sum[10][10];
int rows, cols;
// Input rows and columns
printf("Enter number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Input elements of first matrix
printf("Enter elements of first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input elements of second matrix
printf("Enter elements of second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Add the matrices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

· W.A.P. for matrix multiplication.


#include <stdio.h>

int main() {
int matrix1[10][10], matrix2[10][10], product[10][10];
int rows1, cols1, rows2, cols2;

// Input size of first matrix


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

// Input size of second matrix


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

// Check if multiplication is possible


if (cols1 != rows2) {
printf("Matrix multiplication not possible. Columns of first
matrix must equal rows of second matrix.\n");
return 0;
}
// Input elements of first matrix
printf("Enter elements of first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Input elements of second matrix


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

// Initialize product matrix with 0


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

// Matrix multiplication logic


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

// Print the product matrix


printf("Product of the matrices:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d ", product[i][j]);
}
printf("\n");
}

return 0;
}

· W.A.P. for sorting an array.


#include <stdio.h>

int main() {
int arr[100], n, temp;
// Input size of array
printf("Enter number of elements: ");
scanf("%d", &n);

// Input array elements


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

// Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

// Print sorted array


printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

· Explain any five string functions in C.


✅ Five String Functions in C:
1. strlen()
o Purpose: Returns the length of a string (excluding the
null character \0).
o Syntax: int len = strlen(str);
o Example:
char str[] = "Hello";
int len = strlen(str); // len = 5
2. strcpy()
o Purpose: Copies one string into another.
o Syntax: strcpy(destination, source);
o Example:
char src[] = "World";
char dest[10];
strcpy(dest, src); // dest now contains "World"
3. strcat()
o Purpose: Appends (concatenates) one string at the end
of another.
o Syntax: strcat(destination, source);
o Example:
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2); // str1 becomes "Hello World"
4. strcmp()
o Purpose: Compares two strings.
o Returns:
▪ 0 if both strings are equal,
▪ < 0 if first string is less,
▪ > 0 if first string is greater.
o Syntax: int result = strcmp(str1, str2);
o Example:
strcmp("apple", "banana"); // returns a negative value
5. strrev() (Note: Not part of standard C, but available in some
compilers like Turbo C)
o Purpose: Reverses a string.
o Syntax: strrev(str);
o Example:
char str[] = "CProgramming";
strrev(str); // str becomes "gnimmargorPC"
· W.A.P. to check if the entered string is a palindrome
or not.
#include <stdio.h>
int main() {
char str[100];
int start = 0, end = 0, isPalindrome = 1;
// Input the string
printf("Enter a string: ");
scanf("%s", str); // Reads string without spaces
// Find length manually
while (str[end] != '\0') {
end++;
}
end--; // Move to the last character index
// Check palindrome
while (start < end) {
if (str[start] != str[end]) {
isPalindrome = 0;
break;
}
start++;
end--;
}
// Print result
if (isPalindrome)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}

· Write a program to count the number of digits,


alphabets, and special characters in an input string.
#include <stdio.h>
int main() {
char str[100];
int i = 0, digits = 0, alphabets = 0, specialChars = 0;
// Input the string
printf("Enter a string: ");
gets(str); // Note: Use fgets() in real-world code to
avoid buffer overflow
// Loop through each character
while (str[i] != '\0') {
if ((str[i] >= '0') && (str[i] <= '9')) {
digits++;
} else if ((str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= 'a' && str[i] <= 'z')) {
alphabets++;
} else {
specialChars++;
}
i++;
}
// Display results
printf("Alphabets: %d\n", alphabets);
printf("Digits: %d\n", digits);
printf("Special Characters: %d\n", specialChars);
return 0;
}

Common questions

Powered by AI

Manually reversing a string involves iterating through the string, swapping characters from the ends towards the center. This process is demonstrated by finding the length of the string first and using a temporary variable to swap characters at positions 'i' and 'length - 1 - i' . In contrast, using strrev, where available, automates this process. The manual method provides more control and understanding of the underlying mechanics, but it also increases the risk of memory issues, such as buffer overflow, which is mitigated when using safe library functions. However, strrev is not standard in C, which makes manual methods necessary in many environments .

One potential pitfall in using scanf for input operations in matrix functions is improper handling of input format and data validation. The scanf function requires precise format specifiers, and improper handling of spaces or incorrect types can lead to undefined behavior or incorrect data being stored in matrix elements . Additionally, scanf does not manage trailing newline characters, which can interfere with subsequent input operations. Moreover, failing to check the return value of scanf might leave unexpected data unhandled, leading to logic errors in matrix operations . Careful management of these aspects is necessary to avoid bugs and ensure data consistency.

The use of fgets over gets is recommended due to memory safety. The gets function doesn't check for buffer overflows, which can lead to program errors and security vulnerabilities if the input string exceeds the defined array size . In contrast, fgets allows specifying a maximum number of characters to read, preventing overflow by limiting the input to the buffer size provided, thus enhancing safety and reliability . Although fgets requires dealing with the newline character it stores, its safe handling of input makes it preferable for robust C programs.

The implementation of special character counting in strings provides a comprehensive analysis of input data, allowing programs to distinguish between different types of input characters. It involves iterating through each character of the input string, incrementing counters for digits, alphabets, and special characters separately . This functionality can be particularly useful in applications requiring data validation, formatting, or sanitizing input, such as password evaluation, text preprocessing, or form input validation, ensuring that proper input types are processed correctly and that potential errors due to unexpected characters are handled .

To implement matrix addition or multiplication beyond the 10x10 size limitation, dynamic memory allocation would be required. This involves using pointers and functions like malloc to allocate sufficient memory for storing larger matrices dynamically. The matrix dimensions should be read into variables, then memory can be allocated based on those sizes, allowing for flexible matrix sizes . Careful memory management is crucial, as there's a need to free allocated memory after matrix operations to avoid memory leaks. Additionally, boundary checks would be needed in loops to ensure operations stay within allocated memory limits.

Matrix multiplication in C requires that the number of columns in the first matrix matches the number of rows in the second matrix, as multiplication is defined as the dot product of the rows of the first matrix and the columns of the second matrix . The provided program ensures this by initializing matrix dimensions and checking their compatibility before proceeding. Additionally, each element in the resulting product matrix is computed by iterating over a common index variable 'k', summing the products of corresponding elements . These constraints ensure that only valid matrix operations are performed, avoiding runtime errors due to dimensional mismatches.

The bubble sort algorithm implemented in the provided C program sorts an array by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. This is done in multiple passes until the array is sorted . The outer loop iterates over the entire array, while the inner loop compares each element with the next, swapping them if necessary, effectively 'bubbling' the largest unsorted element to its correct position. This approach, while simple, is not efficient for large datasets due to its O(n^2) complexity, making it best suited for smaller arrays .

To modify the palindrome-checking program to handle strings with spaces, one approach is to preprocess the string by removing spaces before checking for palindromicity. This can be done by iterating over the input string and constructing a new string that excludes spaces. Instead of scanning using '%s' in scanf, fgets can be used to allow for spaces. The core logic of comparing characters from the start and end would remain the same, factoring in only non-space characters in the comparison process . This modification ensures that sentences like 'A man a plan a canal Panama' can be correctly identified as palindromes.

Arrays in C are collections of elements of the same data type stored in contiguous memory locations, allowing for efficient storage and quick access to multiple values using a single variable name . Within nested structures, arrays can be used to hold multiple values of the same type, enhancing the complexity and capability of the data structure. For instance, in the example given, a 'Student' structure contains a char array for the name and an int array for marks, allowing for the storage of multiple marks entries for each student . This approach is beneficial for organizing and managing data efficiently in programs requiring complex data manipulations.

The strlen function calls an internal library routine optimized for computing string length by counting characters until the null terminator is encountered. It benefits from library-level optimizations not present in a manual iteration . Manual iteration, as is done to find a string's length without using library functions, involves explicitly writing the character-checking loop and counting the characters until the null character, which can be less efficient due to lack of optimizations and increased risk of implementation errors. The performance difference, however, is generally negligible for small strings, but using strlen ensures standardized behavior and reliability .

You might also like