C Unit2
C Unit2
RECURSION
The function which calls the same function, is known as recursive function.
Syntax:
recursionfunction()
{
recursionfunction();//calling self function
}
Example:
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Output:
6
11
extern:
The extern storage class is used to give a reference of a global variable that is visible to all program files.
Variables that are declared outside of all functions are known as external or global variables. They are
accessible from any function inside the program.
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Output:
n=7
ARRAYS
An array is a collection of similar data elemetns. These elements have the same data type.
Elements are stored in consecutive memory locations and are referenced by an index (also known as
subscript).
Array Declaration:
To create an array, define the data type and specify the name of the array followed by square brackets [].
Syntax:
data_type array_name [size];
Array initialization:
We initialize the array along with its declaration. To insert values to it, use a comma-separated list, inside
curly braces.
Syntax:
data_type array_name [size] = {value1, value2, ... valueN};
ex:
int a[4 ] = {34, 56, 25, 67}
int a[ ] = {35, 67, 78, 34, 78};
we created an array variable holding 4 integer values.
Access the Elements of an Array
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Ex:
int a[ ] = {35, 67, 78, 34};
printf(“%d”, a[0]); //35
Update Array Element
We can update the value of an element at the given index by using the array subscript operator [ ] and
assignment operator =.
Syntax:
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array traversal, we use
loops to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++)
{
array_name[i];
}
Example:
// Program to take values of the array from the user and print the array
#include <stdio.h>
int main()
{
int a[5];
printf("Enter the values of an integer array:\n ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &a[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", a[i]);
}
return 0;
}
Enter the values of an integer array:
56
67
88
23
96
Displaying integers:
56
67
88
23
96
#include <stdio.h>
int main() {
result = sum(num);
return 0;
sum += num[i];
return sum;
Output:
162.50
MULTIDIMENSIONAL ARRAY
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions.
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers,
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows [2], while the second dimension represents the number of
columns [3]. The values are placed in row-order, and can be visualized like this:
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
output:
1
4
2
3
6
8
STRUCTURES
Structure in c is a user-defined data type that enables us to store the collection of different data types.
Each element of a structure is called a member.
Structures can store various information
The struct keyword is used to define the structure
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
data_type memberN;
};
Example:
struct employee
{
int id;
char name[20];
float salary;
};
Here,
struct is the keyword; employee is the name of the structure;
id, name, and salary are the members or fields of the structure.
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure easily. There are
two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Example to declare the structure variable by struct keyword.
It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Then write the following code within the main() function
struct employee e1, e2;
2nd way:
Another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by. (member) operator.
p1.id
C Structure example
#include<stdio.h>
#include<conio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Raja");//copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "Rahim");
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
getch();
}
Output:
employee 1 id : 101
employee 1 name : Raja
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : Rahim
employee 2 salary : 126000.000000
Passing structures to functions
The passing of structure to the function can be done in two ways:
• By passing all the elements to the function individually.
• By passing the entire structure to the function.
Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define union for an employee in c.
union employee
{ int id;
char name[50];
float salary;
};
Example:
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Rahim");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 1869508435
employee 1 name : Rahim
POINTERS
Pointers
The pointer in C language is a variable which stores the address of another variable. This variable can be of
type int, char, array, function, or any other pointer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol).
It is also known as indirection pointer used to dereference a pointer.
Example
int *a; //pointer to int
char *c; //pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.
In the above figure, pointer variable stores the address of number variable, i.e., fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Example Program:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefor
e printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a po
inter therefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a
variable.
#include<stdio.h>
int main()
{
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4
Swap two numbers without using the 3rd variable using Pointers
#include<stdio.h>
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
return 0;
}
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
In the second approach memory wastage is more, hence it is preferred to use pointer in such cases.
When we define array of characters, a contiguos memory space is located equal to the maximum size of the
array, which is a wastage, which can be avoided if we use pointers instead.
Pointer to a Structure in C
We have already learned that a pointer is a variable which points to the address of another variable of any data
type like int, char, float etc. Similarly, we can have a pointer to structures, where a pointer variable can point to
the address of a structure variable. Here is how we can declare a pointer to a structure variable.
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
Example:
#include <stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
Accessing members using Pointer
To access members of structure using the structure variable, we used the dot . operator. But when we have a
pointer of structure type, we use arrow -> to access structure members.
Example
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"Computer Science", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
Output:
NAME: Computer Science
NUMBER: 35
RANK: 1