0% found this document useful (0 votes)
27 views23 pages

PPS Pyq

Uploaded by

shubhamsharmak26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

PPS Pyq

Uploaded by

shubhamsharmak26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

1. What is a function? Why we use functions in C language?

Give an
example.
// A function in C is a set of statements that perform a specific task. It acts as
a building block for organizing code, providing modularity, and enabling
code reusability.
Functions are enclosed within curly braces {} and have a name, return
type, and parameters.
They enhance readability, simplify complex tasks, and allow us to avoid
repeating the same code.
Example of a simple function:

#include <stdio.h>

// Function to calculate the sum of two integers


int add(int a, int b) {
return a + b;
}

int main() {
int result = add(5, 3);
printf("Sum: %d\n", result);
return 0;
}

2. Distinguish between Library functions and User defined functions


in C and Explain with examples.
//Library Functions:
Predefined functions provided by the C library
(e.g., printf, scanf, sqrt).
Used for common operations.
Accessed via header files (e.g., #include <stdio.h>).

User-Defined Functions:
Created by programmers to meet specific requirements.
Defined by the user.
No need to include any particular library.
// Library function example
#include <stdio.h>

int main() {
printf("Hello, world!\n");
return 0;
}

// User-defined function example


#include <stdio.h>

// User-defined function to greet


void greet() {
printf("Hello, world!\n");
}

int main() {
greet(); // Calling user-defined function
return 0;
}
3. Write some properties and advantages of user defined functions in
C?
//Code Reusability: Functions can be called multiple times, reducing code
repetition.
Modularity: Breaks down complex programs into smaller sub-programs.
Easy Debugging and Maintenance: Isolates faulty functions during
debugging.
Readability: Divides complex problems into clear sub-programs.
Enhanced Organization: Keeps code organized and manageable.
4. Explain the various categories of user defined functions in C with
examples?
//Categories of user-defined functions in C include:
 Functions with no arguments and no return value
 Functions with arguments but no return value
 Functions with no arguments but with a return value
 Functions with arguments and a return value
Example:
cCopy code
#include <stdio.h>

// Function with no arguments and no return value


void greet() {
printf("Hello!\n");
}

// Function with arguments but no return value


void printNum(int num) {
printf("Number: %d\n", num);
}

// Function with no arguments but with a return


value
int generateRandom() {
return rand();
}

// Function with arguments and a return value


int add(int a, int b) {
return a + b;
}

int main() {
greet();
printNum(10);
printf("Random Number: %d\n",
generateRandom());
printf("Sum: %d\n", add(5, 3));
return 0;
}

5. Explain the Parameter Passing Mechanisms in C-Language with


examples.
//Parameter Passing Mechanisms in C:
Pass By Value:
Copies actual parameters to formal parameters.
Changes inside the function do not affect the caller.
Example:

void modifyValue(int a) {
a += 5;
}

Pass by Pointers:
Passes memory address (pointer) of a variable.
Allows modification of content at that memory location.
Example:

void modifyValue(int* ptr) {


*ptr += 5;
}

6. Differentiate actual parameters and formal parameters.


//Actual parameters are the parameters passed to a function during a function
call, while formal parameters are the parameters defined in the function
declaration. For example, in the function call add(5, 3), 5 and 3 are
actual parameters, while in the function definition int add(int a, int
b), a and b are formal parameters.
7. What is recursive function? Write syntax for recursive functions.
//A function that calls itself directly or indirectly.
Syntax:

return_type function_name(parameters) {
// Base case (terminates recursion)
if (condition) {
return base_value;
}
// Recursive case
else {
return function_name(modified_parameters);
}
}

8. Write a program to find factorial of a number using recursion.


//#include <stdio.h>

// Recursive function to calculate factorial


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

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}
9. Differentiate between recursion and non recursion.
//Recursion is a technique in which a function calls itself directly or
indirectly. Non-recursion refers to solving a problem without using recursive
function calls. Recursion often simplifies the code and makes it more
readable but can sometimes lead to stack overflow errors if not implemented
carefully. Non-recursive solutions usually involve iteration or using auxiliary
data structures like stacks or queues.
10. How to Pass Array Individual Elements to Functions? Explain
with example program.
//Passing Individual Array Elements to Functions:
To pass individual elements of an array to a function in C, you can treat
them like regular variables. Here’s an example:

#include <stdio.h>

void display(int age1, int age2) {


printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};
display(ageArray[1], ageArray[2]);
return 0;
}

11. write a Program using call function by value and call by address
or reference.
//Call by Value and Call by Address (Reference):
In C, we can pass arguments to functions either by value or by address
(reference).
Call by Value: The function receives a copy of the argument’s value.
Call by Address (Reference): The function receives the memory address of
the argument.
Example of call by value:

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

Example of call by address (reference):

void calculate(int *length, int *width, int *area,


int *perimeter) {
*area = (*length) * (*width);
*perimeter = 2 * (*length + *width);
}

12. What are different types of storage classes in C ?


//C has four standard storage classes:
Auto: Default storage class for local variables within a block or function.
Limited to the block’s scope.
Extern: Used for global variables shared between files. Accessible
throughout the program.
Static: Preserves value across function calls. Local to the function where
defined.
Register: Suggests storing variables in CPU registers for faster access.
Example of auto:

auto int age; // Declares an auto variable


Example of extern:

extern void display(); // Declares an external


function

Example of static:

static int count = 0; // Declares a static variable

Example of register:

register int x; // Declares a register variable

13. Explain briefly auto and static storage classes with examples?
//Auto and Static Storage Classes:
 Auto: Variables declared inside a function block are by default auto
variables. They are created when the function is called and destroyed
when the function exits.
cCopy code
#include <stdio.h>

void func() {
auto int x = 10; // Auto variable
printf("Auto variable x: %d\n", x);
}

int main() {
func();
return 0;
}

 Static: Variables declared as static inside a function retain their value


between function calls.
cCopy code
#include <stdio.h>

void func() {
static int y = 10; // Static variable
printf("Static variable y: %d\n", y);
y++;
}

int main() {
func(); // Output: Static variable y: 10
func(); // Output: Static variable y: 11
return 0;
}

14. Explain extern and register storage classes with example


programs.
//Extern and Register Storage Classes:
 Extern: Used to declare variables that are defined elsewhere in the
program.
cCopy code
// File: file1.c
int globalVar = 100;

cCopy code
// File: file2.c
#include <stdio.h>
extern int globalVar; // Declaration
int main() {
printf("Value of globalVar: %d\n", globalVar);
return 0;
}
 Register: Used to define local variables that should be stored in a
register instead of RAM for faster access.
cCopy code
#include <stdio.h>

int main() {
register int x = 10; // Register variable
printf("Register variable x: %d\n", x);
return 0;
}

15. Write a program to generate Fibonacci series using recursive


functions.
//Fibonacci Series using Recursive Functions:
Here’s a recursive function to generate the Fibonacci series:

#include <stdio.h>

int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n = 10; // Change 'n' to the desired number
of terms
for (int i = 0; i < n; ++i) {
printf("%d ", fibonacci(i));
}
return 0;
}
16. Write functions using recursion for the quick sorting.
//#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
17. Write program for the merge sort using functions.
//#include <stdio.h>

void merge(int arr[], int l, int m, int r) {


int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
printf("\n");

mergeSort(arr, 0, arr_size - 1);

printf("Sorted array is \n");


for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
18. Why Do We Use Structures in C? How to Declare Structure
Variables?
//Structures in C are used to group together different data types under one
name. This allows you to create complex data types that can hold multiple
pieces of information. They are useful for organizing related pieces of data
and passing them around as a single unit.
Here's how you declare a structure and structure variables:
#include <stdio.h>

// Declare a structure
struct Person {
char name[50];
int age;
float salary;
};

int main() {
// Declare structure variables
struct Person person1, person2;

// Accessing structure members


strcpy(person1.name, "John");
person1.age = 30;
person1.salary = 50000.0;
printf("Person 1: %s, %d, %.2f\n", person1.name, person1.age,
person1.salary);

return 0;
}
19. What is an Array of Structures?
//An array of structures is a collection of multiple structure variables. It
allows you to manage related data for multiple entities efficiently. Consider
the scenario of storing data for multiple employees or students. Instead of
declaring individual variables for each, you can use an array of structures.
Example of an array of structures:

struct Employee {
char name[50];
int employeeID;
};

struct Employee employees[50]; // An array of 50


Employee structures

20. How to Pass Structures to Functions in C?


//When passing structures to functions in C, keep in mind that the entire
structure is copied. This can be expensive in terms of both time and memory,
especially for large structures. Here are two ways to pass structures to
functions:
1.Call By Value:

Pass the entire structure to the function as an argument.


Example:

struct Car {
char name[30];
int price;
};

void printCarInfo(struct Car c) {


printf("Name: %s\n", c.name);
printf("Price: %d\n", c.price);
}

int main() {
struct Car myCar = {"Tata", 1021};
printCarInfo(myCar);
return 0;
}

2.Call By Reference:
Pass a pointer to the structure (address of the structure) to the function.
Example:

struct Student {
char name[50];
int roll;
float marks;
};

void display(struct Student* studentObj) {


printf("Name: %s\n", studentObj->name);
printf("Roll: %d\n", studentObj->roll);
printf("Marks: %.2f\n", studentObj->marks);
}

int main() {
struct Student st1 = {"Aman", 19, 8.5};
display(&st1);
return 0;
}
21. Why should one prefer call by address method using a function
to swap two numbers?
//Call by Address Method for Swapping Two Numbers:
When using the call by address method (also known as call by reference),
we pass the memory address (pointer) of the variables to a function.
Advantages:
Efficiency: It avoids copying large data (like arrays or structures) during
function calls, which can be more efficient.
In-Place Swapping: Swapping occurs directly in memory, reducing
overhead.
Modifies Original Values: The original variables are modified directly.
Example program to swap two numbers using call by address:

#include <stdio.h>

void swap(int* num1, int* num2) {


int temp = *num1;
*num1 = *num2;
*num2 = temp;
}

int main() {
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a,
b);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a,
b);
return 0;
}

22. How many methods are three to pass value to a function? Write a
program to swap two numbers using call by address method with the
help of a function.
//There are three methods to pass values to a function: call by value, call by
address (or call by reference), and call by pointer. Here's a program to swap
two numbers using the call by address method:
c

#include <stdio.h>

// Function to swap two numbers using call by


address

void swap(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

int main() {

int num1 = 5, num2 = 10;

printf("Before swapping: num1 = %d, num2 = %d\


n", num1, num2);

// Call the swap function with addresses of


num1 and num2
swap(&num1, &num2);

printf("After swapping: num1 = %d, num2 = %d\


n", num1, num2);

return 0;

23. What is a structure? How can we initialize the members of a


structure? Write a program to create a simple structure for storing
information of an employee.
//Structure in C:
A structure is a user-defined data type that groups different variables
(members) of possibly different types into a single unit.
Declaration:

struct Employee {
char name[50];
int empId;
float salary;
};

Initialization:

struct Employee emp1 = {"John Doe", 101, 50000.0};

24. What is recursion? How it is different from other functions?


//Recursion:
Recursion is a process where a function calls itself directly or indirectly.
Properties:
Solves problems by breaking them into smaller sub-problems.
Requires a base case to avoid infinite recursion.
Involves a call stack.
Example: Factorial calculation using recursion:

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

25. What is the difference between string and array? Also explain
how you will decide when to use which data ?
//String:
Represents a sequence of characters.
Immutable (cannot be changed after creation).
Stored as an object.
Example: "Hello, World!".

Array:
Collection of elements of the same data type.
Mutable (elements can be modified).
Stored in contiguous memory locations.
Example: int arr[] = {1, 2, 3, 4}.

When to use a string:


 Use a string when dealing with sequences of characters, such as words,
sentences, or text.
 Strings are specifically designed for handling textual data, so they
provide convenience functions for string manipulation.
When to use an array:
 Use an array when you need to store a collection of elements of the
same data type.
 Arrays are more general-purpose and can be used to store any type of
data, not just characters.
27. Write a program to find roots of an equation entered by the user
in c language.
//#include <math.h>
#include <stdio.h>

int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;

printf("Enter coefficients a, b, and c: ");


scanf("%lf %lf %lf", &a, &b, &c);

discriminant = b * b - 4 * a * c;

// Condition for real and different roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Root1 = %.2lf and Root2 = %.2lf\n", root1, root2);
}
// Condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Root1 = Root2 = %.2lf\n", root1);
}
// If roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Root1 = %.2lf + %.2lfi and Root2 = %.2lf - %.2lfi\n",
realPart, imagPart, realPart, imagPart);
}
return 0;
}
28. Explain any two sorting algorithms and how the differ from
searching algorithm?
//Sorting Algorithms: These algorithms arrange elements in a specific order
(e.g., ascending or descending). Examples include Bubble Sort, Quick Sort,
and Merge Sort.
Bubble Sort: Compares adjacent elements and swaps them if they’re in the
wrong order. Repeats until the list is sorted.
Quick Sort: Divides the list into smaller sublists, sorts them, and combines
them. Efficient but may not be stable.
Merge Sort: Divides the list into halves, sorts each half, and then merges
them. Stable and efficient.
Searching Algorithms: These algorithms find a specific element within a
collection. Examples include Linear Search and Binary Search.
Linear Search: Sequentially checks each element until a match is found.
Works for unsorted lists.
Binary Search: Requires a sorted list. Divides the list in half repeatedly
until the target element is found.
29. How structure is represented?
Representation of Structures in C: In C, structures (structs) are used to
group related variables of different data types into a single unit. The syntax
for defining a structure is as follows:

struct Student {
int rollNumber;
char name[50];
float marks;
};

Here, Student is the structure tag, and rollNumber, name,


and marks are its members.
30. What are the methods through which the parameters are passed
to a function in C language? How do they make a difference?
//Pass by Value: Copies the actual parameter’s value into the formal
parameter. Changes to the formal parameter don’t affect the actual parameter.
Pass by Reference (Pointer): Passes the memory address of the actual
parameter. Changes to the formal parameter affect the actual parameter.
31. Using sorting method of your choice, write a program to sort 8
numbers
//#include <stdio.h>

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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int arr[] = {8, 3, 1, 6, 4, 7, 2, 5};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array: ");


for (int i)

You might also like