Professional Documents
Culture Documents
BY
KARAN GUPTA
FE/A/(EXTC)
Q1) Explain recursive function with example
#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;
}
return 0;
}
#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;
}
#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);
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;
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() {
int main() {
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() {
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.
• 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;
}
#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.
#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;
}
#include <stdio.h>
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;
}
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] = "";
strcat_custom(str1, str2);
printf("Concatenated string: %s\n", str1);
strcpy_custom(str4, str3);
printf("Copied string: %s\n", str4);
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;
reverseString(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>
int main() {
int rows, cols;
int matrix[rows][cols];
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;
}
int main() {
char dest[20] = "Hello";
const char src[] = ", World!";
strcat(dest, src);
printf("Concatenated string: %s\n", dest);
return 0;
}
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>
int main() {
struct Employee employees[2];
// 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>
int main() {
int n, 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;
}
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’.
#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);
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);
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;
return 0;
}
#include <stdio.h>
int main() {
int num = 10;
int *ptr; // Declare a pointer variable
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;
return 0;
}
Q31) Find largest of n number using one dimensional array
#include <stdio.h>
return largest;
}
int main() {
int n;
int numbers[MAX_SIZE];
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
C) Address relocation
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");
}
C) PISTA COUNT=10
A) One
By
Karan Gupta
FE/A/EXTC
-----------------------------------------------------------------------------------------------------------------------------