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

C language important questions

The document discusses important concepts in C language, including Call by Value and Call by Reference, which describe how functions receive parameters. It also explains Dynamic Memory Allocation, detailing functions like malloc(), calloc(), and realloc(), and covers recursion, pointers, and the differences between static and dynamic memory allocation. Additionally, it provides code examples illustrating these concepts.

Uploaded by

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

C language important questions

The document discusses important concepts in C language, including Call by Value and Call by Reference, which describe how functions receive parameters. It also explains Dynamic Memory Allocation, detailing functions like malloc(), calloc(), and realloc(), and covers recursion, pointers, and the differences between static and dynamic memory allocation. Additionally, it provides code examples illustrating these concepts.

Uploaded by

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

C language important questions

Q-1 Call by reference and call by value

Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are
generally differentiated by the type of values passed to them as parameters.

• Call by value - In call by value method of parameter passing, the values of actual parameters
are copied to the function’s formal parameters.
o There are two copies of parameters stored in different memory locations.
o One is the original copy and the other is the function copy.
o Any changes made inside functions are not reflected in the actual parameters of the
caller.

// C program to illustrate call by value

#include <stdio.h>

// Function Prototype

void swapx(int x, int y);

// Main function

int main()

int a = 10, b = 20;

// Pass by Values

swapx(a, b); // Actual Parameters

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;

// Swap functions that swaps

// two values

void swapx(int x, int y) // Formal Parameters

int t;

t = x;
x = y;

y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

• Call by reference - 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.
o Both the actual and formal parameters refer to the same locations.
o Any changes made inside the function are actually reflected in the actual parameters
of the caller.

// C program to illustrate Call by Reference

#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}
Q-2 Explain Dynamic Memory Allocation in C

Dynamic Memory Allocation is the process of allocating memory to variables at runtime (while
the program is executing) instead of at compile time. It allows programs to manage memory
efficiently by requesting and releasing memory as needed, making it suitable for handling data
structures like arrays, linked lists, and trees whose sizes may change during execution.

Key Features:
• Memory is allocated from the heap instead of the stack.
• The size of memory blocks can be specified dynamically.
• Functions like malloc(), calloc(), realloc(), and free() in C are used to manage dynamic memory.

Memory Layout of a C Program:


1. Stack:
o Purpose: Stores local variables (declared inside functions or blocks).
o Explanation: Stack is used for temporary storage, like function calls and their
variables, and is automatically managed.
2. Heap:
o Purpose: Stores dynamically allocated memory (using malloc(), calloc(), etc.).
o Explanation: Memory is manually allocated and freed by the programmer during
runtime.
3. Data Segment (Permanent Storage):
o Global Variables: Declared outside functions, accessible throughout the program, and
exist until the program ends.
o Static Variables: Retain their values across function calls and are initialized only once.
4. Code Segment:
o Purpose: Stores the program’s machine instructions (the actual code).

Functions used for dynamic memory allocation in C

malloc()
• The malloc (memory allocation) function is used to allocate a specified number of bytes in
memory. When memory is allocated successfully, it returns a pointer to that block,
otherwise it returns NULL.
Syntax – (datatype*) malloc(size*sizeof(datatype));

Example - int* ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers

Calloc()

• The calloc() function in C is used for dynamic memory allocation. Unlike malloc, which leaves
the memory uninitialized, calloc initializes all allocated bytes to zero.

Syntax – (datatype*) calloc(size, sizeof(datatype);


Example – int *a = (int*)callloc(5,sizeof(int); // Allocates memory for 5 integer

realloc()
• The realloc (reallocate) function allows you to resize a previously allocated memory block.
It takes a pointer to the existing block and the new size in bytes as arguments. If
reallocation is successful, it returns a pointer to the reallocated memory. Otherwise, it
returns NULL.

Syntax – (datatype*)realloc(ptr,size*sizeof(datatype));

Example

1. int* ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers


2. ptr = (int*) realloc(ptr, 10 * sizeof(int)); // Reallocates memory for 10 integers

free()

• deallocate the memory


free(ptrname);

Q – write a program to illustrate dynamic memory allocation in C ?

#include <stdio.h> // header file for i/o

#include<stdlib.h> // header file for DMA

int main() {

// variable declaration

int *A,r,size;

// input

printf("Enter size of array : ");


scanf("%d",&size);

// Dynamically allocated size of array

A = (int*)malloc(size*4);

// array input

printf("Enter %d value : ",size);

for(r=0;r<size;r++)

scanf("%d",A+r);

printf("\n");

//output

for(r=0;r<size;r++)

printf("%d ",*(A+r));

// free memory

free(A);

return 0;

Q – Explain Recursion in C language ?

Q 5. Explain recursion in C programming?


Ans :- Function calling itself it is alternative of looping, It improve the response time of
program execution and reduce the complexity of the program. It is especially used in data
structure problems like Tree , Graph ,Stack ,queue.
But it is not necessary each looping program may convert into recursion program till it follows
two necessary properties :-
1) It must have terminating condition otherwise it become uncontrolled form or recursion may
lead the problem of stack overflow abnormal program termination or memory crash .
2) Problem must be divide into subproblems.

Syntax:-
return_type function_name(parameters) {
if (base_case_condition) {
// Base case: Stop recursion
return value;
} else {
// Recursive case: Function calls itself
return function_name(smaller_problem);
}
}
Conditions for Recursion to Work
1. Base Case:
o There must be a clear stopping condition to avoid infinite recursion.
2. Progress Toward Base Case:
o Each recursive call must make progress toward the base case (e.g., reducing the size of the
problem).
3. Well-Defined Problem:
o The problem should be divisible into smaller sub-problems that resemble the original
problem.

Q – Write difference between static and dynamic memory allocation ( PYQ RGPV )

Aspect Static Memory Allocation Dynamic Memory Allocation

Memory Allocated at runtime.


Allocated at compile time.
Assignment
Size of memory is fixed and Size of memory can be
Flexibility cannot be changed during adjusted during execution.
execution.
Requires explicit
Managed automatically by the management by the
Control
compiler. programmer.

Faster because memory is Slower because memory is


Speed allocated during runtime.
allocated during compile time.
Aspect Static Memory Allocation Dynamic Memory Allocation

May lead to memory wastage if Optimizes memory usage as


Memory Usage it is allocated as needed.
allocated size is not fully used.

The memory remains until the The memory remains until


Scope explicitly freed using free().
end of the program or its block.

Functio Uses heap and functions like


Uses stack and keywords like
ns/Keywords malloc(), calloc(), realloc().
static, arrays, etc.
Used

Automatically deallocated when Must be manually deallocated


Lifetime to avoid memory leaks.
the block or program ends.

int *arr = (int *)malloc(10 *


Example int arr[10]; (array of fixed size). sizeof(int)); (dynamic array).

May fail at runtime if


Fewer runtime errors; allocation sufficient memory is
Error Handling
is certain if space exists. unavailable.

Q – Demonstrate pointer arithmetic

#include <stdio.h> // header file for i/o

int main() {
// variable initialization + declaration
int a = 5,b=3,c=0;

// pointer initialization + declaration


int* aptr = &a;
int* bptr = &b;
int* cptr = &c;

// pointer arithmetic

*cptr = *aptr + *bptr;


printf("sum of a and b = %d\n",*cptr);

*cptr = *aptr - *bptr;


printf("subtraction of a and b = %d\n",*cptr);

*cptr = *aptr * *bptr;


printf("mulitiplicaton of a and b = %d\n",*cptr);

return 0;
}
Q – Write about pointers in C language

Pointers in C

A pointer is a variable that stores the memory address of another variable. Pointers are powerful
tools in C that allow direct memory access and manipulation.

Key Features:

1. Pointers store addresses, not values.

2. They provide efficient handling of arrays, strings, and dynamic memory.

3. They enable call-by-reference in functions.

Syntax:

• c

• Copy code

• data_type *pointer_name;

Example:

#include <stdio.h>

int main() {

int num = 10;

int *ptr = &num; // Pointer stores the address of num

printf("Value of num: %d\n", num); // Prints valueof num

printf("Address of num: %p\n", &num);// Prints addressof num

printf("Value using pointer: %d\n", *ptr);// Accessvalu using pointer

return 0;

Types of Pointers in C:

1. Null Pointer:

o A pointer initialized to NULL.

o Example: int *ptr = NULL;

2. Void Pointer:
o A generic pointer that can point to any data type.

o Example: void *ptr;

3. Dangling Pointer:

o A pointer that points to a memory location that has been freed or is no longer valid.

4. Wild Pointer:

o A pointer that has not been initialized.

o Example: int *ptr; // Wild pointer

5. Constant Pointer:

o A pointer that cannot change the address it is pointing to.

o Example: int num = 10, num2 = 20; int *const ptr = &num;

6. Pointer to Constant:

o A pointer that points to a constant value.

o Example: const int num = 10; const int *ptr = &num;

7. Function Pointer:

o A pointer that points to a function and can invoke the function.

o Example: void (*funcPtr)(int) = &myFunction;

8. Double Pointer:

o A pointer to another pointer.

o Example: int **ptr2;

Why Use Pointers?

• Dynamic memory allocation.

• Efficient array and string handling.

• Direct memory access for system-level programming.

Near and Far pointer


Near Pointer:

• A near pointer is a pointer that contains only the offset address within a segment.

• It is 16 bits (2 bytes) long.

• Can access memory only within the current segment (64 KB).

• Faster but limited in range.

Far Pointer:

• A far pointer is a pointer that contains both the segment address and the offset address.

• It is 32 bits (4 bytes) long.

• Can access memory across different segments (up to 1 MB).

• Slightly slower than near pointer.

You might also like