PC Material Unit 2
PC Material Unit 2
data_type array_name[array_size];
• data_type: The type of data the array will store (e.g., int, float, char, etc.).
• array_size: The number of elements the array will hold. This must be a positive integer.
Example:
This declares an array named numbers that can store 5 integers. The elements can be accessed using
indices like numbers[0], numbers[1], and so on.
One-Dimensional Array:
Two-Dimensional Array:
Key Differences:
int main() {
int matrixA[SIZE][SIZE], matrixB[SIZE][SIZE], sum[SIZE][SIZE], difference[SIZE][SIZE];
clrscr();
// Input elements for the first matrix
printf("Enter elements of the first 3x3 matrix:\n");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrixA[i][j]);
}
}
#include <stdio.h>
#include <ctype.h> // For character classification functions
#include<conio.h>
int main() {
char str[100]; // Declare a string of max length 99 + null terminator
int vowels = 0, consonants = 0, digits = 0, whitespaces = 0; // Initialize counters
clrscr();
// Input the string from the user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Use fgets to read the string including spaces
output
Enter a string: Hello World! 123
Number of Vowels: 3
Number of Consonants: 7
Number of Digits: 3
Number of Whitespaces: 2
Explanation:
1. Input String: The program uses fgets() to read a string from the user, which allows spaces in
the input.
2. Character Classification: It uses the ctype.h library functions:
o tolower(): Converts characters to lowercase to simplify vowel checking.
o isalpha(): Checks if a character is an alphabetic letter.
o isdigit(): Checks if a character is a digit.
o isspace(): Checks if a character is a whitespace character.
3. Counters: Four counters are initialized to keep track of vowels, consonants, digits, and
whitespaces.
4. Loop Through String: The program traverses the string character by character, updating the
respective counters based on the character type.
5. Output: Finally, the program prints the counts of vowels, consonants, digits, and
whitespaces.
int main() {
int matrixA[MAX][MAX], matrixB[MAX][MAX], result[MAX][MAX];
int rowA, colA, rowB, colB;
clrscr()
// Input dimensions for the first matrix
printf("Enter rows and columns for the first matrix: ");
scanf("%d %d", &rowA, &colA);
int main() {
int n;
clrscr();
// Input the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Input elements
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
printf("Element [%d]: ", i);
scanf("%d", &arr[i]);
}
Mean: 6.40
Median: 5.00
Explanation of the Program:
1. Include Libraries: The program includes stdio.h for standard input/output and stdlib.h for
using the qsort() function to sort the array.
2. Compare Function: The compare function is defined to be used with qsort() for sorting the
integers in ascending order.
3. Mean Calculation: The calculateMean function sums all the elements in the array and
divides by the number of elements to compute the mean.
4. Median Calculation:
o The calculateMedian function first sorts the array.
o It then checks if the number of elements is even or odd to determine how to
calculate the median.
5. Main Function:
o It prompts the user to enter the number of elements and the elements themselves.
o It then calls the functions to calculate and display the mean and median.
5. Classify various string handling functions with an example program. ( 16
Marks)
In C, string handling functions are provided in the <string.h> library. These functions are classified
into several categories based on their functionality. Below is a classification of various string handling
functions along with a sample program demonstrating their usage.
Classification of String Handling Functions:
1. String Length Functions:
o strlen(): Returns the length of a string.
2. String Copy Functions:
o strcpy(): Copies one string to another.
o strncpy(): Copies a specified number of characters from one string to another.
3. String Concatenation Functions:
o strcat(): Concatenates (appends) one string to another.
o strncat(): Appends a specified number of characters from one string to another.
4. String Comparison Functions:
o strcmp(): Compares two strings.
o strncmp(): Compares a specified number of characters of two strings.
5. String Search Functions:
o strchr(): Searches for the first occurrence of a character in a string.
o strstr(): Searches for the first occurrence of a substring in a string.
6. String Modification Functions:
o strrev(): Reverses a string.
o strupr(): Converts a string to uppercase.
o strlwr(): Converts a string to lowercase.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<conio.h>
int main() {
char str1[100], str2[100], str3[100];
int length;
clrscr();
// Input string
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = 0; // Remove newline character if present
// String length
length = strlen(str1);
printf("Length of the first string: %d\n", length);
// Copy string
strcpy(str2, str1);
printf("Copied string: %s\n", str2);
// Concatenate strings
printf("Enter the second string: ");
fgets(str3, sizeof(str3), stdin);
str3[strcspn(str3, "\n")] = 0; // Remove newline character if present
strcat(str1, str3);
printf("Concatenated string: %s\n", str1);
// Compare strings
int cmpResult = strcmp(str1, str2);
if (cmpResult == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
// Convert to uppercase
for (int i = 0; str1[i]; i++) {
str1[i] = toupper(str1[i]);
}
printf("String in uppercase: %s\n", str1);
int main() {
int n;
clrscr();
// Input the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Input elements
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
printf("Element [%d]: ", i);
scanf("%d", &arr[i]);
}
7. Apply the insertion sort technique to sort the given numbers 56,1,7,9,7,14
with an example program. ( 16 Marks)
Insertion Sort is a simple sorting algorithm that works by repeatedly moving one element at a time
to its correct position in the sorted part of the array. It's efficient for small datasets or partially sorted
arrays.
#include <stdio.h>
#include<conio.h>
// Function to perform insertion sort
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i]; // The element to be inserted
int j = i - 1;
int main() {
int arr[] = {56, 1, 7, 9, 7, 14}; // Given numbers
clrscr();
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; // Sorted array
int size = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements
int target;
clrscr();
// Input target value
printf("Enter the element to search: ");
scanf("%d", &target);
Output
Enter the element to search: 9
Element 9 found at index 4.
Explanation of the Program:
1. Binary Search Function:
o The binarySearch function takes an array, its size, and the target element as input.
o It initializes the low and high pointers and enters a loop that continues until the
search space is exhausted.
o It calculates the middle index and compares the middle element with the target
value to decide which half of the array to continue searching.
2. Print Function:
o The printArray function displays the elements of the array (not directly used in this
example, but useful for debugging).
3. Main Function:
o The program initializes a sorted array of integers.
o It prompts the user to input the target element to search for.
o It calls the binarySearch function and outputs the result.
Linear Search is a straightforward search algorithm that checks each element in a list sequentially
until the desired element is found or the list ends. This method works on both sorted and unsorted
arrays.
Algorithm:
1. Start from the first element and compare it with the target value.
2. If the current element matches the target, return its index.
3. If it does not match, move to the next element.
4. Repeat steps 2 and 3 until you find the target or reach the end of the list.
5. If the target is not found after checking all elements, return an indication that the element is
absent (e.g., -1).
#include <stdio.h>
#include<conio.h>
// Function for linear search
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
// Check if the current element matches the target
if (arr[i] == target) {
return i; // Target found
}
}
return -1; // Target not found
}
int main() {
int arr[] = {56, 1, 7, 9, 7, 14}; // Given numbers
int size = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements
int target;
clrscr();
// Input target value
printf("Original array: ");
printArray(arr, size);
printf("Enter the element to search: ");
scanf("%d", &target);
Program
#include <stdio.h>
#include<conio.h>
// Function to calculate the determinant of a 2x2 matrix
float determinant(float matrix[2][2]) {
return (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]);
}
int main() {
float matrix[2][2] = { {4, 2}, {3, 1} }; // Sample 2x2 matrix
float det, transposed[2][2];
clrscr();
// Calculate the determinant
det = determinant(matrix);
printf("Matrix:\n");
printMatrix(matrix);
printf("Determinant: %.2f\n", det);