You are on page 1of 32

C PROGRAMING

IAT-2 Question Bank (Answer)

BY
KARAN GUPTA
FE/A/(EXTC)
Q1) Explain recursive function with example

A recursive function in programming is a function that calls itself during its


execution.

#include <stdio.h>
int factorial(int n)
{
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}

The function has two cases:


Base case: If n is 0, the factorial is defined as 1.
Recursive case: If n is greater than 0, the factorial of n is calculated as n multiplied by
the factorial of n-1.
This function calls itself with a smaller argument (n-1) until it reaches the base case,
where the recursion stops.
Recursive functions are elegant and concise for certain types of problems but can be
less efficient compared to iterative solutions due to the overhead of function calls
and potential stack overflow if the recursion depth becomes too large.
Q2) Write a program to find y=xn using recursion.
#include <stdio.h>
double power(double x, int n) {
if (n == 0) {
return 1;
}
else if (n > 0) {
return x * power(x, n - 1);
}
else {
return (1 / x) * power(x, n + 1);
}
}
int main() {
double x;
int n;
printf("Enter the value of x: ");
scanf("%lf", &x);
printf("Enter the value of n: ");
scanf("%d", &n);
double result = power(x, n);
printf("%.2lf^%d = %.2lf\n", x, n, result);

return 0;
}

Q3) Write a program to print Fibonacci series upto n using recursion.

#include <stdio.h>
void fibonacci(int n, int a, int b)
{
if (n <= 0) {
return;
}
printf("%d ", a);
fibonacci(n - 1, b, a + b);
}
int main() {
int n;
printf("Enter the number of terms in Fibonacci series: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid input. Number of terms should be positive.\n");
return 1;
}
printf("Fibonacci series up to %d terms: ", n);
fibonacci(n, 0, 1);
printf("\n");

return 0;
}
Q4) Write a program to calculate factorial of a number using recursion.

#include <stdio.h>
int factorial(int n)
{
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}

Q5) Write a program to calculate the reverse of a number using recursion.

#include <stdio.h>
int reverse(int num, int rev)
{
if (num == 0) {
return rev;
}
else {
return reverse(num / 10, rev * 10 + num % 10);
}
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int reversed = reverse(num, 0);
printf("Reverse of %d is %d\n", num, reversed);

return 0;
}
Q6) Write a program to calculate sum of digits of a number using recursion.
#include <stdio.h>

int sum_of_digits(int n) {
if (n == 0) {
return 0;
} else {
return (n % 10) + sum_of_digits(n / 10);
}
}

int main() {
int num;
printf("Enter a Number to Sum it's digit: ");
scanf("%d", &num);
int sum = sum_of_digits(num);
printf("Sum of digits: %d\n", sum);
return 0;
}

Q7) Write a program to find GCD and LCM using a recursive function.
#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
int gcd_result = gcd(num1, num2);
int lcm_result = lcm(num1, num2);
printf("GCD of %d and %d is %d\n", num1, num2, gcd_result);
printf("LCM of %d and %d is %d\n", num1, num2, lcm_result);

return 0;
}
Q8) Explain call by value and call by reference with suitable example
1. Call by Value:
In call by value, when a function is called, the actual value (or copy of the data) is
passed to the function as an argument. This means that changes made to the
parameter inside the function do not affect the original variable outside the
function. The function works with a copy of the data, and any modifications made
to that copy are local to the function.

#include <stdio.h>

void changeValue(int x) {
x = 10;
}

int main() {
int num = 5;
changeValue(num);
printf("Original value: %d\n", num); // Output: Original value: 5
return 0;
}

2. Call by Reference:
In call by reference, instead of passing the actual value, the address (reference) of
the variable is passed to the function. This means that changes made to the
parameter inside the function will affect the original variable outside the function
because they are working with the same memory location.

#include <stdio.h>
void changeValue(int *x)

*x = 10;

int main() {

int num = 5;

changeValue(&num);

printf("Original value: %d\n", num);

return 0;

}
Q9) Explain with example local, global and static variables.

1. Local Variables:
• Local variables are declared within a function or a block and are accessible only within
that function or block.
• They are created when the function or block is called and destroyed when the function
or block exits.
• Local variables are typically used for temporary storage or for holding intermediate
results within a function.
• They are initialized with garbage values if not explicitly initialized.
• Local variables can be redeclared with the same name in different functions or blocks
without any conflict.

#include <stdio.h>
void exampleFunction()

int x = 10;

printf("Value of x inside function: %d\n", x);

int main() {

exampleFunction();

return 0;

2. Global Variables:
• Global variables are declared outside of all functions and blocks and are accessible from
any part of the program.
• They are created when the program starts execution and destroyed when the program
terminates.
• Global variables can be accessed and modified by any function in the program, which
makes them useful for storing values that need to be shared among multiple functions.
• They are initialized with zero if not explicitly initialized.
• Global variables should be used with caution as they can make the program difficult to
understand and debug.
#include <stdio.h>
int globalVariable = 20;

void exampleFunction() {

printf("Value of globalVariable inside function: %d\n", globalVariable);

int main() {

printf("Value of globalVariable in main function: %d\n", globalVariable);

exampleFunction();

return 0;

3. Static Variables:
• Static variables are declared within a function or a block with the keyword static.
• They retain their value between function or block calls and are initialized only once.
• Static variables have local scope but static storage duration, meaning they exist
throughout the program's execution.
• They are initialized with zero if not explicitly initialized.
• Static variables are useful when you want to preserve the value of a variable across
function calls without using global variables.

#include <stdio.h>
void exampleFunction() {

static int count = 0;

count++;

printf("Value of count inside function: %d\n", count);

int main() {

exampleFunction();

exampleFunction();

exampleFunction();

return 0;

}
Q10) Differentiate between Structure and union
Structure Union
Structure allocates storage space for all its Union allocates one common storage space
members separately. for all its members. Union finds that which of
its member needs high storage space over
other members and allocates that much space
Structure occupies higher memory Union occupies lower memory space over
space. structure.
We can access all members of structure We can access only one member of union at a
at a time. time.
All members may be initialized. Only first member may be initialized.

Consume more space than union. Conservation of memory is possible.

Syntax: struct name Syntax: Union tag-name


{ {
data-type member-1; data-type member1;
data-type member-2; data-type member 2;
data-type member-n; data-type member n;
} }

Q11) Explain nested structures with example


The structure that contains another structure as its members is called a nested structure or a
structure within a structure is called nested structure. The structure should be declared
separately and then be grouped into high level structure.
Explanation:

• We define an inner structure Address, which contains members for city, state, and
pincode.
• We define an outer structure Person, which contains members for name, age, and
another structure Address.
• We declare and initialize a variable person1 of type Person with some sample data.
• We access and print members of both the outer and inner structures using the dot
operator (.) to access nested members.
#include <stdio.h>
struct Address
{
char city[50];
char state[50];
int pincode;
};
struct Person {
char name[50];
int age;
struct Address address;
};
int main()
{
struct Person person1 = {"John", 30, {"New York", "NY", 10001}};
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("City: %s\n", person1.address.city);
printf("State: %s\n", person1.address.state);
printf("Pincode: %d\n", person1.address.pincode);

return 0;
}

Q12) Explain array of structures with example.


An array of structures is a collection of structure variables that are stored in contiguous memory
locations. It is a powerful data structure that allows you to store and manage related data
efficiently.

#include <stdio.h>
struct Book {
char title[100];
char author[100];
int year;
};
int main() {
struct Book library[3] = {
{"The Great Gatsby", "F. Scott Fitzgerald", 1925},
{"To Kill a Mockingbird", "Harper Lee", 1960},
{"1984", "George Orwell", 1949}
};
printf("Library Catalog:\n");
for (int i = 0; i < 3; i++) {
printf("Book %d:\n", i + 1);
printf("Title: %s\n", library[i].title);
printf("Author: %s\n", library[i].author);
printf("Year: %d\n", library[i].year);
printf("\n");
}
return 0;
}
Explanation:
I. We define a structure named Book that represents information about a book, including
its title, author, and publication year.
II. In the main() function, we declare an array of structures library of type Book, with a size
of 3.
III. We initialize each element of the array with data representing different books. Each
element is initialized using the structure initialization syntax {}.
IV. We use a loop to iterate over each element of the array and print the details of each book
stored in the array.

Q13) Create a structure Employer with following variables


(i) Employee code
(ii) Employee name
(iii) Employee salary
(iv) Employee designation.
Write a program to read the structure for 10 employees and display record in sorted
order of employee code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Employer
{
int emp_code;
char emp_name[50];
float emp_salary;
char emp_designation[50];
};
int compare(const void *a, const void *b)
{
struct Employer *emp1 = (struct Employer *)a;
struct Employer *emp2 = (struct Employer *)b;
return (emp1->emp_code - emp2->emp_code);
}
int main()
{
struct Employer employees[10];
printf("Enter details for 10 employees:\n");
for (int i = 0; i < 10; i++) {
printf("Employee %d:\n", i + 1);
printf("Employee Code: ");
scanf("%d", &employees[i].emp_code);
printf("Employee Name: ");
scanf("%s", employees[i].emp_name);
printf("Employee Salary: ");
scanf("%f", &employees[i].emp_salary);
printf("Employee Designation: ");
scanf("%s", employees[i].emp_designation);
}
qsort(employees, 10, sizeof(struct Employer), compare);
printf("\nEmployee records sorted by employee code:\n");
printf("-------------------------------------------\n");
printf("Employee Code\tEmployee Name\tEmployee Salary\tEmployee Designation\n");
printf("-------------------------------------------\n");
for (int i = 0; i < 10; i++) {
printf("%d\t\t%s\t\t%.2f\t\t%s\n", employees[i].emp_code, employees[i].emp_name, employees[i].emp_salary,
employees[i].emp_designation);
}
return 0;
}

Q14) Create a program to perform matrix operations.

#include <stdio.h>

// Function to print a matrix


void printMatrix(int rows, int cols, int matrix[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

// Function to add two matrices


void addMatrix(int rows, int cols, int matrix1[rows][cols], int matrix2[rows][cols], int result[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to subtract two matrices


void subtractMatrix(int rows, int cols, int matrix1[rows][cols], int matrix2[rows][cols], int result[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}

// Function to multiply two matrices


void multiplyMatrix(int rows1, int cols1, int matrix1[rows1][cols1], int rows2, int cols2, int matrix2[rows2][cols2], int
result[rows1][cols2]) {
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
int main() {
int rows1, cols1, rows2, cols2;

// Input dimensions of first matrix


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

// Input dimensions of second matrix


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

if (cols1 != rows2) {
printf("Multiplication not possible: Number of columns of first matrix must be equal to number of rows of second
matrix.\n");
return 1;
}

int matrix1[rows1][cols1], matrix2[rows2][cols2], result[rows1][cols2];

// 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++) {
printf("Enter element (%d,%d): ", i + 1, j + 1);
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++) {
printf("Enter element (%d,%d): ", i + 1, j + 1);
scanf("%d", &matrix2[i][j]);
}
}

// Perform matrix operations


addMatrix(rows1, cols1, matrix1, matrix2, result);
printf("\nAddition of matrices:\n");
printMatrix(rows1, cols1, result);

subtractMatrix(rows1, cols1, matrix1, matrix2, result);


printf("\nSubtraction of matrices:\n");
printMatrix(rows1, cols1, result);

multiplyMatrix(rows1, cols1, matrix1, rows2, cols2, matrix2, result);


printf("\nMultiplication of matrices:\n");
printMatrix(rows1, cols2, result);

return 0;
}
Q15) Implement all the string library functions (strlen, strcat, strcpy, strcmp) without using
library functions.

#include <stdio.h>
// Function to calculate length of a string
int strlen_custom(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
// Function to concatenate two strings
void strcat_custom(char *dest, const char *src) {
int dest_len = strlen_custom(dest);
int i;
for (i = 0; src[i] != '\0'; i++) {
dest[dest_len + i] = src[i];
}
dest[dest_len + i] = '\0';
}
// Function to copy one string to another
void strcpy_custom(char *dest, const char *src) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
// Function to compare two strings
int strcmp_custom(const char *str1, const char *str2) {
int i = 0;
while (str1[i] != '\0' || str2[i] != '\0') {
if (str1[i] != str2[i]) {
return str1[i] - str2[i];
}
i++;
}
return 0;
}
int main() {
// Test cases
char str1[50] = "Hello";
char str2[50] = "World";
char str3[50] = "Hello";
char str4[50] = "";

printf("Length of str1: %d\n", strlen_custom(str1));


printf("Length of str2: %d\n", strlen_custom(str2));

strcat_custom(str1, str2);
printf("Concatenated string: %s\n", str1);

strcpy_custom(str4, str3);
printf("Copied string: %s\n", str4);

printf("Comparison result (str1 vs str2): %d\n", strcmp_custom(str1, str2));


printf("Comparison result (str1 vs str3): %d\n", strcmp_custom(str1, str3));

return 0;
}
Q16) Write a program to reverse a string and check whether it’s palindrome or not.

#include <stdio.h>
#include <string.h>
// Function to reverse a string
void reverseString(char *str) {
int length = strlen(str);
int i, j;
char temp;

for (i = 0, j = length - 1; i < j; i++, j--) {


temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
// Function to check if a string is palindrome or not
int isPalindrome(char *str) {
int length = strlen(str);
int i, j;

for (i = 0, j = length - 1; i < j; i++, j--) {


if (str[i] != str[j]) {
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}
int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

reverseString(str);

printf("Reversed string: %s\n", str);

if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}

return 0;
}
Q17) Write a program to reverse a string and check whether it’s palindrome or not without
using string library functions
#include <stdio.h>
// Function to calculate length of a string
int strlen_custom(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
// Function to reverse a string
void reverseString(char *str) {
int length = strlen_custom(str);
int i, j;
char temp;
for (i = 0, j = length - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
// Function to check if a string is palindrome or not
int isPalindrome(char *str) {
int length = strlen_custom(str);
int i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
reverseString(str);
printf("Reversed string: %s\n", str);
if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Q18) Write a program to check whether a matrix is symmetric or not

#include <stdio.h>

// Function to check if a matrix is symmetric


int isSymmetric(int rows, int cols, int matrix[rows][cols]) {
if (rows != cols) {
return 0; // Not a square matrix, so not symmetric
}

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
if (matrix[i][j] != matrix[j][i]) {
return 0; // Not symmetric
}
}
}
return 1; // Symmetric
}

int main() {
int rows, cols;

// Input dimensions of the matrix


printf("Enter number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);

int matrix[rows][cols];

// Input elements of the matrix


printf("Enter elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element (%d,%d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Check if the matrix is symmetric


if (isSymmetric(rows, cols, matrix)) {
printf("The matrix is symmetric.\n");
} else {
printf("The matrix is not symmetric.\n");
}

return 0;
}
Q19) Explain following functions with example strlen() strcat() strcmp() sizeof()

I. strlen() function:
strlen() function calculates the length of a string, i.e., the number of characters in the string
excluding the null terminator ('\0').
Prototype: size_t strlen(const char *str);
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, World!";
printf("Length of the string: %zu\n", strlen(str));
return 0;
}

II. strcat() function:


strcat() function appends a copy of the source string to the destination string. It concatenates
the source string to the end of the destination string, overwriting the null terminator of the
destination string, and then adds a new null terminator at the end.
Prototype: char *strcat(char *dest, const char *src);
#include <stdio.h>
#include <string.h>

int main() {
char dest[20] = "Hello";
const char src[] = ", World!";
strcat(dest, src);
printf("Concatenated string: %s\n", dest);
return 0;
}

III. strcmp() function:


strcmp() function compares two strings and returns an integer representing the comparison
result. It returns 0 if the strings are equal, a negative value if the first string is lexicographically
less than the second string, and a positive value if the first string is lexicographically greater than
the second string.
Prototype: int strcmp(const char *str1, const char *str2);
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
printf("Comparison result: %d\n", strcmp(str1, str2));
return 0;
}
IV. sizeof() operator:
sizeof() operator is used to calculate the size in bytes of a variable or data type.
#include <stdio.h>

int main() {
int arr[5];
printf("Size of int data type: %zu bytes\n", sizeof(int));
printf("Size of arr array: %zu bytes\n", sizeof(arr));
return 0;
}

Q20) Write a program to sort the numbers in ascending order and display smallest number
#include <stdio.h>
// Function to sort numbers in ascending order using bubble sort algorithm
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
// Input number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input elements
printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort the numbers in ascending order
bubbleSort(arr, n);
// Display the sorted array
printf("Numbers in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Display the smallest number (first element after sorting)
printf("Smallest number: %d\n", arr[0]);

return 0;
}
Q21) Write a program to design structure employ and with employee no. id, salary. Read the
information of 100 employees and display employee information that is having experience
5years or more and salary less than 10000.

#include <stdio.h>

// Define structure for employee


struct Employee {
int emp_id;
float salary;
int experience_years;
};

int main() {
struct Employee employees[2];

// Input information for each employee


printf("Enter information for 100 employees:\n");
for (int i = 0; i < 2; i++) {
printf("Employee %d:\n", i + 1);
printf("Employee ID: ");
scanf("%d", &employees[i].emp_id);
printf("Salary: ");
scanf("%f", &employees[i].salary);
printf("Experience (in years): ");
scanf("%d", &employees[i].experience_years);
}

// Display information for employees with 5 years or more experience and salary less
than 10000
printf("\nEmployees with 5 years or more experience and salary less than 10000:\n");
printf("------------------------------------------------------------------\n");
printf("Employee ID\tSalary\tExperience (years)\n");
printf("------------------------------------------------------------------\n");
for (int i = 0; i < 2; i++) {
if (employees[i].experience_years >= 5 && employees[i].salary <=10000) {
printf("%d\t\t%.2f\t%d\n", employees[i].emp_id, employees[i].salary,
employees[i].experience_years);
}
}

return 0;
}
Q22) write a function which gets one integer as parameter and return factorial of that integer
used this function in the main Program to find the value of ncr =n!/ (n-r)! r!
#include <stdio.h>

// Function to calculate factorial


int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

// Function to calculate ncr


int ncr(int n, int r) {
return factorial(n) / (factorial(n - r) * factorial(r));
}

int main() {
int n, r;

printf("Enter the value of n: ");


scanf("%d", &n);
printf("Enter the value of r: ");
scanf("%d", &r);

if (n < r) {
printf("Error: Value of n must be greater than or equal to r.\n");
} else {
printf("Value of ncr: %d\n", ncr(n, r));
}

return 0;
}

Q23) Explain storage class with example.


Q24) What is a pointer? How will you declare and initialize a pointer?
A pointer is a variable that stores the memory address of another variable. In simple terms, it
"points to" the location of another variable in the computer's memory.
1. Declaration:
To declare a pointer variable, you specify the data type of the variable it will point to,
followed by an asterisk (‘*’), and then the pointer variable name.

int *ptr; // Declares a pointer to an integer

2. Initialization:
After declaring a pointer variable, you can initialize it by assigning the memory address of
another variable to it using the address-of operator (‘&’), or by assigning the value ‘NULL’.

int x = 10; // Declare and initialize an integer variable


int *ptr; // Declare a pointer to an integer
ptr = &x; // Initialize the pointer with the address of variable x

Q25) write a program to display the result of multiplication of two matrices

#include <stdio.h>
#define MAX_SIZE 10 // Maximum size of the matrices
// Function to multiply two matrices
void multiplyMatrices(int mat1[][MAX_SIZE], int mat2[][MAX_SIZE], int result[][MAX_SIZE], int rows1, int
cols1, int cols2) {
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
// Function to display a matrix
void displayMatrix(int matrix[][MAX_SIZE], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int mat1[MAX_SIZE][MAX_SIZE], mat2[MAX_SIZE][MAX_SIZE], result[MAX_SIZE][MAX_SIZE];
int rows1, cols1, rows2, cols2;
// Input dimensions of first matrix
printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &rows1, &cols1);
// Input elements of first matrix
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &mat1[i][j]);
}
}
// Input dimensions of second matrix
printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &rows2, &cols2);

// Input elements of second matrix


printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &mat2[i][j]);
}
}
// Check if matrices can be multiplied
if (cols1 != rows2) {
printf("Error: Number of columns of the first matrix must be equal to the number of rows of the
second matrix for multiplication.\n");
return 1;
}
// Multiply matrices
multiplyMatrices(mat1, mat2, result, rows1, cols1, cols2);
// Display result matrix
printf("Result of matrix multiplication:\n");
displayMatrix(result, rows1, cols2);
return 0;
}
Q26) Write a short note on structure

I. A structure in C is a user-defined data type that allows you to group together variables
of different data types under a single name. It is used to represent a collection of
related data items.
II. Structures are defined using the struct keyword followed by a structure tag and a list of
member variables enclosed in curly braces ‘{ }’ .
struct StructureName {
dataType member1;
dataType member2;
// ... more members
};

III. Members of a structure are accessed using the dot operator (.) followed by the member
name.
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.2f\n", person2.height);

IV. Memory Allocation:


• Memory for structure variables is allocated in contiguous memory locations.
• The size of a structure is determined by the sum of the sizes of its individual
members, possibly with padding for alignment0.
V. Structures are commonly used to represent complex data types such as records,
entities, or objects.

Q27) Write a program to access elements of a square matrix and display the sum of diagonal
element of matrix.
#include <stdio.h>
#define MAX_SIZE 10 // Maximum size of the matrix
// Function to display the elements of a square matrix
void displayMatrix(int mat[][MAX_SIZE], int size) {
printf("Matrix:\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}
// Function to calculate and display the sum of diagonal elements of a square matrix
void sumDiagonalElements(int mat[][MAX_SIZE], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += mat[i][i]; // Add diagonal elements (row index = column index)
}
printf("Sum of diagonal elements: %d\n", sum);
}

int main() {
int size;

// Input the size of the square matrix


printf("Enter the size of the square matrix: ");
scanf("%d", &size);

// Declare the square matrix


int matrix[MAX_SIZE][MAX_SIZE];

// Input elements of the square matrix


printf("Enter elements of the square matrix:\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter element (%d,%d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

// Display the elements of the square matrix


displayMatrix(matrix, size);

// Calculate and display the sum of diagonal elements


sumDiagonalElements(matrix, size);

return 0;
}

Q28) write a program to display the address of a variable (use pointer).

#include <stdio.h>

int main() {
int num = 10;
int *ptr; // Declare a pointer variable

// Assign the address of 'num' to the pointer


ptr = &num;

// Display the address of the variable 'num'


printf("Address of the variable 'num': %p\n", ptr);

return 0;
}
Q29) Define typedef with suitable example

In C, ‘typedef’ is a keyword used to create an alias or alternative name for existing data types.
It allows the programmer to define custom data types using more intuitive names.
#include <stdio.h>
// Define a new data type using typedef
typedef unsigned int uint; // 'uint' is an alias for 'unsigned int'
int main() {
uint x = 10; // Using the new data type 'uint'
printf("Value of x: %u\n", x); // %u is the format specifier for unsigned int
return 0;
}

We use ‘typedef’ to define a new data type ‘uint’ as an alias for ‘unsigned int’.
We declare a variable ‘x’ of type ‘uint’ and assign it the value ‘10’.
We then print the value of ‘x’ using the ‘%u’ format specifier for ‘unsigned int’.

Define a structure STUDENT to store the following data for a student: name (null-terminated
string of length at most 20 chars), roll no. (integer), CGPA (float). Then
1. In main, declare an array of 100 STUDENT structures. Read an integer n and then read in the
Q30)
details of n students in this array
2. Write a function to search the array for a student by name. Returns the structure for the
student if found. If not found,return a special structure with the name field set to empty
string (just a ‘\0’)

#include <stdio.h>
#include <string.h>
#define MAX_NAME_LENGTH 20
#define MAX_STUDENTS 100
// Define structure STUDENT
struct STUDENT {
char name[MAX_NAME_LENGTH + 1]; // Null-terminated string of length at most 20 chars
int roll_no; // Roll number
float CGPA; // CGPA
};
// Function to search the array for a student by name
struct STUDENT searchStudentByName(struct STUDENT students[], int n, const char *name) {
struct STUDENT notFound = {"\0", 0, 0}; // Special structure for not found case
for (int i = 0; i < n; i++) {
if (strcmp(students[i].name, name) == 0) {
return students[i]; // Return the student if found
}
}
return notFound; // Return special structure if not found
}
int main() {
struct STUDENT students[MAX_STUDENTS];
int n;

// Input number of students


printf("Enter the number of students (max 100): ");
scanf("%d", &n);

// Input details of n students


for (int i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll No.: ");
scanf("%d", &students[i].roll_no);
printf("CGPA: ");
scanf("%f", &students[i].CGPA);
}

// Search for a student by name


char searchName[MAX_NAME_LENGTH + 1];
printf("Enter the name of the student to search: ");
scanf("%s", searchName);
struct STUDENT foundStudent = searchStudentByName(students, n, searchName);

// Display the result


if (strcmp(foundStudent.name, "\0") == 0) {
printf("Student with name '%s' not found.\n", searchName);
} else {
printf("Student found:\n");
printf("Name: %s\n", foundStudent.name);
printf("Roll No.: %d\n", foundStudent.roll_no);
printf("CGPA: %.2f\n", foundStudent.CGPA);
}

return 0;
}
Q31) Find largest of n number using one dimensional array

#include <stdio.h>

#define MAX_SIZE 100 // Maximum size of the array

// Function to find the largest element in an array


int findLargest(int arr[], int n) {
int largest = arr[0]; // Assume the first element as the largest

// Iterate through the array to find the largest element


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

return largest;
}

int main() {
int n;
int numbers[MAX_SIZE];

// Input the number of elements


printf("Enter the number of elements (max %d): ", MAX_SIZE);
scanf("%d", &n);

// Input the elements of the array


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

// Find the largest element in the array


int largest = findLargest(numbers, n);

// Display the result


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

return 0;
}
MCQ
Q32) What is the output of C Program?
int main()
{ int a[3] = {10,12,14};
a[1]=20; int i=0;
while(i<3)
{ printf("%d ", a[i]);
i++; } }
I'm not sure about this answer
D) Compiler error

Q33) What is the output of C program with arrays?


int main()
{ int a[3] = {20,30,40};
int b[3];
b=a;
printf("%d", b[0]);
}
I'm not sure about this answer
D) Compiler error

Q34) An entire array is always passed by ___ to a called function.

C) Address relocation

Q35) What is a String in C Language?


B) String is an array of Characters with null character as the last element of array.

Q36) What is the output of C Program?


int main()
{
int str[]={'g','l','o','b','y'};
printf("A%c ",str);
printf("A%s ",str);
printf("A%c ",str[0]);
return 0;
}
B) A Ag Ag
Q37) What is the output of C program with strings?
int main()
{
char str1[]="JOHN";
char str2[20];
str2= str1;
printf("%s",str2);
return 0;
}
D) Compiler error

Q38) What is the output of C Program with arrays?


int main()
{
char str[25];
scanf("%s", str);
printf("%s",str);
return 0;
}

A) South

Q39) The______function tests for any character for which isalpha or isdigit is true.

c) isalnum()
Q40) Choose a correct statement about C Function?
main()
{
printf("Hello");
}

B) main() is same as int main()

Q41) What is the output of C Program with functions?


int main()
{
show();
printf("BANK ");
return 0;
}
void show()
{
printf("CURRENCY ");
}
A) CURRENCY BANK

Q42) How many values can a C Function return at a time?


A) Only One Value

Q43) What is the output of C Program?


void show();
void main()
{
printf("PISTA ");
show();
}
void show()
{
printf("CASHEW ");
return 10;
}
A) PISTA CASHEW
Q44) What is the output of C Program with functions?
int show();
void main()
{
int a;
printf("PISTA COUNT=");
a=show();
printf("%d", a);
}
int show()
{
return 10;
}

C) PISTA COUNT=10

Q45) How many functions are required to create a recursive functionality?

A) One

By
Karan Gupta
FE/A/EXTC
-----------------------------------------------------------------------------------------------------------------------------

You might also like