PART -B (Question and Answers)
1. Write a program to implement binary search using recursion on a sorted array.
Answer:
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
if (low > high) {
return -1;
}
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearch(arr, mid + 1, high, target);
} else {
return binarySearch(arr, low, mid - 1, target);
}
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1) {
printf("Element is not present in array\n");
} else {
printf("Element is present at index %d\n", result);
}
return 0;
}
Output:
Element is present at index 5
The program implements binary search recursively. The binarySearch function takes a
sorted array arr, the lower bound low, the upper bound high, and the target
value target as input. It returns the index of the target element if found, and -1
otherwise. The main function demonstrates the usage of the binarySearch function with
a sample array and target value.
2. What is difference between pass by value and pass by reference? Write the C coding
To explain both concepts
Answer:
Call By Value Call By Reference
While calling a function, we pass the While calling a function, instead of passing
values of variables to it. Such the values of variables, we pass the address
functions are known as "Call By of variables(location of variables) to the
Values". function known as "Call By References.
In this method, the value of each In this method, the address of actual
variable in the calling function is variables in the calling function is copied
copied into corresponding dummy into the dummy variables of the called
variables of the called function. function.
With this method, the changes made
With this method, using addresses we
to the dummy variables in the called
would have access to the actual variables
function have no effect on the values
and hence we would be able to manipulate
of actual variables in the calling
them.
function.
In call-by-values, we cannot alter the
In call by reference, we can alter the values
values of actual variables through
of variables through function calls.
function calls.
Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.
This method is preferred when we
This method is preferred when we have to
have to pass some small values that
pass a large amount of data to the function.
should not change.
Call by value is considered safer as Call by reference is risky as it allows direct
Call By Value Call By Reference
original data is preserved modification in original data
Call By Value in C
In call by value method of parameter passing, the values of actual parameters are
copied to the function’s formal parameters.
There are two copies of parameters stored in different memory locations.
One is the original copy and the other is the function copy.
Any changes made inside functions are not reflected in the actual parameters of
the caller.
Example
#include <stdio.h>
// Swap functions that swaps two values
void swapx(int x, int y) {
int t;
t = x;
x = y;
y = t;
printf("Inside swapx: x = %d y = %d\n", x, y);
}
// Main function
int main() {
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
printf("Inside main: a = %d b = %d", a, b);
return 0;
}
Output
Inside swapx: x = 20 y = 10
Inside main: a = 10 b = 20
Thus, actual values of a and b remain unchanged even after exchanging the values of x
and y in the function.
Call by Reference in C
In call by reference method of parameter passing, the address of the actual parameters
is passed to the function as the formal parameters. In C, we use pointers to achieve call-
by-reference.
Both the actual and formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the actual
parameters of the caller.
Example:
#include <stdio.h>
// Function to swap two variables
// by references
void swapx(int* x, int* y) {
int t;
t = *x;
*x = *y;
*y = t;
printf("Inside swapx: x = %d y = %d\n", *x, *y);
}
int main() {
int a = 10, b = 20;
// Pass by reference
swapx(&a, &b);
printf("Inside main: a = %d b = %d", a, b);
return 0;
}
Output
Inside swapx: x = 20 y = 10
Inside main: a = 20 b = 10
Thus, actual values of a and b get changed after exchanging values of x and y.
3. Explain the purpose of a function in C Program with example program. And specify
the difference between the user defined function and built-in function.
Answer:
Purpose of Functions in C
Modularity: Breaking down complex problems into smaller, manageable
functions.
Reusability: Writing a function once and reusing it multiple times.
Readability: Enhancing code clarity by separating logic into distinct functions.
Maintainability: Simplifying updates and debugging by isolating code segments.
User-Defined Functions vs. Built-in (Library) Functions
Feature User-Defined Functions Built-in (Library) Functions
Created by the programmer to perform Predefined in C libraries to
Definition
specific tasks. perform common operations.
Fully customizable based on program Fixed functionality; not
Customization
requirements. modifiable by the user.
add(), calculateArea(), printf(), scanf(), sqrt(),
Examples
displayMessage() strlen()
Header File Not necessarily; depends on usage. Yes; appropriate header files must
Needed be included (e.g., stdio.h,
Feature User-Defined Functions Built-in (Library) Functions
math.h).
Universally reusable across
Reusable within the same program or
Reusability programs by including the
across programs if properly declared.
relevant headers.
Example: User-Defined Function in C
#include <stdio.h>
int add(int a, int b); // Function declaration
int main() {
int result = add(10, 20); // Function call
printf("Sum = %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
add is a user-defined function that takes two integers as parameters and returns
their sum.
The main function calls add with arguments 10 and 20, and prints the result.
4. Explain about pointers and write the use of pointers in arrays with suitable example.
Answer:
What Is a Pointer?
A pointer holds the address of a variable. By using pointers, you can directly access
and manipulate memory locations, which is essential for tasks like dynamic memory
allocation and efficient array processing.
Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x; // ptr stores the address of x
printf("Value of x: %d\n", x); // Outputs: 10
printf("Address of x: %p\n", &x); // Outputs: memory address of x
printf("Value of ptr: %p\n", ptr); // Outputs: same as address of x
printf("Value pointed by ptr: %d\n", *ptr); // Outputs: 10
return 0;
}
In this example, ptr is a pointer to an integer, storing the address of variable x. The *
operator is used to dereference the pointer, accessing the value stored at the memory
address.
Relationship Between Pointers and Arrays
In C, arrays and pointers are closely related. The name of an array acts as a pointer
to its first element. This means that if you have an array arr, then arr and &arr[0]
can be used interchangeably.
Example: Accessing Array Elements Using Pointers
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of arr
printf("Accessing array elements using pointers:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i));
}
return 0;
}
Explanation:
arr is an array of integers.
ptr is a pointer that stores the address of the first element of arr.
*(ptr + i) accesses the ith element of the array by pointer arithmetic.
[Link] the function prototype with suitable [Link] c programming\
Answer:
What is Function Prototype in C?
A function prototype in C is a declaration of a function that specifies its name,
return type, and parameters without providing the actual implementation. It acts
as a "blueprint" for the compiler, informing it about the function before it is
used. This helps in detecting mismatches in the number, types of arguments, and
return values during compilation
1. Simple Prototype with Parameters and Return Type
Prototype:
int add(int a, int b);
Implementation:
#include <stdio.h>
int add(int a, int b); // Function prototype
int main() {
int result = add(3, 5); // Function call
printf("Sum: %d\n", result);
return 0;
}
int add(int a, int b) { // Function definition
return a + b;
}
2. Prototype Without Parameters
A prototype for a function that takes no parameters and returns nothing.
Prototype:
void displayMessage();
Implementation:
#include <stdio.h>
void displayMessage(); // Function prototype
int main() {
displayMessage(); // Function call
return 0;
}
void displayMessage() { // Function definition
printf("Hello, World!\n");
3. Prototype with No Return Type
A prototype for a function that takes parameters but does not return a value.
Prototype:
void printSum(int a, int b);
Implementation:
#include <stdio.h>
void printSum(int a, int b); // Function prototype
int main() {
printSum(4, 6); // Function call
return 0;
}
void printSum(int a, int b) { // Function definition
printf("Sum: %d\n", a + b);
}
4. Prototype with Array as Parameter
A prototype for a function that takes an array and its size as parameters.
Prototype:
void printArray(int arr[], int size);
Implementation:
#include <stdio.h>
void printArray(int arr[], int size); // Function prototype
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5); // Function call
return 0;
}
void printArray(int arr[], int size) { // Function definition
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Write a C program to design a scientific calculator using built-in functions.
Answer:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define PI 3.14159265
void displayMenu() {
printf("\n--- Scientific Calculator ---\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Power (x^y)\n");
printf("6. Square Root\n");
printf("7. Sine (in degrees)\n");
printf("8. Cosine (in degrees)\n");
printf("9. Tangent (in degrees)\n");
printf("10. Logarithm (base 10)\n");
printf("11. Natural Logarithm (ln)\n");
printf("12. Exponential (e^x)\n");
printf("13. Exit\n");
printf("Choose an operation: ");
}
int main() {
int choice;
double num1, num2, result;
while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case 2:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case 3:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case 4:
printf("Enter numerator and denominator: ");
scanf("%lf %lf", &num1, &num2);
if (num2 != 0)
result = num1 / num2;
else {
printf("Error: Division by zero is undefined.\n");
break;
}
printf("Result: %.2lf\n", result);
break;
case 5:
printf("Enter base and exponent: ");
scanf("%lf %lf", &num1, &num2);
result = pow(num1, num2);
printf("Result: %.2lf\n", result);
break;
case 6:
printf("Enter a number: ");
scanf("%lf", &num1);
if (num1 >= 0)
result = sqrt(num1);
else {
printf("Error: Square root of negative number is undefined.\n");
break;
}
printf("Result: %.2lf\n", result);
break;
case 7:
printf("Enter angle in degrees: ");
scanf("%lf", &num1);
result = sin(num1 * PI / 180);
printf("Result: %.2lf\n", result);
break;
case 8:
printf("Enter angle in degrees: ");
scanf("%lf", &num1);
result = cos(num1 * PI / 180);
printf("Result: %.2lf\n", result);
break;
case 9:
printf("Enter angle in degrees: ");
scanf("%lf", &num1);
result = tan(num1 * PI / 180);
printf("Result: %.2lf\n", result);
break;
case 10:
printf("Enter a number: ");
scanf("%lf", &num1);
if (num1 > 0)
result = log10(num1);
else {
printf("Error: Logarithm of non-positive number is undefined.\n");
break;
}
printf("Result: %.2lf\n", result);
break;
case 11:
printf("Enter a number: ");
scanf("%lf", &num1);
if (num1 > 0)
result = log(num1);
else {
printf("Error: Natural logarithm of non-positive number is undefined.\n");
break;
}
printf("Result: %.2lf\n", result);
break;
case 12:
printf("Enter a number: ");
scanf("%lf", &num1);
result = exp(num1);
printf("Result: %.2lf\n", result);
break;
case 13:
printf("Exiting the calculator. Goodbye!\n");
exit(0);
default:
printf("Invalid choice. Please select a valid operation.\n");
}
}
return 0;
}
7. Write a program to calculate the sum and mean of elements in an array using
pointers.
Answer:
#include <stdio.h>
int main() {
int size, i, sum = 0;
float mean;
printf("Enter the number of elements: ");
scanf("%d", &size);
int arr[size];
int *ptr = arr;
printf("Enter %d elements:\n", size);
for(i = 0; i < size; i++) {
scanf("%d", ptr + i);
}
// Calculate sum using pointer arithmetic
for(i = 0; i < size; i++) {
sum += *(ptr + i);
}
// Calculate mean
mean = (float)sum / size;
// Display results
printf("Sum = %d\n", sum);
printf("Mean = %.2f\n", mean);
return 0;
}
8. What is the purpose of structure in C language? Explain in detail with example
program.
C programming, a structure (defined using the struct keyword) is a user-defined data type that
allows grouping variables of different types under a single name. This feature is particularly
useful for representing complex data entities, such as records, where multiple attributes of
varying types need to be associated together.
There are two steps of creating a structure in C:
1. Structure Definition
2. Creating Structure Variables
Structure Definition
A structure is defined using the struct keyword followed by the structure name and its
members. It is also called a structure template or structure prototype, and no memory is
allocated to the structure in the declaration.
struct structure_name {
data_type1 member1;
data_type2 member2;
…
};
structure_name: Name of the structure.
member1, member2, …: Name of the members.
data_type1, data_type2, …: Type of the members.
Creating Structure Variable
After structure definition, we have to create variable of that structure to use it. It is
similar to the any other type of variable declaration:
struct strcuture_name var;
We can also declare structure variables with structure definition.
struct structure_name {
…
}var1, var2….;
Example Program: Student Record Using Structure
#include <stdio.h>
#include <string.h>
// Define a structure to represent a student
struct Student {
int id;
char name[50];
float grade;
};
int main() {
// Declare a variable of type struct Student
struct Student student1;
// Assign values to the structure members
[Link] = 101;
strcpy([Link], "Alice");
[Link] = 89.5;
// Display the student's information
printf("Student ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("Grade: %.2f\n", [Link]);
return 0;
}
Nested Structures
Structures can also be nested, meaning a structure can contain another structure as a
member. This is useful for modeling more complex data relationships.
#include <stdio.h>
#include <string.h>
// Define a structure for address
struct Address {
char city[50];
char state[50];
int zip;
};
// Define a structure for student that includes Address
struct Student {
int id;
char name[50];
struct Address addr;
};
int main() {
struct Student student1;
// Assign values
[Link] = 102;
strcpy([Link], "Bob");
strcpy([Link], "Chennai");
strcpy([Link], "Tamil Nadu");
[Link] = 600001;
// Display information
printf("Student ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("City: %s\n", [Link]);
printf("State: %s\n", [Link]);
printf("ZIP: %d\n", [Link]);
return 0;
}