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

Notes On C Prog

The document provides examples and explanations of different ways to pass arguments to functions in C programming. It discusses call by value vs call by reference, and provides code examples to illustrate the differences. Specifically, it shows how call by reference allows changes made to formal parameters to affect actual parameters because operations are performed on the addresses of actual parameters. It also provides examples of passing arrays to functions using both call by value and call by reference approaches.

Uploaded by

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

Notes On C Prog

The document provides examples and explanations of different ways to pass arguments to functions in C programming. It discusses call by value vs call by reference, and provides code examples to illustrate the differences. Specifically, it shows how call by reference allows changes made to formal parameters to affect actual parameters because operations are performed on the addresses of actual parameters. It also provides examples of passing arrays to functions using both call by value and call by reference approaches.

Uploaded by

Asim khandual
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1|Page Notes On C Porg.

Example of Array In C programming to find out the average of 4 integers


#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
What is Function Call By Reference?
When we call a function by passing the addresses of actual parameters then this way of calling the function is known
as call by reference. In call by reference, the operation performed on formal parameters, affects the value of actual
parameters because all the operations performed on the value stored in the address of actual parameters. It may
sound confusing first but the following example would clear your doubts.
Example of Function call by Reference
Lets take a simple example. Read the comments in the following program.
#include <stdio.h>
void increment(int *var)
{
/* Although we are performing the increment on variable
* var, however the var is a pointer that holds the address
* of variable num, which means the increment is actually done
* on the address where value of num is stored.
*/
*var = *var+1;
}
int main()
{
int num=20;
/* This way of calling the function is known as call by
* reference. Instead of passing the variable num, we are
* passing the address of variable num
*/
2|Page Notes On C Porg.

increment(&num);
printf("Value of num is: %d", num);
return 0;
}
Output:
Value of num is: 21
Example 2: Function Call by Reference – Swapping numbers
Here we are swapping the numbers using call by reference. As you can see the values of the variables have been
changed after calling the swapnum() function because the swap happened on the addresses of the variables num1
and num2.
#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);

/*calling swap function*/


swapnum( &num1, &num2 );

printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output:
Before swapping:
num1 value is 35
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35
What is Function Call By value?
When we pass the actual parameters while calling a function then this is known as function call by value. In this case
the values of actual parameters are copied to the formal parameters. Thus operations performed on the formal
parameters don’t reflect in the actual parameters.
Example of Function call by Value
As mentioned above, in the call by value the actual arguments are copied to the formal arguments, hence any
operation performed by function on arguments doesn’t affect actual parameters. Lets take an example to
understand this:
#include <stdio.h>
int increment(int var)
{
var = var+1;
return var;
}

int main()
3|Page Notes On C Porg.

{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);

return 0;
}

Output:
num1 value is: 20
num2 value is: 21
Explanation
We passed the variable num1 while calling the method, but since we are calling the function using call by value
method, only the value of num1 is copied to the formal parameter var. Thus change made to the var doesn’t reflect
in the num1.
Example 2: Swapping numbers using Function Call by Value
#include <stdio.h>
void swapnum( int var1, int var2 )
{
int tempnum ;
/*Copying var1 value into temporary variable */
tempnum = var1 ;

/* Copying var2 value into var1*/


var1 = var2 ;

/*Copying temporary variable value into var2 */


var2 = tempnum ;

}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);

/*calling swap function*/


swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}
Output:
Before swapping: 35, 45
After swapping: 35, 45
Why variables remain unchanged even after the swap?
The reason is same – function is called by value for num1 & num2. So actually var1 and var2 gets swapped (not num1
& num2). As in call by value actual parameters are just copied into the formal parameters.
Passing array to function using call by value method
As we already know in this type of function call, the actual parameter is copied to the formal parameters.
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
4|Page Notes On C Porg.

for (int x=0; x<10; x++)


{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}
Output:
abcdefghij
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called function call by reference. When we
pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed
address.
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}

return 0;
}
Output:
1234567890
How to pass an entire array to a function as an argument?
In the above example, we have passed the address of each array element one by one using a for loop in C. However
you can also pass an entire array to a function like this:
Note: The array name itself is the address of first element of that array. For example if array name is arr then you can
say that arr is equivalent to the &arr[0].
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}

int main()
5|Page Notes On C Porg.

{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
C Program to arrange numbers in ascending order
*
* C program to accept numbers as an input from user
* and to sort them in ascending order.
*/
#include <stdio.h>

void sort_numbers_ascending(int number[], int count)


{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("Numbers in ascending order:\n");
for (i = 0; i < count; ++i)
printf("%d\n", number[i]);
}
void main()
{
int i, count, number[20];

printf("How many numbers you are gonna enter:");


scanf("%d", &count);
printf("\nEnter the numbers one by one:");

for (i = 0; i < count; ++i)


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

sort_numbers_ascending(number, count);
}
Output
C Program to find largest element of an Array

include <stdio.h>

/* This is our function to find the largest


* element in the array arr[]
*/
int largest_element(int arr[], int num)
{
int i, max_element;
6|Page Notes On C Porg.

// Initialization to the first array element


max_element = arr[0];

/* Here we are comparing max_element with


* all other elements of array to store the
* largest element in the max_element variable
*/
for (i = 1; i < num; i++)
if (arr[i] > max_element)
max_element = arr[i];

return max_element;
}

int main()
{
int arr[] = {1, 24, 145, 20, 8, -101, 300};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Largest element of array is %d", largest_element(arr, n));
return 0;
}
Output:
Largest element of array is 300
C Program to find sum of array elements using pointers, recursion & functions
Method 1: Sum of array elements using Recursion: Function calling itself
This program calls the user defined function sum_array_elements() and the function calls itself recursively.
Here we have hardcoded the array elements but if you want user to input the values, you can use a for loop
and scanf function, same way as I did in the next section (Method 2: Using pointers) of this post.
#include<stdio.h>
int main()
{
int array[] = {1,2,3,4,5,6,7};
int sum;
sum = sum_array_elements(array,6);
printf("\nSum of array elements is:%d",sum);
return 0;
}
int sum_array_elements( int arr[], int n ) {
if (n < 0) {
//base case:
return 0;
} else{
//Recursion: calling itself
return arr[n] + sum_array_elements(arr, n-1);
}
}
Output:
Sum of array elements is:28
Method 2: Sum of array elements using pointers
Here we are setting up the pointer to the base address of array and then we are incrementing pointer and
using * operator to get & sum-up the values of all the array elements.
#include<stdio.h>
int main()
{
int array[5];
int i,sum=0;
int *ptr;

printf("\nEnter array elements (5 integer values):");


for(i=0;i<5;i++)
scanf("%d",&array[i]);

/* array is equal to base address


* array = &array[0] */
7|Page Notes On C Porg.

ptr = array;

for(i=0;i<5;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}

printf("\nThe sum is: %d",sum);


}
Output:
Enter array elements (5 integer values): 1 2 3 4 5
The sum is: 15
C Program to Find the Number of Elements in an Array
Here we will write a C program to find the number of elements in a given array.
Example: Program to find the size of an array
The formula that we are using to find the number of elements is common for all types of array. In this example, we
have an array of double data type, however you can use the same logic for arrays of other data types like: int, float,
long, char etc.
#include <stdio.h>
int main()
{
double arr[] = {11, 22, 33, 44, 55, 66};
int n;

/* Calculating the size of the array with this formula.


* n = sizeof(array_name) / sizeof(array_name[0])
* This is a universal formula to find number of elements in
* an array, which means it will work for arrays of all data
* types such as int, char, float etc.
*/
n = sizeof(arr) / sizeof(arr[0]);
printf("Size of the array is: %d\n", n);
return 0;
}

Output:
Size of the array is: 6
Passing individual array elements

Example 1: Passing an array


#include <stdio.h>
void display(int age1, int age2)
{
printf("%d\n", age1);
printf("%d\n", age2);
}

int main()
{
int ageArray[] = {2, 8, 4, 12};

// Passing second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}
Output
8|Page Notes On C Porg.

8
4

Example 2: Passing arrays to functions


// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float age[]);

int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};

// age array is passed to calculateSum()


result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float age[]) {

float sum = 0.0;

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


sum += age[i];
}

return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(age);
However, notice the use of [] in the function definition.
float calculateSum(float age[]) {
... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.

Passing Multidimensional Arrays to a Function


To pass multidimensional arrays to a function, only the name of the array is passed to the function(similar to one-
dimensional arrays).
Example 3: Passing two-dimensional arrays
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);

// passing multi-dimensional array to a function


displayNumbers(num);
return 0;
}
9|Page Notes On C Porg.

void displayNumbers(int num[2][2])


{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
C Program to Store Information of a Student Using Structure
Store Information and Display it Using Structure
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;

int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");


scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);

return 0;
}
Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
C Program to Add Two Complex Numbers by Passing Structure to a Function
10 | P a g e Notes On C Porg.

Add Two Complex Numbers


#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;

complex add(complex n1, complex n2);

int main() {
complex n1, n2, result;

printf("For 1st complex number \n");


printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);

result = add(n1, n2);

printf("Sum = %.1f + %.1fi", result.real, result.imag);


return 0;
}

complex add(complex n1, complex n2) {


complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}
Output
For 1st complex number
Enter the real and imaginary parts: 2.1
-2.3

For 2nd complex number


Enter the real and imaginary parts: 5.6
23.2
Sum = 7.7 + 20.9i
In this program, a structure named complex is declared. It has two members: real and imag. We then created two
variables n1 and n2 from this structure.
These two structure variables are passed to the add() function. The function computes the sum and returns the
structure containing the sum.
Finally, the sum of complex numbers is printed from the main() function.
C Program to Store Information of Students Using Structure
Store Information in Structure and Display it
#include <stdio.h>
struct student {
char firstName[50];
int roll;
float marks;
} s[10];

int main() {
int i;
printf("Enter information of students:\n");
11 | P a g e Notes On C Porg.

// storing information
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");

// displaying information
for (i = 0; i < 5; ++i) {
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
return 0;
}
Output
Enter information of students:

For roll number1,


Enter name: Tom
Enter marks: 98

For roll number2,


Enter name: Jerry
Enter marks: 89
.
.
.
Displaying Information:

Roll number: 1
Name: Tom
Marks: 98
.
.
.
In this program, a structure student is created. The structure has three members: name (string), roll (integer) and
marks (float).
Then, we created an array of structures s having 5 elements to store information of 5 students.
Using a for loop, the program takes the information of 5 students from the user and stores it in the array of
structure. Then using another for loop, the information entered by the user is displayed on the screen.
Uses of structures in C:
C Structures can be used to store huge data. Structures act as a database.
C Structures can be used to send data to the printer.
C Structures can interact with keyboard and mouse to store the data.
C Structures can be used in drawing and floppy formatting.
C Structures can be used to clear output screen contents.
C Structures can be used to check computer’s memory size etc.
structure in C programming
C Structure is a collection of different data types which are grouped together and each element in a C structure is
called member.
12 | P a g e Notes On C Porg.

If you want to access structure members in C, structure variable should be declared.


Many structure variables can be declared for same structure and memory will be allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to structure members.
Difference between C variable, C array and C structure:
A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types and Data types can be int, char, float, double and long
double etc.
C Structure:
struct student
{
Syntax int a;
char b[10];
}
a = 10;
Example
b = “Hello”;
C Variable:
Syntax: int a;
int
Example: a = 20;
Syntax: char b;
char
Example: b=’Z’;
C Array:
Syntax: int a[3];
Example:
a[0] = 10;
int
a[1] = 20;
a[2] = 30;
a[3] = ‘\0’;
Syntax: char b[10];
char Example:
b=”Hello”;
Below table explains following concepts in C structure.
How to declare a C structure?
How to initialize a C structure?
How to access the members of a C structure?
Using normal variable Using pointer variable
Syntax: Syntax:
struct tag_name struct tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
struct student struct student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring structure using normal variable: Declaring structure using pointer variable:
struct student report; struct student *report, rep;
13 | P a g e Notes On C Porg.

Initializing structure using pointer variable:


Initializing structure using normal variable:
struct student rep = {100, “Mani”, 99.5};
struct student report = {100, “Mani”, 99.5};
report = &rep;
Accessing structure members using normal variable: Accessing structure members using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;
Example program for C structure:
This program is used to store and access “id, name and percentage” for one student. We can also store and access
these data for many students using array of structures. You can check “C – Array of Structures” to know how to store
and access these data for many students.

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

struct student

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[20];
8 float percentage;
9 };
10
11 int main()
12 {
13 struct student record = {0}; //Initializing to null
14
15 record.id=1;
16 strcpy(record.name, "Raju");
17 record.percentage = 86.5;
18
19 printf(" Id is: %d \n", record.id);
20 printf(" Name is: %s \n", record.name);
21 printf(" Percentage is: %f \n", record.percentage);
22 return 0;
23 }
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program – Another way of declaring C structure:
In this program, structure variable “record” is declared while declaring structure itself. In above structure example
program, structure variable “struct student record” is declared inside main function which is after declaring
structure.
C
#include <stdio.h>
#include <string.h>

struct student
14 | P a g e Notes On C Porg.

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[20];
8 float percentage;
9 } record;
10
11 int main()
12 {
13
14 record.id=1;
15 strcpy(record.name, "Raju");
16 record.percentage = 86.5;
17
18 printf(" Id is: %d \n", record.id);
19 printf(" Name is: %s \n", record.name);
20 printf(" Percentage is: %f \n", record.percentage);
21 return 0;
22 }
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C structure declaration in separate header file:
In above structure programs, C structure is declared in main source file. Instead of declaring C structure in main
source file, we can have this structure declaration in another file called “header file” and we can include that header
file in main source file as shown below.
Header file name – structure.h
Before compiling and executing below C program, create a file named “structure.h” and declare the below structure.
struct student
{
int id;
char name[20];
float percentage;
} record;
Main file name – structure.c:
In this program, above created header file is included in “structure.c” source file as #include “Structure.h”. So, the
structure declared in “structure.h” file can be used in “structure.c” source file.
C
// File name - structure.c
#include <stdio.h>
#include <string.h>
#include "structure.h" /* heade

1 // File name - structure.c


2 #include <stdio.h>
3 #include <string.h>
4 #include "structure.h" /* header file where C structure is
5 declared */
6
7 int main()
8 {
9
15 | P a g e Notes On C Porg.

10 record.id=1;
11 strcpy(record.name, "Raju");
12 record.percentage = 86.5;
13
14 printf(" Id is: %d \n", record.id);
15 printf(" Name is: %s \n", record.name);
16 printf(" Percentage is: %f \n", record.percentage);
17 return 0;
18 }
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C – Array of Structures

Example program for array of structures in C:


This program is used to store and access “id, name and percentage” for 3 students. Structure array is used in this
program to store and display records for many students. You can store “n” number of students record by declaring
structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>

struct student

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[30];
8 float percentage;
9 };
10
11 int main()
12 {
13 int i;
14 struct student record[2];
15
16 // 1st student's record
17 record[0].id=1;
18 strcpy(record[0].name, "Raju");
19 record[0].percentage = 86.5;
20
21 // 2nd student's record
22 record[1].id=2;
23 strcpy(record[1].name, "Surendren");
24 record[1].percentage = 90.5;
25
26 // 3rd student's record
27 record[2].id=3;
28 strcpy(record[2].name, "Thiyagu");
29 record[2].percentage = 81.5;
30
31 for(i=0; i<3; i++)
32 {
16 | P a g e Notes On C Porg.

33 printf(" Records of STUDENT : %d \n", i+1);


34 printf(" Id is: %d \n", record[i].id);
35 printf(" Name is: %s \n", record[i].name);
36 printf(" Percentage is: %f\n\n",record[i].percentage);
37 }
38 return 0;
39 }
Output:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000

Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
Example program for declaring many structure variable in C:
In this program, two structure variables “record1″ and “record2″ are declared for same structure and different
values are assigned for both structure variables. Separate memory is allocated for both structure variables to store
the data.
C
printf(" Percentage is: %f \n

return 0;
}

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[30];
8 float percentage;
9 };
10
11 int main()
12 {
13 int i;
14 struct student record1 = {1, "Raju", 90.5};
15 struct student record2 = {2, "Mani", 93.5};
16
17 printf("Records of STUDENT1: \n");
18 printf(" Id is: %d \n", record1.id);
19 printf(" Name is: %s \n", record1.name);
20 printf(" Percentage is: %f \n\n", record1.percentage);
21
22 printf("Records of STUDENT2: \n");
23 printf(" Id is: %d \n", record2.id);
24 printf(" Name is: %s \n", record2.name);
17 | P a g e Notes On C Porg.

25 printf(" Percentage is: %f \n\n", record2.percentage);


26
27 return 0;
28 }
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
C – Passing struct to function
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.

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[20];
8 float percentage;
9 };
10
11 void func(struct student record);
12
13 int main()
14 {
15 struct student record;
16
17 record.id=1;
18 strcpy(record.name, "Raju");
19 record.percentage = 86.5;
20
21 func(record);
22 return 0;
23 }
24
25 void func(struct student record)
18 | P a g e Notes On C Porg.

26 {
27 printf(" Id is: %d \n", record.id);
28 printf(" Name is: %s \n", record.name);
29 printf(" Percentage is: %f \n", record.percentage);
30 }
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
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.

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[20];
8 float percentage;
9 };
10
11 void func(struct student *record);
12
13 int main()
14 {
15 struct student record;
16
17 record.id=1;
18 strcpy(record.name, "Raju");
19 record.percentage = 86.5;
20
21 func(&record);
22 return 0;
23 }
24
25 void func(struct student *record)
26 {
27 printf(" Id is: %d \n", record->id);
28 printf(" Name is: %s \n", record->name);
29 printf(" Percentage is: %f \n", record->percentage);
30 }
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
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.
19 | P a g e Notes On C Porg.

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5 {
6 int id;
7 char name[20];
8 float percentage;
9 };
10 struct student record; // Global declaration of structure
11
12 void structure_demo();
13
14 int main()
15 {
16 record.id=1;
17 strcpy(record.name, "Raju");
18 record.percentage = 86.5;
19
20 structure_demo();
21 return 0;
22 }
23
24 void structure_demo()
25 {
26 printf(" Id is: %d \n", record.id);
27 printf(" Name is: %s \n", record.name);
28 printf(" Percentage is: %f \n", record.percentage);
29 }

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

C – Nested Structure
Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure
as we declare structure members inside a structure.
The structure variables can be a normal structure variable or a pointer variable to access the data. You can learn
below concepts in this section.
Structure within structure in C using normal variable
Structure within structure in C using pointer variable
1. Structure within structure in C using normal variable:
This program explains how to use structure within structure in C using normal variable. “student_college_detail’
structure is declared inside “student_detail” structure in this program. Both structure variables are normal structure
variables.
Please note that members of “student_college_detail” structure are accessed by 2 dot(.) operator and members of
“student_detail” structure are accessed by single dot(.) operator.
C
#include <stdio.h>
#include <string.h>

struct student_college_detail

1 #include <stdio.h>
2 #include <string.h>
20 | P a g e Notes On C Porg.

3
4 struct student_college_detail
5 {
6 int college_id;
7 char college_name[50];
8 };
9
10 struct student_detail
11 {
12 int id;
13 char name[20];
14 float percentage;
15 // structure within structure
16 struct student_college_detail clg_data;
17 }stu_data;
18
19 int main()
20 {
21 struct student_detail stu_data = {1, "Raju", 90.5, 71145,
22 "Anna University"};
23 printf(" Id is: %d \n", stu_data.id);
24 printf(" Name is: %s \n", stu_data.name);
25 printf(" Percentage is: %f \n\n", stu_data.percentage);
26
27 printf(" College Id is: %d \n",
28 stu_data.clg_data.college_id);
29 printf(" College Name is: %s \n",
30 stu_data.clg_data.college_name);
31 return 0;
32 }
Output:
Id is: 1
Name is: Raju
Percentage is: 90.500000

College Id is: 71145


College Name is: Anna University
Structure within structure in C using pointer variable:
This program explains how to use structure within structure in C using pointer variable. “student_college_detail’
structure is declared inside “student_detail” structure in this program. one normal structure variable and one
pointer structure variable is used in this program.
Please note that combination of .(dot) and ->(arrow) operators are used to access the structure member which is
declared inside the structure.

1 #include <stdio.h>
2 #include <string.h>
3
4 struct student_college_detail
5 {
6 int college_id;
7 char college_name[50];
8 };
9
10 struct student_detail
11 {
21 | P a g e Notes On C Porg.

12 int id;
13 char name[20];
14 float percentage;
15 // structure within structure
16 struct student_college_detail clg_data;
17 }stu_data, *stu_data_ptr;
18
19 int main()
20 {
21 struct student_detail stu_data = {1, "Raju", 90.5, 71145,
22 "Anna University"};
23 stu_data_ptr = &stu_data;
24
25 printf(" Id is: %d \n", stu_data_ptr->id);
26 printf(" Name is: %s \n", stu_data_ptr->name);
27 printf(" Percentage is: %f \n\n",
28 stu_data_ptr->percentage);
29
30 printf(" College Id is: %d \n",
31 stu_data_ptr->clg_data.college_id);
32 printf(" College Name is: %s \n",
33 stu_data_ptr->clg_data.college_name);
34
35 return 0;
36 }
Output:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University

C struct
In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

How to define structures?


Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword
is used.
Syntax of struct
struct structureName
{
dataType member1;
dataType member2;
...
};
Here is an example:
struct Person
{
char name[50];
int citNo;
float salary;
};
Here, a derived type struct Person is defined. Now, you can create variables of this type.

Create struct variables


22 | P a g e Notes On C Porg.

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and
work with it, we need to create variables.
Here's how we create structure variables:
struct Person
{
char name[50];
int citNo;
float salary;
};

int main()
{
struct Person person1, person2, p[20];
return 0;
}
Another way of creating a struct variable is:
struct Person
{
char name[50];
int citNo;
float salary;
} person1, person2, p[20];
In both cases, two variables person1, person2, and an array variable p having 20 elements of type struct Person
are created.

Access members of a structure


There are two types of operators used for accessing members of a structure.
. - Member operator
-> - Structure pointer operator (will be discussed in the next tutorial)
Suppose, you want to access the salary of person2. Here's how you can do it.
person2.salary

Example: Add two distances


// Program to add two distances (feet-inch)
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;

int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);

printf("Enter inch: ");


scanf("%f", &dist1.inch);
printf("2nd distance\n");

printf("Enter feet: ");


scanf("%d", &dist2.feet);

printf("Enter inch: ");


scanf("%f", &dist2.inch);
23 | P a g e Notes On C Porg.

// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;

// changing to feet if inch is greater than 12


while (sum.inch >= 12)
{
++sum.feet;
sum.inch = sum.inch - 12;
}

printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);


return 0;
}
Output
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15'-5.7"

Keyword typedef
We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify
the syntax of declaring variables.
This code
struct Distance{
int feet;
float inch;
};

int main() {
structure Distance d1, d2;
}
is equivalent to
typedef struct Distance{
int feet;
float inch;
} distances;

int main() {
distances d1, d2;
}

Nested Structures
You can create structures within a structure in C programming. For example,
struct complex
{
int imag;
float real;
};

struct number
{
24 | P a g e Notes On C Porg.

struct complex comp;


int integers;
} num1, num2;
Suppose, you want to set imag of num2 variable to 11. Here's how you can do it:
num2.comp.imag = 11;

Why structs in C?
Suppose, you want to store information about a person: his/her name, citizenship number, and salary. You can
create different variables name, citNo and salary to store this information.
What if you need to store information of more than one person? Now, you need to create different variables for
each information per person: name1, citNo1, salary1, name2, citNo2, salary2, etc.
A better approach would be to have a collection of all related information under a single name Person structure
and use it for every person.

C Structure and Function


In this tutorial, you'll learn to pass struct variables as arguments to a function. You will learn to return struct from a
function with the help of examples.
Similar to variables of built-in types, you can also pass structure variables to a function.

Passing structs to functions


We recommended you to learn these tutorials before you learn how to pass structs to functions.
C structures
C functions
User-defined Function
Here's how you can pass structures to a function
#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
void display(struct student s);

int main()
{
struct student s1;

printf("Enter name: ");


scanf("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;
}
void display(struct student s)
{
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Output
25 | P a g e Notes On C Porg.

Enter name: Bond


Enter age: 13

Displaying information
Name: Bond
Age: 13
Here, a struct variable s1 of type struct student is created. The variable is passed to the display() function
using display(s1); statement.

Return struct from a function


Here's how you can return structure from a function:
#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf ("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

return s1;
}
Here, the getInformation() function is called using s = getInformation(); statement. The function returns
a structure of type struct student. The returned structure is displayed from the main() function.
Notice that, the return type of getInformation() is also struct student.

Passing struct by reference


You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We
suggest you to read pass by reference tutorial before you proceed.
During pass by reference, the memory addresses of struct variables are passed to the function.
#include <stdio.h>
typedef struct Complex
{
float real;
26 | P a g e Notes On C Porg.

float imag;
} complex;

void addNumbers(complex c1, complex c2, complex *result);

int main()
{
complex c1, c2, result;

printf("For first number,\n");


printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);

printf("For second number, \n");


printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);

addNumbers(c1, c2, &result);


printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);

return 0;
}
void addNumbers(complex c1, complex c2, complex *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
Output
For first number,
Enter real part: 1.1
Enter imaginary part: -2.4
For second number,
Enter real part: 3.4
Enter imaginary part: -3.2

result.real = 4.5
result.imag = -5.6
In the above program, three structure variables c1, c2 and the address of result is passed to the addNumbers()
function. Here, result is passed by reference.
When the result variable inside the addNumbers() is altered, the result variable inside the main() function is also
altered accordingly.
Array of Structures in C
Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of
elements of the same type. In an array of structures, each element of an array is of the structure type.
Let’s take an example:
1 struct car
2{
3 char make[20];
4 char model[30];
5 int year;
6 };
Here is how we can declare an array of structure car.
27 | P a g e Notes On C Porg.

1 struct car arr_car[10];

Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to
store 10 structure variables of type struct car. To access individual elements we will use subscript notation ([])
and to access the members of each element we will use dot (.) operator as usual.
1 arr_stu[0] : points to the 0th element of the array.
2 arr_stu[1] : points to the 1st element of the array.
and so on. Similarly,
1 arr_stu[0].name : refers to the name member of the 0th element of the array.
2 arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the array.
3 arr_stu[0].marks : refers to the marks member of the 0th element of the array.
Recall that the precedence of [] array subscript and dot(.) operator is same and they evaluates from left to right.
Therefore in the above expression first array subscript([]) is applied followed by dot (.) operator. The array
subscript ([]) and dot(.) operator is same and they evaluates from left to right. Therefore in the above expression
first [] array subscript is applied followed by dot (.) operator.
Let’s rewrite the program we used in the last chapter as an introduction to structures.
1 #include<stdio.h>
2 #include<string.h>
3 #define MAX 2
4
5 struct student
6 {
7 char name[20];
8 int roll_no;
9 float marks;
10 };
11
12 int main()
13 {
14 struct student arr_student[MAX];
15 int i;
16
17 for(i = 0; i < MAX; i++ )
18 {
19 printf("\nEnter details of student %d\n\n", i+1);
20
21 printf("Enter name: ");
22 scanf("%s", arr_student[i].name);
23
28 | P a g e Notes On C Porg.

24 printf("Enter roll no: ");


25 scanf("%d", &arr_student[i].roll_no);
26
27 printf("Enter marks: ");
28 scanf("%f", &arr_student[i].marks);
29 }
30
31 printf("\n");
32
33 printf("Name\tRoll no\tMarks\n");
34
35 for(i = 0; i < MAX; i++ )
36 {
37 printf("%s\t%d\t%.2f\n",
38 arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks);
39 }
40
41 // signal to operating system program ran fine
42 return 0;
43 }
Expected Output:
1 Enter details of student 1
2
3 Enter name: Jim
4 Enter roll no: 1
5 Enter marks: 44
6
7 Enter details of student 2
8
9 Enter name: Tim
10 Enter roll no: 2
11 Enter marks: 76
12
13 Name Roll no Marks
14 Jim 1 44.00
15 Tim 2 76.00
How it works:
In lines 5-10, we have declared a structure called the student.
In line 14, we have declared an array of structures of type struct student whose size is controlled by symbolic
constant MAX. If you want to increase/decrease the size of the array just change the value of the symbolic constant
and our program will adapt to the new size. In line 17-29, the first for loop is used to enter the details of the student.
In line 36-40, the second for loop prints all the details of the student in tabular form. Initializing Array of Structures
We can also initialize the array of structures using the same syntax as that for initializing arrays. Let’s take an
example:
1 struct car
2 {
3 char make[20];
4 char model[30];
5 int year;
6 };
7 struct car arr_car[2] = {
8 {"Audi", "TT", 2016},
9 {"Bentley", "Azure", 2002}
10 };

You might also like