Section-A:
1. What are header files and their uses?
Header files in C contain declarations of functions,
macros, constants, and data types used in programs. They allow code reuse and
modular programming by providing predefined functions and simplifying complex
tasks.
Common Header Files:
- #include
<stdio.h> – Standard Input/Output functions (e.g., printf(),
scanf()).
- #include
<stdlib.h> – Memory allocation and process control (malloc(),
exit()).
- #include
<string.h> – String handling functions (strlen(), strcpy()).
Uses:
- Code
Reusability: Avoids rewriting common code.
- Modularity:
Organizes code logically.
- Simplifies
Complex Operations: Provides ready-to-use functions.
2. What is the difference between macro and functions?
Feature |
Macro |
Function |
Definition |
Defined using #define preprocessor directive. |
Defined using the return_type and function_name. |
Execution |
Replaced by code during compilation. |
Called during program execution. |
Speed |
Faster (no function call overhead). |
Slower due to function call overhead. |
Debugging |
Harder to debug (no type checking). |
Easier to debug (type checking enforced). |
Example |
#define SQUARE(x) ((x)*(x)) |
int square(int x) { return x*x; } |
3. What is a structure? How is it different from Union?
A structure (struct) in C is a user-defined data type
that allows grouping variables of different types under one name.
Structure Example:
struct Student {
int id;
char name[20];
float marks;
};
A union also groups variables of different types but
shares the same memory location for all members.
Union Example:
union Data {
int i;
float f;
char str[20];
};
Difference Between Structure and Union:
Feature |
Structure |
Union |
Memory |
Allocates memory for all members. |
Shares memory among members. |
Usage |
All members can be used simultaneously. |
Only one member holds a value at a time. |
Size |
Sum of all members' sizes. |
Size of the largest member. |
4. What is static memory allocation and dynamic memory
allocation?
Static Memory Allocation:
- Memory
is allocated during compile-time.
- The
size is fixed and cannot be changed during runtime.
- Faster
and safer.
- Example:
- int
arr[10]; // Static array of size 10
Dynamic Memory Allocation:
- Memory
is allocated during runtime.
- The
size can change as needed.
- Managed
using functions like malloc(), calloc(), realloc(), and free().
- Example:
- int
*ptr;
- ptr
= (int *)malloc(10 * sizeof(int));
// Dynamic array of size 10
Difference:
Feature |
Static Memory Allocation |
Dynamic Memory Allocation |
When Allocated |
Compile-time |
Runtime |
Memory Size |
Fixed |
Flexible |
Functions Used |
None |
malloc(), calloc() |
Efficiency |
Faster |
Slightly slower |
5. What is the difference between getc(), getchar(),
getch(), and getche()?
Function |
Purpose |
Echo Input? |
Buffered? |
Header File |
getc() |
Reads a character from a file or stdin. |
Yes |
Yes |
stdio.h |
getchar() |
Reads a character from standard input. |
Yes |
Yes |
stdio.h |
getch() |
Reads a character without echoing input. |
No |
No |
conio.h |
getche() |
Reads a character and echoes input. |
Yes |
No |
conio.h |
Examples:
char ch;
// Using getc()
ch = getc(stdin);
// Using getchar()
ch = getchar();
// Using getch()
ch = getch();
// Using getche()
ch = getche();
Section-B Detailed Solutions
Question 6: Write a C program that reads 20 integer
numbers from keywords and sorts them in ascending order.
Explanation:
This program takes 20 integer inputs from the user, stores them in an array,
and sorts them using the Bubble Sort algorithm. Bubble Sort repeatedly steps
through the list, compares adjacent elements, and swaps them if they are in the
wrong order.
C Program:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i <
n - 1; i++) {
for (j = 0; j
< n - i - 1; j++) {
if (arr[j]
> arr[j + 1]) {
temp =
arr[j];
arr[j]
= arr[j + 1];
arr[j
+ 1] = temp;
}
}
}
}
int main() {
int arr[20], i;
printf("Enter
20 integers:\n");
for (i = 0; i <
20; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr,
20);
printf("Sorted numbers in ascending order:\n");
for (i = 0; i <
20; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation of the Program:
- Input:
The program uses a loop to take 20 integer inputs.
- Sorting:
The bubbleSort function sorts the array in ascending order.
- Output:
The sorted array is printed.
Time Complexity: O(n^2)
Space Complexity: O(1)
Question 7: Write a C program to check input string is
palindrome or not without using any string library function.
Explanation:
A palindrome is a string that reads the same backward as forward. This program
reads a string from the user and checks if it is a palindrome without using
string library functions.
C Program:
#include <stdio.h>
int stringLength(char str[]) {
int length = 0;
while (str[length]
!= '\0') {
length++;
}
return length;
}
int isPalindrome(char str[]) {
int i, len = stringLength(str);
for (i = 0; i <
len / 2; i++) {
if (str[i] !=
str[len - i - 1]) {
return 0;
// Not a palindrome
}
}
return 1; //
Palindrome
}
int main() {
char str[100];
printf("Enter
a string: ");
scanf("%s", str);
if
(isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Explanation of the Program:
- Input:
Reads a string from the user.
- Length
Calculation: The stringLength function calculates the length of the
string.
- Palindrome
Check: Compares characters from both ends moving towards the center.
- Output:
Displays whether the string is a palindrome.
Example Output:
Enter a string: madam
The string is a palindrome.
Enter a string: hello
The string is not a palindrome.
Time Complexity: O(n)
Space Complexity: O(1)
Section-C Detailed Solutions
Question 8: Write a C program to add two complex numbers
by passing structure to a function.
Explanation:
A complex number has a real and an imaginary part. This program defines a
structure for complex numbers and uses a function to add two complex numbers.
C Program:
#include <stdio.h>
typedef struct {
float real;
float imag;
} Complex;
Complex addComplex(Complex a, Complex b) {
Complex result;
result.real =
a.real + b.real;
result.imag =
a.imag + b.imag;
return result;
}
int main() {
Complex num1,
num2, sum;
printf("Enter
real and imaginary parts of first complex number: ");
scanf("%f
%f", &num1.real, &num1.imag);
printf("Enter
real and imaginary parts of second complex number: ");
scanf("%f
%f", &num2.real, &num2.imag);
sum =
addComplex(num1, num2);
printf("Sum =
%.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
Explanation of the Program:
- Defines
a Complex structure with real and imaginary parts.
- addComplex
function adds two complex numbers.
- Reads
two complex numbers from the user and prints their sum.
Question 9: What do you mean by pointer? Write a C
program to access elements in a 2-dimensional array using a pointer.
Explanation:
A pointer is a variable that stores the address of another variable. This
program demonstrates accessing a 2D array using pointers.
C Program:
#include <stdio.h>
int main() {
int arr[3][3],
*ptr, i, j;
printf("Enter
elements of 3x3 matrix:\n");
for (i = 0; i <
3; i++) {
for (j = 0; j
< 3; j++) {
scanf("%d", &arr[i][j]);
}
}
ptr =
&arr[0][0];
printf("Matrix elements:\n");
for (i = 0; i <
3; i++) {
for (j = 0; j
< 3; j++) {
printf("%d ", *(ptr + i * 3 + j));
}
printf("\n");
}
return 0;
}
Explanation of the Program:
- Reads
a 3x3 matrix from the user.
- Uses
a pointer to access and print matrix elements.
Question 10: How string is different from an array? Write
a C program to convert a lowercase string to uppercase without using string
manipulation functions.
Explanation:
Strings are arrays of characters ending with a null character \0. This program
converts lowercase letters to uppercase manually.
C Program:
#include <stdio.h>
void toUpperCase(char str[]) {
int i = 0;
while (str[i] !=
'\0') {
if (str[i]
>= 'a' && str[i] <= 'z') {
str[i] =
str[i] - 32;
}
i++;
}
}
int main() {
char str[100];
printf("Enter
a lowercase string: ");
scanf("%s", str);
toUpperCase(str);
printf("Uppercase String: %s\n", str);
return 0;
}
Explanation of the Program:
- Reads
a lowercase string.
- Converts
each character to uppercase by subtracting 32 from its ASCII value.
Question 11: Write a program in C to count the number of
words and characters in an input file test1.txt.
Explanation:
This program reads text from a file and counts the number of words and
characters.
C Program:
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *file;
char ch;
int words = 0,
chars = 0, inWord = 0;
file =
fopen("test1.txt", "r");
if (file == NULL)
{
printf("File not found!\n");
return 1;
}
while ((ch =
fgetc(file)) != EOF) {
chars++;
if
(isspace(ch)) {
inWord =
0;
} else if
(inWord == 0) {
inWord =
1;
words++;
}
}
fclose(file);
printf("Total
characters: %d\n", chars);
printf("Total
words: %d\n", words);
return 0;
}
Explanation of the Program:
- Opens
test1.txt for reading.
- Counts
characters and words.
Question 12: Write a program in C for the multiplication
of two matrices of size 4x4.
Explanation:
This program multiplies two 4x4 matrices entered by the user.
C Program:
#include <stdio.h>
int main() {
int a[4][4],
b[4][4], result[4][4] = {0}, i, j, k;
printf("Enter
elements of first 4x4 matrix:\n");
for (i = 0; i <
4; i++) {
for (j = 0; j
< 4; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter
elements of second 4x4 matrix:\n");
for (i = 0; i <
4; i++) {
for (j = 0; j
< 4; j++) {
scanf("%d", &b[i][j]);
}
}
for (i = 0; i <
4; i++) {
for (j = 0; j
< 4; j++) {
for (k =
0; k < 4; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
printf("Resultant matrix:\n");
for (i = 0; i <
4; i++) {
for (j = 0; j
< 4; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Explanation of the Program:
- Reads
two 4x4 matrices.
- Multiplies
them and prints the result.
Detailed Explanation for Question 8:
"Write a C program to add two complex numbers by
passing structure to a function."
Concepts Involved:
- Complex
Numbers:
A complex number has two parts: - Real
part
- Imaginary
part
Example: 3+4i3 + 4i → Real part = 3, Imaginary part = 4 - Structures
in C:
Structures allow grouping different data types under a single name. Here, a structure can hold the real and imaginary parts of a complex number. - Function
with Structure as Argument:
Passing a structure to a function allows performing operations like addition using separate logic.
Steps to Solve the Problem:
- Define
a structure to represent a complex number with two float members: real
and imaginary.
- Create
a function that takes two complex numbers as parameters and returns
their sum.
- Input
values for two complex numbers from the user.
- Call
the function to compute the sum.
- Display
the result.
C Program:
#include <stdio.h>
// Define a structure for complex numbers
struct Complex {
float real;
float imag;
};
// Function to add two complex numbers
struct Complex addComplex(struct Complex c1, struct Complex
c2) {
struct Complex
result;
result.real =
c1.real + c2.real;
result.imag =
c1.imag + c2.imag;
return result;
}
int main() {
struct Complex
num1, num2, sum;
// Input for first
complex number
printf("Enter
real and imaginary part of first complex number:\n");
scanf("%f
%f", &num1.real, &num1.imag);
// Input for
second complex number
printf("Enter
real and imaginary part of second complex number:\n");
scanf("%f
%f", &num2.real, &num2.imag);
// Add the two
complex numbers
sum =
addComplex(num1, num2);
// Display the
result
printf("Sum
of the complex numbers = %.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
Explanation of the Program:
- Structure
Definition:
- struct Complex {
- float real;
- float imag;
- };
This structure holds the real and imaginary parts of a
complex number.
- Function
to Add Complex Numbers:
- struct Complex
addComplex(struct Complex c1, struct Complex c2) {
- struct Complex result;
- result.real = c1.real + c2.real;
- result.imag = c1.imag + c2.imag;
- return result;
- }
- Takes
two Complex structures as input.
- Adds
the real parts and imaginary parts separately.
- Returns
the result as a Complex structure.
- User
Input:
- scanf("%f %f",
&num1.real, &num1.imag);
- scanf("%f %f",
&num2.real, &num2.imag);
Reads real and imaginary parts for both complex numbers.
- Function
Call and Result:
- sum = addComplex(num1,
num2);
- printf("Sum of the
complex numbers = %.2f + %.2fi\n", sum.real, sum.imag);
Calls the addComplex() function and prints the result.
Sample Output:
Enter real and imaginary part of first complex number:
3.5 2.5
Enter real and imaginary part of second complex number:
1.5 4.5
Sum of the complex numbers = 5.00 + 7.00i
Key Points to Remember:
- Structures
help organize related data.
- Functions
can accept structures as arguments for modularity.
- Real
and imaginary parts are added separately in complex addition.
Detailed Explanation for Question 9:
"What do you mean by pointer? Write a C program to
access elements in a 2-dimensional array using a pointer."
Concepts Involved:
1. Pointer in C:
A pointer is a variable that stores the memory
address of another variable. It is used to access and manipulate data stored in
memory directly.
- Declaration:
- int *ptr; // Pointer to an integer
- Usage:
- &
(Address-of operator): Gives the address of a variable.
- *
(Dereference operator): Accesses the value at the address stored in a
pointer.
2. 2D Array in C:
A 2D array is an array of arrays.
Example:
int arr[2][3] = { {1, 2, 3}, {4, 5, 6} };
Memory Representation:
Row 0 → 1 2 3
Row 1 → 4 5 6
3. Pointer with 2D Arrays:
In C, a 2D array is stored in row-major order,
meaning the elements are stored row by row in memory.
- Accessing
elements:
Using pointers, an element at arr[i][j] can be accessed as: - *(*(arr + i) + j)
Program to Access 2D Array Elements Using Pointers
#include <stdio.h>
#define ROW 2
#define COL 3
int main() {
int arr[ROW][COL]
= { {1, 2, 3}, {4, 5, 6} };
int *ptr;
// Pointer
pointing to the first element of the array
ptr =
&arr[0][0];
printf("Accessing 2D array elements using pointer:\n");
// Loop through
the 2D array using pointer arithmetic
for(int i = 0; i
< ROW; i++) {
for(int j = 0;
j < COL; j++) {
// Using
pointer to access elements
printf("%d ", *(ptr + i * COL + j));
}
printf("\n");
}
return 0;
}
Explanation of the Program:
- Array
Initialization:
- int arr[ROW][COL] = {
{1, 2, 3}, {4, 5, 6} };
Creates a 2D array with 2 rows and 3 columns.
- Pointer
Declaration and Initialization:
- int *ptr;
- ptr = &arr[0][0];
The pointer ptr is assigned the address of the first element
of the array.
- Accessing
Elements Using Pointer Arithmetic:
- *(ptr + i * COL + j)
- ptr
+ i * COL + j moves the pointer to the desired element.
- *
dereferences the pointer to access the value.
- Nested
Loops for Traversing:
Loops iterate over each row and column to print the array.
Memory Representation:
In memory, the 2D array is stored as:
Index: 0 1 2 3 4 5
Value: 1 2 3 4 5 6
So,
- *(ptr
+ 0) → 1
- *(ptr
+ 1) → 2
- *(ptr
+ 3) → 4
Sample Output:
Accessing 2D array elements using pointer:
1 2 3
4 5 6
Alternate Method Using Double Pointers:
#include <stdio.h>
#define ROW 2
#define COL 3
void printArray(int (*ptr)[COL]) {
for(int i = 0; i
< ROW; i++) {
for(int j = 0;
j < COL; j++) {
printf("%d ", *(*(ptr + i) + j));
}
printf("\n");
}
}
int main() {
int arr[ROW][COL]
= { {1, 2, 3}, {4, 5, 6} };
printArray(arr);
return 0;
}
Explanation:
- int
(*ptr)[COL] is a pointer to an array of integers with COL elements.
- *(*(ptr
+ i) + j) accesses elements.
Key Points to Remember:
- A
pointer can access all elements of a 2D array through pointer arithmetic.
- The
formula *(ptr + i * COL + j) is based on row-major order.
- Efficient
in terms of memory and performance, especially for large arrays.
Detailed Explanation for Question 10:
"How is a string different from an array? Write a C
program to convert a lower case string to upper case string without using
string manipulation functions."
Part 1: Difference Between a String and an Array
Aspect |
Array |
String |
Definition |
Collection of elements of the same data type. |
Array of characters ending with a null character (\0). |
Data Types |
Can be of any type (int, float, char, etc.). |
Always an array of characters. |
Null Terminator |
Does not have a null character automatically. |
Ends with \0 to mark the end of the string. |
Access |
Accessed by index. |
Accessed by index but ends at \0. |
Example |
int arr[5] = {1, 2, 3, 4, 5}; |
char str[] = "hello"; → { 'h', 'e', 'l', 'l',
'o', '\0' } |
Operations |
No direct functions for operations. |
Has built-in functions (strlen(), strcpy()). |
Part 2: C Program to Convert Lowercase to Uppercase
Without String Functions
Concept Used:
- ASCII
Values:
- Lowercase
letters (a–z) have ASCII values from 97 to 122.
- Uppercase
letters (A–Z) have ASCII values from 65 to 90.
- Difference:
A - a = -32 → To convert lowercase to uppercase, subtract 32.
Logic:
- Traverse
each character in the string.
- If
the character is between 'a' and 'z', convert it by subtracting 32.
- Else,
leave it unchanged.
C Program:
#include <stdio.h>
void toUpperCase(char *str) {
int i = 0;
// Traverse each
character in the string
while (str[i] !=
'\0') {
// Check if
the character is lowercase
if (str[i]
>= 'a' && str[i] <= 'z') {
str[i] =
str[i] - 32; // Convert to uppercase
}
i++;
}
}
int main() {
char str[100];
// Input from the
user
printf("Enter
a lowercase string: ");
scanf("%[^\n]%*c", str);
// Reads string with spaces
// Convert to
uppercase
toUpperCase(str);
// Display result
printf("Uppercase string: %s\n", str);
return 0;
}
Explanation of the Program:
- Function
to Convert to Uppercase:
- void toUpperCase(char *str)
- Takes
a character array (string) as input.
- Loops
through the string until '\0' is reached.
- Conversion
Logic:
- if (str[i] >= 'a'
&& str[i] <= 'z') {
- str[i] = str[i] - 32;
- }
- If
the character is lowercase, subtract 32 to convert it to
uppercase.
- User
Input:
- scanf("%[^\n]%*c",
str);
- Reads
the entire input, including spaces.
- Output:
- printf("Uppercase
string: %s\n", str);
- Prints
the converted uppercase string.
Sample Run:
Input:
Enter a lowercase string: hello world
Output:
Uppercase string: HELLO WORLD
Key Points:
- ASCII
conversion avoids using built-in functions like strupr() or toupper().
- The
program preserves non-alphabetic characters (spaces, punctuation).
- Efficient
and lightweight solution.
Would you like me to explain any part of this further or
modify the program?
Detailed Explanation for Question 11:
"Write a program in C to count the number of words
and characters in an input file test1.txt."
Concepts Involved:
- File
Handling in C:
- C
uses file pointers (FILE *) to handle files.
- Functions
like fopen(), fgetc(), and fclose() are used to read/write files.
- Character
Counting:
- Count
every character until the End of File (EOF) is reached.
- Word
Counting:
- A
word is detected when a sequence of characters is followed by a space,
newline, or tab.
- Handle
multiple spaces or line breaks to avoid miscounts.
C Program to Count Words and Characters in a File
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *file;
char filename[] =
"test1.txt";
char ch;
int characters =
0, words = 0;
int inWord = 0;
// Open the file
in read mode
file =
fopen(filename, "r");
// Check if the
file was opened successfully
if (file == NULL)
{
printf("Error: Could not open the file %s\n", filename);
return 1;
}
// Read each
character until EOF
while ((ch =
fgetc(file)) != EOF) {
characters++; // Count every
character
// Check for
word boundaries
if
(isspace(ch)) {
inWord =
0; // Outside a word when whitespace is
found
} else if
(inWord == 0) {
inWord =
1; // Start of a new word
words++;
}
}
// Close the file
fclose(file);
// Display the
counts
printf("Total
Characters: %d\n", characters);
printf("Total
Words: %d\n", words);
return 0;
}
Explanation of the Program:
- File
Pointer Declaration:
- FILE *file;
- Declares
a file pointer to manage file operations.
- Opening
the File:
- file = fopen(filename,
"r");
- Opens
test1.txt in read mode ("r").
- If
the file doesn't exist, it prints an error.
- Reading
the File:
- while ((ch =
fgetc(file)) != EOF)
- Reads
each character one by one using fgetc() until End of File (EOF).
- Character
Counting:
- characters++;
- Increments
for every character read, including spaces and newlines.
- Word
Counting Logic:
- if (isspace(ch)) {
- inWord = 0;
- } else if (inWord == 0)
{
- inWord = 1;
- words++;
- }
- isspace(ch)
checks for spaces, tabs, or newlines.
- inWord
tracks if the current character is inside a word.
- Closing
the File:
- fclose(file);
- Always
close the file to free system resources.
- Displaying
the Result:
- printf("Total
Characters: %d\n", characters);
- printf("Total
Words: %d\n", words);
Sample Content of test1.txt:
Hello World!
This is a file with words.
Program Output:
Total Characters: 35
Total Words: 7
Explanation:
- Characters
(35): Includes all letters, spaces, punctuation, and newline
characters.
- Words
(7): Hello, World!, This, is, a, file, with, words.
Edge Cases to Consider:
- Empty
File:
- Output
→ Characters: 0, Words: 0
- Multiple
Spaces or Newlines:
- Handled
correctly due to the use of isspace().
- Special
Characters:
- Counted
as characters but not as words.
Key Points:
- File
handling ensures reading the file content efficiently.
- Word
detection is based on whitespace separation.
- Proper
error handling prevents crashes if the file is missing.
Detailed Explanation for Question 12:
"Write a program in C for the multiplication of two
matrices of size 4×4."
Concepts Involved:
1. Matrix Multiplication Basics:
Matrix multiplication involves multiplying rows of the first
matrix by columns of the second matrix.
- Formula:
For two matrices A and B, the element at position (i, j) in the result matrix C is calculated as: C[i][j]=∑k=0n−1A[i][k]×B[k][j]C[i][j] = \sum_{k=0}^{n-1} A[i][k] \times B[k][j] Where: - i
→ Row index of matrix A.
- j
→ Column index of matrix B.
- k
→ Iterates over the shared dimension.
2. Matrix Dimension Compatibility:
- Matrix
A of size m x n can only be multiplied with Matrix B of size
n x p.
- The
resulting matrix will be of size m x p.
- In
this case: Both matrices are 4×4, so the result will also be 4×4.
C Program for 4×4 Matrix Multiplication
#include <stdio.h>
#define SIZE 4 //
Define the size of the matrix
void multiplyMatrices(int A[SIZE][SIZE], int B[SIZE][SIZE],
int result[SIZE][SIZE]) {
// Initialize the
result matrix to zero
for (int i = 0; i
< SIZE; i++) {
for (int j =
0; j < SIZE; j++) {
result[i][j] = 0;
}
}
// Perform matrix
multiplication
for (int i = 0; i
< SIZE; i++) {
for (int j =
0; j < SIZE; j++) {
for (int k
= 0; k < SIZE; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
}
// Function to print the matrix
void printMatrix(int matrix[SIZE][SIZE]) {
for (int i = 0; i
< SIZE; i++) {
for (int j =
0; j < SIZE; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
// Define two 4x4
matrices
int A[SIZE][SIZE]
= {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11,
12},
{13, 14, 15,
16}
};
int B[SIZE][SIZE]
= {
{16, 15, 14,
13},
{12, 11, 10,
9},
{8, 7, 6, 5},
{4, 3, 2, 1}
};
int
result[SIZE][SIZE]; // Result matrix
// Multiply
matrices A and B
multiplyMatrices(A, B, result);
// Display the
result
printf("Resultant Matrix after Multiplication:\n");
printMatrix(result);
return 0;
}
Explanation of the Program:
- Matrix
Initialization:
Two 4×4 matrices A and B are defined with predefined values. - Matrix
Multiplication Logic:
- result[i][j] += A[i][k]
* B[k][j];
- Three
nested loops are used:
- Outer
loop (i): Iterates over rows of matrix A.
- Middle
loop (j): Iterates over columns of matrix B.
- Inner
loop (k): Multiplies and sums the corresponding elements.
- Result
Matrix Initialization:
The result matrix is initialized to zero before starting the multiplication. - Matrix
Printing:
A separate function printMatrix() is used to display the resulting matrix in a formatted way.
Step-by-Step Example Calculation:
Given:
Matrix A:
1 2 3
4
5 6 7
8
9 10 11 12
13 14 15 16
Matrix B:
16 15 14 13
12 11 10 9
8 7 6
5
4 3 2 1
Calculation for Element at (0,0):
C[0][0]=(1×16)+(2×12)+(3×8)+(4×4)=16+24+24+16=80C[0][0] = (1
\times 16) + (2 \times 12) + (3 \times 8) + (4 \times 4) = 16 + 24 + 24 + 16 =
80
Sample Output:
Resultant Matrix after Multiplication:
80 70 60 50
240 214 188 162
400 358 316 274
560 502 444 386
Key Points to Remember:
- Time
Complexity: O(n3)O(n^3) due to three nested loops.
- Space
Complexity: Requires additional space for the result matrix.
- Matrix
Compatibility: Both matrices must have the same size for this program.
Detailed Explanation for Question 13:
"Create a structure named 'Book' to store book
details like title, author, and price. Write a C program to input details for
three books, find the most expensive and the lowest priced books, and display
their information."
Concepts Involved:
- Structures
in C:
- Used
to group related data of different types under a single name.
- Allows
combining variables like strings (for title and author) and floats (for
price).
- Array
of Structures:
- An
array can store multiple instances of a structure, making it easy to
handle multiple books.
- Input/Output
Operations:
- Using
scanf() and printf() to take user input and display output.
- Finding
Maximum and Minimum Values:
- Comparing
prices to determine the most expensive and cheapest books.
C Program to Handle Book Details
#include <stdio.h>
#include <string.h>
// Define a structure for Book
struct Book {
char title[100];
char author[100];
float price;
};
int main() {
struct Book
books[3]; // Array to store 3 books
int i, maxIndex =
0, minIndex = 0;
// Input details
for 3 books
for (i = 0; i <
3; i++) {
printf("Enter details for Book %d:\n", i + 1);
// Input title
printf("Title: ");
getchar(); // Clears the buffer
fgets(books[i].title,
sizeof(books[i].title), stdin);
books[i].title[strcspn(books[i].title, "\n")] = '\0'; // Remove newline character
// Input
author
printf("Author: ");
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0'; // Remove newline character
// Input price
printf("Price: ");
scanf("%f", &books[i].price);
}
// Find the most
expensive and the cheapest books
for (i = 1; i <
3; i++) {
if
(books[i].price > books[maxIndex].price) {
maxIndex =
i; // Most expensive book
}
if
(books[i].price < books[minIndex].price) {
minIndex =
i; // Cheapest book
}
}
// Display the
most expensive book
printf("\nMost Expensive Book:\n");
printf("Title: %s\n", books[maxIndex].title);
printf("Author: %s\n", books[maxIndex].author);
printf("Price: %.2f\n", books[maxIndex].price);
// Display the
cheapest book
printf("\nCheapest Book:\n");
printf("Title: %s\n", books[minIndex].title);
printf("Author: %s\n", books[minIndex].author);
printf("Price: %.2f\n", books[minIndex].price);
return 0;
}
Explanation of the Program:
- Structure
Definition:
- struct Book {
- char title[100];
- char author[100];
- float price;
- };
- title
→ Stores the book title.
- author
→ Stores the author's name.
- price
→ Stores the price of the book.
- Array
of Structures:
- struct Book books[3];
- Stores
details of 3 books.
- Input
for Book Details:
- fgets(books[i].title,
sizeof(books[i].title), stdin);
- fgets(books[i].author,
sizeof(books[i].author), stdin);
- scanf("%f",
&books[i].price);
- fgets()
is used for multi-word input.
- scanf()
reads the price.
- getchar()
clears the input buffer to avoid skipping input.
- Finding
Maximum and Minimum Prices:
- if (books[i].price >
books[maxIndex].price)
- maxIndex = i;
- if (books[i].price <
books[minIndex].price)
- minIndex = i;
- Iterates
through the books and tracks the index of the most expensive (maxIndex)
and the cheapest (minIndex) books.
- Displaying
Results:
- printf("\nMost
Expensive Book:\n");
- printf("Title:
%s\n", books[maxIndex].title);
- printf("Author:
%s\n", books[maxIndex].author);
- printf("Price:
%.2f\n", books[maxIndex].price);
- Prints
the details of the most expensive and the cheapest books.
Sample Run:
Input:
Enter details for Book 1:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: 450
Enter details for Book 2:
Title: 1984
Author: George Orwell
Price: 300
Enter details for Book 3:
Title: War and Peace
Author: Leo Tolstoy
Price: 600
Output:
Most Expensive Book:
Title: War and Peace
Author: Leo Tolstoy
Price: 600.00
Cheapest Book:
Title: 1984
Author: George Orwell
Price: 300.00
Key Points:
- Structures
allow grouping related data types, making the program clean and organized.
- Array
of structures efficiently stores multiple records.
- String
handling with fgets() and strcspn() ensures correct multi-word input.
- Comparison
logic correctly identifies the most expensive and cheapest books.
Comments
Post a Comment