0% found this document useful (0 votes)
4 views8 pages

unit 4

The document provides an overview of recursion and pointers in C programming, including syntax and examples for recursive functions to calculate factorial and Fibonacci series. It also explains pointers, their advantages and disadvantages, and how to define and use structures and unions in C. Additionally, it highlights the differences between structures and unions, emphasizing memory allocation and data access methods.

Uploaded by

manjulak.comp
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)
4 views8 pages

unit 4

The document provides an overview of recursion and pointers in C programming, including syntax and examples for recursive functions to calculate factorial and Fibonacci series. It also explains pointers, their advantages and disadvantages, and how to define and use structures and unions in C. Additionally, it highlights the differences between structures and unions, emphasizing memory allocation and data access methods.

Uploaded by

manjulak.comp
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/ 8

C-Programming

FUNCTIONS
Recursion/Recursive Function
Ex:
 Recursion is the process of repeating items in a self-similar way.
 In programming languages, if a program allows you to call a function inside the same function,
then it is called a recursive call of the function.

Syntax:
void recursion()
{
recursion(); /*function calls itself*/
}
int main()
{
recursion();
}

Note:

 The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.

 Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.

Program to generate factorial of given number using recursive function.


#include<stdio.h>
unsigned long long int factorial(unsigned int i)
{
if(i <= 1)
{
return1;
}
return i*factorial(i-1);
}
int main()
{
int i = 5;
printf("*****Factorial using recursion*****\n");
printf("Factorial of %d is %d\n", i, factorial(i));
return0;
}

Manjula K, Asst. Professor, FCIT, GMU Page 1


C-Programming

OUTPUT

Program to generate fibonacci of given number using recursive function.

#include<stdio.h>
int Fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return1;
}
return Fibonacci(i-1)+Fibonacci(i-2);
}
int main()
{
int i;
printf("Recursion of Fibonacci Series\n");
for(i=0;i<10;i++)
{
printf("%d\t\n", Fibonacci(i));
}
return 0;
}
OUTPUT

Manjula K, Asst. Professor, FCIT, GMU Page 2


C-Programming
Pointers in C
Definition
A pointer is a variable itself, which stores the address of another variable of some specific data
type. The contents of pointer are address of another variable of type int, float, char etc.
OR
A pointer is a special type of variable; the pointer contains the address of another
variable. Normal variables meant for storing value, whereas pointer variables for
storing address of other variables.

Syntax:
data type *pointer_variable_name;

 data_type : Data type of the pointer like int, float.


 pointer_variable_name : Name of the pointer variable.
 “*”: is the notation for declaring pointer variables.

Example :
int *p;
float *f;

Declaration and Initialization of pointers


Pointers declaring are done as follows
int *ptr;
Pointers initialization is done as follows
ptr=&a;

 &a gives the address of the variable a


 ptr is the pointer variable Address of the variable as assigned to
point ptr.

 Reference operator (&) and Dereference operator (*)


 Reference operator (&) is used to get the address of the variable
 Dereference operator (*) operator is used to get the value of the variable from the
address.

EX:
#include <stdio.h>
int main()
{
int num = 42; // Declare and initialize an integer variable
int *ptr; // Declare a pointer to an integer
ptr = &num; // Initialize the pointer with the address of num
printf("Value of num: %d\n", *ptr);
*ptr = 100;
printf("Modified value of num: %d\n", num);
printf("Address of num: %p\n", (void*)&num);
printf("Address stored in ptr: %p\n", (void*)ptr);

Manjula K, Asst. Professor, FCIT, GMU Page 3


C-Programming
return 0;
}

OUTPUT:
Value of num: 42
Modified value of num: 100
Address of num: 0x7ffc5a7a0c4c
Address stored in ptr: 0x7ffc5a7a0c4c

Accessing the address and value of a variable

 The value of the variable is accessed through dereference operator (*) as below:

printf("The value of the variable a is :%d\n",*ptr);

 The address of the variable is accessed as below:

printf("The value of the variable a is:%u\n",ptr);

EX:
#include<stdio.h>
void main()
{
int a = 10;
int *ptr;
ptr=&a;
printf("\n*********Pointer Demo*********\n");
printf("\n Accessing address and value of variable through variable\n");
printf("The address of variable a is:%d\n", &a);
printf("The value of the variable a is:%d\n", a);
printf("\n Accessing address and value of variable through normal pointer
variable\n"); printf("The address of variable a is :%d\n", ptr);
printf("The address of variable a is : %p\n", ptr);
printf("The value of the variable a is : %d\n", *ptr);
}

OUTPUT:

Manjula K, Asst. Professor, FCIT, GMU Page 4


C-Programming
Advantages of pointers in c
 Pointers provide direct access to memory.
 Pointers provide away 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 object scan be extract educing pointers.

Disadvantages of pointers in c
 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.

 Basically, pointer bugs are difficult to debug. Its programmer’s responsibility to use

pointers effectively and correctly.

User defined data types


Structure

 Structures are collection of variables of same or different data types under a


single name.
 Structures are group of items in which each item is identified by its own
identifies, each of which is known as member of the structure.
 Keyword struct is used for creating a structure
 A Structure is a derived data type.

Defining a Structure
To define a structure, we must use the struct statement. The struct statement defines a new
data type, with more than one member.

Syntax: struct [structure tag]


{
Member definition;
Member definition;
...
Member definition;
} [one or more structure variables];

Manjula K, Asst. Professor, FCIT, GMU Page 5


C-Programming
Note:
[structure tag] is Optional.
Don't forget the semicolon}; in the ending line.

Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage or memory is allocated,
but for structure variables memory gets created.

EXAMPLE FOR STRUCTURE TO STORE STUDENT INFORMATION

#include <stdio.h>
struct Student
{
char name[50];
int rollNumber;
float marks;
};
int main()
{
// Declare a structure variable
struct Student student;
// Input student information
printf("Enter student name: ");
fgets(student.name, sizeof(student.name), stdin); // Read a string including spaces
printf("Enter roll number: ");
scanf("%d", &student.rollNumber);
printf("Enter marks: ");
scanf("%f", &student.marks);
// Display student information
printf("\nStudent Information:\n");
printf("Name: %s", student.name);
printf("Roll Number: %d\n", student.rollNumber);
printf("Marks: %.2f\n", student.marks);
return 0;
}

OUTPUT:

Manjula K, Asst. Professor, FCIT, GMU Page 6


C-Programming
Unions
Definition

Unions are derived data types like structure, Creation and accessing union variables is
similar to the accessing and creating of structures.

Defining a Union

Union variables are created in same manner as structure variables. The keyword union is used to
define unions in C language.

Syntax:

union [union tag]


{
member definition;
member definition;
...
member definition;
} [one or more union variables];

 The "union tag" is optional and each member definition is a normal variable definition,
such as "int i;" or "float f;" or any other valid variable definition.
 At the end of the union's definition, before the final semicolon, you can specify one or
more union variables.

Declare union variables


A union variable is declared using the union keyword, followed by the union name, and then
the variable name. Just like structures, unions allow declaring variables globally, locally, or
within another structure.

EXAMPLE:

#include <stdio.h>
union Data
{
int intValue;
float floatValue;
char charValue;
};
int main()
{
// Declare a union variable
union Data data;
// Assign values to the union members one at a time
data.intValue = 42;

Manjula K, Asst. Professor, FCIT, GMU Page 7


C-Programming
printf("Integer Value: %d\n", data.intValue);
data.floatValue = 3.14f; // Overwrites previous value
printf("Float Value: %.2f\n", data.floatValue);
data.charValue = 'A'; // Overwrites previous value
printf("Character Value: %c\n", data.charValue);
return 0;
}

OUTPUT:

DIFFERENCE BETWEEN STRUCTURES AND UNIONS

Structure Union
To define a structure, we utilize the struct statement To define a union, we use the union keyword
Every member has their own memory place A memory location is shared by all data
members
A change in the value of one data member has no A change in one data member’s value has
effect on the structure’s other data members an impact on the value of other data
members
Multiple members can be initialized at the same Only the first member can be initialized at a
time time
Multiple values of various members can be stored in For all of its members, a union stores one value
a structure at a time
The overall size of a structure is the sum of the sizes The biggest data member determines the
of all data members total size of a union

At any moment, users can access or recover any Only one member can be accessed or retrieved at
member a time

Manjula K, Asst. Professor, FCIT, GMU Page 8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy