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

c Notes Updated

C is a procedural and general-purpose programming language developed by Dennis Ritchie in 1972, known for its simplicity, speed, and low-level memory access. It is widely used in system programming, GUI development, and has influenced many other programming languages. Key features include portability, a rich library, and support for dynamic memory allocation, making it a popular choice for beginners and experienced programmers alike.

Uploaded by

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

c Notes Updated

C is a procedural and general-purpose programming language developed by Dennis Ritchie in 1972, known for its simplicity, speed, and low-level memory access. It is widely used in system programming, GUI development, and has influenced many other programming languages. Key features include portability, a rich library, and support for dynamic memory allocation, making it a popular choice for beginners and experienced programmers alike.

Uploaded by

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

C PROGRAMMING

What is C – Introduction to C
Programming Language
C programming language is a procedural and general-purpose
programming language. It is fast and simple to learn and implement. It
was developed by Dennis Ritchie in the year of 1972.

The c programming language offers various features and functionalities


to the programmers. It includes low-level memory access, simple syntax,
and a clean style. It makes the C programming language suitable for
system programming like compiler development and operating system
development.

After C, several programming languages like PHP, JavaScript, Java, and


many others have borrowed the syntax and the features directly or
indirectly from the C language.

If someone wants to learn a programming language then he/she should


start learning the C programming language in the first place. C is the
base for programming.

Real-World Applications of C
The use of the C programming language is not limited to the
development of operating systems and applications. It is also used in
GUI development, IDE development etc. Some uses of C language are:-

 Operating Systems { Mac ,IOS , Android ,Window}


 Assemblers
 Text Editors
 Print Spoolers
 Modern Programs
 Databases
 Utilities
Hold Tight, because I am going to tell you some exciting real-world
applications of C.

1. Operating Systems:-
Advertisement

With the help of C, you can write your own operating system. Isn’t it
cool? The C programming language is used to develop windows and
linux kernels and also the Apple OS X kernel.

2. Graphical User Interface:-


It stands for Graphical User Interface. Apart from creating operating
systems, C is also used to develop popular adobe softwares such as
photoshop, premier pro, After Effects etc.

3. Embedded Systems:-
In daily life, we use different embedded systems like coffee machines,
microwaves, climate control systems etc. C makes it easy to develop
these systems.

4. Database:-
Popular database management software, MySQL was developed using
the C programming language.

5. Ease of Computation:-
C provides faster computation in programs. The implementation of
algorithms and data structures is swift in C. With the help of C, you can
perform high degree calculations such as MATLAB, Mathematica etc.

6. Gaming:-
C programming is relatively faster than Java or Python. C language has
been used in various gaming applications and graphics. Many popular
games like Tic-Tac-Toe, The Snake game, Sudoku etc. are developed
using the C language.
7. Development of New languages:-
The C language is fast and easy to understand. So many programming
languages like Java, Python, PHP etc. get influenced by this. Even the
libraries of Python are developed using C. The syntax and control
structures of PERL, PHP and C++ are based upon the C language.

8. Assemblers:-
Assemblers are mainly used to translate assembly level language to
machine level language. C also helped in developing GNU assembler.

9. Text Editors:-
C also helped in creating various text editors like Vim, Gedit etc.

Advertisement

10. Interpreters:-
You can also create language interpreters using the C programming
langauge. C helped in developing different programming language
interpreters like Python and MATLAB interpreters etc.

11. Compiler Design:-


C also helped in designing several popular compilers like Clang C,
MINGW, Apple C etc. This is one of the most popular uses of C language.
Features of C:-

1. Portability:- In C, you can execute a block of code in different


environments. Suppose, you create a program in one platform and you
are running or modifying the program in other platforms. Portability is
one of the best features of the C language.
2. Simple and Efficient:- The C programming language is easy to
implement. The syntax of the C programming language is easy to
understand. If you are confused about which programming language you
should learn as a beginner then the C programming language is the best
choice for you. It is efficient and simple to learn and use.
Advertisement

3. Speed:- It compiles and executes faster than Java or Python. Because


C is a compiler based programming language and Java and Python are
an interpreter based programming language.
4. Popular:- The C programming language is used in making operating
systems and embedded systems. It is one of the most widely used
programming languages in the world.
5. Rich Library:- The C programming language has a rich library which
offers useful built-in functions. Apart from these functions, you can also
add or define user-defined functions to the library. These functions help
in solving numerous types of problems easily and also help in better and
clean coding.
6. Dynamism:- The C programming language supports dynamic
memory allocation. It is used for utilizing and managing memory. C
library has some functions such as malloc(), calloc(), free() etc. to
perform dynamic memory allocation.
7. Case Sensitive:- C programming language is case sensitive. If we
declare two variables such as “X” and “x” as an integer then the C
language treats these two variables differently.
8. Pointer:- Pointer is one of the most useful features in C. With
pointers, you can work with the memory in C. You can also use pointers
with arrays, structures, functions etc.
9. Recursion:- In C, you can define a function inside of a function. This
technique is called Recursion. This will help you in code reusability.
10. Middle-Level Language:- It has features of high-level languages
and it has capabilities of assembly language.
11. General-Purpose Language:- The C programming language is
being used in various domains like photo editing software to system
programming. Also, it is used to develop databases such as MySQL,
PostgreSQL, Oracle etc.
Why is C popular?
The C programming language has left marks in pretty much every area
of Science and Technology. C is easy to understand and the syntax of the
C language is simple. That’s what makes C popular. Almost every
renowned and successful programmer is very much familiar with the C
programming language.

C language has a vast collection of built-in functions which will make


your coding a lot easier. It also supports dynamic memory allocation.
This is a compiler-based programming language. It is faster than
interpreter-based languages like Java or Python.

Advertisement

Working of C programming language:-


The C programming language is a compiled language. A compiler first
compiles the program code and then it converts it into the object code
which is machine-readable. Then the linker will combine different object
files and it produces an executable to run the program.

Following is a diagram of executing a C program code.


Below is the list of some compilers:-

 Clang Compiler
 MinGW Compiler
 Turbo C etc.
Advertisement

Why you should learn C:-


As we said earlier, the C programming language is the base for
programming languages. Nowadays, the C programming language is
being used widely all over the world. The C language is a faster and
much simpler language. C language is also known as a structured
programming language. That’s why C is easy to debug and test.

The C programming language contains 32 keywords, a set of powerful


built-in functions, several data types which makes the C very useful and
powerful. In C, you can also make use of user-defined functions. This
helps you with complex programming.

History of C programming language:-


The father of programming languages is ALGOL. It came in the year
1960. With the help of ALGOL, the developer community learned about
the concept of structured programming language.

In the year of 1967, a new programming language named BCPL was


introduced. BCPL stands for Basic Combined Programming Language. It
is specially used for writing system software.
After 3 long years, a new programming language called B was created
by Ken Thompson. It contained multiple features of BCPL. These two
programming languages such as B and BCPL were also known as system
programming languages.

In 1972, a great computer scientist named Dennis Ritchie created the C


programming language. It includes all the features of B, BCPL,
ALGOL, and many more additional features too. That’s what makes it
unique compared to these languages. Most of the UNIX operating
systems are created using the C language.
Nowadays, the C is used on a variety of operating systems and hardware
platforms. In the year 1990, C was approved by the International
Standards Organization(ISO). C language is also known as ‘ANSI C’.

Preprocessor directive-it attach header file with program


Stdio.h-Header file- Standard Input-Output
Structure of C Program
Documentation section
//print hello program – comments
/* gmtl
*/
Link Section
#include<stdio.h> - standard input output
header file

Global variable declaration

Main() function

int main()
{
Declaration part;
Executable part;
return 0;
}
Function definition;

Structure of C programming
language:-
Following is a basic example of C language:-

Commands Meaning

#include<stdio.h It helps you to include the stdio.h header file into your program. With this,
> you can perform input/output operations.

int main() From here the execution of the C program starts. It is the main() function.

{ Used for indicating the beginning of the main() function.

/* comments */ If you write something inside this ‘/* */’ then it won’t get executed.

printf(“Hello
Used for printing the output to the screen.
World”);

return 0; Used for terminating a C program and it returns 0.

} Used for indicating the end of the main() function.

Including header files:-


Advertisement

In a C program code, at first you have to include a header file. To


execute the program, you must include a header file into your program
code.

Below are some of the header files:-


 stddef.h – Used for defining various types and macros.
 stdint.t – Used for defining exact width integer types.
 stdio.h – Used for defining input and output functions.
 stdlib.h – Used for defining numeric conversion functions,
pseudo-random network generator, memory allocation.
 string.h – Used for defining string handling functions.
 math.h – Used for defining mathematical functions.
Main Method Declaration:-
In C, you will have to declare a main method after including the header
file.
Syntax:-

int main()

{}

Variable Declaration:-
Next, you have to declare some variables to start with the program code.
In C, you cannot use any variables if you have not declared it first.

Example:-

int main(){

float a;

int f;

Body:-
Advertisement

In body, you write codes to perform a specific task or operation such as


manipulations, searching, sorting, printing etc.

Example:-

int main(){
float a = 2.3;

printf("%d",a);

Return Statement:-
It is the last part of each and every C program. It depends on the return
type of the function. Return Statement is used for returning values from
a function. If the return type is void then you don’t have to write the
return statement in the program code.

int main(){

float a = 2.3;

printf("%d",a);

return 0;

What is a Compiler:-
You can say that a compiler is a computer program that is used for
converting the program code to machine understandable code. It is
software that converts the code to machine-friendly language.

The high-level language is machine-independent and is human readable.


So, we have to convert a low-level language to a high-level language.
Through compilation, a high-level language gets converted to a low-level
language.

Advantages of C:-
1. Portability:- In C, you can execute a block of code in different
environments. Suppose, you create a program in one platform and you
are running or modifying the program in other platforms. Portability is
one of the best features of the C programming language.
2. Simple and Efficient:- The C programming language is easy to
implement. The syntax of the C language is easy to understand. If you
are confused about which programming language you should learn as a
beginner then the C language is the best choice for you. It is efficient
and simple to learn and use.
3. Speed:- It compiles and executes faster than Java or Python. Because
C is a compiler-based programming language and Java and Python are
interpreter-based programming languages.
4. Popular:- The C language is used in making operating systems and
embedded systems. It is one of the most widely used programming
languages in the world.
5. Rich Library:- The C language has a rich library that offers useful
built-in functions. Apart from these functions, you can also add or define
user-defined functions to the library. These functions help in solving
numerous types of problems easily and also help in better and clean
coding.
Advertisement

6. Recursion:- In C, you can define a function inside of a function. This


technique is called Recursion. This will help you in code reusability.
7. Structured/Modular Programming language:- In C, you can break
the program into small blocks of code with the help of a function.
Instead of writing a long and complex code, you can divide the program
into small blocks of code as functions then you can perform multiple
tasks such as finding the area of square, rectangle, circle etc. A function
is used for code reusability.

How to Install VS Code:


You have to download Visual Studio Code directly from the official website: https://code.visualstudio.com/.
If you want, you can also install VS Code Insiders, and the same process is applicable for that as well.
Visual Studio Code Insiders is actually the "Insiders" build of Visual Studio Code, which contains all the latest
features that are shipped daily. You can think of VS Code as the stable release and the VS Code Insiders as the
Insiders release of that.
If you want to experience the latest updates instantly, then you might also try Visual Studio Code Insiders (I use it
myself). For downloading VS Code Insiders, you can visit the official website for VS Code Insiders
here: https://code.visualstudio.com/insiders/
Make sure to download the exact file for your operating system.
Download Page: VS Code

Download Page: VS Code Insiders


The installation process is pretty basic. But I am going to show you all the steps sequentially. For now, I am going
to show you the installation process using VS Code Insiders, but everything you will see here is going to be
exactly the same for VS Code as well.
Make sure to click the box on the "I accept the agreement " box and click on Next.

Accept the agreement and click Next


Keep everything as it is. Do not change anything from here.
Click Next
Click Next. Again, simply click Next.
Click
Next
Make sure to add the checkmark (✔) on all of the boxes. Then click on Next.
Check all of the boxes, and click Next
Click on Install.
Click Install
It might take a little time to finish the installation.
Let it finish...
Click on Finish.
Clic
k Finish
Congrats - you've successfully installed VS Code/VS Code Insiders on your system. Now, cheers! 🥂
How to Prepare VS Code/VS Code Insiders For C and C++ Code
First, open VS Code or VS Code Insiders.
Go to the Extension tab. Search for "C" or "C++" and install the first one that is already verified by Microsoft
itself.
Install C/C++ extension
Also, install C/C++ Extension Pack. It should also be verified by Microsoft.

Install C/C++ Extension Pack


Then you have to search for Code Runner and install the extension as well.
Install Code Runner Extension
Now, we need to change some settings.

Change some settings


Click the gear box (It is called the Manage section), and then click Settings. Alternatively, you can also use the
shortcut keys Ctrl + ,. You need to replace the Ctrl key with the Command key for Mac.
Type "Run code in terminal" and press Enter key
In the search bar, type "Run code in terminal" and press the Enter key.
Scroll down a little bit until you find Code-runner: Run In Terminal. Make sure that the box is checked (✔).

Make sure to check the box


Now you need to restart your VS Code/VS Code Insiders. Simply close and reopen the program.
How to Test Your Code
Simply open VS Code/VS Code Insiders, open any folder, and create any file with the extension .c for the C file
and .cpp for the C++ file.
After writing your code, you can run the code directly using the play button you'll find in the upper right corner.
First C Program
// print Hello C Language

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

#include <stdio.h> includes the standard input output library functions. The printf() function is defined
in stdio.h .

int main() The main() function is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.

The following are the phases through which our program passes before being
transformed into an executable form:

o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code
file is given an extension ".c". This source code is first passed to the preprocessor,
and then the preprocessor expands this code. After expanding the code, the
expanded code is passed to the compiler.

Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.

Assembler
The assembly code is converted into object code by using an assembler. The name
of the object file generated by the assembler is the same as the source file. The
extension of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the
name of the source file is 'hello.c', then the name of the object file would be
'hello.obj'.

Linker
Mainly, all the programs written in C use library functions. These library functions
are pre-compiled, and the object code of these library files is stored with '.lib' (or
'.a') extension. The main working of the linker is to combine the object code of
library files with the object code of our program. Sometimes the situation arises
when our program refers to the functions defined in other files; then linker plays a
very important role in this. It links the object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object code of our
program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the
source file but differs only in their extensions. In DOS, the extension of the
executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'.
For example, if we are using printf() function in a program, then the linker adds its
associated code in an output file.

Let's understand through an example.

hello.c

1. // Print Hello world


2. #include <stdio.h>
3. int main()
4. {
5. printf("Hello World");
6. return 0;
7. }

Now, we will create a flow diagram of the above program:


Comments in C
used for documenting code. There are 2 types of comments in the C language.

1. Single Line Comments


2. Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of a
single line comment in C.

// Print Hello World

1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello World");
5. return 0;
6. }

Output:

Hello C

Even you can place the comment after the statement. For example:

1. printf("Hello C");//printing information

Mult Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many
lines of code, but it can't be nested. Syntax:

1. /*
2. code
3. to be commented
4. */

Let's see an example of a multi-Line comment in C.

1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi-Line Comment*/
5. printf("Hello C");
6. return 0;
7. }

Output:

Hello C

printf() and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).

printf() function
The printf() function is used for output. It prints the given statement to the
console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",&argument_list);
Program to print cube of given number
Let's see a simple example of c language that gets input from the user and prints
the cube of the given number.

1. #include<stdio.h>
2. int main(){
3. int number,cb;
4. printf("enter a number:");
5. scanf("%d",&number);
6. cb= number*number*number;
7. printf("cube of number is:%d ",cb);
8. return 0;
9. }

Output
enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console


and stores the given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement


prints the cube of number on the console.

Program to print sum of 2 numbers


Let's see a simple example of input and output in C language that prints addition
of 2 numbers.

1. #include<stdio.h>
2.
3. int main(){
4. int x,,y,result;
5.
6. printf("enter first number:");
7. scanf("%d",,&x);
8. printf("enter second number:");
9. scanf("%d",,&y);
10.
11.result=x+y;
12. printf("sum of 2 numbers:%d ",result);
13.
14. return 0;
15.}

Output

enter first number:9


enter second number:9
sum of 2 numbers:18

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can
be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily


identified.

Let's see the syntax to declare a variable:©


1. datatype variable_list;

The example of declaring the variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with
a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 2;
2. int a b;
3. int long;

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable
A variable that is declared outside the function or block is called a global variable.
Any function can change the value of the global variable. It is available to all the
functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }
Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }

If you call this function many times, the local variable will print the same
value for each function call, e.g, 11,11,11 and so on. But the static variable will
print the incremented value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by
default. We can explicitly declare an automatic variable using auto keyword.

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
External Variable
We can share a variable in multiple C source files by using an external variable. To
declare an external variable, you need to us extern keyword.

myfile.h

1. extern int x=10;//external variable (also global)


program1.c

1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }

Tokens in C
Tokens in C is the most important element to be used in creating a program in C.
We can define the token as the smallest individual element in C. For `example, we
cannot create a sentence without using words; similarly, we cannot create a
program in C without using tokens in C. Therefore, we can say that tokens in C is
the building block or the basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:


o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C

Let's understand each token one by one.

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having


its own importance, and each keyword has its own functionality. Since keywords
are the pre-defined words used by the compiler, so they cannot be used as the
variable names. If the keywords are used as the variable names, it means that we
are assigning a different meaning to the keyword, which is not allowed. C language
supports 32 keywords given below:

Auto double Int Struct

Break else long Switch

Case enum register Typedef

Char extern return Union

Const float short Unsigned

Continue for signed Void


Default goto sizeof Volatile

Do If static While

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase
letters, lowercase letters, underscore, or digits, but the starting letter should be
either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules
for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore,


and then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.

Strings in C

Strings in C are always represented as an array of characters having null character


'\0' at the end of the string. This null character denotes the end of the string.
Strings in C are enclosed within double quotes, while characters are enclosed
within single characters. The size of a string is a number of characters that the
string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form


of characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items
on which the operators are applied are known as operands. Operators are applied
between the operands. Depending on the number of operands, operators are
classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example:


increment operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is
the list of the binary operators:

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword : const float pi=3.14


o Using #define pre-processor #define PI 3.14

Types of constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.


String constant "java", "c++", ".net", etc.

Special characters in C

Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes
that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.


Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type Void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647


signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

Float 4 byte

Double 8 byte

long double 10 byte

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant
name, etc. There are only 32 reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

Auto Break Case char const continue default do

double Else Enum extern float for goto if

Int Long register return short signed sizeof static

Struct Switch typedef union unsigned void volatile while

C Identifiers
C identifiers represent the name in the C program, for example, variables,
functions, arrays, structures, unions, labels, etc. An identifier can be composed of
letters such as uppercase, lowercase letters, underscore, digits, but the starting
letter should be either an alphabet or an underscore. If the identifier is not used in
the external linkage, then it is called as an internal identifier. If the identifier is
used in the external linkage, then it is called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins


either with an alphabetical character or an underscore, which are used to
represent various programming elements such as variables, functions, arrays,
structures, unions, labels, etc. There are 52 alphabetical characters (uppercase
and lowercase), underscore character, and ten numerical digits (0-9) that
represent the identifiers. There is a total of 63 alphanumerical characters that
represent the identifiers.

Rules for constructing C identifiers


o The first character of an identifier should be either an alphabet or an underscore,
and then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1. 2sum (starts with a numerical digit)


2. int (reserved word)
3. char (reserved word)
4. m+n (special character, i.e., '+')

Types of identifiers
o Internal identifier
o External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external


identifier. The external identifiers can be function names, global variables.

Differences between Keyword and Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word


It must be written in a lowercase It can be written in both lowercase and
letter. uppercase letters.

Its meaning is pre-defined in the Its meaning is not defined in the c


c compiler. compiler.

It is a combination of It is a combination of alphanumeric


alphabetical characters. characters.

It does not contain the It can contain the underscore character.


underscore character.

Let's understand through an example.

1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }

Output

Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are
different. Therefore, we conclude that the identifiers are case sensitive.

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

Arithmetic Operators in C

Arithmetic Operators are the type of operators in C that are used to


perform mathematical operations in a C program. They can be used in
programs to define expressions and mathematical formulas.

What are C Arithmetic Operators?


The C arithmetic operators are the symbols that are used to perform
mathematical operations on operands. There are a total of 9 arithmetic
operators in C to provide the basic arithmetic operations such as addition,
subtraction, multiplication, etc.

Types of Arithmetic Operators in C


The C Arithmetic Operators are of two types based on the number of
operands they work. These are as follows:
1. Binary Arithmetic Operators
2. Unary Arithmetic Operators

1. Binary Arithmetic Operators in C


The C binary arithmetic operators operate or work on two operands. C
provides 5 Binary Arithmetic Operators for performing arithmetic functions
which are as follows:
Name of the
Operator Operator Arithmetic Operation Syntax

+ Addition Add two operands. x+y

Subtraction Subtract the second operand from the first


– operand. x–y

* Multiplication Multiply two operands. x*y

/ Division Divide the first operand by the second operand. x/y

Calculate the remainder when the first operand is


% Modulus divided by the second operand. x%y
// C program to demonstrate syntax of binary arithmetic
// operators
#include <stdio.h>

int main()
{
int a = 10, b = 4, res;

// printing a and b
printf("a is %d and b is %d\n", a, b);

res = a + b; // addition
printf("a + b is %d\n", res);

res = a - b; // subtraction
printf("a - b is %d\n", res);

res = a * b; // multiplication
printf("a * b is %d\n", res);

res = a / b; // division
printf("a / b is %d\n", res);

res = a % b; // modulus
printf("a %% b is %d\n", res);

return 0;
}

Output
a is 10 and b is 4
a + b is 14
a - b is 6
a * b is 40
a / b is 2
a % b is 2
2. Unary Arithmetic Operators in C
The unary arithmetic operators operate or work with a single operand. In C,
we have two unary arithmetic operators which are as follows:

Symbo
Operator l Operation Implementation

Decrement Decreases the integer value of the


— –h or h–
Operator variable by one.

Increment Increases the integer value of the


++ ++h or h++
Operator variable by one.

Unary Plus
+ Returns the value of its operand. +h
Operator

Unary Minus Returns the negative of the value of its


– -h
Operator operand.

Increment Operator in C

The ‘++’ operator is used to increment the value of an integer. It can be


used in two ways:
1. Pre-Increment
When placed before the variable name (also called the pre-
increment operator), its value is incremented instantly. Consider the
example:
a = ++x;
This example can be expanded to
a = (x = x + 1);
2. Post Increment
When it is placed after the variable name (also called post-
increment operator), its value is preserved temporarily until the execution of
this statement and it gets updated before the execution of the next
statement. For example:
a = x++;
It can be expanded to
a = x;
x = x + 1;

Decrement Operator in C

The ‘–‘ operator is used to decrement the value of an integer. Just like the
increment operator, the decrement operator can also be used in two ways:
1. Pre-Decrement
When placed before the variable name (also called the pre-
decrement operator), its value is decremented instantly. For example, – –
x.
2. Post Decrement
When it is placed after the variable name (also called post-
decrement operator), its value is preserved temporarily until the execution
of this statement and it gets updated before the execution of the next
statement. For example, x – –.

Example of Unary Operators in C

// C program to demonstrate working


// of Unary arithmetic
// operators
#include <stdio.h>

int main()
{
int a = 10, res;

printf("Post Increment and Decrement\n");


// post-increment example:
// res is assigned 10 only, a is not updated yet
res = a++;
printf("a is %d and result is %d\n", a,
res); // a becomes 11 now

// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
printf("a is %d and result is %d\n", a,
sizrsize res); // a becomes 10 now

printf("\nPre Increment and Decrement\n");


// pre-increment example:
// res is assigned 11 now since
// a is updated here itself
res = ++a;

// a and res have same values = 11


printf("a is %d and result is %d\n", a, res);

// pre-decrement example:
// res is assigned 10 only since a is updated here
// itself
res = --a;

// a and res have same values = 10


printf("a is %d and result is %d\n", a, res);

return 0;
}

Output
Post Increment and Decrement
a is 11 and result is 10
a is 10 and result is 11
Relational Operators
Relational operators are used for the comparison of two values to
understand the type of relationship a pair of number shares. For example,
less than, greater than, equal to, etc. Let’s see them one by one

1. Equal to operator: Represented as ‘==’, the equal to operator


checks whether the two given operands are equal or not. If so, it
returns true. Otherwise, it returns false. For example, 5==5 will
return true.
2. Not equal to operator: Represented as ‘!=’, the not equal to
operator checks whether the two given operands are equal or not.
If not, it returns true. Otherwise, it returns false. It is the exact
boolean complement of the ‘==’ operator. For example, 5!=5 will
return false.
3. Greater than operator: Represented as ‘>’, the greater than
operator checks whether the first operand is greater than the
second operand or not. If so, it returns true. Otherwise, it returns
false. For example, 6>5 will return true.
4. Less than operator: Represented as ‘<‘, the less than operator
checks whether the first operand is lesser than the second
operand. If so, it returns true. Otherwise, it returns false. For
example, 6<5 will return false.
5. Greater than or equal to operator: Represented as ‘>=’, the
greater than or equal to operator checks whether the first operand
is greater than or equal to the second operand. If so, it returns true
else it returns false. For example, 5>=5 will return true.
6. Less than or equal to operator: Represented as ‘<=’, the less
than or equal to operator checks whether the first operand is less
than or equal to the second operand. If so, it returns true else
false. For example, 5<=5 will also return true.
Examples:

C
// C program to demonstrate working of
relational operators
#include <stdio.h>

int main()
{
int a = 10, b = 4;

// greater than example


if (a > b)
printf("a is greater than b\n");
else
printf("a is less than or equal
to b\n");

// greater than equal to


if (a >= b)
printf("a is greater than or
equal to b\n");
else
printf("a is lesser than b\n");

// less than example


if (a < b)
printf("a is less than b\n");
else
printf("a is greater than or
equal to b\n");

// lesser than equal to


if (a <= b)
printf("a is lesser than or equal
to b\n");
else
printf("a is greater than b\n");

// equal to
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\
n");

// not equal to
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");

return 0;
}

Logical Operators:
They are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition under consideration.
They are described below:

1. Logical AND operator: The ‘&&’ operator returns true when both
the conditions under consideration are satisfied. Otherwise, it
returns false. For example, a && b returns true when both a and b
are true (i.e. non-zero).
2. Logical OR operator: The ‘||’ operator returns true even if one
(or both) of the conditions under consideration is satisfied.
Otherwise, it returns false. For example, a || b returns true if one
of a or b, or both are true (i.e. non-zero). Of course, it returns true
when both a and b are true.
3. Logical NOT operator: The ‘!’ operator returns true the condition
in consideration is not satisfied. Otherwise, it returns false. For
example, !a returns true if a is false, i.e. when a=0.
Examples:

C
// C program to demonstrate working of
logical operators
#include <stdio.h>

int main()
{
int a = 10, b = 4, c = 10, d = 20;
// logical operators

// logical AND example


if (a > b && c == d)
printf("a is greater than b AND c
is equal to d\n");
else
printf("AND condition not
satisfied\n");

// logical OR example
if (a > b || c == d)
printf("a is greater than b OR c
is equal to d\n");
else
printf("Neither a is greater than
b nor c is equal "
" to d\n");

// logical NOT example


if (!a)
printf("a is zero\n");
else
printf("a is not zero");

return 0;
}

sizeof operator in C

Sizeof is a much-used operator in the C. It is a compile-time unary operator


which can be used to compute the size of its operand. The result of sizeof
is of the unsigned integral type which is usually denoted by size_t. sizeof can
be applied to any data type, including primitive types such as integer and
floating-point types, pointer types, or compound datatypes such as
Structure, union, etc.
Syntax:
sizeof(Expression);
where ‘Expression‘ can be a data type or a variable of any type.
Return: It returns the size size of the given expression.
Time Complexity: O(1)
Auxiliary Space: O(1)

Usage of sizeof() operator


sizeof() operator is used in different ways according to the operand type.
1. When the operand is a Data Type: When sizeof() is used with the data
types such as int, float, char… etc it simply returns the amount of memory
allocated to that data types.
Example:
 C
// C Program To demonstrate
// sizeof operator
#include <stdio.h>
int main()
{
printf("%lu\n", sizeof(char));
printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}

Output
1
4
4
8
Note: sizeof() may give different output according to machine, we have run
our program on a 32-bit gcc compiler.
Assignment Operators in C

Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of
the assignment operator is a value. The value on the right side must be of
the same data-type of the variable on the left side otherwise the compiler
will raise an error.
Different types of assignment operators are shown below:
 “=”: This is the simplest assignment operator. This operator is used
to assign the value on the right to the variable on the left.
For example:
 a = 10;
 b = 20;
 ch = 'y';
 “+=”: This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the
value on the right and then assigns the result to the variable on the
left.
Example:
 (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
 “-=”This operator is combination of ‘-‘ and ‘=’ operators. This
operator first subtracts the current value of the variable on left from
the value on the right and then assigns the result to the variable on
the left.
Example:
 (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
 “*=”This operator is combination of ‘*’ and ‘=’ operators. This
operator first multiplies the current value of the variable on left to
the value on the right and then assigns the result to the variable on
the left.
Example:
 (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”This operator is combination of ‘/’ and ‘=’ operators. This
operator first divides the current value of the variable on left by the
value on the right and then assigns the result to the variable on the
left.
Example:
 (a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Below example illustrates the various Assignment Operators:

// C program to demonstrate
// working of Assignment operators

#include <stdio.h>

int main()
{

// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a


// using "+=" operator
a += 10;
printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a


// using "-=" operator
a -= 10;
printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a


// using "*=" operator
a *= 10;
printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a


// using "/=" operator
a /= 10;
printf("Value of a is %d\n", a);

return 0;
}

Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

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.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C Format Specifier
The Format specifier is a string used in the formatted input and output functions.
The format string determines the format of the input and output. The format
string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

Format Description
specifier

%d or %i It is used to print the signed integer value where signed


integer means that the variable can hold both positive and
negative values.

%u It is used to print the unsigned integer value where the


unsigned integer means that the variable can hold only
positive value.

%o It is used to print the octal unsigned integer where octal


integer value always starts with a 0 value.

%x It is used to print the hexadecimal unsigned integer where the


hexadecimal integer value always starts with a 0x value. In
this, alphabetical characters are printed in small letters such
as a, b, c, etc.

%X It is used to print the hexadecimal unsigned integer, but %X


prints the alphabetical characters in uppercase such as A, B,
C, etc.

%f It is used for printing the decimal floating-point values. By


default, it prints the 6 values after '.'.

%e/%E It is used for scientific notation. It is also known as Mantissa or


Exponent.

%g It is used to print the decimal floating-point values, and it uses


the fixed precision, i.e., the value after the decimal in input
would be exactly the same as the value in the output.

%p It is used to print the address in a hexadecimal form.

%c It is used to print the unsigned character.

%s It is used to print the strings.

%ld It is used to print the long-signed integer value.

Let's understand the format specifiers in detail through an example.

o %d

1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b);
6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }

In the above code, we are printing the integer value of b and c by using the %d
specifier.

Output
o %u

1. int main()
2. {
3. int b=10;
4. int c= -10;
5. printf("Value of b is:%u", b);
6. printf("\nValue of c is:%u",c);
7.
8. return 0;
9. }

In the above program, we are displaying the value of b and c by using an unsigned
format specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact
value of b, but it does not print the value of c as c contains the negative value.

Output

o %o
1. int main()
2. {
3. int a=0100;
4. printf("Octal value of a is: %o", a);
5. printf("\nInteger value of a is: %d",a);
6. return 0;
7. }

In the above code, we are displaying the octal value and integer value of a.

Output

o %x and %X

1. int main()
2. {
3. int y=0xA;
4. printf("Hexadecimal value of y is: %x", y);
5. printf("\nHexadecimal value of y is: %X",y);
6. printf("\nInteger value of y is: %d",y);
7. return 0;
8. }

In the above code, y contains the hexadecimal value 'A'. We display the
hexadecimal value of y in two formats. We use %x and %X to print the
hexadecimal value where %x displays the value in small letters, i.e., 'a' and %X
displays the value in a capital letter, i.e., 'A'.

Output
o %f

1. int main()
2. {
3. float y=3.4;
4. printf("Floating point value of y is: %f", y);
5. return 0;
6. }

The above code prints the floating value of y.

Output

o %e

1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %e", y);
5. return 0;
6. }
Output

o %E

1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %E", y);
5. return 0;
6. }

Output

o %g

1. int main()
2. {
3. float y=3.8;
4. printf("Float value of y is: %g", y);
5. return 0;
6. }

In the above code, we are displaying the floating value of y by using %g specifier.
The %g specifier displays the output same as the input with a same precision.

Output

o %p

1. int main()
2. {
3. int y=5;
4. printf("Address value of y in hexadecimal form is: %p", &y);
5. return 0;
6. }

Output

o %c

1. int main()
2. {
3. char a='c';
4. printf("Value of a is: %c", a);
5. return 0;
6. }

Output

o %s

1. int main()
2. {
3. printf("%s", "javaTpoint");
4. return 0;
5. }

Output

Minimum Field Width Specifier


Suppose we want to display an output that occupies a minimum number of spaces
on the screen. You can achieve this by displaying an integer number after the
percent sign of the format specifier.
1. int main()
2. {
3. int x=900;
4. printf("%8d", x);
5. printf("\n%-8d",x);
6. return 0;
7. }

In the above program, %8d specifier displays the value after 8 spaces while %-8d
specifier will make a value left-aligned.

Output

Now we will see how to fill the empty spaces. It is shown in the below
code:

1. int main()
2. {
3. int x=12;
4. printf("%08d", x);
5. return 0;
6. }

In the above program, %08d means that the empty space is filled with zeroes.

Output
Specifying Precision
We can specify the precision by using '.' (Dot) operator which is followed by
integer and format specifier.

1. int main()
2. {
3. float x=12.2;
4. printf("%.2f", x);
5. return 0;
6. }

Output

bi

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't
represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n


represents new line.
List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number

\xhh hexadecimal number

\0 Null

Escape Sequence Example


1. #include<stdio.h>
2. int main(){
3.
4. printf("You \n are \n learning\v \n \' c \' language \n \" Do you know \t \t
C language \?\" ");
5. return 0;
6. }

Output:

You
are
learning
'c' language
"Do you know C language?"

ASCII value in C
What is ASCII code?
The full form of ASCII is the American Standard Code for information
interchange. It is a character encoding scheme used for electronics
communication. Each character or a special character is represented by some
ASCII code, and each ascii code occupies 7 bits in memory.

In C programming language, a character variable does not contain a character


value itself rather the ascii value of the character variable. The ascii value
represents the character variable in numbers, and each character variable is
assigned with some number range from 0 to 127. For example, the ascii value of
'A' is 65.

In the above example, we assign 'A' to the character variable whose ascii value is
65, so 65 will be stored in the character variable rather than 'A'.

Let's understand through an example.

We will create a program which will display the ascii value of the
character variable.

1. #include <stdio.h>
2.
3. int main()
4. {
5. char ch; // variable declaration
6.
7. printf("\n Enter a character");
8. scanf("%c",&ch); // user input
9. printf("\n The ascii value of the ch variable is : %d", ch);
10. Return 0;
11. }

In the above code, the first user will give the character input, and the input will get
stored in the 'ch' variable. If we print the value of the 'ch' variable by using %c
format specifier, then it will display 'A' because we have given the character input
as 'A', and if we use the %d format specifier then its ascii value will be displayed,
i.e., 65.

Output
The above output shows that the user gave the input as 'A', and after giving input,
the ascii value of 'A' will get printed, i.e., 65.

Now, we will create a program which will display the ascii value of all the
characters.

1. #include <stdio.h>
2. int main()
3. {
4. int k; // variable declaration
5. for(int k=0;k<=255;k++) // for loop from 0-255
6. {
7. printf("\nThe ascii value of %c is %d", k,k);
8. }
9. return 0;
10.}

The above program will display the ascii value of all the characters. As we know
that ascii value of all the characters starts from 0 and ends at 255, so we iterate
the for loop from 0 to 255.

Now we will create the program which will sum the ascii value of a string.

1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. char name[20]; // variable initialization
6. int i=0; // variable initialization
7. printf("Enter a name: ");
8. scanf("%s", name);
9. while(name[i]!='\0') // while loop
10. {
11. printf("\nThe ascii value of the character %c is %d", name[i],name
[i]);
12. sum=sum+name[i];
13. i++;
14. }
15. printf("\nSum of the ascii value of a string is : %d", sum);
16. return 0;
17. }

In the above code, we are taking user input as a string. After taking user input, we
execute the while loop which adds the ascii value of all the characters of a string
and stores it in a 'sum' variable.

Output

Constants in C
A constant is a value or variable that can't be changed in the program, for
example: 10, 20, 'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.


Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

2 ways to define constant in C


There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.

1. const float PI=3.14;

Now, the value of PI variable can't be changed.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }

Output:
Compile Time Error: Cannot modify a const object

2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about
#define preprocessor directive later.

Visit here for: #define preprocessor directive.

What are literals?


Literals are the constant values assigned to the constant variables. We can say
that the literals represent the fixed values that cannot be modified. It also contains
memory but does not have references as variables. For example, const int =10; is
a constant integer expression in which 10 is an integer literal.

Types of literals
There are four types of literals that exist in C programming:

o Integer literal
o Float literal
o Character literal
o String literal

Integer literal

It is a numeric literal that represents only integer type values. It represents the
value neither in fractional nor exponential part.

It can be specified in the following three ways:


Decimal number (base 10)

It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.

Octal number (base 8)

It is defined as a number in which 0 is followed by digits such as 0,1,2,3,4,5,6,7.


For example, 012, 034, 055, etc.

Hexadecimal number (base 16)

It is defined as a number in which 0x or 0X is followed by the hexadecimal digits


(i.e., digits from 0 to 9, alphabetical characters from (a-z) or (A-Z)).

An integer literal is suffixed by following two sign qualifiers:

L or l: It is a size qualifier that specifies the size of the integer type as long.
U or u: It is a sign qualifier that represents the type of the integer as unsigned. An
unsigned qualifier contains only positive values.

Note: The order of the qualifier is not considered, i.e., both lu and ul are the same.

Let's look at a simple example of integer literal.

1. #include <stdio.h>
2. int main()
3. {
4. const int a=23; // constant integer literal
5. printf("Integer literal : %d", a);
6. return 0;
7. }

Output

Integer literal : 23
Float literal

It is a literal that contains only floating-point values or real numbers. These real
numbers contain the number of parts such as integer part, real part, exponential
part, and fractional part. The floating-point literal must be specified either in
decimal or in exponential form. Let's understand these forms in brief.

Decimal form

The decimal form must contain either decimal point, exponential part, or both. If it
does not contain either of these, then the compiler will throw an error. The decimal
notation can be prefixed either by '+' or '-' symbol that specifies the positive and
negative numbers.

Examples of float literal in decimal form are:

1. 1.2, +9.0, -4.5

Let's see a simple example of float literal in decimal form.

1. #include <stdio.h>
2. int main()
3. {
4. const float a=4.5; // constant float literal
5. const float b=5.6; // constant float literal
6. float sum;
7. sum=a+b;
8. printf("%f", sum);
9. return 0;
10.}

Output

10.100000
Exponential form

The exponential form is useful when we want to represent the number, which is
having a big magnitude. It contains two parts, i.e., mantissa and exponent. For
example, the number is 2340000000000, and it can be expressed as 2.34e12 in an
exponential form.

Syntax of float literal in exponential form

1. [+/-] <Mantissa> <e/E> [+/-] <Exponent>

Examples of real literal in exponential notation are:

1. +1e23, -9e2, +2e-25

Rules for creating an exponential notation

The following are the rules for creating a float literal in exponential
notation:

o In exponential notation, the mantissa can be specified either in decimal or fractional


form.
o An exponent can be written in both uppercase and lowercase, i.e., e and E.
o We can use both the signs, i.e., positive and negative, before the mantissa and
exponent.
o Spaces are not allowed

Character literal

A character literal contains a single character enclosed within single quotes. If


multiple characters are assigned to the variable, then we need to create a
character array. If we try to store more than one character in a variable, then the
warning of a multi-character character constant will be generated. Let's
observe this scenario through an example.

1. #include <stdio.h>
2. int main()
3. {
4. const char c='ak';
5. printf("%c",c);
6. return 0;
7. }
In the above code, we have used two characters, i.e., 'ak', within single quotes. So,
this statement will generate a warning as shown below.

Warning generated:

1. main.c:6:18: warning: multi-character character constant


2. [-Wmultichar]
3. const char c='ak';
4. main.c:6:18: warning: implicit conversion from 'int' to 'char'
5. changes value from 24939 to 107 [-Wconstant-conversion]
6. const char c='ak';
7. ~ ^~~~
8. 2 warnings generated.
9. ? ./main

Representation of character literal

A character literal can be represented in the following ways:

o It can be represented by specifying a single character within single quotes. For


example, 'a', 'b', etc.
o We can specify the escape sequence character within single quotes to represent a
character literal. For example, '\n', '\a', '\b'.
o We can also use the ASCII in integer to represent a character literal. For example,
the ascii value of 65 is 'A'.
o The octal and hexadecimal notation can be used as an escape sequence to
represent a character literal. For example, '\023', '\0x12'.

String literal

A string literal represents multiple characters enclosed within double-quotes. It


contains an additional character, i.e., '\0' (null character), which gets automatically
inserted. This null character specifies the termination of the string. We can use the
'+' symbol to concatenate two strings.

For example,

String1= "javatpoint";

String2= "family";

To concatenate the above two strings, we use '+' operator, as shown in the below
statement:

"javatpoint " + "family"= javatpoint family


Note: If we represent a single character, i.e., 'b', then this character will occupy a single
byte as it is a character literal. And, if we represent the character within double quotes "b"
then it will occupy more bytes as it is a string literal.

Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the
behavior of the program abnormal, and experienced developers can also make
these faults. Programming errors are also known as the bugs or faults, and the
process of removing these bugs is known as debugging.

These errors are detected either during the time of compilation or execution. Thus,
the errors must be removed from the program for the successful execution of the
program.

There are mainly five types of errors exist in C programming:

o Syntax error
o Run-time error
o Linker error
o Logical error
o Semantic error
Syntax error
Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the
compilers. These errors are mainly occurred due to the mistakes while typing or do
not follow the syntax of the specified programming language. These mistakes are
generally made by beginners only because they are new to the language. These
errors can be easily debugged or corrected.

For example:

1. If we want to declare the variable of type integer,


2. int a; // this is the correct form
3. Int a; // this is an incorrect form.

Commonly occurred syntax errors are:

o If we miss the parenthesis (}) while writing the code.


o Displaying the value of a variable without its declaration.
o If we miss the semicolon (;) at the end of the statement.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }

Output

In the above output, we observe that the code throws the error that 'a' is
undeclared. This error is nothing but the syntax error only.
There can be another possibility in which the syntax error can exist, i.e., if we
make mistakes in the basic construct. Let's understand this scenario through an
example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }

In the above code, we put the (.) instead of condition in 'if', so this generates the
syntax error as shown in the below screenshot.

Output

Run-time error
Sometimes the errors exist during the execution-time even after the successful
compilation known as run-time errors. When the program is running, and it is not
able to perform the operation is the main cause of the run-time error. The division
by zero is the common example of the run-time error. These errors are very
difficult to find, as the compiler does not point to these errors.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. int b=2/0;
6. printf("The value of b is : %d", b);
7. return 0;
8. }
Output

In the above output, we observe that the code shows the run-time error, i.e.,
division by zero.

Linker error
Linker errors are mainly generated when the executable file of the program is not
created. This can be happened either due to the wrong function prototyping or
usage of the wrong header file. For example, the main.c file contains
the sub() function whose declaration and definition is done in some other file such
as func.c. During the compilation, the compiler finds the sub() function
in func.c file, so it generates two object files, i.e., main.o and func.o. At the
execution time, if the definition of sub() function is not found in the func.o file,
then the linker error will be thrown. The most common linker error that occurs is
that we use Main() instead of main().

Let's understand through a simple example.

1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }

Output

Logical error
The logical error is an error that leads to an undesired output. These errors
produce the incorrect output, but they are error-free, known as logical errors.
These types of mistakes are mainly done by beginners. The occurrence of these
errors mainly depends upon the logical thinking of the developer. If the
programmers sound logically good, then there will be fewer chances of these
errors.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
7. {
8. sum=sum+k;
9. k++;
10. }
11. printf("The value of sum is %d", sum);
12. return 0;
13. }

Output

In the above code, we are trying to print the sum of 10 digits, but we got the
wrong output as we put the semicolon (;) after the for loop, so the inner
statements of the for loop will not execute. This produces the wrong output.

Semantic error
Semantic errors are the errors that occurred when the statements are not
understandable by the compiler.

The following can be the cases for the semantic error:

o Use of a un-initialized variable.


int i;
i=i+2;
o Type compatibility
int b = "javatpoint";
o Errors in expressions
int a, b, c;
a+b = c;
o Array index out of bound
int a[10];
a[10] = 34;

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. a=2;
6. b=3;
7. c=1;
8. a+b=c; // semantic error
9. return 0;
10.}

In the above code, we use the statement a+b =c, which is incorrect as we cannot
use the two operands on the left-side.

Output



BASIC C PROGRAMS

1. Write a C program to Print Hello World.

#include <stdio.h>
int main()
{
printf("Hello World!"); // printf() is use to display string
return 0;
}

2. Write a C program to add two integers.


#include<stdio.h>
int main()
{
int num1,num2,total;

printf("Enter first number : ");


scanf("%d",&num1);
sca
printf("Enter second number : ");
scanf("%d",&num2);

total = num1 + num2;


printf("Total is = %d",total);
return 0;
}

3. Write a C Program to swap values of two variables.

#include<stdio.h>
int main()
{
int num1,num2,temp;

printf("Type value of number 1 : ");


scanf("%d",&num1);

printf("\nType value of number 2 : ");


scanf("%d",&num2);

temp = num1;
num1 = num2;
num2 = temp;

printf("After swapping values \n");


printf("number 1 : %d",num1);
printf("\nnumber 2 : %d",num2);
return 0;
}

4. Write a C Program to Multiply two floating point numbers.

#include<stdio.h>

Int main()
{
double num1, num2, total;
printf("Enter two numbers: ");

scanf("%lf %lf", &num1, &num2);


total = num1 * num2;

printf("Product = %.2lf", total);

return 0;
}

5. Write a C Program to perform Arithmetic Operations.


#include <stdio.h>

int main()
{
int num1, num2;
int sum, sub, mult, mod;
float div;

printf("Enter first number : ");


scanf("%d", &num1);

printf("Enter second number : ");


scanf("%d", &num2);

sum = num1 + num2;


sub = num1 - num2;
mult = num1 * num2;
mod = num1 % num2;
div = (float)num1 / num2;

printf("Sum of num1 and num2 = %d \n", sum);


printf("Difference of num1 and num2 = %d \n", sub);
printf("Product of num1 and num2 = %d \n", mult);
printf("Modulus of num1 and num2 = %d \n", mod);
printf("Quotient of num1 and num2 = %f ", div);

return 0;
}

6. Write a C Program to perform to convert feet to meter.


#include<stdio.h>
int main()
{
float meter,feet;

printf("Enter feet : ");


scanf("%f",&feet);

meter = feet * 0.308;


printf("meter: %f",meter);

return 0;
}

7. Write a C Program to convert Celsius to Fahrenheit.

#include <stdio.h>

int main()
{
float celsius, fahrenheit;

printf("\nEnter Temperature in Celsius : ");


scanf("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf("\nTemperature in Fahrenheit : %f ", fahrenheit);

return 0;
}

8. Write a C Program to find the size of data types.

#include <stdio.h>
int main()
{
char c;
short s;
int a;
long l;
float b;
double g;

// Sizeof operator is used to evaluate the size of a declared


data type

printf("Size of char: %ld byte\n",sizeof(c));


printf("Size of Short: %ld bytes\n",sizeof(s);

printf("Size of int: %ld bytes\n",sizeof(a));


printf("Size of long: %ld bytes\n",sizeof(l));

printf("Size of float: %ld bytes\n",sizeof(b));


printf("Size of double: %ld bytes\n",sizeof(g));

return 0;
}

9. Write a C Program to print ASCII value.

#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");

scanf("%c", &c);// Reads character input

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}

10. Write a C Program to calculate Area and circumference of a Circle.

#include <stdio.h>

int main()
{
/*write a c program to find area and circumference of circle*/
int rad;
float PI = 3.14, area, ci;

printf("\nEnter radius of circle: ");


scanf("%d", &rad);

area = PI *rad * rad;


printf("\nArea of Circle : %f ", area);

ci = 2 *PI * rad;
printf("\nCircumference of Circle : %f ", ci);

return (0);
}

11. Write a C Program to convert days to years, weeks and days.

#include <stdio.h>

int main()
{
int days, years, weeks;

printf("Enter days: "); // Read total number of days from user


scanf("%d", &days);

years = (days / 365);


weeks = (days % 365)/7;
days = days - ((years * 365) + (weeks * 7));

printf("Years: %d\n", years);


printf("Weeks: %d\n", weeks);
printf("Days: %d\n", days);

return 0;
}

12. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40%
of basic salary, and house rent allowance is 20% of basic salary. Write a program to
calculate his gross salary.
#include <stdio.h>

void main()
{
float basic,da,hra,gs;
clrscr();

printf(“\n Enter Basic Salary:”);


scanf(“%f”,&basic);

da=basic*40/100;
hra=basic*20/100;
gs=basic+da+hra;

printf(“\n Gross Salary:%f”,gs);


getch();
}

13. If the marks obtained by a student in five different subjects are input through the
keyboard, write a program to find out the Total marks and percentage marks
obtained by the student. Assume that the maximum marks that can be obtained by a
student in each subject is 100.
#include <stdio.h>

void main()
{

int m1,s1,e1,c1,h1,total;
float perc;

printf(“\n Enter Marks for Maths:”);


scanf(“%d”,&m1);
printf(“\n Enter Marks for Science:”);
scanf(“%d”,&s1);

printf(“\n Enter Marks for English:”);


scanf(“%d”,&e1);

printf(“\n Enter Marks for Computer:”);


scanf(“%d” ,&c1);
printf(“\n Enter Marks for Hindi:”);
scanf(“%d”,&h1);

total=m1+s1+e1+c1+h1;
perc=total/5;

printf/(“\n Total marks:%d \n Percentage:%f”,total,perc);


getch();
}

14. Write a C program to calculate Net Amount of product, enter Product name,
quantity and price of per product. Tax is 2.5% of amount, Discount is 5% of amount,
find Net amount=Amount + Tax - discount. Display Invoice.
15. Calculate Simple Interest based on formula SI=p*n*r/100, Enter the value of
Principle amount, no. of years and rate of interest.

C Program – Control Flow

IF…ELSE 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.

There are the following variants of if statement in C language.


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
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

Program to find the largest number of the three.


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");
22. }
23. }

Output

Enter three numbers?


12 23 34
34 is largest

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. }

Flowchart of the if-else statement in C


Let's see the simple example to check whether a number is even or odd using if-
else statement in C language.

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

Program to check whether a person is eligible to vote or not.


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

Enter your age?18


You are eligible to vote...
Enter your age?13
Sorry ... you can't vote

If else-if ladder Statement


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.}

Flowchart of else-if ladder statement in C

The example of an if-else-if statement in C language is given below.

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

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

Enter your marks?10


Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

Programs:

1. C Program to Check Whether a Number is Positive, Negative, or Zero.


#include <stdio.h>

int main()
{
int A;

printf("Enter the number A: ");


scanf("%d", &A);

if (A > 0)
printf("%d is positive.", A);
else if (A < 0)
printf("%d is negative.", A);
else
printf("%d is zero.", A);

return 0;
}

2. C Program to Check Whether Number is Even or Odd.


#include<stdio.h>
#include<conio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if(num%2 == 0)
printf("\nIt's an even number.");
else
printf("\nIt's an odd number.");

return 0;
}

3. C Program to Check Whether a Character is Vowel or Consonant


4. C Program to Find Largest Number Among Two Numbers
5. C Program to Check Leap Year
#include<stdio.h>
#include<conio.h>
int main()
{
int year;
printf("Enter Year: ");
scanf("%d", &year);
if(year%4==0)
printf("\nIt's a Leap Year");
else
printf("\nIt's not a Leap Year");

return 0;
}

6. C Program to check whether the person is eligible for voting or not.


7. Find all roots of a quadratic equation. ax 2+bx+c=0
# include<stdio.h>
# include<math.h>
main (){
float a,b,c,r1,r2,d;
printf (“enter the values of a b c”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0){
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“The real roots = %f %f”, r1, r2);
}
else if (d= =0){
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“roots are equal =%f %f”, r1, r2);
}
else
printf(“Roots are imaginary”);
return 0;
}

8. Calculate profit or loss.


/**
* C program to calculate profit or loss
*/

#include <stdio.h>

int main()
{
int cp,sp, amt;

/* Input cost price and selling price of a product */


printf("Enter cost price: ");
scanf("%d", &cp);
printf("Enter selling price: ");
scanf("%d", &sp);

if(sp > cp)


{
/* Calculate Profit */
amt = sp - cp;
printf("Profit = %d", amt);
}
else
{
/* Calculate Loss */
amt = cp - sp;
printf("Loss = %d", amt);
}

return 0;
}

Switch

C Switch Statement
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.

The syntax of switch statement in c language is given below:

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.}

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

Rules for switch statement in C language


1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

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;
Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;

Flowchart of switch statement in C

Functioning of switch case statement


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
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.

// C Program to create a simple calculator using


switch
// statement
#include <stdio.h>
// driver code
int main()
{
// switch variable
char choice;
// operands
int x, y;

printf("Enter the Operator :”);


scanf(" %c", &choice);

printf("Enter the two numbers: ");


scanf("%d %d", &x, &y);

// switch case with operation for each


operator
switch (choice) {
case '+':
printf("%d + %d = %d\n", x, y, x + y);
break;

case '-':
printf("%d - %d = %d\n", x, y, x - y);
break;

case '*':
printf("%d * %d = %d\n", x, y, x * y);
break;
case '/':
printf("%d / %d = %d\n", x, y, x / y);
break;
default:
printf("Invalid Operator Input\n");
}
}
return 0;
}

Output
Enter the operator (+, -, *, /)

+
Enter the two numbers: 100 + 200
100 + 200 = 300

2. // C program to print the day using switch


#include <stdio.h>

// Driver Code
int main()
{
int day;
printf(“\n Enter day number:”);
scanf(“%d”,&day);

printf("The day with number %d is ", day);


switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid Input");
break;
}
return 0;
}

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.

Why use loops in C language?


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.

Advantage of loops in C
1) It provides code reusability.

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
There are three types of loops in C language that is given below:

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).

The syntax of do-while loop in c language is given below:

1. do{
2. //code to be executed
3. }while(condition);

Flowchart and Example of do-while loop

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.

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }

Flowchart and Example of while loop

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.

The syntax of for loop in c language is given below:


1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

Flowchart and Example of for loop

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.

do while loop syntax

The syntax of the C language do-while loop is given below:

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");
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
Flowchart of do while loop

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
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
Infinitive do while loop

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);

while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part
of the code to be executed multiple times depending upon a given boolean
condition. It can be viewed as a repeating if statement. The while loop is mostly
used in the case where the number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C

Example of the while loop in C language


Let's see the simple program of while loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while loop
in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10.return 0;
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

Properties of while loop


o A conditional expression is used to check the condition. The statements defined
inside the while loop will repeatedly execute until the given condition fails.
o The condition will be true if it returns 0. The condition will be false if it returns any
non-zero number.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while loop.
o If the loop body contains only one statement, then the braces are optional.

Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int j = 1;
5. while(j+=2,j<=10)
6. {
7. printf("%d ",j);
8. }
9. printf("%d",j);
10.}
Output
3 5 7 9 11
Example 2
1. #include<stdio.h>
2. void main ()
3. {
4. while()
5. {
6. printf("hello Javatpoint");
7. }
8. }
Output
compile time error: while loop can't be empty
Example 3
1. #include<stdio.h>
2. void main ()
3. {
4. int x = 10, y = 2;
5. while(x+y-1)
6. {
7. printf("%d %d",x--,y--);
8. }
9. }
Output
infinite loop

Infinitive while loop in C


If the expression passed in while loop results in any non-zero value then the loop
will run the infinite number of times.

1. while(1){
2. //statement
3. }

for loop in C
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.

Syntax of for loop in C


The syntax of for loop in c language is given below:

1. for(Expression 1; Expression 2; Expression 3){


2. //code to be executed
3. }
Flowchart of for loop in C

C for loop Examples


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;
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
2000
3000
4000
5000
6000
7000
8000
9000
10000

Properties of Expression 1
o The expression represents the initialization of the loop variable.
o We can initialize more than one variable in Expression 1.
o Expression 1 is optional.
o In C, we can not declare the variables in Expression 1. However, It can be an
exception in some compilers.

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. }
9. }

Output

1 2 3 4

Properties of Expression 2
o Expression 2 is a conditional expression. It checks for a specific condition to be
satisfied. If it is not, the loop is terminated.
o Expression 2 can have more than one condition. However, the loop will iterate until
the last condition becomes false. Other conditions will be treated as statements.
o Expression 2 is optional.
o Expression 2 can perform the task of expression 1 and expression 3. That is, we can
initialize the variable as well as update the loop variable in expression 2 itself.
o We can pass zero or non-zero value in expression 2. However, in C, any non-zero
value is true, and zero is false by default.

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

0 1 2 3 4

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);
8. j+=2;
9. k+=3;
10. }
11. }

Output

0 0 0
1 2 3
2 4 6
3 6 9
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. }
9. }

Output

0 2
1 4
2 6
3 8
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

Infinitive for loop in C


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. }

Nested Loops in C
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.

Syntax of Nested 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.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for' loop.

1. for (initialization; condition; update)


2. {
3. for(initialization; condition; update)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }

Example of nested 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
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. }

Explanation of the above code

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:
Nested while loop

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. }

Example of nested while loop

1. #include <stdio.h>
2. int main()
3. {
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. }

Explanation of the above code.

o We have created the 2d array, i.e., int a[rows][columns].


o The program initializes the 'i' variable by 1.
o Now, control moves to the while loop, and this loop checks whether the condition is
true, then the program control moves to the inner loop.
o After the execution of the inner loop, the control moves to the update of the outer
loop, i.e., i++.
o After incrementing the value of 'i', the condition (i<=rows) is checked.
o If the condition is true, the control then again moves to the inner loop.
o This process continues until the condition of the outer loop is true.

Output:

Nested do..while loop

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);

Example of nested do..while loop.

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("*");
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }

Output:
Explanation of the above code.

o First, we initialize the outer loop counter variable, i.e., 'i' by 1.


o As we know that the do..while loop executes once without checking the condition,
so the inner loop is executed without checking the condition in the outer loop.
o After the execution of the inner loop, the control moves to the update of the i++.
o When the loop counter value is incremented, the condition is checked. If the
condition in the outer loop is true, then the inner loop is executed.
o This process will continue until the condition in the outer loop is true.

Infinite Loop in C
What is infinite loop?
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.

When to use an infinite loop


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.
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.

Let's understand through an example.

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
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.

Let's look at a simple example.

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.

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.

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.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. char ch;
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.

Unintentional infinite loops

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>
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. }
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:

1. With switch case


2. With loop

Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c

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

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case


Click here to see the example of C break with the switch statement.

C break statement with the nested loop


In such case, it breaks only the 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. 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

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
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.

break statement with while loop


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");
13. }

Output

0 1 2 3 4 5 6 7 8 9 came out of while loop

break statement with do-while loop


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 no
n-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

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 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
3 X 1 = 3
3 X 2 = 6
3 X 3 = 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

Continue statement example 2

1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
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. }

Loops Programs
1. Find Factorial of a Number
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}

2. C Program to reverse number


3. #include<stdio.h>
4. int main()
5. {
6. int n, reverse=0, rem;
7. printf("Enter a number: ");
8. scanf("%d", &n);
9. while(n!=0)
10. {
11. rem=n%10;
12. reverse=reverse*10+rem;
13. n/=10;
14. }
15. printf("Reversed Number: %d",reverse);
16.return 0;
17. }

Output:

Enter a number: 123


Reversed Number: 321
3. Sum of digits program in C.
1. #include<stdio.h>
2. int main()
3. {
4. int n,sum=0,m;
5. printf("Enter a number:");
6. scanf("%d",&n);
7. while(n>0)
8. {
9. m=n%10;
10. sum=sum+m;
11. n=n/10;
12.
13.
14.
15. }
16. printf("Sum is=%d",sum);
17. return 0;
18. }

Output:

Enter a number:654
Sum is=15

Enter a number:123
Sum is=6

4.Print Even Numbers from 1 to n:


/**
* C program to print all even numbers from 1 to n
*/

#include <stdio.h>

int main()
{
int i, n;

/* Input upper limit of even number from user */


printf("Print all even numbers till: ");
scanf("%d", &n);

printf("Even numbers from 1 to %d are: \n", n);


/*
* Start loop counter from 1, increment it by 1,
* will iterate till n
*/
for(i=1; i<=n; i++)
{
/* Check even condition before printing */
if(i%2 == 0)
{
printf("%d\n", i);
}
}

return 0;
}

5. Program to print alphabets from


a-z
/**
* C program to print all alphabets from a to z
*/

#include <stdio.h>

int main()
{
char ch;

printf("Alphabets from a - z are: \n");


for(ch='a'; ch<='z'; ch++)
{
printf("%c\n", ch);
}

return 0;
}
6.Check whether number is palindrome or not.

1. #include<stdio.h>
2. int main()
3. {
4. int n,r,rev=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. rev=(rev*10)+r;
12. n=n/10;
13. }
14. if(temp==rev)
15. printf("palindrome number ");
16. else
17. printf("not palindrome");
18. return 0;
19. }

Output:

enter the number=151


palindrome number

enter the number=5621


not palindrome number

7. Fibonacci Series in C

1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already prin
ted
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }

Output:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

8. Nested For loop: (Patterns)

star.c

1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. int i, j, rows;
6. printf (" Enter a number to define the rows: \n ");
7. scanf("%d", &rows);
8. printf("\n");
9. for (i = 1; i <= rows; ++i) // outer loop
10. {
11.
for (j = 1; j <= i; ++j) // inner loop
12. {
13. printf ("* "); // print the Star
14. }
15. printf ("\n");
16. }
17. getch();
18.}

Output
9. Star Pattern

1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5.
6. int i, j, rows, k = 0;
7. printf (" Enter a number to define the rows: \n");
8. scanf ("%d", &rows);
9.
10. for ( i =1; i <= rows; i++)
11. {
12. for ( j = 1; j <= rows - i; j++)
13. {
14. printf (" ");
15. }
16. // use for loop where k is less than equal to (2 * i -1)
17. for ( k = 1; k <= ( 2 * i - 1); k++)
18. {
19. printf ("* "); // print the Star
20. }
21. printf ("\n");
22. }
23. getch();
24.}

Output
10. Program to print the half Pyramid of number
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. // declare the local variables
6. int i, j, rows;
7. printf (" Enter a number to define the rows: \n ");
8. scanf("%d", &rows);
9. printf("\n");
10. for (i = 1; i <= rows; ++i)
11. {
12. for (j = 1; j <= i; ++j)
13. {
14. printf ("%d ", j);
15. }
16. printf ("\n");
17. }
18. getch();
19. }

Output
11. Number Pattern

1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. // declare the local variables
6. int i, j, rows;
7. printf (" Enter a number to define the rows: \n ");
8. scanf("%d", &rows);
9. printf("\n");
10. for (i = 1; i <= rows; ++i)
11. {
12. for (j = 1; j <= i; ++j)
13. {
14. printf ("%d ", i); // print the number
15. }
16. printf ("\n");
17. }
18. getch();
19. }

Output
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
The array contains the following properties.

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
1) Code Optimization: Less code to the access the data.

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.
Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

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

80
60
70
85
75

C Array: Declaration with Initialization


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};

Let's see the C program to declare and initialize the array in C.

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

Sorting an array
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;
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[i] > a[j])
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. }

+--Find largest number from an array

/*
* C Program to find the largest number in an array using loops
*/

#include <stdio.h>

int main()
{
int size, i, largest;

printf("\n Enter the size of the array: ");


scanf("%d", &size);
int array[size]; //Declaring array
//Input array elements

printf("\n Enter %d elements of the array: \n", size);

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


{
scanf(" %d", &array[i]);
}

//Declaring Largest element as the first element


largest = array[0];

for (i = 1; i < size; i++)


{
if (largest < array[i])
largest = array[i];
}

printf("\n largest element present in the given array is : %d",


largest);

return 0;
}

Reverse the elements of an array


// C program to reverse an array

#include<stdio.h>

int main()

int n;

printf(“\n Enter No. of Array elements:”);

scanf(“%d”,&n);

int arr[n];

int i;
for(i = 0; i < n; i++)

scanf(“%d”,&arr[i]);

printf(“Reversed array is:\n”);

for(i = n-1; i >= 0; i- -)

printf(“%d\n”,arr[i]);

return 0;

Find Sum of all the elements of an array


#include <stdio.h>

void main()

int a[100];

int i, n, sum=0;

printf("\n\nFind sum of all elements of array:\n");

printf("--------------------------------------\n");

printf("Input the number of elements to be stored in the array


:");

scanf("%d",&n);
printf("Input %d elements in the array :\n",n);

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

printf("element - %d : ",i);

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

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

sum += a[i];

printf("Sum of all elements stored in the array is : %d\n\n",


sum);

Sample Output:
Find sum of all elements of array:
--------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is : 15

Write a program to separate Odd and Even Numbers from an


array:

#include<stdio.h>
main()
{
int i,size;
printf("Enter size of array\n");
scanf("%d",&size);
int a[size];
printf("Enter numbers to separate even and odd\n");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("Even numbers are:\n");
for(i=0;i<size;i++)
{
if(a[i]>=0)
{
if(a[i]%2==0)
{
printf("%d\n",a[i]);
}

}
}

printf("Odd numbers are:\n");


for(i=0;i<size;i++)
{
if(a[i]>=0)
{
if(a[i]%2==1)
{
printf("%d\n",a[i]);
}

}
}

Write a program to merge two arrays and print it in sorted


order.
#include<stdio.h>
main()
{
int i,size1,size2,j=0,temp;
printf("Enter size of an array1\n");
scanf("%d",&size1);
printf("Enter size of an array2\n");
scanf("%d",&size2);
int a[size1],b[size2],c[size1+size2];
printf("Enter numbers for array 1\n");
for(i=0;i<size1;i++)
{
scanf("%d",&a[i]);

printf("Enter numbers for array 2\n");


for(i=0;i<size2;i++)
{
scanf("%d",&b[i]);
}
//merging
for(i=0;i<size1;i++)
{
c[i]=a[i];

}
for(j=size1,i=0;i<size2;i++)
{
c[j]=b[i];
j++;
}
printf("Array after merging\n");
for(i=0;i<size1+size2;i++)
{
printf("%d\n",c[i]);
}

//Sorting
for(i=0;i<size1+size2;i++)
{
for(j=i+1;j<size1+size2;j++)
{
if(c[i]>c[j])
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
printf("Array afetr sorting the merged array\n");
for(i=0;i<size1+size2;i++)
{
printf("%d\n",c[i]);
}
}
Output:

2-D Array:
Write a Program in c to Add all element of 2D Array
\* C Program to to Add all element of 2D Array *\

# include < stdio.h >


int main( )
{

int i,j,r,c,sum=0;
printf(“\n Enter No. of rows:”);
scanf(“%d”,&r);

printf(“\n Enter No. of Columns:”);


scanf(“%d”,&c);
int a[r][c];

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


{
for ( j = 0 ; j < c ; j++)
{
printf("Enter array elements:”);
scanf(“ %d ", & a[i][j]) ;
}
printf(" \n ") ;
}

printf("\n Element in the Matrix are : \n") ;


for ( i = 0 ; i < r ; i++)
{
for ( j = 0 ; j < c ; j++)
{
printf("\t %d ", a[i][j]) ;
}
printf(" \n ") ;
}
for ( i = 0 ; i < r ; i++)
{
for ( j = 0 ; j < c ; j++)
sum = sum + a[i][j] ;
}
printf("\t Sum of All element of Matrix is :%d", sum) ;
return ( 0 ) ;
}
Output of Program:
Matrix addition:
Addition of two 3x3 matrix
Q. Write a C program for addition of two 3x3
matrix.

Ans.

/*source code of addition of 3x3 matrix c program*/


#include<stdio.h>
#include<conio.h>
int main()
{
int matA[3][3],matB[3][3],matC[3][3];
int r,c,k;
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
printf("Enter first matrix : ");
scanf("%d", &matA[r][c]);
}
}
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
printf("Enter second matrix : ");
scanf("%d", &matB[r][c]);
}
}
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
matC[r][c] = matA[r][c] + matB[r][c];
}
}
printf("\n New addition matrix : \n");
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
printf(" %d",matC[r][c]);
printf("\n");
}

return 0;
}

/************************************************************
The output of above Addition of two 3x3 martix C program would be:
***********************************************************/
Figure: Screen shot for addition of two 3x3 matrix
C program

C Strings
The string can be defined as the one-dimensional array of characters terminated
by a null ('\0'). The character array or the string is used to manipulate text such as
word or sentences. Each character in the array occupies one byte of memory, and
the last character must always be 0. The termination character ('\0') is important
in a string since it is the only way to identify where the string ends. When we
define a string as char s[10], the character s[10] is implicitly initialized with the
null in the memory.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.

1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure


given below.
While declaring string, size is not mandatory. So we can write the above code as
given below:

1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

We can also define the string by the string literal in C language. For example:

1. char ch[]="javatpoint";

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal


There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas, it
is appended internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

String Example in C
Let's see a simple example where a string is declared and being printed. The '%s'
is used as a format specifier for the string in c language.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10.}

Output

Char Array Value is: javatpoint


String Literal Value is: javatpoint

Traversing String
Traversing the string is one of the most important aspects in any of the
programming languages. We may need to manipulate a very large text which can
be done by traversing the text. Traversing string is somewhat different from the
traversing an integer array. We need to know the length of the array to traverse an
integer array, whereas we may use the null character in the case of string to
identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.

o By using the length of string


o By using the null character.

Let's discuss each one of them.

Using the length of string


Let's see an example of counting the number of vowels in a string.

1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16.}

Output

The number of vowels 4

Using the null character


Let's see the same example of counting the number of vowels by using the null
character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16.}

Output

The number of vowels 4

Accepting string as the input


Till now, we have used scanf to accept the input from the user. However, it can
also be used in the case of strings but with a different scenario. Consider the below
code which stores the string while space is encountered.

1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }

Output

Enter the string?javatpoint is the best


You entered javatpoint
C gets() and puts() functions
The gets() and puts() are declared in the header file stdio.h. Both the functions are
involved in the input/output operations of the strings.

C gets() function
The gets() function enables the user to enter some characters followed by the
enter key. All the characters entered by the user get stored in a character array.
The null character is added to the array to make it a string. The gets() allows the
user to enter the space-separated strings. It returns the string entered by the user.

Declaration

1. char[] gets(char[]);
Reading string using gets()
1. #include<stdio.h>
2. void main ()
3. {
4. char s[30];
5. printf("Enter the string? ");
6. gets(s);
7. printf("You entered %s",s);
8. }
Output
Enter the string?
javatpoint is the best
You entered javatpoint is the best

The gets() function is risky to use since it doesn't perform any array bound
checking and keep reading the characters until the new line (enter) is
encountered. It suffers from buffer overflow, which can be avoided by using
fgets(). The fgets() makes sure that not more than the maximum limit of
characters are read. Consider the following example.

1. #include<stdio.h>
2. void main()
3. {
4. char str[20];
5. printf("Enter the string? ");
6. fgets(str, 20, stdin);
7. printf("%s", str);
8. }
Output
Enter the string? javatpoint is the best website
javatpoint is the b
C puts() function
The puts() function is very much similar to printf() function. The puts() function is
used to print the string on the console which is previously read by using gets() or
scanf() function. The puts() function returns an integer value representing the
number of characters being printed on the console. Since, it prints an additional
newline character with the string, which moves the cursor to the new line on the
console, the integer value returned by puts() will always be equal to the number of
characters present in the string plus 1.

Declaration

1. int puts(char[])

Let's see an example to read a string using gets() and print it on the console using
puts().

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10.}
Output:
Enter your name: 0
Your name is: Sonoo Jaiswal

C String Functions
There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, copies the contents of source string to


source) destination string.

3) strcat(first_string, concats or joins first string with second


second_string) string. The result of the string is stored in
first string.
4) strcmp(first_string, compares the first string with second string.
second_string) If both strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

Character Input and


Output Functions in C
C language provides getchar( ), getch( ) for reading single character and putchar( ), putch( )
for displaying single character on screen. Let us see syntax and use of these functions in C
program.

getchar() and putchar() Functions


1. getchar( ):

It reads a single character from input device i.e. stdin. This function is defined in <stdio.h>
header file.

Syntax: int getchar( );

Usage: var_name=getchar( );

Where var_name is of type int or char.

The characters accepted by getchar( ) are buffered until RETURN is hit. It is a buffered
function. The buffered function gets the input from the keyboard and store it in the memory
buffer temporally until user press the Enter key.

It means getchar( ) requires Enter key to be pressed following the character that you typed. It
echoes typed character. If an end-of-file(EOF) condition error occurs, getchar() returns EOF.

The EOF macro is defined in <stdio.h> and is often equal to -1.

2. putchar():

It displays or writes a single character to the standard output device or screen at the current
cursor position. This function is defined in <stdio.h> header file.

Syntax: int putchar(int c);


Usage: putchar( var_name);

Where var_name is of type int or char.

The putchar( ) function returns the character written or EOF if an error occurs.
Example:

//Learnprogramo

#include<stdio.h>

int main()

char x;

printf(“\n Enter Character:”);

x=getchar();

printf(“\n Entered character is:”);

putchar(x);

return 0;

}
Output:

If we input any character say j then output is j. So the output is: y /* the keypress is echoed on
the screen */ y

getch(), getche() and putch() Functions


1. getch():

This function is used to read a character from the console but does not echo to the screen.
This function is included in header file <conio.h>

Syntax: int getch( );

Usage: var_name=getch( );

where var_name is of type int or char.

getch() function is a non-buffered function. It does not use any buffer, so the entered character
is immediately returned without waiting for the enter key.
The character data read by this function is directly assigned to a variable rather it goes to the
memory buffer.

Another use of this function is to maintain the output on the screen until you have not to press
the Enter key. getch() works only on dos like TC compiler. It does not work on a Linux
platform.

2. getche():

getche( ) function is used to read a character from the console and echoes that character to
the screen. This function is included in header file <conio.h>.

Syntax: int getche( );

Usage: var_name=getche( );

It does not use any buffer, so the entered character is immediately returned without waiting for
the enter key. getche() works only on DOS-like TC compiler. It does not work on a Linux
platform.

The main difference between getch() and getche() is getch() does not echo character after
reading, while getche() echoes character after reading.

3. putch():

putch() function displays or writes single character to the standard output device(i.e. stdout).
This function is defined in <conio.h> header file.

Syntax: int putch(int c);

Usage: putch(var_name);

Where, var_name is of type int or char.

putch() does not translate linefeed characters (\n) into carriage-return/linefeed pairs. The
putch() function returns the character written or EOF if an error occurs.

//Learnprogramo

#include<stdio.h>

#include<conio.h>

int main()

char x;

x=getch();
putch(x);

return 0;

}
Output:

If we input any character say y then output is y. So the output is:

_ /* the keypress is not echoed on the screen */ y

String Input and Output


Functions in C
The functions gets() and puts() are used for string reading(input) and string writing(output)
purpose from standard library functions.

1. gets():

gets() function accepts single or multiple characters of string including spaces from the
standard input device until ENTER key is pressed. This function in <stdio.h> header file.

Syntax: gets(var_name);

Where var_name is string or array of characters.

gets() is also buffered function. It will read a string from the keyboard until the user presses the
Enter key from the keyboard. It will mark the null character (‘\0’) in the memory at the string
when you press the enter key.

gets stops when either the newline character is read or when the end-of-file(EOF) is reached,
whichever comes first.

2. puts():

puts() function displays or writes a string to the standard output device. It appends a newline
character to string. This function is defined in <stdio.h> header file.

Syntax: puts(var_name);

Where var_name is string or array of characters.

//Learnprogramo

#include<stdio.h>
int main()

char name[20];

puts("Enter the name");

gets(name);

puts("Name is:");

puts(name);

return 0;

}
Output:

The following table summarizes basic console I/O functions:

Function Operation

getchar() Reads character from keyboard and waits for return.

getche() Reads a character with echo and do not wait for return.

getch() Reads a character without echo and do not wait for return.

putchar(
Writes a character to the screen.
)

putch() Writes a character to the screen.

gets() Reads a string from the keyboard.

puts() Writes a string to the screen.


String Copy Program
#include <stdio.h>

int main() {
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to hold value

int length = 0;

while(s1[length] != '\0') {
s2[length] = s1[length];
length++;
}

s2[length] = '\0'; // Terminate the string

printf("Value in s1 = %s \n", s1);


printf("Value in s2 = %s \n", s2);

return 0;
}

Output
Output of this program should be −
Value in s1 = TajMahal
Value in s2 = TajMahal

Reverse the string


#include <stdio.h>

int main() {
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to store reverse string

int length = 0;-


int loop = 0;

while(s1[length] != '\0') {
length++;
}

printf("\nPrinting in reverse - ");


for(loop = --length; loop>=0; loop--)
printf("%c", s1[loop]);

loop = 0;

printf("\nStoring in reverse - ");

while(length >= 0) {
s2[length] = s1[loop];
length--;
loop++;
}

s1[loop] = '\0'; // Terminates the string

printf("%s\n", s2);

return 0;
}

Output
Output of this program should be −
Printing in reverse - lahaMjaT
Storing in reverse - lahaMjaT

Program to check Strings are same or not.


#include <stdio.h>

int main() {
char s1[] = "advise";
char s2[] = "advice";

int n = 0;
unsigned short flag = 1;

while (s1[n] != '\0') {


if(s1[n] != s2[n]) {
flag = 0;
break;
}
n++;
}

if(flag == 1) {
printf("%s and %s are identical\n", s1, s2);
} else {
printf("%s and %s are NOT identical\n", s1, s2);
}

return 0;
}
Output
Output of this program should be −
advise and advice are NOT identical

Concatenate two strings

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

int main() {
char s1[10] = "Taj";
char s2[] = "Mahal";

int i, j, n1, n2;

n1 = strlen(s1);
n2 = strlen(s2);

j = 0;
for(i = n1; i< n1+n2; i++ ) {
s1[i] = s2[j];
j++;
}

s1[i] = '\0';

printf("%s", s1);

return 0;
}
Output of this program should be −
TajMahal

C Functions
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 procedure or subroutine in other
programming languages.

Advantage of functions in C
There are the following advantages of C functions.
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
There are three aspects of a C function.

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.

S C function Syntax
N aspects

1 Function return_type function_name (argument list);


declaration

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list)


{function body;}

The syntax of creating function in c language is given below:


1. return_type function_name(data_type parameter...){
2. //code to be executed
3. }

Types of Functions
There are two types of functions in C programming:

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.

Example without return value:

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.

Example with return value:

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. }

Now, you need to call the function, to get the value of the function.

Different aspects of function calling


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.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value


Example 1

1. #include<stdio.h>
2. void printName();
3. int main ()
4. {
5. printf("Hello ");
6. printName();
7. return 0;
8. }
9. void printName()
10. {
11. printf("Javatpoint");
12. }

Output

Hello Javatpoint

Example 2

1. #include<stdio.h>
2. void sum();  function declaration
3. int main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum(); function call
7. Return 0;
8. }
9. void sum() // definition
10.
11. {
12. int a,b,c;
13. printf(“\n Enter two Numbers:”);
14. scanf(“%d %d”,&a,&b);
15. c=a+b;
16. Printf(“\n Sum is:%d”,c);
17.}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value


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

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square

1. #include<stdio.h>
2. int square();
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

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value
Example 1

1. #include<stdio.h>
2. void sum(int, int);
3. int 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.}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.

1. #include<stdio.h>
2. void average(int, int, int, int, int); // declaraction
3. int 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); // call
10.}
11. void average(int a, int b, int c, int d, int e) // defination
12.{
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16.}

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value


Example 1

1. #include<stdio.h>
2. int 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. 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

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

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.{
21. if(n%2==0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

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.
S Header Description
N file

1 stdio.h This is a standard input/output header file. It contains all


the library functions regarding standard input/output.

2 conio.h This is a console input/output header file.

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.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header


file.

9 signal.h All the signal handling functions are defined in this header
file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

Power=Pow(base,exponent)

Find Maximum of two numbers


#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

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.

Factorial Program using recursion in C


Let's see the factorial program in c using recursion.

1. #include<stdio.h>
2.
3. long factorial(int n)
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1));
9. }
10. Long factorial(int);
11. void main()
12. {
13. int number;
14. long fact;
15. printf("Enter a number: ");
16. scanf("%d", &number);
17.
18. fact = factorial(number);
19. printf("Factorial of %d is %ld\n", number, fact);
20. return 0;
21. }

Output:

Enter a number: 6
Factorial of 5 is: 720

Fibonacci Series using Recursion:

#include <stdio.h>

int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return (fibonacci(n-1) + fibonacci(n-2));
}

int main() {
int n;

printf("Enter the number of terms\n");


scanf("%d", &n);

printf("Fibonacci Series: ");

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


printf("%d ", fibonacci(i));
}

return 0;
}

0 1 1 2 3 5 8 13…

File Handling in C
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the
file. A list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function is
used to open a file. The syntax of the fopen() is given below.

1. FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.txt".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

R opens a text file in read mode

W opens a text file in write mode

A opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

Rb opens a binary file in read mode

Wb opens a binary file in write mode

Ab- opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

1. #include<stdio.h>
2. int main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10.if ( ch == EOF )
11. break ;
12.printf("%c",ch) ;
13. }
14.fclose (fp ) ;
15.return 0;
16. }
Output

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character
file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after
performing all the operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );


C fprintf() and fscanf()

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.

Syntax:

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

1. int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

1. #include <stdio.h>
2. Int main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a word
from the file and returns EOF at the end of file.

Syntax:

1. int fscanf(FILE *stream, const char *format [, argument, ...])


Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10.}

Output:

Hello file by fprintf...

C File Example: Storing employee information


Let's see a file handling example to store employee information as entered by user
from console. We are going to store id, name and salary of the employee.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24.}

Output:

Enter the id
1
Enter the name
sonoo
Enter the salary
120000

Now open file from current directory. For windows operating system, go to TC\bin
directory, you will see emp.txt file. It will have following information.

Emp.txt

Id= 1
Name= sonoo
Salary= 120000

C fputc() and fgetc()

Writing File : fputc() function


The fputc() function is used to write a single character into file. It outputs a
character to a stream.

Syntax:

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

1. int fputc(int c, FILE *stream)

Example:
1. #include <stdio.h>
2. Int main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }

file1.txt

Reading File : fgetc() function


The fgetc() function returns a single character from the file. It gets a character
from the stream. It returns EOF at the end of file.

Syntax:

1. int fgetc(FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. int main(){
4. FILE *fp;
5. char c;
6.
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10.printf("%c",c);
11. }
12.fclose(fp);
13.
14.}

myfile.txt

this is simple text message


C fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read string from
stream. Let's see examples of writing and reading file using fgets() and fgets()
functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a
stream.

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

Syntax:

1. int fputs(const char *s, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5.
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10.fclose(fp);

11.}
myfile2.txt

hello c programming

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a
stream.

Syntax:

1. char* fgets(char *s, int n, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);

12. }

Output:

hello c programming

C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used
to write data into file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET,
SEEK_CUR and SEEK_END.

Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }

myfile.txt

This is sonoo jaiswal

C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is
useful if you have to use stream many times.

Syntax:

1. void rewind(FILE *stream)

Example:

File: file.txt

1. this is a simple text


File: rewind.c

1. #include<stdio.h>
2. int main()
3. {
4. FILE *fp;
5. char c;
6.
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF)
10. {
11.printf("%c",c);
12.
13. }
14.
15. rewind(fp);//moves the file pointer at beginning of the file
16.
17. while((c=fgetc(fp))!=EOF){
18.printf("%c",c);
19. }
20.
21. fclose(fp);
22. return 0;
23. }

Output:

this is a simple textthis is a simple text

As you can see, rewind() function moves the file pointer at beginning of the file
that is why "this is simple text" is printed 2 times. If you don't call rewind()
function, "this is simple text" will be printed only once.

C ftell() function
The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end
of file. We can use SEEK_END constant to move the file pointer at the end of file.

Syntax:

1. long int ftell(FILE *stream)

Example:

File: ftell.c

1. #include <stdio.h>
2. int main ()
3. {
4. FILE *fp;
5. int length;
6. fp = fopen("file.txt", "r");
7. fseek(fp, 0, SEEK_END);
8. length = ftell(fp);
9. fclose(fp);
10. printf("Size of file: %d bytes", length);
11. Return 0;
12. }
Output:

Size of file: 21 bytes

Structure in C
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. };

Let's see the example to define a structure for an entity employee in c.

1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };

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:

Declaring structure variable


We can declare a variable for the structure so that we can access the member of
the structure easily. There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should
be declared within the main function.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Now write given code inside the main() function.

1. struct employee e1, e2;

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.

AD

If no. of variables are fixed, use 2nd approach. It saves your code to declare a
variable in main() function.

AD

Accessing members of the structure


There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by. (member) operator.

1. p1.id
C Structure example
Let's see a simple example of structure in C language.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
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:

AD
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, "Sonu Gupta");//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
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

Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The
array of structures in C are used to store information about multiple entities of
different data types. The array of structures is also known as the collection of
structures.
Let's see an example of an array of structures that stores information of 5 students
and prints it.

1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10.printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12.printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14.printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16.}
17. printf("\nStudent Information List:");
18.for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20.}
21. return 0;
22.}

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Nested Structure in C
C provides us the feature of nesting one structure within another structure by
using which, complex data types are created. For example, we may need to store
the address of an entity employee in a structure. The attribute address may also
have the subparts as street number, city, state, and pin code. Hence, to store the
address of the employee, we need to store the address of the employee into a
separate structure and nest the structure address into the structure employee.
Consider the following program.

1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12.};
13. void main ()
14.{
15. struct employee emp;
16. printf("Enter employee information?\n");
17. scanf("%s %s %d %s",&emp.name,&emp.add.city, &emp.add.pin, &
emp.add.phone);
18. printf("Printing the employee information....\n");
19. printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s
",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
20.}

Output

Enter employee information?

Arun

Delhi

110001

1234567890

Printing the employee information....


name: Arun

City: Delhi

Pincode: 110001

Phone: 1234567890

The structure can be nested in the following ways.

1. By separate structure
2. By Embedded structure

1) Separate structure
Here, we create two structures, but the dependent structure should be used inside
the main structure as a member. Consider the following example.

1. struct Date
2. {
3. int dd;
4. int mm;
5. int yyyy;
6. };
7. struct Employee
8. {
9. int id;
10. char name[20];
11. struct Date doj;
12.}emp1;

As you can see, doj (date of joining) is the variable of type Date. Here doj is used
as a member in Employee structure. In this way, we can use Date structure in
many structures.

2) Embedded structure
The embedded structure enables us to declare the structure inside the structure.
Hence, it requires less line of codes but it can not be used in multiple data
structures. Consider the following example.

1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;

Accessing Nested Structure


We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:

1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy

C Nested Structure example


Let's see a simple example of the nested structure in C language.

1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14.int main( )
15. {
16. //storing employee information
17. e1.id=101;
18. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
19. e1.doj.dd=10;
20. e1.doj.mm=11;
21. e1.doj.yyyy=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", e1.id);
25. printf( "employee name : %s\n", e1.name);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.
mm,e1.doj.yyyy);
27. return 0;
28.}

Output:

employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

Passing structure to function


Just like other variables, a structure can also be passed to a function. We may pass
the structure members into the function or pass the structure variable at once.
Consider the following example to pass the structure variable employee to a
function display() which is used to display the details of an employee.

1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12.};
13. void display(struct employee);
14.void main ()
15. {
16. struct employee emp;
17. printf("Enter employee information?\n");
18. scanf("%s %s %d %s",&emp.name,&emp.add.city, &emp.add.pin, &emp.add.pho
ne);
19. display(emp);
20.}
21. void display(struct employee emp)
22.{
23. printf("Printing the details....\n");
24. printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
25. }

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c
language is possible by 4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program. program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

malloc() function in C
The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.


It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

1. ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22.}

Output

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

calloc() function in C
The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.


The syntax of calloc() function is given below:

1. ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16.
17. printf("Sum=%d",sum);
18. free(ptr);
19. return 0;
20.}

Output

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory
by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

AD

1. ptr=realloc(ptr, new-size)
AD
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling
free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() func

Use of realloc() in C
CProgrammingServer Side Programming

The function realloc is used to resize the memory block which is allocated by
malloc or calloc before.
Here is the syntax of realloc in C language,
void *realloc(void *pointer, size_t size)
Here,
pointer − The pointer which is pointing the previously allocated memory block by
malloc or calloc.
size − The new size of memory block.
Here is an example of realloc() in C language,

Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}

Output
Enter elements of array : 3 34 28 8
Sum : 73
Enter elements of array : 3 28 33 8 10 15
Sum : 145

POINTERS

C Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-bit
architecture the size of a pointer is 2 byte.
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.

1. int *a;//pointer to int


2. char *c;//pointer to char
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
6. printf("Address of p variable is %x \n",p); // p contains the address of the number th
erefore printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to deref
erence a pointer therefore if we print *p, we will get the value stored at the a
ddress contained by p.
8. return 0;
9. }

Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50

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
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of 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.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation


In c language, we can dynamically allocate memory using malloc() and calloc()
functions where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It


reduces the code and improves the performance.

AD

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use
%u to display the address of a variable.

AD

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

value of number is 50, address of number is fff4

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;

In the most libraries, the value of the pointer is 0 (zero).

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;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12.}

Output

Before swap: *p1=10 *p2=20


After swap: *p1=20 *p2=10

C Double Pointer (Pointer to Pointer)


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.

The syntax of declaring a double pointer is given below.

1. int **p; // pointer to a pointer which is pointing to an integer.

Consider the following example.

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
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 co
ntained by p i.e. 10 will be printed
12. printf("value stored at pp: %d\n",**pp); // value stored at the address contained b
y 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

C double pointer example


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",*p2);
13. return 0;
14.}
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 9of **p variable is 50
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

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.

The Rule to increment the pointer is given below:

1. new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.

32-bit
For 32-bit int variable, it will be incremented by 2 bytes.

64-bit
For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p); // in our case, p will get in
cremented by 4 bytes.
9. return 0;
10.}

Output

Address of p variable is 3214864300


After increment: Address of p variable is 3214864304

Traversing an array by using pointer


1. #include<stdio.h>
2. void main ()
3. {
4. int arr[5] = {1, 2, 3, 4, 5};
5. int *p = arr;
6. int i;
7. printf("printing array elements...\n");
8. for(i = 0; i< 5; i++)
9. {
10. printf("%d ",*(p+i));
11. }
12. }

Output

printing array elements...


1 2 3 4 5

Decrementing Pointer in C
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:

1. new_address= current_address - i * size_of(data type)


32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.

Let's see the example of decrementing pointer variable on 64-bit OS.

1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p); // P will now point to the i
mmidiate previous location.
9. }

Output

Address of p variable is 3214864300


After decrement: Address of p variable is 3214864296

C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer
is given below:

AD

1. new_address= current_address + (number * size_of(data type))


32-bit
For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+3; //adding 3 to pointer variable
8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10.}

Output

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312

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.

AD
AD

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:

1. new_address= current_address - (number * size_of(data type))


32-bit
For 32-bit int variable, it will subtract 2 * number.

64-bit
For 64-bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from the pointer variable on 64-bit
architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10.}

Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288

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.

If two pointers are of the same type,

1. Address2 - Address1 = (Subtraction of two addresses)/size of data type whic


h pointer points

Consider the following example to subtract one pointer from an another.

1. #include<stdio.h>
2. void main ()
3. {
4. int i = 100;
5. int *p = &i;
6. int *temp;
7. temp = p;
8. p = p + 3;
9. printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
10.}

Output

Pointer Subtraction: 1030585080 - 1030585068 = 3

Illegal arithmetic with pointers


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.

o Address + Address = illegal


o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal
o ~Address = illegal

AD

Pointer to function in C
As we discussed in the previous chapter, a pointer can point to a function in C.
However, the declaration of the pointer variable must be the same as the function.
Consider the following example to make a pointer pointing to the function.

1. #include<stdio.h>
2. int addition ();
3. int main ()
4. {
5. int result;
6. int (*ptr)();
7. ptr = &addition;
8. result = (*ptr)();
9. printf("The sum is %d",result);
10.}
11. int addition()
12.{
13. int a, b;
14. printf("Enter two numbers?");
15. scanf("%d %d",&a,&b);
16. return a+b;
17. }

Output

Enter two numbers?10 15


The sum is 25

Pointer to Array of functions in C


To understand the concept of an array of functions, we must understand the array
of function. Basically, an array of the function is an array which contains the
addresses of functions. In other words, the pointer to an array of functions is a
pointer pointing to an array which contains the pointers to the functions. Consider
the following example.

1. #include<stdio.h>
2. int show();
3. void showadd(int);
4. int (*arr[3])();
5. int (*(*ptr)[3])();
6.
7. int main ()
8. {
9. int result1;
10. arr[0] = show;
11. arr[1] = showadd;
12. ptr = &arr;
13. result1 = (**ptr)();
14. printf("printing the value returned by show : %d",result1);
15. (*(*ptr+1))(result1);
16.}
17. int show()
18.{
19. int a = 65;
20. return a++;
21. }
22.Void showadd(int b)
23. {
24. printf("\nAdding 90 to the value returned by show: %d",b+90);
25. }

Output

printing the value returned by show : 65


Adding 90 to the value returned by show: 155

What is a Null Pointer?


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 0 th 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.

Applications of Null Pointer


Following are the applications of 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.

Examples of Null Pointer


int *ptr=(int *)0;
float *ptr=(float *)0;
char *ptr=(char *)0;
double *ptr=(double *)0;
char *ptr='\0';
int *ptr=NULL;

Let's look at the situations where we need to use the null pointer.

o When we do not assign any memory address to the pointer variable.

AD

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.

How to avoid the above situation?

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.

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.

Let's see a simple example.

1. #include <stdio.h>
2. int main()
3. {
4. printf("Address of main() function is %p",main);
5. return 0;
6. }

The above code prints the address of main() function.

Output

In the above output, we observe that the main() function has some address.
Therefore, we conclude that every function has some address.

Declaration of a function pointer


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.

Syntax of function pointer

1. return type (*ptr_name)(type1, type2…);

For example:

1. int (*ip) (int);

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.

1. float (*fp) (float);


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.

1. float (*fp) (int , int); // Declaration of a function pointer.


2. float func( int , int ); // Declaration of function.
3. fp = func; // Assigning address of func to the fp pointer.

In the above declaration, 'fp' pointer contains the address of the 'func' function.

Note: Declaration of a function is necessary before assigning the address of a function to


the function pointer.
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.

Suppose we declare a function as given below:

1. float func(int , int); // Declaration of a function.

Calling an above function using a usual way is given below:

1. result = func(a , b); // Calling a function using usual ways.

Calling a function using a function pointer is given below:

AD

1. result = (*fp)( a , b); // Calling a function using function pointer.

Or

1. result = fp(a , b); // Calling a function using function pointer, and indirec
tion operator can be removed.

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.

Let's understand the function pointer through an example.

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;
18. return c;
19. }

Output

Passing a function's address as an argument to other function


We can pass the function's address as an argument to other functions in the same
way we send other arguments to the function.

AD

Let's understand through an example.

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

Array of Function Pointers


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.

Let's understand through an example.

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 arra
y 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.}
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

You might also like