pcl pyq unit-2
pcl pyq unit-2
STRUCTURES,ARRAYS,FUNCTIONS,STRINGS)
Control Structures
1Q.Differentiate between
(a) While Vs do while
1. if Statement:
o Syntax:
C
if (condition) {
// code to be executed if condition is true
}
o Example:
C
int age = 18;
if (age >= 18) {
printf("You are eligible to vote.\n");
}
2. if-else Statement:
o Syntax:
C
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
o Example:
C
int number = 10;
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
o Example:
C
int marks = 75;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 80) {
printf("Grade B\n");
} else if (marks >= 70) {
printf("Grade C\n");
} else {
printf("Grade D\n");
}
4. Switch Statement:
o Syntax:
C
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// ... more cases
default:
// code to be executed if no case matches
}
o Example:
C
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
// ... more cases
default:
printf("Invalid day\n");
}
These decision control instructions provide the flexibility to create complex programs that
can make decisions based on various conditions, leading to diverse and dynamic program
behavior.
3Q. What are loops? Explain its types with syntax and example.
Ans. Loops in C
Loops are control flow statements that allow you to execute a block of code repeatedly until
a certain condition is met. They are essential for repetitive tasks and iterative processes.
Types of Loops in C:
1. for Loop:
o Syntax:
C
for (initialization; condition; increment/decrement) {
// code to be executed
}
o Example:
C
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
2. while Loop:
o Syntax:
C
while (condition) {
// code to be executed
}
o Example:
C
int i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
}
3. do-while Loop:
o Syntax:
C
do {
// code to be executed
} while (condition);
o Example:
C
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 10);
Key Differences:
Condition Check Before the loop body Before the loop body After the loop
body
4Q. Explain switch case/Decision using switch case with syntax and code. How is it different
from multiple else if statement?
Ans. A switch case statement provides a more efficient and readable way to make decisions
based on multiple possible values of an expression. It's particularly useful when you have a
variable and want to execute different code blocks depending on its value.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// ... more cases
default:
// code to be executed if no case matches
Example:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
// ... more cases
default:
printf("Invalid day\n");
}
return 0;
}
1. Readability:
o Switch case often leads to more readable code, especially when dealing with many
cases.
o Multiple if-else statements can become complex and difficult to follow as the number
of conditions increases.
Efficiency:
o In some cases, the compiler can optimize switch case statements to execute more
efficiently than multiple if-else statements.
3. Clarity:
o Switch case explicitly shows the different possible values and their corresponding
actions.
o Multiple if-else statements can sometimes be less clear, especially when conditions
are complex.
When to Use Switch Case:
• When you have a variable and want to execute different code blocks based on its specific
values.
• When the values being compared are discrete and well-defined.
Array
1Q. Difference between 1D array Vs 2D array.
Ans.
2Q. What do you mean by array? What are its types? Explain in detail along with declaration
and initialization.
Ans. Array in C
An array in C is a collection of variables of the same data type, stored in contiguous memory
locations. It provides a way to store multiple values under a single name.
Types of Arrays in C
1. One-Dimensional Arrays:
o Stores a sequence of elements.
o Declared as: data_type array_name[array_size];
o Example: int numbers[5];
o This declares an array named numbers that can hold 5 integer values.
2. Two-Dimensional Arrays:
o Stores elements in a tabular format (rows and columns).
o Declared as: data_type array_name[row_size][column_size];
o Example: int matrix[3][4];
o This declares a 2D array named matrix with 3 rows and 4 columns.
Array Initialization
1. Static Initialization:
o Values are assigned during declaration.
o Example:
C
int numbers[5] = {10, 20, 30, 40, 50};
2. Dynamic Initialization:
o Values are assigned after declaration.
Example:
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
3Q. What is Dynamic array? What is advantage of using it? Explain with example.
Ans. Dynamic arrays, also known as resizable arrays, are data structures that can grow or
shrink in size as needed during program execution. Unlike static arrays, which have a fixed
size determined at compile time, dynamic arrays offer more flexibility in handling varying
amounts of data.
1. Flexibility:
o Dynamic arrays can adapt to changing data requirements, avoiding the need to
pre-allocate a fixed size.
2. Efficient Memory Usage:
o They only allocate memory as needed, reducing memory waste.
3. Ease of Use:
o Many programming languages provide built-in dynamic array
implementations or libraries that simplify their use.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = NULL;
int size = 0, capacity = 5;
return 0;
}
Control Structures
1Q. What is a function? What is the significance/importance of using it?
Ans. A function in C is a block of code that performs a specific task. It's a modular approach
to programming that breaks down complex problems into smaller, more manageable
functions.
1. Modularity:
o Functions divide a program into smaller, independent units, making it easier to
understand, debug, and maintain.
2. Reusability:
o Functions can be called multiple times from different parts of the program,
reducing code duplication.
3. Code Organization:
o Well-structured functions improve code readability and maintainability.
4. Code Efficiency:
o Complex tasks can be broken down into smaller, more efficient functions.
5. Teamwork: Functions allow for better collaboration among programmers, as
different team members can work on different functions.
return_type function_name(parameter_list) {
// Function body // ...
return value;
}
2Q. What is recursion? Explain with the help of an example.
Ans. Recursion is a programming technique where a function calls itself directly or indirectly.
It's a powerful tool for solving problems that can be broken down into smaller, self-similar
subproblems.
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
int result = factorial(num);
printf("Factorial of %d is %d\n", num, result);
return 0;
}
3Q. What do you mean by Storage Classes? Explain in detail with its types.
Ans. storage classes define the scope (visibility) and lifetime (duration) of variables and
functions within a program. They determine where in memory a variable or function is stored
and how long it exists during program execution. Here's a breakdown of the four main
storage classes in C:
• Scope: Local to the block (function or compound statement) where it's declared.
• Lifetime: Exists only during the execution of the block where it's declared.
• Memory Allocation: Automatically allocated on the stack when the block is entered and
deallocated when the block exits.
• Default Value: Garbage value (undefined) when declared, needs to be explicitly initialized
before use.
Example:
void myFunction() {
int x = 10; // Local variable with automatic storage
// ...
}
In this example, x is a local variable with automatic storage. It exists only while
myFunction is executing and is discarded once the function returns.
// main.c
#include "header.h"
int main() {
global_var = 20;
// ...
}
Here, global_var is declared as external in the header file and accessed in main.c. It's a
global variable with a lifetime that lasts until the program ends.
• Scope: Local to the block where it's declared, but retains its value between function calls.
• Lifetime: Exists throughout the entire program execution.
• Memory Allocation: Allocated on the data segment like external variables.
• Default Value: Zero (0) for numeric types, null pointer for pointers.
Example:
void myFunction() {
static int counter = 0; // Static variable
counter++;
// ...
}
In this example, counter is a static variable. It's local to myFunction but retains its value
(keeps incrementing) across multiple function calls.
Ans. We can pass arrays to functions by passing a pointer to the first element of the array. 1
In both cases, the function receives a pointer to the first element of the array. The array
size is optional because the function can determine the size using other techniques like
a separate size parameter or by using a null terminator for string arrays.
2. Function Call: To call the function, you simply pass the array name as an argument:
C
int main() {
int arr[5] = {1, 2, 3, 4, 5};
function_name(arr);
return 0;
}
3. Function Definition: Inside the function, you can access and manipulate the array
elements using array indexing or pointer arithmetic:
C
void function_name(int arr[]) {
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
5Q. Briefly explain various Memory management functions.
Ans.C provides a set of functions to manage dynamic memory allocation and deallocation.
These functions are essential for allocating memory at runtime, as the size of data structures
may not be known beforehand.
1. malloc(size):
2. calloc(num, size):
• Allocates a block of memory for an array of num elements, each of size bytes.
• Initializes the allocated memory to zero.
• Returns a void pointer to the allocated memory block.
• If allocation fails, it returns NULL.
3. realloc(ptr, new_size):
4. free(ptr):
1. Function Header:
o Return Type: Specifies the data type of the value returned by the function. If
the function doesn't return any value, the return type is 1 void.
o Function Name: A unique identifier for the function.
o Parameter List: A comma-separated list of parameters (variables) that the
function receives as input. Each parameter has a data type and a name.
2. Function Body:
o Local Variable Declarations: Variables declared within the function body
are local to the function and can only be accessed within its scope.
o Executable Statements: The actual code that performs the function's task.
o Return Statement: An optional statement that returns a value to the calling
function. If the function has a non-void return type, it must have at least one
return statement.
return_type function_name(parameter_list) {
// Function body
// ...
return value; // Optional, if the function returns a value
}
7Q. Differentiation
➢ Calling function Vs Called Function
➢ Formal Vs Actual Arguments
➢ Call by value Vs Call by reference
➢ User defined function Vs Library function
➢ Function declaration Vs Function Definition
➢ malloc() Vs calloc()
➢ getchar() Vs gets()
➢ putchar() Vs puts()
Function Does not include the function Includes the function body,
Body body. which contains the code to be
executed.
Feature Function Declaration Function Definition
Memory Does not allocate memory for the Allocates memory for the
Allocation function. function when it is defined.
Key Point Essential for the compiler to Contains the actual logic of the
check the correctness of function function.
calls.
Strings
1Q. Explain various string handling functions (Inbuilt/Library).
Ans.C provides a rich set of string handling functions in the <string.h> header file. These
functions allow you to manipulate strings in various ways, such as copying, concatenating,
comparing, searching, and modifying.
Here are some of the most commonly used string handling functions:
1. strlen(str):
2. strcpy(dest, src):
4. strcat(dest, src):
• Concatenates (appends) the string src to the end of the string dest.
• The null terminator of dest is overwritten with the first character of src.
6. strcmp(str1, str2):
8. strchr(str, ch):
9. strrchr(str, ch):
• Searches for the first occurrence of the substring str2 within the string str1.
• Returns a pointer to the first occurrence, or NULL if not found.
11. strrev(str):
12. strlwr(str):
1. String Length:
2. String Concatenation:
3. String Comparison:
4. String Reversal:
Ans. A pointer to a string in C is a variable that stores the memory address of the first
character of a string. In other words, it points to the beginning of a character array.
Declaration:
char *ptr;
Example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
char *ptr = str;
return 0;
}
4Q. Explain the concept of array of string with example.
Ans. An array of strings in C is a collection of strings, each of which is a character array. It's
essentially a two-dimensional character array.
Declaration:
char array_name[rows][columns];
#include <stdio.h>
int main() {
char names[3][20] = {
"Alice",
"Bob",
"Charlie"
};
return 0;
}
Concept:
char *array_name[size];
int main() {
char *colors[3];
strcpy(colors[0], "Red");
strcpy(colors[1], "Green");
strcpy(colors[2], "Blue");
return 0;
}
6Q. How do we pass string to a function?
1. Function Declaration:
Here, char *str declares that the function my_function takes a character pointer as an
argument. This pointer will point to the first character of the string passed to the function.2
2. Function Call:
Here, we pass the array name my_string to the function. Remember, in C, an array name
decays into a pointer to its first element when passed to a function. So, my_string is
3
implicitly converted to a character pointer pointing to the first character of the string.
3. Function Definition: