Functions Structures and Unions
Programming in C тАУ Part 4: Functions, Structures and Unions
Class 12 ┬╖ Computer Science ┬╖ Unit 4: Programming in C
All programs below were compiled and run, and the outputs are real.
Navigation: тЖР Part 3: Arrays and Strings ┬╖ Part 4 ┬╖ Part 5: Pointers and File Handling тЖТ
Table of Contents
- Functions
- Types of Functions
- Passing Arrays to Functions
- Recursion
- Call by Value and Call by Reference
- Structures
- Unions
- Quick Revision Table
- Practice Questions
1. Functions
A function is a self-contained block of statements that performs a specific task and can be called whenever needed. Every C program has at least one function, main().
| Kind | Meaning | Example |
|---|---|---|
| Library function | Ready-made, supplied with the compiler | printf(), sqrt(), strlen() |
| User-defined function | Written by the programmer | area(), swap() |
Features and advantages of functions
- Reusability: write once, call many times
- Modularity: a big problem is broken into small, manageable parts
- Easy debugging: an error is found in one small function
- Shorter programs: repeated code is not rewritten
- Teamwork: different programmers can write different functions
Three parts of a user-defined function
| Part | Syntax | Meaning |
|---|---|---|
| Declaration (prototype) | int add(int x, int y); | Tells the compiler the name, return type and parameters. Ends with ; |
| Definition | int add(int x, int y) { return x + y; } | The actual body of the function |
| Call | s = add(a, b); | Uses the function |
- Actual arguments: the values written in the call (
a,b) - Formal parameters: the variables in the definition (
x,y) returnsends one value back to the caller. A function with return typevoidreturns nothing.
2. Types of Functions
According to arguments and return value, there are four forms:
| # | Form | Arguments | Return value |
|---|---|---|---|
| 1 | No arguments, no return value | No | No |
| 2 | With arguments, no return value | Yes | No |
| 3 | No arguments, with return value | No | Yes |
| 4 | With arguments, with return value | Yes | Yes |
The program below shows all four forms:
#include <stdio.h>
void greet(void); /* no arguments, no return value */
void print_square(int n); /* with argument, no return value */
int read_number(void); /* no arguments, returns a value */
int add(int x, int y); /* with arguments, returns a value */
int main(void)
{
int a, b;
greet(); /* function call */
a = read_number();
b = read_number();
print_square(a);
printf("%d + %d = %d\n", a, b, add(a, b));
return 0;
}
void greet(void) /* function definition */
{
printf("Welcome to functions in C!\n");
}
void print_square(int n)
{
printf("Square of %d = %d\n", n, n * n);
}
int read_number(void)
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
return n;
}
int add(int x, int y)
{
return x + y;
}
Sample run:
Welcome to functions in C!
Enter a number: 4
Enter a number: 6
Square of 4 = 16
4 + 6 = 10
More examples
Form 4 (arguments and a return value) is the most useful form:
#include <stdio.h>
float interest(float p, float t, float r); /* function declaration */
int main(void)
{
float p, t, r, si;
printf("Enter principal, time and rate: ");
scanf("%f %f %f", &p, &t, &r);
si = interest(p, t, r); /* function call */
printf("Simple interest = %.2f\n", si);
return 0;
}
float interest(float p, float t, float r) /* function definition */
{
return (p * t * r) / 100; /* value sent back to main() */
}
Sample run:
Enter principal, time and rate: 10000 2 5
Simple interest = 1000.00
Form 3 (no arguments, with a return value):
#include <stdio.h>
int area(void); /* no arguments, but returns a value */
int main(void)
{
int a;
a = area();
printf("Area of rectangle = %d\n", a);
return 0;
}
int area(void)
{
int l, b;
printf("Enter length and breadth: ");
scanf("%d %d", &l, &b);
return l * b;
}
Sample run:
Enter length and breadth: 12 5
Area of rectangle = 60
#include <stdio.h>
float area(float r);
int main(void)
{
float rad, res;
printf("Enter the radius of a circle: ");
scanf("%f", &rad);
res = area(rad);
printf("Area of the circle = %.2f\n", res);
return 0;
}
float area(float r)
{
const float pi = 3.14159f;
return pi * r * r;
}
Sample run:
Enter the radius of a circle: 3.5
Area of the circle = 38.48
3. Passing Arrays to Functions
When an array is passed, the function receives the address of the first element, not a copy. So changes made inside the function change the original array.
#include <stdio.h>
int sum_array(int arr[], int n)
{
int i, sum = 0;
for (i = 0; i < n; i++)
sum = sum + arr[i];
return sum;
}
void double_all(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
arr[i] = arr[i] * 2; /* changes the ORIGINAL array */
}
int main(void)
{
int marks[5] = {10, 20, 30, 40, 50};
int i;
printf("Sum = %d\n", sum_array(marks, 5));
double_all(marks, 5);
printf("After double_all(): ");
for (i = 0; i < 5; i++)
printf("%d ", marks[i]);
printf("\n");
return 0;
}
Output:
Sum = 150
After double_all(): 20 40 60 80 100
4. Recursion
Recursion is the process in which a function calls itself. Every recursive function needs:
- A base (terminating) condition that stops the calls, otherwise it never ends
- A recursive call that moves towards the base condition
#include <stdio.h>
unsigned long fact(int n);
int main(void)
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("The factorial of %d is %lu\n", n, fact(n));
return 0;
}
unsigned long fact(int n)
{
if (n <= 1)
return 1; /* terminating (base) condition */
else
return n * fact(n - 1); /* function calls itself */
}
Sample run:
Enter a number: 5
The factorial of 5 is 120
#include <stdio.h>
int sum_digits(int n);
int main(void)
{
int n;
printf("Enter any number: ");
scanf("%d", &n);
printf("The sum of individual digits is %d\n", sum_digits(n));
return 0;
}
int sum_digits(int n)
{
if (n == 0)
return 0; /* base condition */
return (n % 10) + sum_digits(n / 10);
}
Sample run:
Enter any number: 2345
The sum of individual digits is 14
#include <stdio.h>
int sum(int n);
int main(void)
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Sum of the first %d natural numbers = %d\n", n, sum(n));
return 0;
}
int sum(int n)
{
if (n <= 0)
return 0;
return n + sum(n - 1);
}
Sample run:
Enter a number: 10
Sum of the first 10 natural numbers = 55
#include <stdio.h>
int fib(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return fib(n - 1) + fib(n - 2);
}
int main(void)
{
int i, n;
printf("How many terms? ");
scanf("%d", &n);
for (i = 0; i < n; i++)
printf("%d ", fib(i));
printf("\n");
return 0;
}
Sample run:
How many terms? 10
0 1 1 2 3 5 8 13 21 34
#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("GCD of %d and %d = %d\n", a, b, gcd(a, b));
return 0;
}
Sample run:
Enter two numbers: 48 18
GCD of 48 and 18 = 6
Recursion vs iteration
| Basis | Recursion | Iteration (loop) |
|---|---|---|
| Idea | Function calls itself | Statements repeat in a loop |
| Stops by | Base condition | Loop condition |
| Memory | More (each call uses stack space) | Less |
| Speed | Slower | Faster |
| Code | Short and clear for some problems | Usually longer |
5. Call by Value and Call by Reference
| Basis | Call by value | Call by reference |
|---|---|---|
| What is sent | A copy of the value | The address of the variable |
| Formal parameters | Ordinary variables | Pointers (int *x) |
| Effect on original | Not changed | Changed |
| Memory | Separate memory for the copy | Same memory shared |
| Call | swap(a, b); | swap(&a, &b); |
Call by value: the swap does not work
#include <stdio.h>
void swap(int x, int y)
{
int r;
r = x;
x = y;
y = r;
printf("Inside swap : x = %d, y = %d\n", x, y);
}
int main(void)
{
int a = 10, b = 20;
printf("Before swap : a = %d, b = %d\n", a, b);
swap(a, b); /* copies of a and b are sent */
printf("After swap : a = %d, b = %d\n", a, b);
return 0;
}
Output:
Before swap : a = 10, b = 20
Inside swap : x = 20, y = 10
After swap : a = 10, b = 20
The values are swapped only inside swap(). The originals in main() are untouched.
Call by reference: the swap works
#include <stdio.h>
void swap(int *x, int *y)
{
int r;
r = *x;
*x = *y;
*y = r;
}
int main(void)
{
int a = 10, b = 20;
printf("Before swap : a = %d, b = %d\n", a, b);
swap(&a, &b); /* addresses of a and b are sent */
printf("After swap : a = %d, b = %d\n", a, b);
return 0;
}
Output:
Before swap : a = 10, b = 20
After swap : a = 20, b = 10
C itself has only call by value. "Call by reference" is done by sending addresses (pointers), which Part 5 explains.
6. Structures
A structure groups variables of different data types under one name. It is used for a record such as a student (roll, name, marks).
struct tag_name {
data_type member1;
data_type member2;
}; /* semicolon is required */
| Operation | Syntax |
|---|---|
| Create a variable | struct student s1; |
| Access a member | s1.roll (dot operator) |
| Access through a pointer | p->roll (arrow operator) |
| Copy a whole structure | s2 = s1; |
#include <stdio.h>
struct student {
int roll;
char name[30];
char section;
float height;
};
int main(void)
{
struct student s1;
printf("Enter roll number: ");
scanf("%d", &s1.roll);
printf("Enter name: ");
scanf("%29s", s1.name);
printf("Enter section: ");
scanf(" %c", &s1.section);
printf("Enter height: ");
scanf("%f", &s1.height);
printf("\nYou have entered:\n");
printf("Roll number: %d\n", s1.roll);
printf("Name : %s\n", s1.name);
printf("Section : %c\n", s1.section);
printf("Height : %.1f\n", s1.height);
return 0;
}
Sample run:
Enter roll number: 5
Enter name: Gita
Enter section: A
Enter height: 5.4
You have entered:
Roll number: 5
Name : Gita
Section : A
Height : 5.4
Initialization, typedef and copying
typedef gives a structure a shorter type name.
#include <stdio.h>
typedef struct {
int id;
char name[20];
float salary;
} Employee; /* Employee is now a type name */
int main(void)
{
Employee e1 = {101, "Ram", 45000.50f};
Employee e2;
e2 = e1; /* one structure can be copied to another */
e2.id = 102; /* the dot operator reaches a member */
printf("%d %s %.2f\n", e1.id, e1.name, e1.salary);
printf("%d %s %.2f\n", e2.id, e2.name, e2.salary);
return 0;
}
Output:
101 Ram 45000.50
102 Ram 45000.50
Array of structures
An array of structures stores many records.
#include <stdio.h>
struct employee {
char name[30];
int salary;
};
int main(void)
{
struct employee e[100];
int i, n;
printf("How many records? ");
scanf("%d", &n);
if (n < 1 || n > 100)
return 1;
for (i = 0; i < n; i++) {
printf("Enter name of employee %d: ", i + 1);
scanf("%29s", e[i].name);
printf("Enter salary: ");
scanf("%d", &e[i].salary);
}
printf("\nEmployee\t\tSalary\n");
printf("==============================\n");
for (i = 0; i < n; i++)
printf("%-20s\t%d\n", e[i].name, e[i].salary);
printf("==============================\n");
return 0;
}
Sample run:
How many records? 3
Enter name of employee 1: Ram
Enter salary: 25000
Enter name of employee 2: Sita
Enter salary: 32000
Enter name of employee 3: Hari
Enter salary: 28000
Employee Salary
==============================
Ram 25000
Sita 32000
Hari 28000
==============================
Sorting records
#include <stdio.h>
#include <string.h>
struct student {
char name[50];
char address[50];
};
int main(void)
{
struct student s[200], t;
int i, j, n;
printf("How many records do you want to store? ");
scanf("%d", &n);
if (n < 1 || n > 200)
return 1;
for (i = 0; i < n; i++) {
printf("Enter name of student %d: ", i + 1);
scanf("%49s", s[i].name);
printf("Enter address: ");
scanf("%49s", s[i].address);
}
for (i = 0; i < n - 1; i++) { /* bubble sort on the name member */
for (j = 0; j < n - 1 - i; j++) {
if (strcmp(s[j].name, s[j + 1].name) > 0) {
t = s[j]; /* whole records are swapped */
s[j] = s[j + 1];
s[j + 1] = t;
}
}
}
printf("\nRecords after sorting:\n");
printf("%-15s %s\n", "Name", "Address");
for (i = 0; i < n; i++)
printf("%-15s %s\n", s[i].name, s[i].address);
return 0;
}
Sample run:
How many records do you want to store? 4
Enter name of student 1: Ram
Enter address: Pokhara
Enter name of student 2: Sita
Enter address: Butwal
Enter name of student 3: Hari
Enter address: Chitwan
Enter name of student 4: Anita
Enter address: Dang
Records after sorting:
Name Address
Anita Dang
Hari Chitwan
Ram Pokhara
Sita Butwal
Passing structures to functions
#include <stdio.h>
struct point {
int x;
int y;
};
void show(struct point p) /* structure passed by value */
{
printf("Point = (%d, %d)\n", p.x, p.y);
}
struct point move(struct point p, int dx, int dy)
{
p.x = p.x + dx;
p.y = p.y + dy;
return p; /* a structure can be returned */
}
int main(void)
{
struct point a = {2, 3};
struct point b;
show(a);
b = move(a, 5, 1);
show(b);
show(a); /* a is unchanged */
return 0;
}
Output:
Point = (2, 3)
Point = (7, 4)
Point = (2, 3)
Nested structure
#include <stdio.h>
struct date {
int day;
int month;
int year;
};
struct student {
int roll;
char name[20];
struct date dob; /* a structure inside a structure */
};
int main(void)
{
struct student s = {7, "Sita", {15, 8, 2008}};
printf("Roll: %d, Name: %s\n", s.roll, s.name);
printf("Date of birth: %d/%d/%d\n", s.dob.day, s.dob.month, s.dob.year);
return 0;
}
Output:
Roll: 7, Name: Sita
Date of birth: 15/8/2008
Array vs structure
| Basis | Array | Structure |
|---|---|---|
| Data types | Same type only | Different types allowed |
| Keyword | None | struct |
| Access | By index a[2] | By member name s.roll |
| Memory | Continuous | Members laid out in order (may have padding) |
| Example | Marks of 5 students | Roll, name, marks of one student |
7. Unions
A union is declared like a structure but all its members share the same memory. Only one member holds a valid value at a time. Its size equals the size of its largest member.
union data { int i; float f; char ch; };
#include <stdio.h>
struct sdata {
int i;
float f;
char ch;
};
union udata {
int i;
float f;
char ch;
};
int main(void)
{
union udata u;
printf("Size of structure = %zu bytes\n", sizeof(struct sdata));
printf("Size of union = %zu bytes\n", sizeof(union udata));
u.i = 65;
printf("\nAfter u.i = 65 : u.i = %d\n", u.i);
u.f = 3.5f;
printf("After u.f = 3.5 : u.f = %.1f\n", u.f);
printf("u.i now holds : %d (same memory, so the old value is lost)\n", u.i);
return 0;
}
Output:
Size of structure = 12 bytes
Size of union = 4 bytes
After u.i = 65 : u.i = 65
After u.f = 3.5 : u.f = 3.5
u.i now holds : 1080033280 (same memory, so the old value is lost)
The structure needs room for every member, but the union only needs the largest one. When u.f was written, the old value of u.i was lost. The odd integer printed is just the bit pattern of the float.
Structure vs union
| Basis | Structure | Union |
|---|---|---|
| Keyword | struct | union |
| Memory | Each member has its own memory | All members share one memory |
| Size | Sum of the members (plus padding) | Size of the largest member |
| Values | All members can hold values at once | Only one member at a time |
| Use | Records with several fields | Saving memory when only one field is needed at a time |
8. Quick Revision Table
| Topic | Key point |
|---|---|
| Function | Named block that does one job; reusable |
| Four forms | (args / no args) ├Ч (return / no return) |
| Actual vs formal | In the call vs in the definition |
| Recursion | A function calling itself; needs a base condition |
| Call by value | Copy sent; original unchanged |
| Call by reference | Address sent; original changed |
| Structure | Different types under one name; . operator |
| Union | Shared memory; size = largest member |
9. Practice Questions
Short-answer questions
- What is a function? Write its advantages. (NEB Q9)
- Differentiate between library and user-defined functions.
- Differentiate between actual and formal parameters.
- What is recursion? Write its merits and demerits. (NEB Q10)
- Differentiate between call by value and call by reference. (NEB Q16)
- What is a structure? Differentiate between array and structure. (NEB Q12тАУ13)
- Differentiate between structure and union. (NEB Q14)
Programming questions (exam favourites)
- Write a function to find the area of a circle. Use it from
main(). - Write a program to find the factorial of a number using recursion.
- Write a program to swap two numbers using a function (by reference).
- Define a structure for a student, read the data of
nstudents and print them. - Sort the records of students by name.
- Find the sum of the digits of a number using recursion.
Navigation: тЖР Part 3: Arrays and Strings ┬╖ Part 4 ┬╖ Part 5: Pointers and File Handling тЖТ
Prepared for NEB Class 12 Computer Science exam revision.