0% found this document useful (0 votes)
29 views18 pages

Foc - unit-III Question Bank With Answer

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)
29 views18 pages

Foc - unit-III Question Bank With Answer

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

UNIT- III - FUNCTIONS, ARRAYS AND POINTERS

PART A (2 Marks)

1. Examine why functions are needed in C? Justify.


1. Modularity

2. Reusability

3. Organization

4. Ease of Maintenance

5. Abstraction

6. Scope Management

7. Parameterization

8. Recursion

2. What is a pointer? How a variable is declared to the pointer?


A pointer in C is a variable that stores the memory address of another variable. Pointers are powerful
tools for managing memory, creating dynamic data structures, and facilitating efficient data
manipulation.

Declaring a Pointer

To declare a pointer variable, you use the following syntax:

data_type *pointer_name;

- data_type: This specifies the type of data the pointer will point to (e.g., `int`, `float`, `char`, etc.).

- pointer_name: This is the name you give to the pointer variable.

Example

Here's an example of declaring a pointer to an integer:

int *ptr; // Declares a pointer to an integer

3. Define array data structure and give an example of a float array


of size 5 and assign values to it.

An array is a data structure in C that allows you to store a fixed-size sequential collection of elements
of the same type. Each element can be accessed using an index, making arrays efficient for storing
and manipulating lists of data.

Example of a Float Array

#include <stdio.h>

int main() {

// Define a float array of size 5

1
float numbers[5];

// Assign values to the array

numbers[0] = 1.5;

numbers[1] = 2.5;

numbers[2] = 3.5;

numbers[3] = 4.5;

numbers[4] = 5.5;

// Print the values

for (int i = 0; i < 5; i++) {

printf("numbers[%d] = %.1f\n", i, numbers[i]);

return 0;

4. Write short notes on self-referential structures.

Definition

A self-referential structure is a structure that includes a member that is a pointer to the same
type of structure. This enables the creation of dynamic data structures where each element
can point to another element of the same type.

Key Features

1. Dynamic Memory Allocation: Self-referential structures often use dynamic memory


(e.g., malloc), enabling flexible sizes and efficient memory use.
2. Flexible Data Structures: They facilitate the creation of linked data structures like
linked lists, trees, and graphs, which can grow and shrink in size during program
execution.
3. Access and Manipulation: Each node can be accessed and manipulated via pointers,
allowing for efficient traversal and modification.

5. Outline any four advantages of pointer

 Dynamic Memory Management


 Efficient Array and String Manipulation
 Pass by Reference
 Facilitating Complex Data Structures

2
Part –B

11. A(i). Discuss about pointers and address.

Pointers and addresses are fundamental concepts in C programming that work together to
manage memory and facilitate data manipulation. Here’s an overview of both:

Pointers

Definition: A pointer is a variable that stores the memory address of another variable. It
allows programmers to directly access and manipulates the memory where data is stored.

Declaration: Pointers are declared using the

syntax `data_type *pointer_name;`.

For example, `int *ptr;` declares a pointer to an integer.

Initialization: Pointers are typically initialized by assigning them the address of a variable
using the address-of operator (`&`).

For example, `ptr = &var;` assigns the address of `var` to `ptr`.

Dereferencing: To access the value stored at the address a pointer points to, you use the
dereference operator (`*`).

For example, `value = *ptr;` retrieves the value stored at the address held by `ptr`.

Addresses

Definition: An address is a unique identifier for a memory location in a computer's memory.


Every variable in C is stored at a specific address, which can be accessed using the address-of
operator (`&`).

Memory Layout: When a program runs, memory is divided into different sections, such as
the stack (for local variables) and the heap (for dynamically allocated memory). Each section
has its own addresses.

Address Size: The size of an address depends on the architecture of the system (e.g., 32-bit
or 64-bit). In a 32-bit system, addresses are typically 4 bytes long, while in a 64-bit system,
they are 8 bytes.

Relationship between Pointers and Addresses

1. Accessing Memory: Pointers use addresses to directly access and manipulate data in
memory. By storing the address of a variable, a pointer provides a way to reference and
modify the value at that location.

3
2. Dynamic Memory: Pointers are essential for dynamic memory management. Functions
like `malloc` and `free` return pointers to memory blocks, enabling the allocation and
deallocation of memory at runtime.

3. Efficient Data Structures: Pointers allow the creation of complex data structures that
rely on addresses for linking elements (e.g., linked lists). Each node in such structures
contains a pointer to the next node, facilitating traversal and manipulation.

11.a(ii). Write a C Program to count number of vowels and consonants

in the given input string.

#include <stdio.h>

#include <ctype.h>

int main() {

char str[100];

int vowels = 0, consonants = 0;

// Input string

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Iterate through each character in the string

for (int i = 0; str[i] != '\0'; i++) {

char ch = tolower(str[i]); // Convert to lowercase for uniformity

// Check if the character is an alphabet

if (isalpha(ch)) {

// Check if it is a vowel

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

vowels++;

} else {

// It is a consonant

consonants++;

4
}

// Output the results

printf("Number of vowels: %d\n", vowels);

printf("Number of consonants: %d\n", consonants);

return 0;

12. a(i). Examine the syntax of function definition, declaration, and

function call. Show how it is used to find the biggest of 3

numbers.

1. Function Declaration

A function declaration provides the compiler with the function's name, return type, and
parameters (if any). It does not include the body of the function.

Syntax:

return_type function_name(parameter_type1 parameter_name1, parameter_type2


parameter_name2, ...);

Example:

int findBiggest(int a, int b, int c);

2. Function Definition

The function definition includes the actual implementation of the function, including its body.

Syntax:

return_type function_name(parameter_type1 parameter_name1, parameter_type2


parameter_name2, ...) {

// function body

5
}

Example:

int findBiggest(int a, int b, int c) {

if (a >= b && a >= c) {

return a;

} else if (b >= a && b >= c) {

return b;

} else {

return c;

3. Function Call

A function call is how you execute the function in your code, providing the necessary
arguments.

Syntax:

function_name(argument1, argument2, ...);

Example:

int biggest = findBiggest(num1, num2, num3);

Complete Example: Finding the Biggest of Three Numbers

Here is a complete C program that includes function declaration, definition, and calling to
find the biggest of three numbers:

#include <stdio.h>

// Function declaration

int findBiggest(int a, int b, int c);

int main() {

int num1, num2, num3;

6
// Input from the user

printf("Enter three numbers: ");

scanf("%d %d %d", &num1, &num2, &num3);

// Function call

int biggest = findBiggest(num1, num2, num3);

// Output the result

printf("The biggest number is: %d\n", biggest);

return 0;

// Function definition

int findBiggest(int a, int b, int c) {

if (a >= b && a >= c) {

return a;

} else if (b >= a && b >= c) {

return b;

} else {

return c;

7
12.B( ii). Inspect recursive function and its significance. Develop a C

program to generate first „m‟ Fibonacci numbers using recursion.

Recursive Functions in C

A recursive function is a function that calls itself to solve smaller instances of the same
problem. Recursion is often used in situations where a problem can be broken down into
smaller, similar subproblems, making it a natural fit for problems like calculating factorials,
generating Fibonacci numbers, traversing trees, and more.

Significance of Recursive Functions

1. Simplicity: Recursive functions can simplify the code, making it easier to understand and
maintain, especially for problems that have a clear recursive structure.

2. Natural Fit for Certain Problems: Some algorithms (like traversing a binary tree) are more
straightforward when expressed recursively.

3. Reduction in Code Size: Recursive solutions can often be written in fewer lines than their
iterative counterparts.

C Program to Generate the First `m` Fibonacci Numbers Using Recursion

#include <stdio.h>

// Recursive function to get the nth Fibonacci number

int fibonacci(int n) {

if (n <= 1) {

return n; // Base case: F(0) = 0, F(1) = 1

return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call

int main() {

int m;

// Input from the user

printf("Enter the number of Fibonacci numbers to generate: ");

scanf("%d", &m);

8
printf("First %d Fibonacci numbers are:\n", m);

for (int i = 0; i < m; i++) {

printf("%d ", fibonacci(i)); // Call the recursive function

printf("\n");

return 0;

Output

When you run this program, it will ask for the number of Fibonacci numbers you want to
generate, and then it will display them. For example, if you input `5`, the output will be:

First 5 Fibonacci numbers are:

0 1123

13.Recall an array. How single dimensional and two-dimensional

arrays are declared and initialized? Develop a C program to add

two 2-dimensional matrices.

Arrays in C

An array is a collection of variables of the same type, stored in contiguous memory locations.
In C, arrays can be single-dimensional (1D) or multi-dimensional (such as two-dimensional,
or 2D).

Single-Dimensional Arrays

Declaration:

data_type array_name[size];

Initialization:

data_type array_name[size] = {value1, value2, ..., valueN};

9
Example:

int arr[5] = {1, 2, 3, 4, 5};

Two-Dimensional Arrays

Declaration:

data_type array_name[rows][columns];

Initialization:

data_type array_name[rows][columns] = {

{value11, value12, ..., value1N},

{value21, value22, ..., value2N},

...

};

Example:

int matrix[2][3] = {

{1, 2, 3},

{4, 5, 6}

};

C Program to Add Two 2-Dimensional Matrices

#include <stdio.h>

#define ROWS 3

#define COLS 3

void addMatrices(int first[ROWS][COLS], int second[ROWS][COLS], int result[ROWS]


[COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

result[i][j] = first[i][j] + second[i][j];

10
}

int main() {

int first[ROWS][COLS], second[ROWS][COLS], result[ROWS][COLS];

// Input for first matrix

printf("Enter elements of first matrix (%d x %d):\n", ROWS, COLS);

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

printf("Element [%d][%d]: ", i, j);

scanf("%d", &first[i][j]);

// Input for second matrix

printf("Enter elements of second matrix (%d x %d):\n", ROWS, COLS);

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

printf("Element [%d][%d]: ", i, j);

scanf("%d", &second[i][j]);

// Add matrices

addMatrices(first, second, result);

// Output the result

printf("Resultant matrix after addition:\n");

for (int i = 0; i < ROWS; i++) {

11
for (int j = 0; j < COLS; j++) {

printf("%d ", result[i][j]);

printf("\n");

return 0;

Example Output

Enter elements of first matrix (3 x 3):

Element [0][0]: 1

Element [0][1]: 2

Element [0][2]: 3

Element [1][0]: 4

Element [1][1]: 5

Element [1][2]: 6

Element [2][0]: 7

Element [2][1]: 8

Element [2][2]: 9

Enter elements of second matrix (3 x 3):

Element [0][0]: 9

Element [0][1]: 8

Element [0][2]: 7

Element [1][0]: 6

Element [1][1]: 5

Element [1][2]: 4

12
Element [2][0]: 3

Element [2][1]: 2

Element [2][2]: 1

Resultant matrix after addition:

10 10 10

10 10 10

10 10 10

4. Mention the significance of storage classes in C. Demonstrate

them with suitable C programs and compare them.

In C programming, storage classes define the scope (visibility) and lifetime of variables and
functions. They determine how and where the variables are stored, which affects memory
management, performance, and variable accessibility.

Significance of Storage Classes:

1. Scope: Defines where the variable can be accessed within the code.

2. Lifetime: Determines how long the variable exists in memory during program execution.

3. Memory Location: Specifies whether a variable is stored in stack or static memory.

Types of Storage Classes:

1. Automatic (`auto`): Default storage class for local variables. Scope is limited to the block
in which they are defined, and they are created and destroyed automatically.

2. Register: Suggests to the compiler to store the variable in a register for faster access. It is
still local in scope and has automatic lifetime.

3. Static: Maintains the variable’s value between function calls. Scope is limited to the block,
but the lifetime extends across the entire program execution.

4. External (`extern`): Used to declare a variable that is defined in another file or outside the
current scope. The variable can be accessed across different files.

13
Examples

# 1. Automatic Storage Class

#include <stdio.h>

void demoAuto() {

auto int x = 5; // auto is optional here

printf("Auto variable x: %d\n", x);

int main() {

demoAuto();

// printf("%d", x); // Error: x is not accessible here

return 0;

# 2. Register Storage Class

#include <stdio.h>

void demoRegister() {

register int count = 0; // Hint to use register storage

for (count = 0; count < 5; count++) {

printf("Register variable count: %d\n", count);

int main() {

demoRegister();

return 0;

14
# 3. Static Storage Class

#include <stdio.h>

void demoStatic() {

static int counter = 0; // Static variable retains its value

counter++;

printf("Static variable counter: %d\n", counter);

int main() {

for (int i = 0; i < 5; i++) {

demoStatic();

return 0;

# 4. External Storage Class

#include <stdio.h>

// Declaration of external variable

extern int globalVar;

void demoExtern() {

printf("External variable globalVar: %d\n", globalVar);

int globalVar = 10; // Definition and initialization

int main() {

demoExtern();

return 0;

15
Comparison of Storage Classes

| Storage Class | Scope | Lifetime | Memory Location |

|---------------|------------------------------|----------------------------|--------------------- |

| `auto` | Local to the block | Exists during block execution | Stack |

| `register` | Local to the block | Exists during block execution | Register (if possible)

| `static` | Local to the block (or file) | Exists for the lifetime of the program | Static memory

| `extern` | Global (across files) | Exists for the lifetime of the program | Static memory |

5. Explain with example program to display all prime numbers

between two intervals using function.

To display all prime numbers between two intervals in C using functions, you can follow
these steps:

1. Define a function to check if a number is prime.

2. Use a loop to iterate through the specified interval.

3. Call the prime-checking function for each number in the interval.

Example Program

#include <stdio.h>

// Function to check if a number is prime

int isPrime(int num) {

if (num <= 1) {

return 0; // Not prime

for (int i = 2; i * i <= num; i++) { // Check divisibility

if (num % i == 0) {

return 0; // Not prime

16
}

return 1; // Prime

// Function to display prime numbers in the given range

void displayPrimes(int start, int end) {

printf("Prime numbers between %d and %d are:\n", start, end);

for (int i = start; i <= end; i++) {

if (isPrime(i)) {

printf("%d ", i);

printf("\n");

int main() {

int lower, upper;

// Get input from user

printf("Enter lower limit: ");

scanf("%d", &lower);

printf("Enter upper limit: ");

scanf("%d", &upper);

// Display prime numbers in the range

displayPrimes(lower, upper);

return 0;

17
Example Output

Enter lower limit: 10

Enter upper limit: 30

Prime numbers between 10 and 30 are:

11 13 17 19 23 29

18

You might also like