0% found this document useful (0 votes)
94 views25 pages

Unit-4 Question & Anwers

The document provides information about pointers in C programming: 1. It defines pointers as variables that contain the address of another variable in memory. This allows accessing variables defined outside functions. Pointers increase execution speed and reduce program complexity. 2. It describes how to declare and store addresses in pointers using the address of (&) operator. Pointers can then be used to access the value of the variable being pointed to using the indirection (*) operator. 3. It gives an example program to illustrate pointers and how they can be used to access and modify variable values. The program outputs the addresses and values of variables and a pointer to demonstrate their use.

Uploaded by

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

Unit-4 Question & Anwers

The document provides information about pointers in C programming: 1. It defines pointers as variables that contain the address of another variable in memory. This allows accessing variables defined outside functions. Pointers increase execution speed and reduce program complexity. 2. It describes how to declare and store addresses in pointers using the address of (&) operator. Pointers can then be used to access the value of the variable being pointed to using the indirection (*) operator. 3. It gives an example program to illustrate pointers and how they can be used to access and modify variable values. The program outputs the addresses and values of variables and a pointer to demonstrate their use.

Uploaded by

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

Unit-4

1. Write short notes on pointers.

Sol:-

A pointer is a variable that contains an address which is a location of another variable in


memory. A pointer enables us to access a variable that is defined outside the function.
Pointers reduce the length and complexity of a program. They increase the execution
speed.

A pointer variable or a pointer is similar to a variable but where a variable stores data; a
pointer variable stores address of a memory location. So a pointer does contain all
attributes of a variable but what is stored in pointer is interpreted as an address of a
memory location and not as data.

Declaring a pointer

A pointer variable (or pointer) is declared same as a variable but contains a * before the
name.

Syntax: -

Data Type *Pointer name;

The following is an example of a pointer variable.

int *p;

declares the variable p as a pointer variable that points to an integer data type.
Remember that the type int refers to the data type of the variable being pointed to by p
and not the type of the value of the pointer. Just like a normal variable even a pointer
variable contains memory location.

Storing address into pointer

A pointer is used to contain an address, to store the address of variable into pointer using
address operator (&). The operator & immediately preceding a variable returns the
address of the variable associated with it.
When a pointer contains the address of a variable, then the pointer is said to be pointing
to that variable. For example, in the following code, pointer p is pointing to variable i.

int i=50,*p;
p = &i;

When p contains the address of i then it is read as p is pointing to i.

Accessing a Variable through its pointer

To access the value of the variable using pointer (that contains address of a variable), this
is done by using another unary operator * (asterisk), usually known as the indirection
operator. When a pointer points to a memory location we can access the value of that
memory location using a special operator called indirection operator (*)

When a pointer variable is used with indirection operator then you get the value of the
location to which pointer points. So *p will return 50 because p is pointing to memory
location 200 and that is the location of variable i, where value 50 is stored.

For Example

int quantity,*p,n;
quantity = 150;
p = &quantity;
n = *p;

Example: Program to illustrate the concept of pointers.


#include <stdio.h>
main()
{
int a = 10;
int *p;
p = &a;
clrscr();
printf("\nAddress of a: %u", &a);
printf("\nAddress of a: %u", p);
printf("\nAddress of p: %u", &p);
printf("\nValue of p: %d", p);
printf("\nValue of a: %d", a);
printf("\nValue of a: %d", *(&a));
printf("\nValue of a: %d", *p);
getch();
}
Output:
Address of a: 65494
Address of a: 65494
Address of p: 65496
Value of p: 65494
Value of a: 10
Value of a: 10
Value of a: 10

2. Explain how to access the elements of a union with an example


Sol:-

A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple-purpose.

Defining a Union

To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −

union union name

member definition;

member definition;

...
member definition;

} [one or more union variables];

Example:-

union Data

int i;

float f;

char str[20];

} data;

The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type.

Example:-

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( )
{

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}

3. Describe categories of functions based on arguments and return type and what are
different parameter passing methods in functions ?
Sol:-

A function is a self-contained program segment that carries out a specific, well-defined task. A
function is a collection of instructions that performs a specific task. Every function is given a
name. The name of the function is used to invoke (call) the function. A function may also take
parameters (arguments). If a function takes parameters, parameters are to be passed within
parentheses at the time of invoking function.

In C Programming, as per our requirement, we can define the User-defined functions in multiple
ways. The following are a list of available types of Functions in C

1 No argument and no Return value

2. Argument and No Return value

3. Argument and Return value

1. C Function with No argument and No Return value

In this method, We won’t pass any arguments to the function while defining, declaring, or calling
the function. This type of functions in C will not return any value when we call the function from
main() or any sub-function. When we are not expecting any return value, but we need some
statements to print as output. Then, this type of function in C is very useful.

/* Function with No argument and No Return value Example */


#include<stdio.h>

// Function Declaration
void Addition();

void main()
{
printf("\n ............. \n");

Addition();
}

void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;

printf("\n Sum of a = %d and b = %d is = %d", a, b, Sum);


}

2. Function with argument and No Return value

This method allows us to pass the arguments to the function while calling the function. But, This
type of function will not return any value when we call the function from main () or any
subfunction.

#include<stdio.h>

void Addition(int, int);

void main()
{
int a, b;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Addition(a, b);
}

void Addition(int a, int b)


{
int Sum;

Sum = a + b;

printf("\n Additiontion of %d and %d is = %d \n", a, b, Sum);


}
3. Function with argument and Return value

This method allows us to pass the arguments to the function while calling the function. This type
of function will return some value when we call the function from main () or any subfunction.
Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.

#include<stdio.h>

int Multiplication(int, int);

int main()
{
int a, b, Multi;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Multi = Multiplication(a, b);

printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);


return 0;
}

int Multiplication(int a, int b)


{
int Multi;

Multi = a * b;

return Multi;
}

what are different parameter passing methods in functions ?

Parameter Passing Techniques:

Call by Value & Call by Reference

If data is passed by value, the data is copied from the variable used in main() to a variable
used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the
function.

When we call a function then we will just pass the variables or the arguments and we
doesn’t pass the address of variables , so that the function will never effects on the values
or on the variables.

So Call by value is that the values those are passed to the functions will never effect the
actual values those are Stored into the variables

Example: Program to illustrate the concept of call by value

#include<stdio.h>
void swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(a, b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

Output:
Enter value of a & b: 2 3
Before swapping:
a=2
b=3
After swapping:
a= 2
b=3

Call by Reference:

If data is passed by reference, a pointer to the data is copied instead of the actual variable
as it is done in a call by value. Because a pointer is copied, if the value at that pointers
address is changed in the function, the value is also changed in main().

In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.

When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values

Example: Program to illustrate the concept of call by reference

#include<stdio.h>
void swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
}
void swap (int *a, int *b)
{
int *temp;
*temp = *a;
*a = *b;
*b =* temp;
}

Output:
Enter value of a & b: 2 3
Before swapping:
a=2
b=3
After swapping:
a= 3
b=2

4. Write a program to generate Fibonacci series using static storage class

.
5. Explain about call by value with an example.

Refer Class Notes

6. Write a program to generate Fibonacci series using with argument and return type.

7. Write a program using structures to display the following information for each
customer name, account number, street, city, old balance, current payment, new
balance, account status.

8. List the differences between Structure and Union

Structure Union
You can use a struct keyword to define a
You can use a union keyword to define a union.
structure.
Every member within structure is assigned a In union, a memory location is shared by all the
unique memory location. data members.
Changing the value of one data member will
Changing the value of one data member will not
change the value of other data members in
affect other data members in structure.
union.
It enables you to initialize several members at It enables you to initialize only the first member
once. of union.
The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.
It is mainly used for storing one of the many
It is mainly used for storing various data types.
data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can access one member at a time in the
You can retrieve any member at a time.
union.
It supports flexible array. It does not support a flexible array.

9. Write a program and explain the working of malloc and calloc function.

An array is a collection of a fixed number of values. Once the size of an array is declared,
we cannot change it. Sometimes the size of the array you declared may be insufficient.
To solve this issue, you can allocate memory manually during run-time. This is known as
dynamic memory allocation in C programming.

The mechanism by which storage/memory/cells can be allocated to variables during


the run time is called Dynamic Memory Allocation (not to be confused with DMA).

Advantages :-

1. When we do not know how much amount of memory would be needed for the program
beforehand.
2. When we want data structures without any upper limit of memory space.
3. When you want to use your memory space more efficiently.Example: If you have
allocated memory space for a 1D array as array[20] and you end up using only 10
memory spaces then the remaining 10 memory spaces would be wasted and this wasted
memory cannot even be utilized by other program variables.
4. Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions and
deletions lead to more movements and wastage of memory.
5. When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.

To allocate memory dynamically, library functions are


1.malloc(),
2.calloc(),
3. realloc()
4.free()

These functions are defined in the <stdlib.h> header file.

1. The malloc() function reserves a block of memory of the specified number of


bytes. And, it returns a pointer of void which can be casted into pointers of any
form.

Syntax of malloc()

ptr = (castType*) malloc(size);

Example

ptr = (float*) malloc(100);

Program:-

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &n);

ptr = (int*) malloc(n);

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", (ptr + i));
sum += *(ptr + i);
}

printf("Sum = %d", sum);


}

2.calloc():-

The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.

Syntax of calloc()
ptr = (castType*)calloc( size, No of Bytes);

Example:

ptr = (float*) calloc(25, No of Bytes);

Program :-

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));


printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


}
10. Explain about different storage classes with examples.

Refer Class Notes

11. Explain function prototype and explain different methods to call the functions.

Refer Q.No-3

12. How to initialize and access pointer variables? Discuss.

Refer Q.No-1

13. How to pass structure variable to functions? Explain with example.

Sol:-

• A structure can be passed to any function from main function or from any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those functions by value or
by address(reference).
• Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.

PASSING STRUCTURE TO FUNCTION IN C:


It can be done in below 3 ways.
• Passing structure to a function by value
• Passing structure to a function by address(reference)
• No need to pass a structure – Declare structure variable as global

EXAMPLE PROGRAM –

PASSING STRUCTURE TO FUNCTION IN C BY VALUE:

In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this structure
can be accessed from called function. This concept is very useful while writing very big
programs in C.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

EXAMPLE PROGRAM

PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:

In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(&record);
return 0;
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}

EXAMPLE PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL IN C:

Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a
program. In this scenario, we don’t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

14. What is meant by recursion? What are its uses? How it is implemented? Explain
with example.

Sol:-

Recursion is a process of defining something in terms of itself and is sometimes called


circular definition. When a function calls itself it is called as recursion. Recursion is natural
way of writing certain functions.

Recursive Function: A function is said to be recursive if a statement in the body of the


function calls itself. Each recursive function must specify an exit condition for it to terminate,
otherwise it will go on indefinitely.

A simple example of recursion is presented below:

main()
{
printf("\nThis is an example of recursion");
main();
}

Example: Program to find factorial of given number using recursion.

#include<stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
}
long fact(int n)
{
int m;
if (n == 1)
return 1;
else
m=n * fact(n-1);

return m;
}

15. Explain about


(i) local and global variables
(ii) (ii) actual and formal arguments.

Refer Class Notes

16. Differentiate between direct and indirect pointers with examples.

Sol:-

In C, there are two equivalent ways to access and manipulate a variable content

• Direct access: we use directly the variable name


• Indirect access: we use a pointer to the variable

Example :-

#include <stdio.h>
int var = 1;
int *ptr;
int main( void )
{
ptr = &var;
printf("\nDirect access, var = %d", var); /* Access var directly and indirectly */
printf("\nIndirect access, var = %d", *ptr);
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
/*change the content of var through the pointer*/
*ptr=48;
printf("\nIndirect access, var = %d", *ptr);
return 0;}

17. What is pointer? Is *p is similar to &p? explain

Refer Q.No-1

18. What are the uses with recursive functions

Sol:-

The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are

• Towers of Hanoi (TOH),


• Inorder/Preorder/Postorder Tree Traversals,
• DFS of Graph,

19. What is an user defined function? When these functions are useful? How a function
is declared and what are the rules followed to call a function.

Refer Q.No-3

20. Write a C program to find the arithmetic mean of n values using functions

21. What is a pointer? Explain address arithmetic with example

Sol:-
A pointer in c is an address, which is a numeric value. Therefore, we can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic operators
that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the
address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the
pointer −

ptr++

After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without impacting the
actual value at the memory location. If ptr points to a character whose address is 1000, then the
above operation will point to the location 1001 because the next character will be available at
1001.

Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
The following program increments the variable pointer to access each succeeding element of the
array –

#include <stdio.h>

const int MAX = 3;

int main ()
{

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */


ptr++;
}
return 0;

Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below −
#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


ptr = &var[MAX-1];

for ( i = MAX; i > 0; i--) {

printf("Address of var[%d] = %x\n", i-1, ptr );


printf("Value of var[%d] = %d\n", i-1, *ptr );

/* move to the previous location */


ptr--;
}

return 0;
}
22. Write any two merits and demerits of pointers

Sol:-

Advantages

• Pointers provide direct access to memory


• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth between the calling function and
called function.
• Pointers allows us to perform dynamic memory allocation and deallocation.
• Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
• Pointers allows us to resize the dynamically allocated memory block.
• Addresses of objects can be extracted using pointers

Drawbacks

• Uninitialized pointers might cause segmentation fault.


• Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
• Pointers are slower than normal variables.
• If pointers are updated with incorrect values, it might lead to memory corruption.

23. Give the implementation of multidimensional arrays using pointers. Let the user
specify the number of rows and columns for the array for allocating memory
dynamically.

24. What is dangling pointer?

Sol:-

When a pointer is pointing at the memory address of a variable but after some time that variable
is deleted from that memory location while the pointer is still pointing to it, then such a pointer is
known as a dangling pointer and this problem is known as the dangling pointer problem
Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted).
There are different ways where Pointer acts as dangling pointer

Function Call

The pointer pointing to local variable becomes dangling when local variable is not static.

int *show(void)

int n = 76;

return &n;

Output

Output of this program will be garbage address.

De-allocation of memory

int main()

float *p = (float *)malloc(sizeof(float));

//dynamic memory allocation.

free(p);

//after calling free()

p becomes a dangling pointer p = NULL;

//now p no more a dangling pointer.

25. Write a C program to find the arithmetic mean of n values using functions
26. What are the differences between recursion and iteration?

The Recursion and Iteration both repeatedly execute the set of instructions. Recursion is when
a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly
executes until the controlling condition becomes false. The primary difference between
recursion and iteration is that recursion is a process, always applied to a function
and iteration is applied to the set of instructions which we want to get repeatedly executed.

Recursion

• Recursion uses selection structure.


• Infinite recursion occurs if the recursion step does not reduce the problem in a manner
that converges on some condition (base case) and Infinite recursion can crash the system.
• Recursion terminates when a base case is recognized.
• Recursion is usually slower than iteration due to the overhead of maintaining the stack.
• Recursion uses more memory than iteration.
• Recursion makes the code smaller.

Example

#include<stdio.h>
int factorial(int n);
void main()
{
int n,a;
printf(“Enter Any No:”);
sccanf(“%d”,&n);
a=factorial(n);
printf("Result: %d" , result);
}
int factorial(int n)
{
int f;
if (n==0)
{
return 1;
}
else
{
f=n*factorial(n-1);

}
teturn f;
}

Iteration

• Iteration uses repetition structure.


• An infinite loop occurs with iteration if the loop condition test never becomes false and
Infinite looping uses CPU cycles repeatedly.
• An iteration terminates when the loop condition fails.
• An iteration does not use the stack so it's faster than recursion.
• Iteration consumes less memory.
• Iteration makes the code longer.

Example

#include<stdio.h>

void main()

int i;

for( i = 1; i <= 5; i++) {

printf(“%d\n”,i);

You might also like