0% found this document useful (0 votes)
2 views

pcl pyq unit-2

The document covers control structures, arrays, functions, and strings in C programming. It explains decision control instructions, types of loops, and the significance of functions, including recursion and storage classes. Additionally, it discusses arrays, dynamic arrays, and memory management functions.

Uploaded by

Mansi Panwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

pcl pyq unit-2

The document covers control structures, arrays, functions, and strings in C programming. It explains decision control instructions, types of loops, and the significance of functions, including recursion and storage classes. Additionally, it discusses arrays, dynamic arrays, and memory management functions.

Uploaded by

Mansi Panwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT-2 (CONTROL

STRUCTURES,ARRAYS,FUNCTIONS,STRINGS)

Control Structures

1Q.Differentiate between
(a) While Vs do while

(b)Entry Controlled loop Vs Exit controlled loop


2Q. What is decision control instructions/decision making statements/Branching statements?
Explain its types with syntax and example.
Ans. Decision Control Instructions

Decision control instructions, also known as decision-making statements or branching


statements, are used to alter the flow of execution of a program based on a specific
condition. They allow you to make choices within your code, making it more flexible and
dynamic.

Types of Decision Control Instructions in C:

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");
}

3. Nested if-else Statement:


o Syntax:
C
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and
condition2 is true
} else {
// code to be executed if both conditions are false
}

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:

Feature for Loop while Loop do-while


Loop

Condition Check Before the loop body Before the loop body After the loop
body

Minimum 0 (if condition is false 0 (if condition is false 1 (at least


Executions initially) initially) once)

Choosing the Right Loop:

• for Loop: Ideal for a fixed number of iterations.


• while Loop: Best for indefinite iterations where the number of repetitions is not known
beforehand.
• do-while Loop: Ensures at least one execution of the loop body, even if the condition is
false initially.

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;
}

How Switch Case Differs from Multiple if-else Statements

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.

Advantages of Dynamic Arrays:

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;

// Allocate initial memory


arr = (int*)malloc(capacity * sizeof(int));

// Add elements to the array


for (int i = 0; i < capacity; i++) {
arr[i] = i * 10;
}

// Print the array


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

// Increase capacity if needed


if (size == capacity) {
capacity *= 2;
arr = (int*)realloc(arr, capacity * sizeof(int));
}

// Add more elements


arr[size++] = 50;
arr[size++] = 60;

// Print the array again


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

// Free the allocated memory


free(arr);

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.

Significance of Using 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.

Example: Factorial Calculation

#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:

1. Automatic Storage Class (auto):

• 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.

2. External Storage Class (extern):

• Scope: Global, accessible throughout the program.


• Lifetime: Exists throughout the entire program execution.
• Memory Allocation: Allocated in a separate memory segment (usually data segment)
outside any function.
• Default Value: Zero (0) for numeric types, null pointer for pointers.
• Declaration: Usually declared in a header file and accessed using the extern keyword in
other source files.
Example:
// header.h
extern int global_var;

// 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.

3. Static Storage Class (static):

• 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.

4. Register Storage Class (register):

• Scope: Local to the block where it's declared.


• Lifetime: Exists only during the execution of the block where it's declared.
• Memory Allocation: Compiler attempts (not guaranteed) to store the variable in a CPU
register for faster access.
• Default Value: Garbage value (undefined) when declared, needs to be explicitly initialized
before use.
Example:
void myFunction() {
register int x = 10; // Register variable (suggestion to compiler)
// ...}

4Q. How do we pass array to a function?

Ans. We can pass arrays to functions by passing a pointer to the first element of the array. 1

This is because arrays are essentially pointers to memory locations.

Here's how you can pass an array to a function:

1. Function Declaration: When declaring a function that takes an array as an argument,


you can use either of the following syntaxes:
C
// Syntax 1: Specifying the array size (optional)
void function_name(int arr[10]);

// Syntax 2: Omitting the array size


void function_name(int arr[]);

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.

Here are the primary memory management functions in C:

1. malloc(size):

• Allocates a block of memory of the specified size in bytes.


• Returns a void pointer to the allocated memory block.
• If allocation fails, it returns NULL.

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):

• Reallocates a previously allocated memory block to a new size.


• If the new size is larger, additional memory is allocated and the old contents are
copied to the new block.
• If the new size is smaller, the block is truncated.
• Returns a void pointer to the reallocated memory block.
• If reallocation fails, it returns NULL.

4. free(ptr):

• Deallocates a previously allocated memory block.


• Releases the memory back to the system.
• It's crucial to free memory that is no longer needed to prevent memory leaks.

6Q. Explain elements of function.

Ans. A function typically consists of the following elements:

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.

General Syntax of a Function:

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()

(a) Calling function Vs Called Function


(b) Formal Vs Actual Arguments

(c)Call by value Vs Call by reference

void swap(int a, int b) {


// Swapping a and b
} |c
void swap(int *a, int *b) {
// Swapping *a and *b
}
(d) User defined function Vs Library function

(e) Function declaration Vs Function Definition

Feature Function Declaration Function Definition

Purpose Informs the compiler about the Provides the actual


existence, return type, and implementation of the function,
parameter list of a function. including its body.

Syntax return_type return_type


function_name(parameter_list); function_name(parameter_list) {
function body }

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.

Timing Can be declared before or after Must be defined before the


the function definition, but must function is used.
be declared before the function is
used.

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


b; }

Key Point Essential for the compiler to Contains the actual logic of the
check the correctness of function function.
calls.

(f) malloc() Vs calloc()

Feature malloc() calloc()

Definition Allocates a single block of Allocates multiple blocks of


memory of specified size. memory, each of the same size.

Initialization Allocated memory is not Allocated memory is initialized to


initialized. zero.

Syntax void *malloc(size_t size) void *calloc(size_t num, size_t


size)

Parameters size: Size of the memory block num: Number of blocks to be


to be allocated in bytes. allocated. <br> size: Size of each
block in bytes.

Return Pointer to the allocated Pointer to the allocated memory


Value memory block on success, block on success, NULL on
NULL on failure. failure.
(g) getchar() Vs gets()

Feature getchar() gets()

Definition Reads a single character Reads a string of characters from


from the standard input the standard input stream (stdin)
stream (stdin). until a newline character is
encountered.

Return Value The character read as an A pointer to the string read.


integer (ASCII value).

Header File stdio.h stdio.h

Buffering No buffering (reads one Uses a buffer to store the entire


character at a time). string before returning it.

Safety Safer than gets() as it Prone to buffer overflow


doesn't suffer from buffer vulnerabilities if the input string is
overflow vulnerabilities. longer than the allocated buffer
size.

Recommended Generally preferred for Not recommended due to


Usage reading single characters. security risks. Use fgets() instead.
(h) putchar() Vs puts()

Feature putchar() puts()

Definition Prints a single character to the Prints a string (null-terminated


standard output stream character array) to the standard
(usually the console) output stream, followed by a
newline character

Syntax putchar(character); puts(string);

Parameter Single character Null-terminated string


Type

Return The character written, or EOF 0 on success, non-zero on error


Value on error

Newline Does not automatically add a Automatically adds a newline


newline character character after printing the string

Example putchar('A'); puts("Hello, world!");

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):

• Calculates the length of a string (excluding the null terminator).


• Returns an integer representing the length.

2. strcpy(dest, src):

• Copies a string src to another string dest.


• Overwrites the contents of dest.
3. strncpy(dest, src, n):

• Copies at most n characters from src to dest.


• If src is shorter than n characters, the remaining characters in dest are filled with
null characters.

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.

5. strncat(dest, src, n):

• Concatenates at most n characters from src to the end of dest.

6. strcmp(str1, str2):

• Compares two strings lexicographically.


• Returns a negative value if str1 is less than str2, a positive value if str1 is greater
than str2, and 0 if they are equal.

7. strncmp(str1, str2, n):

• Compares at most n characters of two strings.

8. strchr(str, ch):

• Searches for the first occurrence of a character ch in the string str.


• Returns a pointer to the first occurrence, or NULL if not found.

9. strrchr(str, ch):

• Searches for the last occurrence of a character ch in the string str.


• Returns a pointer to the last occurrence, or NULL if not found.

10. strstr(str1, str2):

• 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):

• Reverses the string str in-place.

12. strlwr(str):

• Converts all uppercase letters in the string str to lowercase.

13. strupr(str):Converts all lowercase letters in the string str to uppercase.


2Q. Explain various string handling functions (User defined).
Ans. While C provides a rich set of built-in string handling functions, there are many
scenarios where you might need to implement your own custom string functions to perform
specific tasks or to optimize performance.

Here are some common user-defined string handling functions:

1. String Length:

int my_strlen(const char *str) {


int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}

2. String Concatenation:

void my_strcat(char *dest, const char *src) {


while (*dest != '\0') {
dest++;
}
while (*src != '\0') {
*dest++ = *src++;
}
*dest = '\0';
}

3. String Comparison:

int my_strcmp(const char *str1, const char *str2) {


while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2) {
str1++;
str2++;
}
return *str1 - *str2;
}

4. String Reversal:

void my_strrev(char *str) {


int len = my_strlen(str) - 1;
int i = 0;
while (i < len) {
char temp = str[i];
str[i] = str[len];
str[len] = temp;
i++;
len--; }
5. String Copying:

void my_strcpy(char *dest, const char *src) {


while (*src != '\0') {
*dest++ = *src++;
}
*dest = '\0';
}
3Q.Explain the concept of Pointer to string with example.

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;

Here, ptr is a pointer to a character, which can be used to point to a string.

Example:

#include <stdio.h>

int main() {
char str[] = "Hello, World!";
char *ptr = str;

// Accessing characters using the pointer


printf("%c\n", *ptr); // Prints 'H'
printf("%s\n", ptr); // Prints "Hello, World!"

// Modifying the string through the pointer


*ptr = 'J';
printf("%s\n", str); // Prints "Jello, World!"

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];

• rows: The number of strings in the array.


• columns: The maximum length of each string (including the null terminator).
Example:

#include <stdio.h>

int main() {
char names[3][20] = {
"Alice",
"Bob",
"Charlie"
};

// Accessing and printing the strings


for (int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}

return 0;
}

5Q. Explain the concept of array of pointers to string with example.


Ans. In C, an array of pointers to strings is a data structure that stores an array of memory
addresses, where each address points to the first character of a separate string. It offers
flexibility and memory efficiency compared to a simple array of strings.

Concept:

• Imagine an array that holds pointers instead of actual strings.


• Each pointer in the array points to the beginning (memory address) of a separate string
stored elsewhere in memory.
Declaration:

char *array_name[size];

• array_name: The name of the array.


• size: The number of pointers the array can hold.
• char *: Indicates each element is a pointer to a character (string).
Example:
#include <stdio.h>

int main() {
char *colors[3];

// Allocate memory for each string (assuming dynamic allocation)


colors[0] = (char*)malloc(20 * sizeof(char)); // "Red"
colors[1] = (char*)malloc(20 * sizeof(char)); // "Green"
colors[2] = (char*)malloc(20 * sizeof(char)); // "Blue"

strcpy(colors[0], "Red");
strcpy(colors[1], "Green");
strcpy(colors[2], "Blue");

// Accessing and printing the strings


for (int i = 0; i < 3; i++) {
printf("%s\n", colors[i]);
}

// Deallocate memory (important to prevent leaks)


for (int i = 0; i < 3; i++) {
free(colors[i]);
}

return 0;
}
6Q. How do we pass string to a function?

Ans. In C, strings are essentially arrays of characters. To pass a string to a function, we


pass the address of the first character of the string, which is effectively a character pointer. 1

Here's how you can do it:

1. Function Declaration:

void my_function(char *str);

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:

char my_string[] = "Hello, world!";


my_function(my_string);

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:

void my_function(char *str) {


printf("%s\n", str); // Print the string
}

You might also like