Programming in C
Programming in C
History of C Language
History of C language is interesting to know. Here we are going to discuss a brief history of the c language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American
Telephone & Telegraph), located in the U.S.A.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
C programming language is a general-purpose language; for every procedure base work, we need this
language because C language is a procedural programming language. The C compiler passes every program
written in the c language to have the correct output. Our very famous windows operating system is written
and designed in C language. Dennis Ritchie prepared the language at bell laboratories in 1972. The language
was mainly invented to design the UNIX OS. C language is the successor of the B language; the language was
Unit 1 : Basics of C
validated by American National Standard Institute (ANSI). Due to its flexibility, Performance, efficiency, and
closeness to the hardware, the C language is ideal for designing Operating Systems.
Advantages of C Language
1. Easy: The main reason for choosing the C language is code portability; C language is highly portable
as you can write code in one system and use the code in another system. the code compilation is
faster and more efficient. Anyone can easily grasp concepts of C language with the help of some
online tutorials. Everyone can easily understand the code; the individual requires no prior or technical
knowledge to understand this language. C language has the one of the simplest syntax in comparison
to another programming language.
2. Libraries for More Practical Programming: For more Practical Programming, C provides access to
more and more libraries for better problem-solving abilities. C Language gives lots of built-in
functions consisting of system-provided and user-defined functions. The developers optimize the
libraries daily to make the programming in c better and optimize for the user. Built-in libraries make
the work for the developer easy, as when the developer develops a function, the function is used
repeatedly. Again then, they chooses to make a library of that function. So, they can use that library
as often as possible, and in any system they wishes.
3. So Easy to Write in The Compiler: Another reason C is so popular as an efficient language among
programmers is that it allows them to create their software without worrying about syntax errors. If
you're unfamiliar with coding, using the structured language, C will help you develop better skills.
You'll create more efficient and effective solutions with C in compare to another programming
languages.
4. Faster Running Speed: Any developer who wants to execute any program or application quickly relies
on the C language for the fast execution cycle. As C uses fewer instructions, it executes faster than
any other programming language, such as Java, Ruby, PHP, etc.
5. Compile Time Speed Accuracy: The C compiler is very efficient; it quickly produces your code into
machine-level code. Lakhs of lines of code can be compiled at one instance of a time and put in front
of a developer in a couple of seconds. The C compiler makes the code more efficient for faster and
Unit 1 : Basics of C
optimized execution. as the compile time is high in the c language, the error detections are also at
high-speed rates.
6. Procedural-Oriented Programming Language: Users create procedures or functions to execute their
programs in C Language. It's very easy to fit a procedure-oriented language because of the way it
works algorithms to execute the statements the developer writes. Suppose the developer wants to
develop a program using procedure-oriented language. In that case, you need to frame an algorithm
and convert it into a function in the C compiler, as the compiler provides better optimization and
faster exception.
7. Easy Debug: Debugging in the c language is easy and practical as the language does not require any
complex statements in the execution, and the speed of compilations and execution is a bit faster than
in any other language, so debugging is a faster and easier task to manipulate the code circumstances.
8. Open Source: The language C is a free and open-source programming language that is publicly
accessible and available in all coding and programming platforms. The code of the c language is also
publicly available. One can easily download the compiler of the language and can start working.
Disadvantages of C Language
1. Missing Concept of OOPs Technology: C is a massive and vast language, but it does not have the
concept of OOPs like Inheritance, Polymorphism, Encapsulation, Abstraction, Data Hiding,
overloading, and overriding. Due to this it is sometimes hectic for the programmer to solve a real-
world problem easily.
2. Run-Time Execution Error: In the C programming language, errors or bugs are not detected after
each line of code in the compiler for faster debugging; the major problem is the compiler shows all
the errors after writing the program, which makes the checking of code corrections very complex in
thousands of lines of code. Thus the developer faces optimization issues in the language.
3. Missing Namespaces: For the declaration of the variable to use on any other line of code, the concept
of a namespace is missing, as we can't declare the same name to another variable in the C language.
The c language is considered the old-school programming language for this major problem.
4. Poor Memory Management: The C language is very smart in that it automatically allocates the
memory for the Developer's program when it's needed for the execution of the program. The
problem arises when the programmer wants to allocate the memory dynamically; the programmer
should keep in mind the memory management techniques to get allocate the memory using the
malloc function.
5. No Garbage Collection: Garbage collection is a feature that automatically reclaims memory from
objects no longer needed by an application or library. It can be used for both automatic and manual
garbage collection. Automatic garbage collection occurs when there is insufficient free space on the
heap to allocate new objects; this may occur because all available physical RAM was allocated to
other processes running on the computer system. Manual garbage collection explicitly frees unused
memory blocks with calls to functions such as malloc.
But in C/C++ languages, there's no such feature of garbage collection as the culture of these
Unit 1 : Basics of C
languages is to leave storage management to the Developer or programmer. Hence, it would be
technically tedious and harsh on pockets to implement a precise garbage collector for C / C++.
6. No Constructor and Destructor: The major drawback in the C language is the missing feature of
constructor and destructor as the language lacks the support of OOPS technology and concepts. Both
constructor and destructor are the member functions created when the class is created. This support
helps memory occupation by the objects as soon as the program terminates or is created. The feature
helps many programmers to perform programming tasks with great ease.
7. Poor Exception Handling: All programming languages have the feature of optimized exception
handling; the critical character is missing from the C language as in the results, and the response to
errors is very slow in C Language.
C Structure
Why use structure?
In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity
has all the information of one type only. It can have different attributes of different data types. For example,
an entity Student may have its name (string), roll number (int), marks (float). To store such type of
information regarding an entity student, we have the following approaches:
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
Unit 1 : Basics of C
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
Output
Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69
The above program may fulfill our requirement of storing the information of an entity student. However, the
program is very complex, and the complexity increase with the amount of the input. The elements of each
of the array are stored contiguously, but all the arrays may not be stored contiguously in the memory. C
provides you with an additional and simpler approach where you can use a special data structure, i.e.,
structure, in which, you can group all the information of different data type regarding an entity.
What is Structure
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 ca; simulate the use of classes and templates as it can
store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
Unit 1 : Basics of C
The following image shows the memory allocation of the structure employee that is defined in the above
example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members
or fields of the structure. Let's understand it by the diagram given below:
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:
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared within the
main function.
Unit 1 : Basics of C
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be
treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;
Which approach is good
If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.
Let's see the code to access the id member of p1 variable by. (member) operator.
1. p1.id
C Structure example
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
Unit 1 : Basics of C
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
Unit 1 : Basics of C
21. printf( "employee 1 id : %d\n", e1.id);
22. printf( "employee 1 name : %s\n", e1.name);
23. printf( "employee 1 salary : %f\n", e1.salary);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", e2.id);
27. printf( "employee 2 name : %s\n", e2.name);
28. printf( "employee 2 salary : %f\n", e2.salary);
29. return 0;
30. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
C Header Files
A header file is a source file that has the .h extension. Header files contain the function prototypes or function
declaration, whereas the source code contains the constants, macros, system-wide global variables.
Whenever we require the definition of a function, then we simply include that header file in which function
is declared.
o System defined header file: The header file which is predefined is known as a system defined header
file.
o User-defined header file: The header file which is defined by the user is known as a user-defined
header file.
Both the user-defined and system-defined header file can be included in a program with the help of using
preprocessing directive (#). These preprocessor directives are used to instruct the compiler to process these
files before compilation. There are two forms of including header file:
o #include<file>
o #include "file"
There is a difference between the header files given above. If the header file is defined within the predefined
source path, we can specify the header within the angular brackets. If the header file is not defined within
the predefined source path then we can specify the full path of the header file within the double-quotes.
Unit 1 : Basics of C
Include Operation
Let's suppose that header.h header file contains the following declaration:
1. int *test()
1. #include"header.h"
2. int main()
3. {
4. puts(test());
5. return 0;
6. }
Compiler would replace the definition of header.h header file as shown below:
1. int *test()
2. int main()
3. {
4. puts(test());
5. return 0;
6. }
If the header file in a source code is included twice, then it leads to an error, i.e., multiple declarations. To
get rid of this problem, there is a standard way of enclosing the real content of the header file in a conditional
as follows:
1. #ifndef my_header_file
2. #define my_header_file
3. --
4. --
5. #endif
In the above condition, if the header is included, then it will not be included again. If the header file is not
included, then the header file will be included. The construct "ifndef" will become false if the header file is
included twice and the preprocessor will skip all the contents of the file, and the compiler will ignore the
second declaration of the header file.
Myheader.h
1. #ifndef my_header_file
Unit 1 : Basics of C
2. #define my_header_file
3. int a = 10;
4. #endif
1. #include <stdio.h>
2. #include "header.h"
3. #include "header.h"
4. int main()
5. {
6. printf("The value of a is : %d", a);
7. return 0;
8. }
9. In the above code, we have included the header file twice but it will not throw any error. Since we have sp
ecified the condition in the header file that if the header file is included then the header file should not be i
ncluded again. When the program control comes to the second statement of #include "header.h" then it wi
ll not include this header file again.
Header file is used to avoid writing large and complex code. When we create our own header file then we
can simply use wherever we want. It enhances code readability and functionality.
The following are the steps to create our own header file:
o First, we will write our own C or C++ code and save the file with .h extension. Below is the example
to create our header file:
o The second step is to include our header file in our main program.
o #include<stdio.h>: It is used for performing input and output operations with the help of using printf()
and scanf() function.
o #include<string.h>: It is used for performing string related functionalities like strlen(), strcmp(), etc.
o #include<iostream>: It is used to perform input and output operations with the help of using cin and
cout objects.
o #include<math.h>: This header file contains some predefined math functions that perform
mathematical operations, such as sqrt(), log2(), pow(), etc.
o #include<iomanip.h>: It contains the definition of set() and setprecision() function to limit the
decimal places in variables.
o #include<signal.h>: It contains the definitions of functions that perform the signal handling functions
such as signal(), raise().
o #include<errno.h>: It performs the error handling related operations like errno(), strerror(), perror(),
etc.
In the above code, we have observed the usage of header files like string.h in which strlen() function is
defined, and pow() function is defined in math.h header file.
Output
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of operations
like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The associativity
specifies the operator direction to be evaluated; it may be left to right or right to left.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).
Computer programming requires input/output (I/O) operations. Using I/O operations, the data is read and
written to and from various sources, including files, keyboards, and screens. I/O operations can be
either formatted or unformatted in the C computer language. In this blog post, we will cover the distinctions
between formatted and unformatted I/O in C, as well as code samples and outputs.
Unit 1 : Basics of C
Formatted I/O in C
The I/O procedure is known as "formatted I/O". It enables you to read or write data in a certain
format. Printf() and scanf() are two examples of C routines that handle formatted I/O. The type and format
of the data to be read or written are specified by format strings, which are used by these operations. The
program's execution replaces the placeholders for the data found in the format strings with the actual data.
Syntax:
Here, the argument list comprises the variables or values to be printed, and the format string determines
the output format.
Here, the argument list comprises the variables that will receive the input, and the format string describes
the format of the input.
Example:
1. #include <stdio.h>
2.
3. int main() {
4. char name[20];
5. int age;
6.
7. printf("Enter your name: ");
8. scanf("%s", name);
9.
10. printf("Enter your age: ");
11. scanf("%d", &age);
12.
13. printf("Your name is %s and your age is %d\n", name, age);
14.
15. return 0;
16. }
Output:
Explanation:
We first declare the variables name and age in the above example. After that, the user is prompted for
their name and age using the printf() function. We utilize the scanf() function to read user input and assign
it to the appropriate variables. To format the input, we finally employ the printf() function once more.
Unformatted I/O in C
Unformatted I/O refers to a category of I/O operations that reads or writes data as a stream
of bytes without regard to any format. Unformatted I/O in C is carried out with the aid of functions
like fread() and fwrite(). Without formatting, these operations are used to read and write data directly to
and from files.
Syntax:
Here, count is the number of elements to be written, size is the size of each element to be written, and
the file pointer is a pointer to the file where the data will be written.
In this syntax, a pointer to the buffer where the data will be read, the size of each element to be read, the
number of elements to be read, and a pointer to the file from which the data will be read.
Example
1. #include <stdio.h>
2. int main() {
3. char data[100];
4. FILE *fp;
5.
6. fp = fopen("file.txt", "w+");
7.
8. fputs("This is an example of unformatted output.", fp);
9. fseek(fp, 0, SEEK_SET);
10.
11. fread(data, sizeof (
12. char), 100, fp);
Unit 1 : Basics of C
13.
14. printf("%s\n", data);
15. fclose(fp);
16.
17. return 0;
18. }
Output:
Explanation:
In the example, we first declare a file pointer (fp) and a character array (data). After that, the file pointer is
assigned to 'fp' after using the 'fopen()' method to open the 'file.txt' file in write mode. The string "This is
an example of unformatted output." is written to the file using the 'fputs()' function. The file pointer is then
moved to the file's beginning using the 'fseek()' function. After that, the data is shown using
the 'printf()' function after being read from the file into the 'data' buffer using the 'fread()' function.
In C, there are a few distinctions between formatted and unformatted I/O. Some of these variations include:
1. Unformatted I/O reads and writes data as a stream of bytes without any format, whereas formatted
I/O enables you to read and write data in a predefined format.
2. Flexibility: Formatted I/O offers greater options for output formatting and data representation,
whereas unformatted I/O offers less flexibility and is better suited to reading and writing binary data.
3. Usability: Formatted I/O is more user-friendly for straightforward input and output activities,
whereas unformatted I/O necessitates more code and is better suited for intricate input and output
procedures.
4. Efficiency: Because unformatted I/O doesn't require any formatting or data type conversion, it is
more efficient than formatted I/O.
Conclusion
Formatted and Unformatted I/O operations are Input/Output operations that are utilized in C
programming. Unformatted I/O is used to read and write data as a stream of bytes without any format,
whereas formatted I/O is used to read and write data in a predefined format. The choice of which form of
I/O operation to use relies on the requirements of the program. Both types of I/O operations have benefits
and drawbacks.
Unit 2 : Decision Control and Looping Statement
C if else Statement
The if-else statement in C is used to perform the operations based on some specific condition. The operations
specified in if block are executed if and only if the given condition is true.
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
The if statement is used to check some given condition and perform some operations depending upon the
correctness of that condition. It is mostly used in the scenario where we need to perform the different
operations for the different conditions. The syntax of the if statement is given below.
1. if(expression){
2. //code to be executed
3. }
Flowchart of if statement in C
Unit 2 : Decision Control and Looping Statement
Let's see a simple example of C language if statement.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
Unit 2 : Decision Control and Looping Statement
22. }
23. }
Output
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is an
extension to the if statement using which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice
that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since
it always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18)
8. {
9. printf("You are eligible to vote...");
10. }
11. else
12. {
13. printf("Sorry ... you can't vote");
14. }
15. }
Output
Unit 2 : Decision Control and Looping Statement
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there
are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is
true then the statements defined in the if block will be executed, otherwise if some other condition is true
then the statements defined in the else-if block will be executed, at the last if none of the condition is true
then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It
is similar to the switch case statement where the default is executed instead of else block if none of the cases
is matched.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
Unit 2 : Decision Control and Looping Statement
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Program to calculate the grade of the student according to the specified marks.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }
Output
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple
operations for the different possibles values of a single variable called switch variable. Here, We can define
various statements in the multiple cases for the different values of a single variable.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the
case, all the cases will be executed present after the matched case. It is known as fall through the state of C
switch statement.
Let's try to understand it by the examples. We are assuming that there are following variables.
1. int x,y,z;
2. char a,b;
3. float f;
First, the integer expression specified in the switch statement is evaluated. This value is then matched one
by one with the constant values given in the different cases. If a match is found, then all the statements
specified in that case are executed along with the all the cases present after that case including the default
Unit 2 : Decision Control and Looping Statement
statement. No two cases can have similar values. If the matched case contains a break statement, then all
the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases
following the matched case will be executed.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
Unit 2 : Decision Control and Looping Statement
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }
Output
hi
C Switch statement is fall-through
In C language, the switch statement is fall through; it means if you don't use a break statement in the switch
case, all the cases after the matching case will be executed.
Let's try to understand the fall through state of switch statement by the example given below.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Unit 2 : Decision Control and Looping Statement
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
Output
enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
We can use as many switch statement as we want inside a switch statement. Such type of statements is
called nested switch case statements. Consider the following example.
1. #include <stdio.h>
2. int main () {
3.
4. int i = 10;
5. int j = 20;
6.
7. switch(i) {
8.
9. case 10:
10. printf("the value of i evaluated in outer switch: %d\n",i);
11. case 20:
12. switch(j) {
13. case 20:
14. printf("The value of j evaluated in nested switch: %d\n",j);
15. }
16. }
17.
18. printf("Exact value of i is : %d\n", i );
19. printf("Exact value of j is : %d\n", j );
20.
21. return 0;
22. }
Output
Unit 2 : Decision Control and Looping Statement
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20
if-else vs switch
An if-else statement in C programming is a conditional statement that executes a different set of statements
based on the condition that is true or false. The 'if' block will be executed only when the specified condition
is true, and if the specified condition is false, then the else block will be executed.
1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }
A switch statement is a conditional statement used in C programming to check the value of a variable and
compare it with all the cases. If the value is matched with any case, then its corresponding statements will
be executed. Each case has some name or number known as the identifier. The value entered by the user
will be compared with all the cases until the case is found. If the value entered by the user is not matched
with any case, then the default statement will be executed.
1. switch(expression)
2. {
3. case constant 1:
4. // statements;
5. break;
6. case constant 2:
7. // statements;
8. break;
9. case constant n:
10. // statements;
11. break;
12. default:
Unit 2 : Decision Control and Looping Statement
13. // statements;
14. }
Both the if-else and switch are the decision-making statements. Here, decision-making statements mean
that the output of the expression will decide which statements are to be executed.
The following are the differences between if-else and switch statement are:
o Definition
if-else
Based on the result of the expression in the 'if-else' statement, the block of statements will be executed. If
the condition is true, then the 'if' block will be executed otherwise 'else' block will execute.
Switch statement
The switch statement contains multiple cases or choices. The user will decide the case, which is to execute.
o Expression
If-else
It can contain a single expression or multiple expressions for multiple choices. In this, an expression is
evaluated based on the range of values or conditions. It checks both equality and logical expressions.
Switch
It contains only a single expression, and this expression is either a single integer object or a string object. It
checks only equality expression.
o Evaluation
Unit 2 : Decision Control and Looping Statement
If-else
An if-else statement can evaluate almost all the types of data such as integer, floating-point, character,
pointer, or Boolean.
Switch
o Sequence of Execution
If-else
In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the
condition.
Switch
In the case of the 'switch' statement, one case after another will be executed until the break keyword is not
found, or the default statement is executed.
o Default Execution
If-else
If the condition is not true within the 'if' statement, then by default, the else block statements will be
executed.
Switch
If the expression specified within the switch statement is not matched with any of the cases, then the default
statement, if defined, will be executed.
o Values
If-else
Values are based on the condition specified inside the 'if' statement. The value will decide either the 'if' or
'else' block is to be executed.
Switch
In this case, value is decided by the user. Based on the choice of the user, the case will be executed.
o Use
If-else
Switch
Unit 2 : Decision Control and Looping Statement
A switch statement compares the value of the variable with multiple cases. If the value is matched with any
of the cases, then the block of statements associated with this case will be executed.
o Editing
If-else
Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will create the havoc.
Switch
Editing in switch statement is easier as compared to the 'if-else' statement. If we remove any of the cases
from the switch, then it will not interrupt the execution of other cases. Therefore, we can say that
the switch statement is easy to modify and maintain.
o Speed
If-else
If the choices are multiple, then the speed of the execution of 'if-else' statements is slow.
Switch
The case constants in the switch statement create a jump table at the compile time. This jump table chooses
the path of the execution based on the value of the expression. If we have a multiple choice, then the
execution of the switch statement will be much faster than the equivalent logic of 'if-else' statement.
Unit 2 : Decision Control and Looping Statement
Let's summarize the above differences in a tabular form.
If-else switch
Definition Depending on the condition in the The user will decide which statement is to be
'if' statement, 'if' and 'else' blocks executed.
are executed.
Expression It contains either logical or equality It contains a single expression which can be either
expression. a character or integer variable.
Evaluation It evaluates all types of data, such as It evaluates either an integer, or character.
integer, floating-point, character or
Boolean.
Sequence of First, the condition is checked. If the It executes one case after another till the break
execution condition is true then 'if' block is keyword is not found, or the default statement is
executed otherwise 'else' block executed.
Default If the condition is not true, then by If the value does not match with any case, then by
execution default, else block will be executed. default, default statement is executed.
Editing Editing is not easy in the 'if-else' Cases in a switch statement are easy to maintain
statement. and modify. Therefore, we can say that the removal
or editing of any case will not interrupt the
execution of other cases.
Speed If there are multiple choices If we have multiple choices then the switch
implemented through 'if-else', then statement is the best option as the speed of the
the speed of the execution will be execution will be much higher than 'if-else'.
slow.
C Loops
The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all
the aspects of C loops.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program
so that instead of writing the same code again and again, we can repeat the same code for a finite number
of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf
statement 10 times, we can print inside a loop which runs up to 10 iterations.
Unit 2 : Decision Control and Looping Statement
Advantage of loops in C
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do while
2. while
3. for
Do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when
it is necessary to execute the loop at least once (mostly menu driven programs).
1. do{
2. //code to be executed
3. }while(condition);
while loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations in advance.
The block of statements is executed in the while loop until the condition specified in the while loop is
satisfied. It is also called a pre-tested loop.
1. while(condition){
2. //code to be executed
3. }
for loop in C
The for loop is used in the case where we need to execute some part of the code until the given condition is
satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration
is known in advance.
Unit 2 : Decision Control and Looping Statement
The syntax of for loop in c language is given below:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts
of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least
once. The do-while loop is mostly used in menu-driven programs where the termination condition depends
upon the end user.
1. do{
2. //code to be executed
3. }while(condition);
Example 1
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("Javatpoint");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
Unit 2 : Decision Control and Looping Statement
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
Output
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n
do while example
There is given the simple program of c language do while loop where we are printing the table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Unit 2 : Decision Control and Looping Statement
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.
1. do{
2. //statement
3. }while(1);
for loop in C
Unit 2 : Decision Control and Looping Statement
The for loop in C language is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like the array and linked list.
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
Unit 2 : Decision Control and Looping Statement
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
Unit 2 : Decision Control and Looping Statement
2000
3000
4000
5000
6000
7000
8000
9000
10000
Properties of Expression 1
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output
35 36
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
Unit 2 : Decision Control and Looping Statement
9. }
Output
1234
Properties of Expression 2
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;i<=4;i++)
6. {
7. printf("%d ",i);
8. }
9. }
output
01234
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
Unit 2 : Decision Control and Looping Statement
8. j+=2;
9. k+=3;
10. }
11. }
Output
000
123
246
369
4 8 12
Example 3
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }
Output
infinite loop
Properties of Expression 3
o Expression 3 is used to update the loop variable.
o We can update more than one variable at the same time.
o Expression 3 is optional.
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i=0,j=2;
5. for(i = 0;i<5;i++,j=j+2)
6. {
7. printf("%d %d\n",i,j);
8. }
Unit 2 : Decision Control and Looping Statement
9. }
Output
02
14
26
38
4 10
Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one statement,
then we don't need to use braces. A loop without a body is possible. The braces work as a block separator,
i.e., the value variable declared inside for loop is valid only for that block and not outside. Consider the
following example.
1. #include<stdio.h>
2. void main ()
3. {
4. int i;
5. for(i=0;i<10;i++)
6. {
7. int i = 20;
8. printf("%d ",i);
9. }
10. }
Output
20 20 20 20 20 20 20 20 20 20
To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to provide
two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.
1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }
Unit 2 : Decision Control and Looping Statement
Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements
inside another loop. Let's observe an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number
of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop;
for example, you can define 'while' loop inside a 'for' loop.
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6. // Displaying the n tables.
7. for(int i=1;i<=n;i++) // outer loop
Unit 2 : Decision Control and Looping Statement
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }
o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the outer loop, i.e.,
i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
Output:
The nested while loop means any type of loop which is defined inside the 'while' loop.
1. while(condition)
2. {
3. while(condition)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
1. #include <stdio.h>
2. int main()
3. {
Unit 2 : Decision Control and Looping Statement
4. int rows; // variable declaration
5. int columns; // variable declaration
6. int k=1; // variable initialization
7. printf("Enter the number of rows :"); // input the number of rows.
8. scanf("%d",&rows);
9. printf("\nEnter the number of columns :"); // input the number of columns.
10. scanf("%d",&columns);
11. int a[rows][columns]; //2d array declaration
12. int i=1;
13. while(i<=rows) // outer loop
14. {
15. int j=1;
16. while(j<=columns) // inner loop
17. {
18. printf("%d\t",k); // printing the value of k.
19. k++; // increment counter
20. j++;
21. }
22. i++;
23. printf("\n");
24. }
25. }
Output:
Unit 2 : Decision Control and Looping Statement
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);
1. #include <stdio.h>
2. int main()
3. {
4. /*printing the pattern
5. ********
6. ********
7. ********
8. ******** */
9. int i=1;
10. do // outer loop
11. {
12. int j=1;
13. do // inner loop
14. {
15. printf("*");
Unit 2 : Decision Control and Looping Statement
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }
Output:
Infinite Loop in C
An infinite loop is a looping construct that does not terminate the loop and executes the loop forever. It is
also called an indefinite loop or an endless loop. It either produces a continuous output or no output.
An infinite loop is useful for those applications that accept the user input and generate the output
continuously until the user exits from the application manually. In the following situations, this type of loop
can be used:
o All the operating systems run in an infinite loop as it does not exist after performing some task. It
comes out of an infinite loop only when the user manually shuts down the system.
Unit 2 : Decision Control and Looping Statement
o All the servers run in an infinite loop as the server responds to all the client requests. It comes out of
an indefinite loop only when the administrator shuts down the server manually.
o All the games also run in an infinite loop. The game will accept the user requests until the user exits
from the game.
We can create an infinite loop through various loop structures. The following are the loop structures through
which we will define the infinite loop:
o for loop
o while loop
o do-while loop
o go to statement
o C macros
For loop
Let's see the infinite 'for' loop. The following is the definition for the infinite for loop:
1. for(; ;)
2. {
3. // body of the for loop.
4. }
As we know that all the parts of the 'for' loop are optional, and in the above for loop, we have not mentioned
any condition; so, this loop will execute infinite times.
1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello javatpoint");
7. }
8. return 0;
9. }
In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will be displayed infinitely.
Output
Unit 2 : Decision Control and Looping Statement
while loop
Now, we will see how to create an infinite loop using a while loop. The following is the definition for the
infinite while loop:
1. while(1)
2. {
3. // body of the loop..
4. }
In the above while loop, we put '1' inside the loop condition. As we know that any non-zero integer
represents the true condition while '0' represents the false condition.
1. #include <stdio.h>
2. int main()
3. {
4. int i=0;
5. while(1)
6. {
7. i++;
8. printf("i is :%d",i);
9. }
10. return 0;
11. }
In the above code, we have defined a while loop, which runs infinite times as it does not contain any
condition. The value of 'i' will be updated an infinite number of times.
Unit 2 : Decision Control and Looping Statement
Output
Do while loop
The do..while loop can also be used to create the infinite loop. The following is the syntax to create the
infinite do..while loop.
1. do
2. {
3. // body of the loop..
4. }while(1);
The above do..while loop represents the infinite condition as we provide the '1' value inside the loop
condition. As we already know that non-zero integer represents the true condition, so this loop will run
infinite times.
Goto statement
We can also use the goto statement to define the infinite loop.
1. infinite_loop;
2. // body statements.
3. goto infinite_loop;
In the above code, the goto statement transfers the control to the infinite loop.
Unit 2 : Decision Control and Looping Statement
Macros
We can also create the infinite loop with the help of a macro constant. Let's understand through an example.
1. #include <stdio.h>
2. #define infinite for(;;)
3. int main()
4. {
5.
6. infinite
7. {
8. printf("hello");
9. }
10.
11. return 0;
12. }
In the above code, we have defined a macro named as 'infinite', and its value is 'for(;;)'. Whenever the word
'infinite' comes in a program then it will be replaced with a 'for(;;)'.
Output
Till now, we have seen various ways to define an infinite loop. However, we need some approach to come
out of the infinite loop. In order to come out of the infinite loop, we can use the break statement.
1. #include <stdio.h>
2. int main()
3. {
4. char ch;
Unit 2 : Decision Control and Looping Statement
5. while(1)
6. {
7. ch=getchar();
8. if(ch=='n')
9. {
10. break;
11. }
12. printf("hello");
13. }
14. return 0;
15. }
In the above code, we have defined the while loop, which will execute an infinite number of times until we
press the key 'n'. We have added the 'if' statement inside the while loop. The 'if' statement contains the
break keyword, and the break keyword brings control out of the loop.
Sometimes the situation arises where unintentional infinite loops occur due to the bug in the code. If we are
the beginners, then it becomes very difficult to trace them. Below are some measures to trace an
unintentional infinite loop:
o We should examine the semicolons carefully. Sometimes we put the semicolon at the wrong place,
which leads to the infinite loop.
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. while(i<=10);
6. {
7. printf("%d", i);
8. i++;
9. }
10. return 0;
11. }
In the above code, we put the semicolon after the condition of the while loop which leads to the infinite
loop. Due to this semicolon, the internal body of the while loop will not execute.
o We should check the logical conditions carefully. Sometimes by mistake, we place the assignment
operator (=) instead of a relational operator (= =).
1. #include <stdio.h>
Unit 2 : Decision Control and Looping Statement
2. int main()
3. {
4. char ch='n';
5. while(ch='y')
6. {
7. printf("hello");
8. }
9. return 0;
10. }
In the above code, we use the assignment operator (ch='y') which leads to the execution of loop infinite
number of times.
o We use the wrong loop condition which causes the loop to be executed indefinitely.
1. #include <stdio.h>
2. int main()
3. {
4. for(int i=1;i>=1;i++)
5. {
6. printf("hello");
7. }
8. return 0;
9. }
The above code will execute the 'for loop' infinite number of times. As we put the condition (i>=1), which
will always be true for every condition, it means that "hello" will be printed infinitely.
o We should be careful when we are using the break keyword in the nested loop because it will
terminate the execution of the nearest loop, not the entire loop.
1. #include <stdio.h>
2. int main()
3. {
4. while(1)
5. {
6. for(int i=1;i<=10;i++)
7. {
8. if(i%2==0)
9. {
10. break;
11. }
Unit 2 : Decision Control and Looping Statement
12. }
13. }
14. return 0;
15. }
In the above code, the while loop will be executed an infinite number of times as we use the break keyword
in an inner loop. This break keyword will bring the control out of the inner loop, not from the outer loop.
o We should be very careful when we are using the floating-point value inside the loop as we cannot
underestimate the floating-point errors.
1. #include <stdio.h>
2. int main()
3. {
4. float x = 3.0;
5. while (x != 4.0) {
6. printf("x = %f\n", x);
7. x += 0.1;
8. }
9. return 0;
10. }
In the above code, the loop will run infinite times as the computer represents a floating-point value as a real
value. The computer will represent the value of 4.0 as 3.999999 or 4.000001, so the condition (x !=4.0) will
never be false. The solution to this problem is to write the condition as (k<=4.0).
C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The break statement
is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case
of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can
be used in the following two scenarios:
Syntax:
Flowchart of break in c
Unit 2 : Decision Control and Looping Statement
Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
Click here to see the example of C break with the switch statement.
In such case, it breaks only the inner loop, but not outer loop.
Unit 2 : Decision Control and Looping Statement
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }
Output
11
12
13
21
22
31
32
33
As you can see the output on the console, 2 3 is not printed because there is a break statement after printing
i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is used to break the inner loop
only.
Consider the following example to use break statement inside while loop.
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(1)
6. {
7. printf("%d ",i);
8. i++;
9. if(i == 10)
10. break;
11. }
12. printf("came out of while loop");
Unit 2 : Decision Control and Looping Statement
13. }
Output
Consider the following example to use the break statement with a do-while loop.
1. #include<stdio.h>
2. void main ()
3. {
4. int n=2,i,choice;
5. do
6. {
7. i=1;
8. while(i<=10)
9. {
10. printf("%d X %d = %d\n",n,i,n*i);
11. i++;
12. }
13. printf("do you want to continue with the table of %d , enter any non-zero value to continue.",n+1);
14. scanf("%d",&choice);
15. if(choice == 0)
16. {
17. break;
18. }
19. n++;
20. }while(1);
21. }
Output
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to continue.1
Unit 2 : Decision Control and Looping Statement
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to continue.0
C continue statement
The continue statement in C language is used to bring the program control to the beginning of the loop. The
continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly
used for a condition so that we can skip some code for a particular condition.
Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }
Output
infinite loop
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
Unit 2 : Decision Control and Looping Statement
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
In such case, C continue statement continues only inner loop, but not outer loop.
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }
Output
11
Unit 2 : Decision Control and Looping Statement
12
13
21
23
31
32
33
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the
program control to a predefined label. The goto statment can be used to repeat some part of the code for a
particular condition. It can also be used to break the multiple loops which can't be done by using a single
break statement. However, using goto is avoided these days since it makes the program less readable and
complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
goto example
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }
Output:
The only condition in which using goto is preferable is when we need to break the multiple loops using a
single statement at the same time. Consider the following example.
1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
000
001
002
010
011
012
020
021
022
030
Unit 2 : Decision Control and Looping Statement
came out of the loop
Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting
which is denoted by (type).
Syntax:
1. (type)value;
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
Let's see a simple example to cast int value into the float.
1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }
Output:
f : 2.250000
Unit 3 : Subcripted variables / Arrays
C Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data such
as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different subject.
Instead of that, we can define an array which can store the marks in each subject at the contiguous memory
locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each element
of the array with the given base address and the size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So,
it doesn't grow the size dynamically like LinkedList which we will learn later.
Unit 3 : Subcripted variables / Arrays
Declaration of C Array
1. data_type array_name[array_size];
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each element
of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
Unit 3 : Subcripted variables / Arrays
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the following code.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
In the following program, we are using bubble sort method to sort the array in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
Unit 3 : Subcripted variables / Arrays
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
Unit 3 : Subcripted variables / Arrays
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which
can be represented as the collection of rows and columns. However, 2D arrays are created to implement a
relational database lookalike data structure. It provides ease of holding the bulk of data at once which can
be passed to any number of functions wherever required.
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second
dimension of the array. The two-dimensional array can be declared and defined in the following way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
Unit 3 : Subcripted variables / Arrays
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
Unit 3 : Subcripted variables / Arrays
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short, we
can say that array is a collection of variables of the same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables
individually, then it becomes a very tedious task. In such a case, we create an array of variables having the
same type. Each element of an array can be accessed using an index of the element.
1. #include <stdio.h>
2. void getarray(int arr[])
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
Unit 3 : Subcripted variables / Arrays
9. }
10. int main()
11. {
12. int arr[5]={45,67,34,78,90};
13. getarray(arr);
14. return 0;
15. }
In the above program, we have first created the array arr[] and then we pass this array to the function
getarray(). The getarray() function prints all the elements of the array arr[].
Output
1. #include <stdio.h>
2. void printarray(char *arr)
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%c ", arr[i]);
8. }
9. }
10. int main()
11. {
12. char arr[5]={'A','B','C','D','E'};
13. printarray(arr);
14. return 0;
15. }
Unit 3 : Subcripted variables / Arrays
In the above code, we have passed the array to the function as a pointer. The function printarray() prints
the elements of an array.
Output
1. #include <stdio.h>
2. int *getarray()
3. {
4. int arr[5];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
10. return arr;
11. }
12. int main()
13. {
14. int *n;
15. n=getarray();
16. printf("\nElements of array are :");
17. for(int i=0;i<5;i++)
18. {
19. printf("%d", n[i]);
20. }
21. return 0;
22. }
Unit 3 : Subcripted variables / Arrays
In the above program, getarray() function returns a variable 'arr'. It returns a local variable, but it is an illegal
memory location to be returned, which is allocated within a function in the stack. Since the program control
comes back to the main() function, and all the variables in a stack are freed. Therefore, we can say that this
program is returning memory location, which is already de-allocated, so the output of the program is
a segmentation fault.
Output
1. #include <stdio.h>
2. int *getarray(int *a)
3. {
4.
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &a[i]);
9. }
10. return a;
11. }
12. int main()
13. {
14. int *n;
15. int a[5];
Unit 3 : Subcripted variables / Arrays
16. n=getarray(a);
17. printf("\nElements of array are :");
18. for(int i=0;i<5;i++)
19. {
20. printf("%d", n[i]);
21. }
22. return 0;
23. }
Output
1. #include <stdio.h>
2. #include<malloc.h>
3. int *getarray()
4. {
5. int size;
6. printf("Enter the size of the array : ");
7. scanf("%d",&size);
8. int *p= malloc(sizeof(size));
9. printf("\nEnter the elements in an array");
10. for(int i=0;i<size;i++)
11. {
12. scanf("%d",&p[i]);
13. }
14. return p;
15. }
16. int main()
17. {
18. int *ptr;
19. ptr=getarray();
20. int length=sizeof(*ptr);
21. printf("Elements that you have entered are : ");
22. for(int i=0;ptr[i]!='\0';i++)
23. {
24. printf("%d ", ptr[i]);
25. }
Unit 3 : Subcripted variables / Arrays
26. return 0;
27. }
Output
1. #include <stdio.h>
2. int *getarray()
3. {
4. static int arr[7];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<7;i++)
7. {
8. scanf("%d",&arr[i]);
9. }
10. return arr;
11.
12. }
13. int main()
14. {
15. int *ptr;
16. ptr=getarray();
17. printf("\nElements that you have entered are :");
18. for(int i=0;i<7;i++)
19. {
20. printf("%d ", ptr[i]);
21. }
22. }
In the above code, we have created the variable arr[] as static in getarray() function, which is available
throughout the program. Therefore, the function getarray() returns the actual memory location of the
variable 'arr'.
Output
Unit 3 : Subcripted variables / Arrays
Using Structure
The structure is a user-defined data type that can contain a collection of items of different types. Now, we
will create a program that returns an array by using structure.
1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
7. struct array getarray()
8. {
9. struct array y;
10. printf("Enter the elements in an array : ");
11. for(int i=0;i<8;i++)
12. {
13. scanf("%d",&y.arr[i]);
14. }
15. return y;
16. }
17. int main()
18. {
19. struct array x=getarray();
20. printf("Elements that you have entered are :");
21. for(int i=0;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26. }
Unit 3 : Subcripted variables / Arrays
Output
In C, there are various general problems which requires passing more than one variable of the same type to
a function. For example, consider a function which sorts the 10 elements in ascending order. Such a function
requires 10 numbers to be passed as the actual parameters from the main function. Here, instead of
declaring 10 different numbers and then passing into the function, we can declare and initialize an array and
pass that into the function. This will resolve all the complexity since the function will now work for any
number of values.
As we know that the array_name contains the address of the first element. Here, we must notice that we
need to pass only the name of the array in the function which is intended to accept an array. The array
defined as the formal parameter will automatically refer to the array specified by the array name defined as
an actual parameter.
1. functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an argument.
First way:
Second way:
You can also use the concept of a pointer. In pointer chapter, we will learn about it.
1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }
Output
minimum number is 3
1. #include<stdio.h>
2. void Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. Bubble_Sort(arr);
7. }
Unit 3 : Subcripted variables / Arrays
Output
As we know that, a function can not return more than one value. However, if we try to write the return
statement as return a, b, c; to return three values (a,b,c), the function will return the last mentioned value
which is c in our case. In some problems, we may need to return multiple values from a function. In such
cases, an array is returned from the function.
Unit 3 : Subcripted variables / Arrays
Returning an array is similar to passing the array into the function. The name of the array is returned from
the function. To make a function returning an array, the following syntax is used.
1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }
To store the array returned from the function, we can define a pointer which points to that array. We can
traverse the array by increasing that pointer since pointer initially points to the base address of the array.
Consider the following example that contains a function returning the sorted array.
1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }
Unit 3 : Subcripted variables / Arrays
Output
In c, we can divide a large program into the basic building blocks known as function. The function contains
the set of programming statements enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the C program. In other words, we can say that the collection of functions
creates a program. The function is also known as procedureor subroutinein other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
o Function declaration A function must be declared globally in a c program to tell the compiler about
the function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions as it
is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice that
only one value can be returned from the function.
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that he/she
can use it many times. It reduces the complexity of a big program and optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any value from the
function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
1. void hello(){
2. printf("hello c");
3. }
If you want to return any value from the function, you need to use any data type such as int, long, char, etc.
The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
1. int get(){
2. return 10;
3. }
In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-
point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.
1. float get(){
2. return 10.2;
3. }
Unit 4 : User defined function
Now, you need to call the function, to get the value of the function.
A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.
Example 1
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }
Output
Hello Javatpoint
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
Unit 4 : User defined function
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Example 1
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
The sum is 34
Unit 4 : User defined function
Example 2: program to calculate the area of the square
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Example 1
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Unit 4 : User defined function
Output
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
Unit 4 : User defined function
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
Unit 4 : User defined function
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place called the
library. Such functions are used to perform some specific operations. For example, printf is a library function
used to print on the console. The library functions are created by the designers of compilers. All C standard
library functions are defined inside the different header files saved with the extension .h. We need to include
these header files in our program to make use of the library functions defined in such header files. For
example, To use the library functions such as printf/scanf we need to include stdio.h in our program which
is a header file that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library functions
regarding standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(),
etc.
5 math.h This header file contains all the math operations related functions like sqrt(), pow(),
etc.
9 signal.h All the signal handling functions are defined in this header file.
There are two methods to pass the data into the function in C language, i.e., call by value and call by
reference.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal parameters. In
other words, we can say that the value of the variable is used in the function call in the call by value
method.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value of the
actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal parameter is
the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
Unit 4 : User defined function
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
o The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do chan
ge in call by reference, a = 10, b = 20
Unit 4 : User defined function
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called
recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to
understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in
terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal
problems.
Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any
problem that can be solved recursively, can also be solved iteratively. However, some problems are best
suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
Unit 4 : User defined function
In the following example, recursion is used to calculate the factorial of a number.
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure given below:
Unit 4 : User defined function
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition
defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the
final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances where the function
keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written
using this format.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Unit 4 : User defined function
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Each recursive call creates a new copy of that method in the memory. Once some data is returned by the
method, the copy is removed from the memory. Since all the variables and other stuff declared inside
function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the
value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much
complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the
stack and track the values of the variables defined in the stack.
Let us consider the following example to understand the memory allocation of the recursive functions.
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which prints the
corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get
destroyed one by one by returning 0 to its calling stack. Consider the following image for more information
regarding the stack trace for the recursive functions.
Unit 4 : User defined function
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a
variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main program, Retains value
between multiple functions call
Automatic
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
Unit 4 : User defined function
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
8. return 0;
9. }
Output:
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
Unit 4 : User defined function
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers depending upon
the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
Unit 4 : User defined function
o The register keyword is used for the variable which should be stored in the CPU register. However, it
is compiler?s choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
5. printf("%d",a);
6. }
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the address of a register vari
able.
6. }
Output:
External
o The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and intended to
specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
o An external variable can be declared many times but can be initialized at only once.
Unit 4 : User defined function
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show an
error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same time
6. printf("%d",a);
7. }
Output
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
Consider the following example to define a pointer which stores the address of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
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.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see 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.
Let's see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
Unit 5 : Pointer in C
6. printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p give
s the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if
we print *p, we will get the value stored at the address contained by p.
8. return 0;
9. }
Output
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
Pointer to a function
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and
used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
Unit 5 : Pointer in C
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer
is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves
the performance.
The address of operator '&' returns the address of a variable. But, we need to use %u to display the address
of a variable.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any address
to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better
approach.
int *p=NULL;
Pointer Program to swap two numbers without using the 3rd variable.
1. #include<stdio.h>
2. int main(){
3. int a=10,b=20,*p1=&a,*p2=&b;
4.
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
Unit 5 : Pointer in C
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12. }
Output
There are several things which must be taken into the consideration while reading the complex pointers in
C. Lets see the precedence and associativity of the operators which are used regarding pointers.
Data type 3 -
o (): This operator is a bracket operator used to declare and define the function.
o []: This operator is an array subscript operator
o * : This operator is a pointer operator.
o Identifier: It is the name of the pointer. The priority will always be assigned to this.
o Data type: Data type is the type of the variable to which the pointer is intended to point. It also
includes the modifier like signed int, long, etc).
To read the pointer, we must see that () and [] have the equal precedence. Therefore, their associativity
must be considered here. The associativity is left to right, so the priority goes to ().
Inside the bracket (), pointer operator * and pointer name (identifier) p have the same precedence.
Therefore, their associativity must be considered here which is right to left, so the priority goes to p, and the
second priority goes to *.
Assign the 3rd priority to [] since the data type has the last precedence. Therefore the pointer will look like
following.
Unit 5 : Pointer in C
o char -> 4
o * -> 2
o p -> 1
o [10] -> 3
Example
Explanation
This pointer will be read as p is a pointer to such function which accepts the first parameter as the pointer
to a one-dimensional array of integers of size two and the second parameter as the pointer to a function
which parameter is void and return type is the integer.
As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the access time of
a variable. However, In C, we can also define a pointer to store the address of another pointer. Such pointer
is known as a double pointer (pointer to pointer). The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of the first pointer. Let's understand it by the
diagram given below.
1. #include<stdio.h>
2. void main ()
3. {
4. int a = 10;
5. int *p;
6. int **pp;
7. p = &a; // pointer p is pointing to the address of a
Unit 5 : Pointer in C
8. pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
9. printf("address of a: %x\n",p); // Address of a will be printed
10. printf("address of p: %x\n",pp); // Address of p will be printed
11. printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be printed
12. printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer stoyred
at pp
13. }
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
Let's see an example where one pointer points to the address of another pointer.
As you can see in the above figure, p2 contains the address of p (fff2), and p contains the address of number
variable (fff4).
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);
9. printf("Address of p variable is %x \n",p);
10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
12. printf("Value of **p2 variable is %d \n",*p);
13. return 0;
14. }
Unit 5 : Pointer in C
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
1. #include<stdio.h>
2. void main ()
3. {
4. int a[10] = {100, 206, 300, 409, 509, 601}; //Line 1
5. int *p[] = {a, a+1, a+2, a+3, a+4, a+5}; //Line 2
6. int **pp = p; //Line 3
7. pp++; // Line 4
8. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 5
9. *pp++; // Line 6
10. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 7
11. ++*pp; // Line 8
12. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 9
13. ++**pp; // Line 10
14. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 11
15. }
Explanation
Unit 5 : Pointer in C
In the above question, the pointer arithmetic is used with the double pointer. An array of 6 elements is
defined which is pointed by an array of pointer p. The pointer array p is pointed by a double pointer pp.
However, the above image gives you a brief idea about how the memory is being allocated to the array a
and the pointer array p. The elements of p are the pointers that are pointing to every element of the array
a. Since we know that the array name contains the base address of the array hence, it will work as a pointer
and can the value can be traversed by using *(a), *(a+1), etc. As shown in the image, a[0] can be accessed in
the following ways.
o a[0]: it is the simplest way to access the first element of the array
o *(a): since a store the address of the first element of the array, we can access its value by using
indirection pointer on it.
o *p[0]: if a[0] is to be accessed by using a pointer p to it, then we can use indirection operator (*) on
the first element of the pointer array p, i.e., *p[0].
o **(pp): as pp stores the base address of the pointer array, *pp will give the value of the first element
of the pointer array that is the address of the first element of the integer array. **p will give the
actual value of the first element of the integer array.
Coming to the program, Line 1 and 2 declare the integer and pointer array relatively. Line 3 initializes the
double pointer to the pointer array p. As shown in the image, if the address of the array starts from 200 and
the size of the integer is 2, then the pointer array will contain the values as 200, 202, 204, 206, 208, 210. Let
us consider that the base address of the pointer array is 300; the double pointer pp contains the address of
pointer array, i.e., 300. Line number 4 increases the value of pp by 1, i.e., pp will now point to address 302.
Line number 5 contains an expression which prints three values, i.e., pp - p, *pp - a, **pp. Let's calculate
them each one of them.
o pp = 302, p = 300 => pp-p = (302-300)/2 => pp-p = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, a = 200 => *pp - a = 202 - 200 = 2/2 = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, *(*pp) = 206, i.e., 206 will be printed.
Therefore as the result of line 5, The output 1, 1, 206 will be printed on the console. On line 6, *pp++ is
written. Here, we must notice that two unary operators * and ++ will have the same precedence. Therefore,
by the rule of associativity, it will be evaluated from right to left. Therefore the expression *pp++ can be
rewritten as (*(pp++)). Since, pp = 302 which will now become, 304. *pp will give 204.
On line 7, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp. Let's calculate each
one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, a = 200 => *pp-a = (204 - 200)/2 = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, *(*pp) = 300, i.e., 300 will be printed.
Therefore, as the result of line 7, The output 2, 2, 300 will be printed on the console. On line 8, ++*pp is
written. According to the rule of associativity, this can be rewritten as, (++(*(pp))). Since, pp = 304, *pp =
204, the value of *pp = *(p[2]) = 206 which will now point to a[3].
Unit 5 : Pointer in C
On line 9, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp. Let's calculate each
one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o pp = 304, *pp = 206, *(*pp) = 409, i.e., 409 will be printed.
Therefore, as the result of line 9, the output 2, 3, 409 will be printed on the console. On line 10, ++**pp is
writen. according to the rule of associativity, this can be rewritten as, (++(*(*(pp)))). pp = 304, *pp = 206,
**pp = 409, ++**pp => *pp = *pp + 1 = 410. In other words, a[3] = 410.
On line 11, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp. Let's calculate
each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o On line 8, **pp = 410.
Therefore as the result of line 9, the output 2, 3, 410 will be printed on the console.
Output
1 1 206
2 2 300
2 3 409
2 3 410
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the pointer will also
be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an
integer value. Following arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Unit 5 : Pointer in C
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size
of the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer which will keep pointing to every
element of the array, perform some operation on that, and update itself in a loop.
32-bit
64-bit
Output
Output
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the
previous location. The formula of decrementing the pointer is given below:
32-bit
64-bit
Output
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
32-bit
64-bit
Let's see the example of adding value to pointer variable on 64-bit architecture.
Unit 5 : Pointer in C
Output
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e.,
4*3=12 increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit
architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit
OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a
pointer will give an address. The formula of subtracting value from the pointer variable is given below:
32-bit
64-bit
Let's see the example of subtracting value from the pointer variable on 64-bit architecture.
Output
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value.
However, instead of subtracting a number, we can also subtract an address from another address (pointer).
This will result in a number. It will not be a simple arithmetic operation, but it will follow the following rule.
Output
There are various operations which can not be performed on pointers. Since, pointer stores address hence
we must ignore the operations which may lead to an illegal address, for example, addition, and
multiplication. A list of such operations is given below.
Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild pointers. Sometimes
the programmer fails to initialize the pointer with a valid address, then this type of initialized pointer is
known as a dangling pointer in C.
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from
memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory,
which is de-allocated. The dangling pointer can point to the memory, which contains either the program
code or the code of the operating system. If we assign the value to this pointer, then it overwrites the value
of the program code or operating system instructions; in such cases, the program will show the undesirable
result or may even crash. If the memory is re-allocated to some other process, then we dereference the
dangling pointer will cause the segmentation faults.
In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer 1 and Pointer 2 are the
pointers that point to the allocated objects, i.e., Object 1 and Object 2, respectively. Pointer 3 is a dangling
pointer as it points to the de-allocated object.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is a integer
variable. The *ptr is a pointer variable which is created with the help of malloc() function. As we know that
malloc() function returns void, so we use int * to convert void pointer into int pointer.
The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown in the below
image:
The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign, and 'ptr'
pointer becomes dangling as it is pointing to the de-allocated memory.
Unit 5 : Pointer in C
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory. Therefore, we can
say that ptr is not a dangling pointer, as shown in the below image:
When the variable goes out of the scope then the pointer pointing to the variable becomes a dangling
pointer.
1. #include<stdio.h>
2. int main()
3. {
4. char *str;
5. {
6. char a = ?A?;
7. str = &a;
8. }
9. // a falls out of scope
10. // str is now a dangling pointer
11. printf("%s", *str);
12. }
Now, we will see how the pointer becomes dangling when we call the function.
1. #include <stdio.h>
2. int *fun(){
3. int y=10;
4. return &y;
5. }
6. int main()
7. {
8. int *p=fun();
9. printf("%d", *p);
10. return 0;
11. }
o First, we create the main() function in which we have declared 'p' pointer that contains the return
value of the fun().
o When the fun() is called, then the control moves to the context of the int *fun(), the fun() returns
the address of the 'y' variable.
o When control comes back to the context of the main() function, it means the variable 'y' is no longer
available. Therefore, we can say that the 'p' pointer is a dangling pointer as it points to the de-
allocated memory.
Output
1. #include <stdio.h>
2. int *fun()
3. {
4. static int y=10;
5. return &y;
6. }
7. int main()
8. {
9. int *p=fun();
10. printf("%d", *p);
11. return 0;
12. }
The above code is similar to the previous one but the only difference is that the variable 'y' is static. We know
that static variable stores in the global memory.
Output
The above diagram shows the stack memory. First, the fun() function is called, then the control moves to
the context of the int *fun(). As 'y' is a static variable, so it stores in the global memory; Its scope is available
throughout the program. When the address value is returned, then the control comes back to the context
of the main(). The pointer 'p' contains the address of 'y', i.e., 100. When we print the value of '*p', then it
prints the value of 'y', i.e., 10. Therefore, we can say that the pointer 'p' is not a dangling pointer as it contains
the address of the variable which is stored in the global memory.
The dangling pointer errors can be avoided by initializing the pointer to the NULL value. If we assign
the NULL value to the pointer, then the pointer will not point to the de-allocated memory.
Assigning NULL value to the pointer means that the pointer is not pointing to any memory location.
sizeof() operator in C
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type
specified in the number of char-sized storage units. The sizeof() operator contains a single operand which
can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The
data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer
data types and compound data types such as unions and structs.
Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type
is constant, it varies when implemented in different platforms. For example, we dynamically allocate the
array space by using sizeof() operator:
1. int *ptr=malloc(10*sizeof(int));
In the above example, we use the sizeof() operator, which is applied to the cast of type int. We
use malloc() function to allocate the memory and returns the pointer which is pointing to this allocated
memory. The memory space is equal to the number of bytes occupied by the int data type and multiplied by
10.
The sizeof() operator behaves differently according to the type of the operand.
1. #include <stdio.h>
2. int main()
3. {
4. int x=89; // variable declaration.
5. printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable.
6. printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integer data type.
7. printf("\nsize of the character data type is %d",sizeof(char)); //Displaying the size of character data type.
8.
9. printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of floating data type.
10. return 0;
11. }
In the above code, we are printing the size of different data types such as int, char, float with the help
of sizeof() operator.
Output
1. #include <stdio.h>
2. int main()
3. {
4. double i=78.0; //variable initialization.
5. float j=6.78; //variable initialization.
6. printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expression (i+j).
7. return 0;
8. }
In the above code, we have created two variables 'i' and 'j' of type double and float respectively, and then
we print the size of the expression by using sizeof(i+j) operator.
Output
A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will
remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot
point to any other variable.
1. #include <stdio.h>
2. int main()
3. {
4. int a=1;
5. int b=2;
6. int *const ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
Output
Unit 5 : Pointer in C
In the above output, we can observe that the above code produces the error "assignment of read-only
variable 'ptr'". It means that the value of the variable 'ptr' which 'ptr' is holding cannot be changed. In the
above code, we are changing the value of 'ptr' from &a to &b, which is not possible with constant pointers.
Therefore, we can say that the constant pointer, which points to some variable, cannot point to another
variable.
Pointer to Constant
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be
changed. The address of these pointers can be changed, but the value of the variable that the pointer points
cannot be changed.
o First, we write the code where we are changing the value of a pointer
1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%u",ptr);
10. return 0;
11. }
Unit 5 : Pointer in C
In the above code:
o We declare two variables, i.e., a and b with the values 100 and 200 respectively.
o We declare a pointer to constant.
o First, we assign the address of variable 'a' to the pointer 'ptr'.
o Then, we assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we try to print the value of 'ptr'.
Output
The above code runs successfully, and it shows the value of 'ptr' in the output.
o Now, we write the code in which we are changing the value of the variable to which the pointer
points.
1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&b;
8. *ptr=300;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
o We declare two variables, i.e., 'a' and 'b' with the values 100 and 200 respectively.
o We declare a pointer to constant.
o We assign the address of the variable 'b' to the pointer 'ptr'.
o Then, we try to modify the value of the variable 'b' through the pointer 'ptr'.
o Lastly, we try to print the value of the variable which is pointed by the pointer 'ptr'.
Output
Unit 5 : Pointer in C
The above code shows the error "assignment of read-only location '*ptr'". This error means that we cannot
change the value of the variable to which the pointer is pointing.
A constant pointer to a constant is a pointer, which is a combination of the above two pointers. It can neither
change the address of the variable to which it is pointing nor it can change the value placed at this address.
Syntax
1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int b=90;
6. const int* const ptr=&a;
7. *ptr=12;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
o We declare two variables, i.e., 'a' and 'b' with the values 10 and 90, respectively.
o We declare a constant pointer to a constant and then assign the address of 'a'.
o We try to change the value of the variable 'a' through the pointer 'ptr'.
o Then we try to assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we print the value of the variable, which is pointed by the pointer 'ptr'.
Output
Unit 5 : Pointer in C
The above code shows the error "assignment of read-only location '*ptr'" and "assignment of read-only
variable 'ptr'". Therefore, we conclude that the constant pointer to a constant can change neither address
nor value, which is pointing by this pointer.
void pointer in C
Till now, we have studied that the address assigned to a pointer should be of the same type as specified in
the pointer declaration. For example, if we declare the int pointer, then this int pointer cannot point to the
float variable or some other type of variable, i.e., it can point to only int type variable. To overcome this
problem, we use a pointer to void. A pointer to void means a generic pointer that can point to any data type.
We can assign the address of any data type to the void pointer, and a void pointer can be assigned to any
type of the pointer without performing any explicit typecasting.
1. void *ptr;
In the above declaration, the void is the type of the pointer, and 'ptr' is the name of the pointer.
p=fp; // incorrect.
fp=&i; // incorrect
ptr=p; // correct
ptr=fp; // correct
Unit 5 : Pointer in C
ptr=&i; // correct
The size of the void pointer in C is the same as the size of the pointer of character type. According to C
perception, the representation of a pointer to void is the same as the pointer of character type. The size of
the pointer will vary depending on the platform that you are using.
1. #include <stdio.h>
2. int main()
3. {
4. void *ptr = NULL; //void pointer
5. int *p = NULL;// integer pointer
6. char *cp = NULL;//character pointer
7. float *fp = NULL;//float pointer
8. //size of void pointer
9. printf("size of void pointer = %d\n\n",sizeof(ptr));
10. //size of integer pointer
11. printf("size of integer pointer = %d\n\n",sizeof(p));
12. //size of character pointer
13. printf("size of character pointer = %d\n\n",sizeof(cp));
14. //size of float pointer
15. printf("size of float pointer = %d\n\n",sizeof(fp));
16. return 0;
17. }
Output
1. #include <stdio.h>
2. #include<malloc.h>
3. int main()
4. {
5. int a=90;
6.
7. int *x = (int*)malloc(sizeof(int)) ;
8. x=&a;
9. printf("Value which is pointed by x pointer : %d",*x);
10. return 0;
11. }
Output
o The void pointer in C can also be used to implement the generic functions in C.
The void pointer in C cannot be dereferenced directly. Let's see the below example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. void *ptr;
6. ptr=&a;
7. printf("Value which is pointed by ptr pointer : %d",*ptr);
8. return 0;
9. }
In the above code, *ptr is a void pointer which is pointing to the integer variable 'a'. As we already know that
the void pointer cannot be dereferenced, so the above code will give the compile-time error because we are
printing the value of the variable pointed by the pointer 'ptr' directly.
Output
Unit 5 : Pointer in C
1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. void *ptr;
6. ptr=&a;
7. printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
8. return 0;
9. }
In the above code, we typecast the void pointer to the integer pointer by using the statement given below:
(int*)ptr;
Then, we print the value of the variable which is pointed by the void pointer 'ptr' by using the statement
given below:
*(int*)ptr;
Output
We cannot apply the arithmetic operations on void pointers in C directly. We need to apply the proper
typecasting so that we can perform the arithmetic operations on the void pointers.
The above code shows the compile-time error that "invalid use of void expression" as we cannot apply the
arithmetic operations on void pointer directly, i.e., ptr=ptr+1.
1. #include<stdio.h>
2. int main()
3. {
4. float a[4]={6.1,2.3,7.8,9.0};
5. void *ptr;
6. ptr=a;
7. for(int i=0;i<4;i++)
8. {
9. printf("%f,",*((float*)ptr+i));
10. }}
The above code runs successfully as we applied the proper casting to the void pointer, i.e., (float*)ptr and
then we apply the arithmetic operation, i.e., *((float*)ptr+i).
Output
We use void pointers because of its reusability. Void pointers can store the object of any type, and we can
retrieve the object of any type by using the indirection operator with proper typecasting.
Output
C dereference pointer
As we already know that "what is a pointer", a pointer is a variable that stores the address of another
variable. The dereference operator is also known as an indirection operator, which is represented by (*).
When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a
pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be
returned.
o It can be used to access or manipulate the data stored at the memory location, which is pointed by
the pointer.
o Any operation applied to the dereferenced pointer will directly affect the value of the variable that it
points to.
1. int x =9;
o Now, we declare the integer pointer variable.
1. int *ptr;
o After the declaration of an integer pointer variable, we store the address of 'x' variable to the pointer
variable 'ptr'.
1. ptr=&x;
o We can change the value of 'x' variable by dereferencing a pointer 'ptr' as given below:
1. *ptr =8;
The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to the 'x' location and
dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.
1. #include <stdio.h>
2. int main()
3. {
4. int x=9;
5. int *ptr;
6. ptr=&x;
7. *ptr=8;
8. printf("value of x is : %d", x);
9. return 0;}
Output
1. #include <stdio.h>
2. int main()
3. {
Unit 5 : Pointer in C
4. int x=4;
5. int y;
6. int *ptr;
7. ptr=&x;
8. y=*ptr;
9. *ptr=5;
10. printf("The value of x is : %d",x);
11. printf("\n The value of y is : %d",y);
12. return 0;
13. }
o We declare two variables 'x' and 'y' where 'x' is holding a '4' value.
o We declare a pointer variable 'ptr'.
o After the declaration of a pointer variable, we assign the address of the 'x' variable to the pointer
'ptr'.
o As we know that the 'ptr' contains the address of 'x' variable, so '*ptr' is the same as 'x'.
o We assign the value of 'x' to 'y' with the help of 'ptr' variable, i.e., y=*ptr instead of using the 'x'
variable.
Output
1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. int *ptr1,*ptr2;
6. ptr1=&a;
7. ptr2=&a;
8. *ptr1=7;
9. *ptr2=6;
Unit 5 : Pointer in C
10. printf("The value of a is : %d",a);
11. return 0;
12. }
Output
A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the
segment. The null pointer basically stores the Null value while void is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null means that the
pointer is referring to the 0th memory location.
If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When
a NULL value is assigned to the pointer, then it is considered as a Null pointer.
o It is used to initialize o pointer variable when the pointer does not point to a valid memory address.
o It is used to perform error handling with pointers before dereferencing the pointers.
o It is passed as a function argument and to return from a function when we do not want to pass the
actual memory address.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. printf("Address: %d", ptr); // printing the value of ptr.
6. printf("Value: %d", *ptr); // dereferencing the illegal pointer
7. return 0;
8. }
In the above code, we declare the pointer variable *ptr, but it does not contain the address of any variable.
The dereferencing of the uninitialized pointer variable will show the compile-time error as it does not point
any variable. According to the stack memory concept, the local variables of a function are stored in the stack,
and if the variable does not contain any value, then it shows the garbage value. The above program shows
some unpredictable results and causes the program to crash. Therefore, we can say that keeping an
uninitialized pointer in a program can cause serious harm to the computer.
We can avoid the above situation by using the Null pointer. A null pointer is a pointer pointing to the
0th memory location, which is a reserved memory and cannot be dereferenced.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=NULL;
5. if(ptr!=NULL)
6. {
7. printf("value of ptr is : %d",*ptr);
8. }
9. else
10. {
11. printf("Invalid pointer");
12. }
13. return 0;
14. }
In the above code, we create a pointer *ptr and assigns a NULL value to the pointer, which means that it
does not point any variable. After creating a pointer variable, we add the condition in which we check
whether the value of a pointer is null or not.
Unit 5 : Pointer in C
o When we use the malloc() function.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. ptr=(int*)malloc(4*sizeof(int));
6. if(ptr==NULL)
7. {
8. printf("Memory is not allocated");
9. }
10. else
11. {
12. printf("Memory is allocated");
13. }
14. return 0;
15. }
In the above code, we use the library function, i.e., malloc(). As we know, that malloc() function allocates
the memory; if malloc() function is not able to allocate the memory, then it returns the NULL pointer.
Therefore, it is necessary to add the condition which will check whether the value of a pointer is null or not,
if the value of a pointer is not null means that the memory is allocated.
C Function Pointer
As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer
pointing to a function. The code of a function always resides in memory, which means that the function has
some address. We can get the address of memory by using the function pointer.
1. #include <stdio.h>
2. int main()
3. {
4. printf("Address of main() function is %p",main);
5. return 0;
6. }
Output
Unit 5 : Pointer in C
In the above output, we observe that the main() function has some address. Therefore, we conclude that
every function has some address.
Till now, we have seen that the functions have addresses, so we can create pointers that can contain these
addresses, and hence can point them.
For example:
In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an
integer value as an argument.
In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts a
float value as an argument.
We can observe that the declaration of a function is similar to the declaration of a function pointer except
that the pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function rather than a
pointer.
Till now, we have learnt how to declare the function pointer. Our next step is to assign the address of a
function to the function pointer.
In the above declaration, 'fp' pointer contains the address of the 'func' function.
Unit 5 : Pointer in C
Calling a function through a function pointer
We already know how to call a function in the usual way. Now, we will see how to call a function using a
function pointer.
Or
1. result = fp(a , b); // Calling a function using function pointer, and indirection operator can be re
moved.
The effect of calling a function by its name or function pointer is the same. If we are using the function
pointer, we can omit the indirection operator as we did in the second case. Still, we use the indirection
operator as it makes it clear to the user that we are using a function pointer.
1. #include <stdio.h>
2. int add(int,int);
3. int main()
4. {
5. int a,b;
6. int (*ip)(int,int);
7. int result;
8. printf("Enter the values of a and b : ");
9. scanf("%d %d",&a,&b);
10. ip=add;
11. result=(*ip)(a,b);
12. printf("Value after addition is : %d",result);
13. return 0;
14. }
15. int add(int a,int b)
16. {
17. int c=a+b;
Unit 5 : Pointer in C
18. return c;
19. }
Output
We can pass the function's address as an argument to other functions in the same way we send other
arguments to the function.
1. include <stdio.h>
2. void func1(void (*ptr)());
3. void func2();
4. int main()
5. {
6. func1(func2);
7. return 0;
8. }
9. void func1(void (*ptr)())
10. {
11. printf("Function1 is called");
12. (*ptr)();
13. }
14. void func2()
15. {
16. printf("\nFunction2 is called");
17. }
In the above code, we have created two functions, i.e., func1() and func2(). The func1() function contains
the function pointer as an argument. In the main() method, the func1() method is called in which we pass
the address of func2. When func1() function is called, 'ptr' contains the address of 'func2'. Inside the func1()
function, we call the func2() function by dereferencing the pointer 'ptr' as it contains the address of func2.
Output
Unit 5 : Pointer in C
Function pointers are used in those applications where we do not know in advance which function will be
called. In an array of function pointers, array takes the addresses of different functions, and the appropriate
function will be called based on the index number.
1. #include <stdio.h>
2. float add(float,int);
3. float sub(float,int);
4. float mul(float,int);
5. float div(float,int);
6. int main()
7. {
8. float x; // variable declaration.
9. int y;
10. float (*fp[4]) (float,int); // function pointer declaration.
11. fp[0]=add; // assigning addresses to the elements of an array of a function pointer.
12. fp[1]=sub;
13. fp[2]=mul;
14. fp[3]=div;
15. printf("Enter the values of x and y :");
16. scanf("%f %d",&x,&y);
17. float r=(*fp[0]) (x,y); // Calling add() function.
18. printf("\nSum of two values is : %f",r);
19. r=(*fp[1]) (x,y); // Calling sub() function.
20. printf("\nDifference of two values is : %f",r);
21. r=(*fp[2]) (x,y); // Calliung sub() function.
22. printf("\nMultiplication of two values is : %f",r);
23. r=(*fp[3]) (x,y); // Calling div() function.
24. printf("\nDivision of two values is : %f",r);
25. return 0;
26. }
Unit 5 : Pointer in C
27.
28. float add(float x,int y)
29. {
30. float a=x+y;
31. return a;
32. }
33. float sub(float x,int y)
34. {
35. float a=x-y;
36. return a;
37. }
38. float mul(float x,int y)
39. {
40. float a=x*y;
41. return a;
42. }
43. float div(float x,int y)
44. {
45. float a=x/y;
46. return a;
47. }
In the above code, we have created an array of function pointers that contain the addresses of four functions.
After storing the addresses of functions in an array of function pointers, we call the functions using the
function pointer.
Output
Unit 5 : Pointer in C
Function pointer as argument in C
Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We
cannot pass the function as an argument to another function. But we can pass the reference of a function as
a parameter by using a function pointer. This process is known as call by reference as the function parameter
is passed as a pointer that holds the address of arguments. If any change made by the function using pointers,
then it will also reflect the changes at the address of the passed variable.
Therefore, C programming allows you to create a pointer pointing to the function, which can be further
passed as an argument to the function. We can create a function pointer as follows:
1. (type) (*pointer_name)(parameter);
In the above syntax, the type is the variable type which is returned by the function, *pointer_name is the
function pointer, and the parameter is the list of the argument passed to the function.
A function pointer can also point to another function, or we can say that it holds the address of another
function.
In the above case, we have declared a function named as 'add'. We have also declared the function pointer
(*a) which returns the floating-type value, and contains two parameters of integer type. Now, we can assign
the address of add() function to the 'a' pointer as both are having the same return type(float), and the same
type of arguments.
Now, 'a' is a pointer pointing to the add() function. We can call the add() function by using the pointer, i.e.,
'a'. Let's see how we can do that:
1. a(2, 3);
The above statement calls the add() function by using pointer 'a', and two parameters are passed in 'a', i.e.,
2 and 3.
Let's see a simple example of how we can pass the function pointer as a parameter.
Output
Now, we will pass the function pointer as a argument in Quicksort function "qsort". It uses an algorithm
that sorts an array.
Unit 5 : Pointer in C
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. #include<string.h>
5. int compare(const int *p, const int *q);
6. int (*f)(const void *a, const void *b);
7. int main()
8. {
9. int a[]={4,7,6,1,3,2};
10. int num=sizeof(a)/sizeof(int);
11. f=&compare;
12. qsort(a, num, sizeof(int), (*f));
13. for(int i=0;i<num;i++)
14. {
15. printf("%d ,",a[i]);
16. }
17.
18. }
19.
20. int compare(const int *p, const int *q)
21. {
22. if (*p == *q)
23. return 0;
24. else if (*p < *q)
25. return -1;
26. else
27. return 1;
28. }
o We have defined an array of integer type. After creating an array, we have calculated the size of an
array by using the sizeof() operator, and stores the size in the num
o We define a compare() function, which compares all the elements in an array and arranges them in
ascending order.
o We also have declared the function pointer, i.e., (*f), and stores the address of compare() function
in (*f) by using the statement f=&compare.
o We call qsort() function in which we pass the array, size of the array, size of the element, and the
comparison function. The comparison function, i.e., compare() will compare the array elements until
the elements in an array get sorted in ascending order.
Unit 5 : Pointer in C
Output