Notes On C Prog
Notes On C Prog
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);
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 ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);
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>
sort_numbers_ascending(number, count);
}
Output
C Program to find largest element of an Array
include <stdio.h>
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;
ptr = array;
for(i=0;i<5;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}
Output:
Size of the array is: 6
Passing individual array elements
int main()
{
int ageArray[] = {2, 8, 4, 12};
8
4
#include <stdio.h>
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
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.
int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
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.
int main() {
complex n1, n2, result;
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:
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.
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
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
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.
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.
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
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.
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.
int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;
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.
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.
// function prototype
void display(struct student s);
int main()
{
struct student s1;
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.
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.
// 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;
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.
float imag;
} complex;
int main()
{
complex c1, c2, result;
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.
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.