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

C Programming Language Tutorial

Uploaded by

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

C Programming Language Tutorial

Uploaded by

ben munjaru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 437

C Programming Language Tutorial

C language Tutorial with programming approach for beginners and professionals, helps you to
understand the C language tutorial easily. Our C tutorial explains each topic with programs. The C
Language is developed by Dennis Ritchie for creating system applications that directly interact with the
hardware devices such as drivers, kernels, etc. C programming is considered as the base for other
programming languages, that is why it is known as mother language. It can be defined by the following
ways:
1. Mother language 4. Structured programming language
2. System programming language 5. Mid-level programming language
3. Procedure-oriented programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the
programming languages follow C syntax, for example, C++, Java, C#, etc. It provides the core concepts
like the array, strings, functions, file handling, etc. that are being used in many languages
like C++, Java, C#, etc.

2) C as a system programming language


A system programming language is used to create system software. C language is a system programming
language because it can be used to do low-level programming (for example driver and kernel). It is
generally used to create hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is written in
C. It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language specifies a
series of steps for the program to solve the problem. A procedural language breaks the program into
functions, data structures, etc. C is a procedural language. In C, variables and function prototypes must be
declared before being used.
4) C as a structured programming language
A structured programming language is a subset of the procedural language. Structure means to break a
program into parts or blocks so that it may be easy to understand. In the C language, we break the
program into parts using functions. It makes the program easier to understand and modify.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both low-level and high-
level languages. C language program is converted into assembly code, it supports pointer arithmetic (low-
level), but it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast to
run. But it is not easy to understand. A High-Level language is not specific to one machine, i.e., machine
independent. It is easy to understand.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the C program
File: main.c code.
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }

History of C Language
History of C language is interesting to know. Here we are going to discuss a brief history of the c language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American
Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc. Initially, C language
was developed to be used in UNIX operating system. It inherits many features of previous languages such
as B and BCPL. Let's see the programming languages that were developed before C language.

Features of C Language

C is the widely used language. It provides many features that are given below.
1. Simple 6. Memory Management
2. Machine Independent or Portable 7. Fast Speed
3. Mid-level programming language 8. Pointers
4. structured programming language 9. Recursion
5. Rich Library 10. Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem into
parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with some machine
specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop system applications such as
kernel, driver, etc. It also supports the features of a high-level language. That is why it is known as mid-
level language.
4) Structured programming language
C is a structured programming language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify. Functions also provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory
at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and hence
the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can
use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for every function. Recursion
enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.
How to install C
There are many compilers available for c and c++. You need to download any one. Here, we are going to
use Turbo C++. It will work for both C and C++. To install the Turbo C software, you need to follow
following steps.
1. Download Turbo C++
2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
3. Double click on install.exe file
4. Click on the tc application file located inside c:\TC\BIN to write the c program

1) Download Turbo C++ software


You can download turbo c++ from many sites. download Turbo c++
2) Create turboc directory in c drive and extract the tc3.zip
Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in c: \truboc
directory.
3) Double click on the install.exe file and follow steps
 Now, click on the install icon located inside the c:\turboc
 It will ask you to install c or not, press enter to install.
 Change your drive to c, press c.
 Press enter, it will look inside the c:\turboc directory for the required files.
 Select Start installation by the down arrow key then press enter.
 Now C is installed, press enter to read documentation or close the software.

4) Click on the tc application located inside c:\TC\BIN


Now double click on the tc icon located in c:\TC\BIN directory to write the c program.
First C Program
General Overview of a Simple C Program's Structure:
The general architecture of a simple C program typically consists of several vital components. Below is an
outline of the essential elements and their purposes:

o Header Files:

The #include directives at the beginning of the program are used to include header files. Header
files provide function prototypes and definitions that allow the C compiler to understand the functions
used in the program.

o Main Function:

Every C program starts with the main function. It is the program's entry point, and execution starts from
here. The main function has a return type of int, indicating that it should return an integer value to the
operating system upon completion.
o Variable Declarations:
Before using any variables, you should declare them with their data types. This section is typically placed
after the main function's curly opening brace.

o Statements and Expressions:


This section contains the actual instructions and logic of the program. C programs are composed of
statements that perform actions and expressions that compute values.
o Comments:
Comments are used to provide human-readable explanations within the code. They are not executed and
do not affect the program's functionality. In C, comments are denoted by // for single-line
comments and /* */ for multi-line comments.
o Functions:
C programs can include user-defined functions and blocks of code that perform specific tasks. Functions
help modularize the code and make it more organized and manageable.
o Return Statement:
Use the return statement to terminate a function and return a value to the caller function. A return
statement with a value of 0 typically indicates a successful execution in the main function, whereas
a non-zero value indicates an error or unexpected termination.

o Standard Input/Output:

C has library functions for reading user input (scanf) and printing output to the console (printf). These
functions are found in C programs and are part of the standard I/O library (stdio.h header file). It is essential
to include these fundamental features correctly while writing a simple C program to ensure optimal
functionality and readability.

Additional Information:
There is some additional information about the C programs. Some additional information is as follows:

o Preprocessor Directives:
C programs often include preprocessor directives that begin with a # symbol. These directives are
processed by the preprocessor before actual compilation and are used to include header files, define
macros, and perform conditional compilation.
o Data Types:
C supports data types such as int, float, double, char, etc. It depends on the program's requirements, and
appropriate data types should be chosen to store and manipulate data efficiently.

o Control Structures:
C provides control structures like if-else, while, for, and switch-case that allow you to make decisions
and control the flow of the program.

o Error Handling:
Robust C programs should include error-handling mechanisms to handle unexpected situations
gracefully. Techniques like exception handling (using try-catch in C++) or returning error codes are
commonly employed.
o Modularization:
As programs grow in complexity, it becomes essential to modularize the code by creating separate
functions for different tasks. This practice improves code reusa bility and maintainability. Remember,
the architecture and complexity of a C program can vary significantly depending on the
specific application and requirements. The outline is a general overview of a simple C program's structure.

Explain the First C program:


To write the first C program, open the C console and write the following code:
Code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
Let us first study the various parts of this C program:

#include <stdio.h>:
In this line, the program includes the standard input/output library (stdio.h) due to the preprocessor
directive. For input and output tasks, the stdio.h library contains methods like printf and scanf.

int main() { ... }:


It is the main function which is the entry point of the C program. The program starts executing from the
beginning of the main function.

printf("Hello World!\n");:printf("Hello World!");:


Use the printf() function to print formatted output to the console. In this example, the string "Hello, C
Language" is printed, followed by a newline character (n) which moves the pointer to the following line
after the message is displayed.

Return 0;
When the return statement is 0, the program has been completed. When determining the state of a
program, the operating system frequently uses the value returned by the main function. A return
value of 0 often indicates that the execution was successful. After compilation and execution, this C
program will quit with a status code 0 and output "Hello, C Language" to the terminal.

The "Hello, C Language" program is frequently used as an introduction to a new programming language
since it introduces learners to essential concepts such as text output and the structure of a C program and
provides a rapid way to validate that the working environment is correctly set up.

To write, compile, and run your first C program, follow these steps:

Step 1: Open a text editor


Open a text editor of your choice, such as Notepad, Sublime Text, or Visual Studio Code. It will be where
you write your C code.

Step 2: Write the C program


Now, copy and paste the following code into the text editor:
1. #include <stdio.h>
2. int main() {
3. printf("Hello, C Language");
4. return 0;
5. }

Step 3: Save the file


After that, save the file with a .c extension such as first_program.c. This extension indicates that it is a C

source code file.

Step 4: Compile the program


Now, compile the program in the command prompt.
Step 5: Run the program
After successful compilation, you can run the program by executing the generated executable file. Enter
the following command into the terminal or command prompt:
1. ./first_program

The program will execute, and you will see the output on the console:

Output:
Hello, C Language

How to compile and run the C program


There are two ways to compile & run the c program by menu and by shortcut.

By Menu
o Now click on the compile menu, then compile sub-menu to compile the c program.
o Then click on the run menu and the sub-menu to run the c program.

By shortcut
o Or, press the ctrl+f9 keys to compile and run the program directly.
o You will see the following output on the user screen.
o You can view the user screen any time by pressing the alt+f5 keys.
o Now press Esc to return to the turbo c++ console.

Conclusion:

Finally, the first C program introduces the C programming language and its fundamental structure. It
illustrates the necessary components for writing, compiling, and running a C program.

The program contains the standard input-output library (stdio.h), which includes routines for output
operations such as printf(). The main() function is the program's entry point, from which execution begins.
The printf() function is used within the main() method to print the message "Hello, C Language" to the
console.

A C compiler such as GCC is required to compile the program. The code is stored in a text file with the .c
extension, and the compiler is started by typing gcc, followed by the names of the input and output files.

The compilation process converts machine-readable instructions from human-readable C code. Once the
program has been successfully constructed, it may be started by double-clicking the resultant executable
file. In a terminal or command prompt, the executable is called by its file name, followed by ./. After that,
the program is performed, and the "Hello C Language" output is shown on the console.

By following these instructions, you will get a basic grasp of developing, constructing, and running a C
program. It offers the groundwork for further investigating more complex ideas and developing more
sophisticated applications using the C programming language.

In windows 7 or window 8, it will show a dialog block to ignore and close the application because fullscreen
mode is not supported. Click on Ignore button. Now it will showing following console.
Compilation process in c

What is a compilation?

The compilation is a process of converting the source code into object code. It is done with the help of the
compiler. The compiler checks the source code for the syntactical or structura l errors, and if the source code
is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or machine code.
The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and
Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the source code.
The preprocessor takes the preprocessor directive and interprets it. For example, if <stdio.h>, the directive
is available in the program, then the preprocessor interprets the directive and replace this directive with the
content of the 'stdio.h' file.

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
Now, we will create a flow diagram of the above program:

In the above flow diagram, the following steps are taken to execute a program:
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the
source code into expanded source code. The extension of the expanded source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this expanded source
code into assembly code. The extension of the assembly code would be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly code into object code.
o After the creation of an object code, the linker creates the executable file. The loader will then load the
executable file for the execution.

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;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }

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. int main(){
3. int x=0,y=0,result=0;
4. printf("enter first number:");
5. scanf("%d",&x);
6. printf("enter second number:");
7. scanf("%d",&y);
8. result=x+y;
9. printf("sum of 2 numbers:%d ",result);
10. return 0;
11. }

Output
enter first number:9
enter second number:9
sum of 2 numbers:18
Variables in C
A variable is the name of the memory location. It is used to store information. Its value can be altered and
reused several times. It is a way to represent memory location through symbols so that it can be easily
identified. Variables are key building elements of the C programming language used to store and modify
data in computer programs. A variable is a designated memory region that stores a specified data type
value. Each variable has a unique identifier, its name, and a data type describing the type of data it may
hold.

Syntax:
The syntax for defining a variable in C is as follows:
1. data_type variable_name;
Here,
o data_type: It represents the type of data the variable can hold. Examples of data types in C include int
(integer), float (a floating-point number), char (character), double (a double-precision floating-
point number),
o variable_name: It is the identifier for the variable, i.e., the name you give to the variable to access
its value later in the program. The variable name must follow specific rules, like starting with
a letter or underscore and consisting of letters, digits, and underscores.

For example, to declare the integer variable age:


1. int age;
It declares an integer variable named age without assigning it a specific value. Variables can also be
initialized at the time of declaration by assigning an initial value to them. For instance:
1. int count = 0;
Here, the variable count is declared an integer and initialized with 0.

Note: Variables should be defined before they are used within the program. The scope of a variable
determines where it is accessible. Variables declared inside a function or block are considered local
variables, while declared outside any function are considered global variables.

Syntax:
Let us see the syntax to declare a variable:
1. type variable_list;
An example of declaring the variable is given below:
1. int a; 2. float b; 3. char c;
Here, a, b, and c are variables. The int, float, and char are the data types.

We may also provide values while defining variables, as shown below:


1. int a=20,b=30;//declaring 2 variable of integ 2. float f=20.9;
er type 3. char c='A';
Rules for defining variables
In C, Variable names must follow a few rules to be valid. The following are the rules for naming variables
in C:
o Allowed Characters:
Variable names include letters ( uppercase and lowercase ), digits, and underscores. They must start
with a letter (uppercase or lowercase) or an underscore.
o Case Sensitivity:
C is a case-sensitive programming language. It means that uppercase and lowercase letters are
considered distinct. For example, myVar, MyVar, and myvar are all considered different variable
names.
o Keywords:
Variable names cannot be the same as C keywords (reserved words), as they have special meanings in
the language. For example, you cannot use int, float, char, for, while, etc., as variable names.
o Length Limitation:
There is no standard limit for the length of variable names in C, but it's best to keep them reasonably short
and descriptive. Some compilers may impose a maximum length for variable names.
o Spaces and Special Characters:
Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, &, *, (, ), -, +, =, [,
], {, }, |, \, /, <, >,., ?;, ', or "). Underscores are the only allowed special characters in variable names.
o Reserved Identifiers:
While not strictly a rule, it is advisable to avoid specific patterns or identifiers common in libraries or
standard usage. For example, variables starting with __ (double underscores) are typically reserved for
system or compiler-specific usage.

Valid examples of variable names:


1. int age; 4. double average_score;
2. float salary; 5. int studentCount;
3. char _status;
Invalid examples of variable names:

1. int 1stNumber; // Starts with a digit


2. float my-salary; // Contains a hyphen (-)
3. char int; // Same as a C keyword
4. int double; // Same as a C keyword
5. float my$var; // Contains an unsupported special character

Following these rules ensures that your variable names are valid and conform to the C language's syntax
and conventions. Choosing meaningful and descriptive names for variables is essential to enhance the
readability and maintainability of your code.

The three components of declaring a variable


Let us explain the three aspects of defining a variable: variable declaration, variable definition, and
variable initialization, along with examples.
1. Variable Declaration:
The process of telling the compiler about a variable's existence and data type is known as variable
declaration. It notifies the compiler that a variable with a specific name and data type will be used in the
program. Still, no memory for the variable is allocated at this moment. It is usually seen at the start of a
function or block before the variable is utilized.

The general syntax for variable declaration is


1. data_type variable_name;

Example of variable declaration:


1. #include <stdio.h>
2. int main() {
3. // Variable declaration
4. int age;
5. float salary;
6. char initial;
7. return 0;
8. }

2. Variable Definition:
The process of reserving memory space for the variable to keep its contents during program execution is
known as a variable definition. It is based on the data type and connects the variable name with a
particular memory address of sufficient size. A variable in C can be declared and defined in the same
statement, although they can also be separated if necessary.

Example of variable definition:


1. #include <stdio.h> 5. float salary = 2500.5;
2. int main() { 6. char initial = 'J';
3. // Variable definition 7. return 0;
4. int age = 25; 8. }

3. Variable Initialization:
Variable declaration is the act of informing the compiler about the existence and data type of a variable.
It informs the compiler that a variable with a specific name and data type will be used in the program, but
that memory for the variable still needs to be allocated.

Not explicitly initialized variables will contain garbage/random data that may result in unexpected
program behavior.

Example of variable initialization:


1. #include <stdio.h> 7. // Later in the program, you can change the value
2. int main() { of the variable
3. // Variable definition and initialization 8. age = 30;
4. int age = 25; 9. salary = 3000.0;
5. float salary = 2500.5; 10. return 0;
6. char initial = 'J'; 11. }
In the example above, we have variable age, salary, and initial declarations. After that, we define these
variables and initialize them with initial values (e.g., age = 25). Later in the program, we can modify the
values of these variables (e.g., age = 30).
Types of Variables in C
There are many types of variables in c:
1. local variable 4. automatic variable
2. global variable 5. external variable
3. static 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 use 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. }

Conclusion:
Variables are critical components in C that store and manipulate data in the memory. They act as named
placeholders for memory regions, making identifying and retrieving stored data simple. The syntax for
creating a variable in C includes the following:
o Declaring the data type.
o Specifying the data that the variable may carry.
o Giving the variable a unique name.
Following specific rules, such as starting with a letter, underscore, and avoiding reserved keywords ,
ensures valid variable names. Variables can be declared without initialization or assigned an initial value at
the time of declaration. Once the variable is declared, variables can be used throughout the program to
store and manipulate data. They can be reassigned with new values as needed during program execution.

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

Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them. It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative numbers because it is
signed by default. An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one byte of memory. Characters such
as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent fractional
units or numbers with decimal places. The float type is usually used for variables that require very good
precision but may not be very precise. It can store values with an accuracy of about 6 decimal places and
a range of about 3.4 x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed, such as in
scientific calculations or financial applications, it provides greater accuracy compared to float. Double type,
which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields larger values. C
treats floating point numbers as doubles by default if no explicit type is supplied.

1. int age = 25; 3. float temperature = 98.6;


2. char grade = 'A'; 4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age, a char variable for
the student's grade, a float variable for the temperature reading, and two variables for the number pi.

Derived Data Type


Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions. These data types give programmers the ability to handle heterogeneous data,
directly modify memory, and build complicated data structures.
Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It
provides a mechanism for joining multiple targets of the same data under the same name. The index is used
to access the elements of the array, with a 0 index for the first entry. The size of the array is fixed at
declaration time and cannot be changed during program execution. The array components are placed in
adjacent memory regions.

Here is an example of declaring and utilizing an array:


1. #include <stdio.h> 9. numbers[4] = 50;
2. int main() { 10. // Display the values stored in the array
3. int numbers[5]; // Declares an integer array wit 11. printf("Values in the array: ");
h a size of 5 elements 12. for (int i = 0; i < 5; i++) {
4. // Assign values to the array elements 13. printf("%d ", numbers[i]);
5. numbers[0] = 10; 14. }
6. numbers[1] = 20; 15. printf("\n");
7. numbers[2] = 30; 16. return 0;
8. numbers[3] = 40; 17. }

Output:
Values in the array: 10 20 30 40 50
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When a pointer is
declared, the data type it refers to is stated first, and then the variable name is preceded by an asterisk
(*). You can have incorrect access and change the value of variable using pointers by specifying the memory
address of the variable. Pointers are commonly used in tasks such as function pointers, data structures,
and dynamic memory allocation.
Here is an example of declaring and employing a pointer:
1. #include <stdio.h>
2. int main() {
3. int num = 42; // An integer variable
4. int *ptr; // Declares a pointer to an integer
5. ptr = # // Assigns the address of 'num' to the pointer
6. // Accessing the value of 'num' using the pointer
7. printf("Value of num: %d\n", *ptr);
8. return 0;
9. }

Output:
Value of num: 42
Structure:
A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name. It gives you the ability to create your own unique data
structures by fusing together variables of various sorts.
1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.
A declaration and use of a structure is demonstrated here:
1. #include <stdio.h>
2. #include <string.h>
3. // Define a structure representing a person
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9. int main() {
10. // Declare a variable of type struct Person
11. struct Person person1;
12. // Assign values to the structure members
13. strcpy(person1.name, "John Doe");
14. person1.age = 30;
15. person1.height = 1.8;
16. // Accessing the structure members
17. printf("Name: %s\n", person1.name);
18. printf("Age: %d\n", person1.age);
19. printf("Height: %.2f\n", person1.height);
20. return 0;
21. }
Output: Name: John Doe Age: 30 Height: 1.80
Union:
A derived data type called a union enables you to store various data types in the samememory address. In
contrast to structures, where each member has a separate memory space, members of a union all share a
single memory space. A value can only be held by one member of a union at any given moment. When you
need to represent many data types interchangeably, unions come in handy. Like structures, you can access
the members of a union by using the dot (.) operator.
Here is an example of a union being declared and used:
1. #include <stdio.h>
2. // Define a union representing a numeric value
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
9. // Declare a variable of type union NumericValue
10. union NumericValue value;
11. // Assign a value to the union
12. value.intValue = 42;
13. // Accessing the union members
14. printf("Integer Value: %d\n", value.intValue);
15. // Assigning a different value to the union
16. value.floatValue = 3.14;
17. // Accessing the union members
18. printf("Float Value: %.2f\n", value.floatValue);
19. return 0;
20. }
Output:
Integer Value: 42
Float Value: 3.14
Enumeration Data Type
A set of named constants or enumerators that represent a collection of connected values can be defined
in C using the enumeration data type (enum). Enumerations give you the means to give names that
make sense to a group of integral values, which makes your code easier to read and maintain.
Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h> 12. int main() {


2. // Define an enumeration for days of the week 13. // Declare a variable of type enum DaysOfWee
3. enum DaysOfWeek { k
4. Monday, 14. enum DaysOfWeek today;
5. Tuesday, 15. // Assign a value from the enumeration
6. Wednesday, 16. today = Wednesday;
7. Thursday, 17. // Accessing the enumeration value
8. Friday, 18. printf("Today is %d\n", today);
9. Saturday, 19. return 0;
10. Sunday 20. }
11. };
Output:
Today is 2
Void Data Type
The void data type in the C language is used to denote the lack of a particular type. Function return types,
function parameters, and pointers are three situations where it is frequently utilized.
Function Return Type:
A void return type function does not produce a value. A void function executes a task or action and ends
rather than returning a value.

Example:
1. void printHello() { printf("Hello, world!\n"); }

Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.

Example:
1. void processInput(void) { /* Function logic */ }

Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a method for
working with pointers to ambiguous or atypical types.

Example:
1. void* dataPtr;
The void data type is helpful for defining functions that don't accept any arguments when working with
generic pointers or when you wish to signal that a function doesn't return a value. It is significant to note
that while void* can be used to build generic pointers, void itself cannot be declared as a variable type.
Here is a sample of code that shows how to utilize void in various situations:
1. #include <stdio.h>
2. // Function with void return type
3. void printHello() {
4. printf("Hello, world!\n");
5. }
6. // Function with void parameter
7. void processInput(void) {
8. printf("Processing input...\n");
9. }
10. int main() {
11. // Calling a void function
12. printHello();
13. // Calling a function with void parameter
14. processInput();
15. // Using a void pointer
16. int number = 10;
17. void* dataPtr = &number;
18. printf("Value of number: %d\n", *(int*)dataPtr);
19. return 0;
20. }
Output:
Hello, world!
Processing input...
Value of number: 10

Conclusion:
As a result, data types are essential in the C programming language because they define the kinds of
information that variables can hold. They provide the data's size and format, enabling the co mpiler to allot
memory and carry out the necessary actions. Data types supported by C include void, enumeration,
derived, and basic types. In addition to floating-point types like float and double, basic data types in C
also include integer-based kinds like int, char, and short. These forms can be signed or unsigned, and they
fluctuate in size and range. To create dependable and efficient code, it is crucial to comprehend the memory
size and scope of these types.

A few examples of derived data types are unions, pointers, structures, and arrays. Multiple elements of
the same kind can be stored together in contiguous memory due to arrays. Pointers keep track of memory
addresses, allowing for fast data structure operations and dynamic memory allocation. While unions allow
numerous variables to share the same memory space, structures group relevant variables together.

Code becomes more legible and maintainable when named constants are defined using enumeration data
types. Enumerations give named constants integer values to enable the meaningful representation of
related data. The void data type indicates the lack of a particular type. It is used as a return type for
both functions and function parameters that don't take any arguments and don't return a value.
The void* pointer also functions as a general pointer that can store addresses of various types.

C programming requires a solid understanding of data types. Programmers can ensure adequate memory
allocation, avoid data overflow or truncation, and enhance the readability and maintainability of their
code by selecting the right data type. C programmers may create effective, dependable, and well-
structured code that satisfies the requirements of their applications by having a firm understanding of data
types.

Keywords in C
Keywords in C are reserved words that have predefined meanings and are part of the Clanguage syntax.
These keywords cannot be used as variable names, function names, or any other identifiers within the
program except for their intended purpose. They are used to define the structure flow and behavior of a C
program.
The compiler recognizes a defined set of keywords in the C programming language. These keywords
have specialized purposes and play critical roles in establishing the logic and behavior of a program. Here
are some characteristics of C keywords:
o Reserved: The C language reserves keywords are those keywords that cannot be used as identifiers in
programs. Using a keyword as a variable name or other identifier will cause a compilation error.
o Predefined Meaning: Each keyword has a specific meaning that is assigned by the C language. These
meanings are built into the C language's grammar and syntax and the compiler interprets them
accordingly.
o Specific Use: Keywords are designed for specific purposes and contexts within the C language. They
define control structures, data types, flow control, and other language constructs. Attempting to use
a keyword outside of its intended purpose will result in a compilation error.
o Standardized: C language keywords are standardized across different compilers and implementations .
It ensures the consistency and portability of C programs across different platforms and environments.

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

Here is a brief explanation of each keyword in the C language along with their syntax and an example:

o auto: This keyword declares an automatic variable with a local scope.

Syntax:
It has the following syntax:
1. auto data_typevariable_name;
Example:

1. auto int count;

Code:
1. #include <stdio.h>
2. int main() {
3. auto int count = 10;
4. printf("Count: %d\n", count);
5. {
6. auto int count = 5;
7. printf("Inner Count: %d\n", count);
8. }
9. printf("Count: %d\n", count);
10. return 0;
11. }

Output:
Count: 10
Inner Count: 5
Count: 10

o break: It is used to terminate the execution of a loop or switch statement.


Syntax:
It has the following syntax:
1. break;

Code:

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

Output:

0 1 2 3 4

o case: It is used in a switch statement to define different cases.

Syntax:
It has the following syntax:
1. case constant_expression:
Code:
1. #include <stdio.h>
2. int main() {
3. int choice = 2;
4. switch (choice) {
5. case 1:
6. printf("You chose option 1.\n");
7. break;
8. case 2:
9. printf("You chose option 2.\n");
10. break;
11. default:
12. printf("Invalid choice.\n");
13. }
14. return 0;
15. }

Output:
You chose option 2.

o char: This keyword is used to declare a character data type.


Syntax:
It has the following syntax:
1. char variable_name;

Example:
1. char grade = 'A';

Code:
1. #include <stdio.h>
2. int main() {
3. char grade = 'A';
4. printf("Grade: %c\n", grade);
5. return 0;
6. }

Output:
Grade: A

o const: It is used to declare constants, whose values cannot be modified.

Syntax:
It has the following syntax:
1. const data_type constant_name = value;

Code:
1. #include <stdio.h>
2. int main() {
3. constint MAX_SIZE = 100;
4. printf("Max Size: %d\n", MAX_SIZE);
5. return 0;
6. }

Output:
Max Size: 100

o continue: It is used to skip the remaining statements in a loop and continue with the next iteration.

Syntax:
It has the following syntax:
1. continue;

Code:
1. #include <stdio.h> 6. }
2. int main() { 7. printf("%d ", i);
3. for (inti = 0; i< 10; i++) { 8. }
4. if (i == 5) { 9. return 0;
5. continue; 10. }

Output:
0 1 2 3 4 6 7 8 9
o default: It is used in a switch statement as the default case when no other cases match.

Syntax:
It has the following syntax:
1. default:

Code:
1. #include <stdio.h>
2. int main() {
3. int choice = 3;
4. switch (choice) {
5. case 1:
6. printf("You chose option 1.\n");
7. break;
8. case 2:
9. printf("You chose option 2.\n");
10. break;
11. default:
12. printf("Invalid choice.\n");
13. }
14. return 0;
15. }

Output:
Invalid choice.ax: default:

o do: It is used to create a do-while loop, which executes a block of code repeatedly until
a condition is met.

Syntax:

It has the following syntax:


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

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

Output:
0 1 2 3 4

o double: This keyword is used to declare a double-precision floating-point data type.


Syntax:
It has the following syntax:
1. double variable_name;

Example:
1. double pi = 3.14159;

Code:
1. #include <stdio.h>
2. int main() {
3. double pi = 3.14159;
4. printf("Pi: %lf\n", pi);
5. return 0;
6. }

Output:
Pi: 3.141590
o else: It is used in an if statement to specify the block of code to be executed when the condition
is false.

Syntax:
It has the following syntax:
1. if (condition) {
2. // code to be executed if the condition is true
3. } else {
4. // code to be executed if the condition is false
5. }

Code:
1. #include <stdio.h>
2. int main() {
3. int age = 20;
4. if (age >= 18) {
5. printf("You are an adult.\n");
6. } else {
7. printf("You are not an adult.\n");
8. }
9. return 0;
10. }

Output:
You are an adult.
o enum: It is used to define an enumeration, which is a set of named values.
Syntax: It has the following syntax:
1. enum enum_name {
2. value1,
3. value2,
4. //...
5. };
Code:
1. #include <stdio.h>
2. enum Days {
3. Monday,
4. Tuesday,
5. Wednesday,
6. Thursday,
7. Friday,
8. Saturday,
9. Sunday
10. };
11. int main() {
12. enum Days today = Tuesday;
13. printf("Today is day number %d\n", today);
14. return 0;
15. }

Output:

Today is day number 1


o extern: It is used to declare a variable or function that is defined in another file or external to the
current scope.

Syntax:
It has the following syntax:
1. extern data_type variable_name;

Code:
1. #include <stdio.h>
2. extern int global_variable;
3. int main() {
4. global_variable = 10;
5. printf("Global variable: %d\n", global_variable);
6. return 0;
7. }
8. int global_variable;

Output:
Global variable: 10

o float: This keyword is used to declare a single-precision floating-point data type.

Syntax:
It has the following syntax:
1. float variable_name;

Example:

1. float weight = 65.5;


Code:
1. #include <stdio.h>
2. int main() {
3. float weight = 65.5;
4. printf("Weight: %.2f\n", weight);
5. return 0;
6. }

Output:
Weight: 65.50
o for: It is used to create a for loop, which repeatedly executes a block of code based on a specified
condition.

Syntax:
It has the following syntax:
1. for (initialization; condition; increment/decrement) {
2. // code to be executed
3. }
Example:
1. for (int i = 0; i< 5; i++) {
2. printf("%d ", i);
3. }
Code:
1. #include <stdio.h>
2. int main() {
3. for (inti = 0; i< 5; i++) {
4. printf("%d ", i);
5. }
6. printf("\n");
7. return 0;
8. }

Output:
0 1 2 3 4

o goto: It is used to transfer control to a labeled statement within the same function.

Syntax:
It has the following syntax:
1. goto label_name;

Code:

1. #include <stdio.h> 5. goto end; 9. end:


2. int main() { 6. } 10. printf("Loop ended.\n");
3. for (inti = 0; i< 10; i++) { 7. printf("%d ", i); 11. return 0;
4. if (i == 5) { 8. } 12. }
Output:

0 1 2 3 4
Loop ended.

o if: It is used to create an if statement to perform a certain action based on a condition.

Syntax:
It has the following syntax:
1. if (condition) {
2. // code to be executed if the condition is true
3. }

Code:

1. #include <stdio.h>
2. int main() {
3. int x = 5;
4. if (x > 0) {
5. printf("x is a positive number.\n");
6. }
7. return 0;
8. }

Output:
x is a positive number.

o int: This keyword is used to declare an integer data type.

Syntax:
It has the following syntax:
1. int variable_name;
Example:
1. int number = 10;

Code:
1. #include <stdio.h>
2.
3. int main() {
4. int number = 10;
5. printf("Number: %d\n", number);
6.
7. return 0;
8. }

Output:

Number: 10
o long: This keyword is used to declare a long integer data type.

Syntax:
It has the following syntax:
1. long variable_name;

Example:
1. long population = 1000000;

Code:
1. #include <stdio.h>
2. int main() {
3. long population = 1000000;
4. printf("Population: %ld\n", population);
5. return 0;
6. }

Output:
Population: 1000000
o register: It is used to declare a register variable, which suggests the compiler to store the variable in
a register for faster access.

Syntax:
It has the following syntax:
1. register data_type variable_name;

Example:
1. register int x = 5;

Code:
1. #include <stdio.h>
2. int main() {
3. register intreg_var = 5;
4. printf("Register Variable: %d\n", reg_var);
5. return 0;
6. }

Output:

Register Variable: 5

o return: It is used to exit a function and return a value (if any) to the calling code.

Syntax:
It has the following syntax:
1. return expression;
Code:
1. #include <stdio.h>
2. int square(intnum) {
3. return num * num;
4. }
5. intmain() {
6. int result = square(5);
7. printf("Square: %d\n", result);
8. return 0;
9. }

Output:
Square: 25

o short: This keyword is used to declare a short integer data type.

Syntax:
It has the following syntax:
1. short variable_name;

Code:
1. #include <stdio.h>
2. int main() {
3. short temperature = -10;
4. printf("Temperature: %d\n", temperature);
5. return 0;
6. }

Output:
Copy code
Temperature: -10
o signed: It is used to declare a signed data type, which can represent both positive and negative
values.

Syntax:
It has the following syntax:
1. signed data_type variable_name;

Example:
1. signed int balance = -100;

Code:
1. #include <stdio.h>
2. int main() {
3. signed int balance = -100;
4. printf("Balance: %d\n", balance);
5. return 0;
6. }
Output:
Balance: -100

o sizeof: It is used to determine the size in bytes of a data type or variable.

Syntax:
It has the following syntax:
1. sizeof(data_type); or sizeof(variable);

Code:
1. #include <stdio.h>
2. int main() {
3. int size = sizeof(int);
4. printf("Size of int: %d bytes\n", size);
5. return 0;
6. }

Output:
Size of int: 4 bytes
o static: It is used to declare a variable or function that retains its value or scope even after the block in
which it is defined has exited.

Syntax:
It has the following syntax:
1. static data_type variable_name;
2. static return_type function_name(arguments);

Code:

1. #include <stdio.h>
2. void increment() {
3. static int count = 0;
4. count++;
5. printf("Count: %d\n", count);
6. }
7. int main() {
8. increment();
9. increment();
10. return 0;
11. }

Output:

Count: 1
Count: 2
o struct: It is used to define a user-defined data type called a structure, which can hold multiple
variables of different data types.
Syntax:
It has the following syntax:
1. struct struct_name {
2. data_type member1;
3. data_type member2;
4. //...
5. };
Code:
1. #include <stdio.h>
2. #include <string.h>
3. struct Person {
4. char name[20];
5. int age;
6. };
7. int main() {
8. struct Person student;
9. strcpy(student.name, "John");
10. student.age = 20;
11. printf("Name: %s, Age: %d\n", student.name, student.age);
12. return 0;
13. }

Output:

Name: John, Age: 20


o switch: It is used to create a switch statement, which allows multiple execution paths based on
different cases.

Syntax:
It has the following syntax:
1. switch (expression) {
2. case constant1:
3. // code to be executed if expression matches constant1
4. break;
5. case constant2:
6. // code to be executed if expression matches constant2
7. break;
8. //...
9. default:
10. // code to be executed if expression does not match any constant
11. }
Code:
1. #include <stdio.h>
2. int main() {
3. int choice = 2;
4. switch (choice) {
5. case 1:
6. printf("You chose option 1.\n");
7. break;
8. case 2:
9. printf("You chose option 2.\n");
10. break;
11. default:
12. printf("Invalid choice.\n");
13. }
14. return 0;
15. }

Output:
You chose option 2.

o typedef: It is used to create a new name (alias) for an existing data type.
Syntax:
It has the following syntax:
1. typedef existing_data_type new_data_type;

Code:
1. #include <stdio.h>
2. typedef int marks;
3. int main() {
4. marks math_marks = 95;
5. printf("Math Marks: %d\n", math_marks);
6. return 0;
7. }

Code:
Math Marks: 95
o union: It is used to define a user-defined data type called a union, which can hold different data types
but only one member at a time.
Code:
1. #include <stdio.h>
2. union Number {
3. int integer;
4. float floating_point;
5. };
6. int main() {
7. union Number num;
8. num.integer = 10;
9. printf("Integer: %d\n", num.integer);
10.
11. return 0;
12. }
Output:
Integer: 10

o unsigned: It is used to declare an unsigned data type, which can represent only positive

Syntax:
It has the following syntax:
1. unsigned data_type variable_name;

Code:
1. #include <stdio.h>
2. int main() {
3. unsigned int count = 100;
4. printf("Count: %u\n", count);
5. return 0;
6. }

Output:
Count: 100
o void: This keyword is used to indicate the absence of a specific type or to define functions that do
not return a value.

Syntax:
It has the following syntax:
1. For function return type: void function_name(arguments);
2. As a data type: void variable_name;

Code:
1. #include <stdio.h>
2. void printMessage() {
3. printf("Hello, World!\n");
4. }
5. int main() {
6. printMessage();
7. return 0;
8. }

Output:
Hello, World!

o volatile: It is used to declare a variable that can be modified externally and should not be optimized
by the compiler.

Syntax:
It has the following syntax:
1. volatile data_type variable_name;
Example:
1. volatile int sensor_reading;
2. // Access and modify the sensor_reading variable in an interrupt service routine

Code:
1. #include <stdio.h>
2. int main() {
3. volatile int sensor_reading = 0;
4. // Simulating sensor reading update
5. for (inti = 0; i< 10; i++) {
6. sensor_reading = i;
7. printf("Sensor Reading: %d\n", sensor_reading);
8. }
9. return 0;
10. }

Output:
Sensor Reading: 0
Sensor Reading: 1
Sensor Reading: 2
Sensor Reading: 3
Sensor Reading: 4
Sensor Reading: 5
Sensor Reading: 6
Sensor Reading: 7
Sensor Reading: 8
Sensor Reading: 9
o while: It is used to create a while loop, which repeatedly executes a block of code based on a specified
condition.

Syntax:
It has the following syntax:
1. while (condition) {
2. // code to be executed
3. }

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

Output:
0 1 2 3 4
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) 3. char (reserved word)
2. int (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 letter. It can be written in both lowercase and


uppercase letters.

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

It is a combination of alphabetical characters. It is a combination of alphanumeric characters.

It does not contain the underscore character. It can contain the 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
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

Arithmetic Operators:

Arithmetic operators carry out fundamental mathematical operations. The arithmetic operators in C are
as follows:

Addition Operator (+): The addition operator adds two operands together.
Syntax:
It has the following syntax:
1. result = operand1 + operand2;

Example:
1. int a = 5;
2. int b = 3;
3. int result = a + b;

Output:

result = 8

Subtraction Operator (-): The second operand is subtracted from the first operand via the subtraction
operator.

Syntax:
It has the following syntax:
1. result = operand1 - operand2;
Example:
1. int a = 8;
2. int b = 3;
3. int result = a - b;

Output:
result = 5

Multiplication Operator (*): This operator is used to multiply the two operands.

Syntax:
It has the following syntax:
1. result = operand1 * operand2;

Example:

1. int a = 4;
2. int b = 5;
3. int result = a * b;

Output:

result = 20
Division Operator (/): The first operand and the second operand are divided using the division operator.

Syntax:
It has the following syntax:
1. result = operand1 / operand2;
Example:
1. int a = 10;
2. int b = 2;
3. int result = a / b;

Output:
result = 5

Modulus Operator (%): The modulus operator determines the remainder of the division between two
operands.

Syntax:
It has the following syntax:
1. result = operand1 % operand2;

Example:
1. int a = 10;
2. int b = 3;
3. int result = a % b;

Output:
result = 1
Relational Operators:

Relational operators assess the relationship between values by comparing them. They return either true
(1) or false (0). The relational operators in C are as follows:

Equality Operator (==): If two operands are equal, the equality operator verifies this.

Syntax:
It has the following syntax:
1. result = operand1 == operand2;

Example:
1. int a = 5;
2. int b = 5;
3. int result = a == b;

Output:
result=1 (true)
Inequality Operator (!=): The inequality operator determines whether two operands are equal or not.
Syntax:
It has the following syntax:
1. result = operand1 != operand2;

Example:
1. int a = 5;
2. int b = 3;
3. int result = a != b;

Output:

result=1 (true)

Greater than Operator (>): The greater than operator determines if the first operand exceeds the second
operand.

Syntax:
It has the following syntax:
1. result = operand1 > operand2;

Example:
1. int a = 7;
2. int b = 4;
3. int result = a > b;

Output:
result=1 (true)

Less than Operator (<): The less-than operator determines if the first operand less is than the second
operand.

Syntax:
It has the following syntax:
1. result = operand1 < operand2;

Example:
1. int a = 2;
2. int b = 6;
3. int result = a < b;

Output:
result=1 (true)
Greater than or Equal to Operator (>=): The greater than or equal to operator determines if the first
operand is more than or equal to the second operand.

Syntax:
It has the following syntax:
1. result = operand1 >= operand2;

Example:
1. int a = 5;
2. int b = 5;
3. int result = a >= b;

Output:
result=1 (true)

Less than or Equal To Operator (<=): The less than or equal to operator determines if the first operand
must be less than or equal to the second operand.

Syntax:
It has the following syntax:
1. result = operand1 <= operand2;

Example:
1. int a = 3;
2. int b = 6;
3. int result = a <= b;

Output:
result=1 (true)

Shift Operators:
A binary number's bits can be moved to the left or right using shift operators. The C shift workers are
listed below:

Left Shift Operator (<<): The left shift operator moves the bits of the first operand to the left by the
number of places indicated by the second argument.

Syntax:
It has the following syntax:
1. result = operand1 << operand2;

Example:
1. unsigned int a = 5; // 0000 0101 in binary
2. int result = a << 2;

Output:
result = 20 // 0001 0100 in binary
Right Shift Operator (>>): The right shift operator shifts the bits of the first operand to the right by the
number of positions specified by the second operand.

Syntax:
It has the following syntax:
1. result = operand1 >> operand2;

Example:
1. unsigned int a = 20; // 0001 0100 in binary
2. int result = a >> 2;

Output:
result = 5 // 0000 0101 in binary

Logical Operators:
Logical operators perform logical operations on boolean values and return either true (1) or false
(0). Here are the logical operators in C:

Logical AND Operator (&&): The logical AND operator returns true if both operands are true.

Syntax:
It has the following syntax:
1. result = operand1 && operand2;

Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > 3) && (b < 5);

Output:
result = 1 (true)

Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true.

Syntax:
It has the following syntax:
1. result = operand1 || operand2;

Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > 3) || (b > 5);

Output:
result = 1 (true)
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.

Syntax:
It has the following syntax:
1. result = !operand;

Example:
1. int a = 5;
2. int result = !(a > 3);

Output:
result = 0 (false)
Bitwise Operators:
Bitwise operators perform operations on individual bits of the operands. Here are the bitwise operators in
C:

Bitwise AND Operator (&): The bitwise AND operator performs a bitwise AND operation on the
corresponding bits of the operands.

Syntax:
It has the following syntax:
1. result = operand1 & operand2;

Example:
1. unsigned int a = 5; // 0000 0101 in binary
2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a & b;

Output:
result = 1 // 0000 0001 in binary
Bitwise OR Operator (|): The bitwise OR operator performs a bitwise OR operation on the corresponding
bits of the operands.

Syntax:
It has the following syntax:
1. result = operand1 | operand2;

Example:
1. unsigned int a = 5; // 0000 0101 in binary
2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a | b;

Output:
result = 7 // 0000 0111 in binary

Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR operation on the
corresponding bits of the operands.
Syntax:
It has the following syntax:
1. result = operand1 ^ operand2;

Example:
1. unsigned int a = 5; // 0000 0101 in binary
2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a ^ b;

Output:
result = 6 // 0000 0110 in binary
Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.

Syntax:
It has the following syntax:
1. result = ~operand;

Example:
1. unsigned int a = 5; // 0000 0101 in binary
2. int result = ~a;

Output:
result = -6 // 1111 1001 in binary (assuming 8-bit representation)
Ternary or Conditional Operator: The ternary or conditional operator allows you to assign a value
based on a condition.

Syntax:
It has the following syntax:
1. result = condition ? value1 : value2;

Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > b) ? a : b;

Output:
result = 5
Assignment Operator:
Assignment operators are used to assign values to variables. Here is some of the assignment operator in
C:

Simple Assignment Operator (=): The simple assignment operator assigns the value from the right side
operands to the left side operands.
Syntax:
It has the following syntax:

1. variable = value;

Example:
1. int a;
2. a = 5;

Output:
No output. The value 5 is assigned to variable 'a'.

Miscellaneous Operator:
The sizeof operator and the comma operator fall under the miscellaneous operator category.
size of Operator: The sizeof operator returns the size, in bytes, of a variable or a data type.

Syntax:
It has the following syntax:
1. result = sizeof(variable / data type);

Example:
1. int a;
2. int size = sizeof(a);

Output:
size = 4 // Assuming int occupies 4 bytes

Comma Operator (,): The comma operator evaluates multiple expressions and returns the value of
the last expression.

Syntax:
It has the following syntax:
1. makefileCopy code
2. result = (expression1, expression2,..., expressionN);
Example:
1. int a = 5, b = 3;
2. int result = (a += 2, b *= 2, a + b);

Output:

result = 15 // a = 7, b = 6, a + b = 13
Uses of Operators:
The following are some common uses for the various kinds of operators in C:
o Calculations in fundamental mathematics are performed using the addition and subtraction
operators (+ and -).
o If the user wants to do some multiplication and division operations, utilize the multiplication and
division operators (* and /).
o The remainder of a division operation is obtained using the modulus operator (%).
o Equality and inequality operators (== and!=) are needed to compare values and determine whether
they are equal or not.
o Use the greater than and less than operators (>and <) to compare values and determine if one value
is larger than or less than
o A value's relationship to another value may be determined using the larger than or equal to and less
than or equal to operators (>= and <=).
o A binary number's bits are shifted to the left using the left shift operator (<<).
o A binary number's bits can be shifted to the right using the right shift operator (>>).
o Use the logical AND operator (&&) to combine many criteria and determine if each condition is true.
o When combining several criteria, the logical OR operator (||) is used to determine if at least one of
the conditions is true.
o The logical NOT operator (!) is used to negate a condition's value.
o When two numbers' individual bits are involved, the bitwise AND operator (&) is utilized to
accomplish the action.
o The bitwise OR operator (|) is employed when two numbers' individual bits are involved.
o Bitwise exclusive OR operator is performed on individual bits of two integers using the bitwise XOR
operator ().
o Use the bitwise NOT operator () to flip or invert the bits of an integer.
o Use the ternary operator (?:) to assign a value depending on a condition in a compact form.
o A value is assigned to a variable using the simple assignment operator (=).
o The sizeof operator is used to calculate a variable's or data type's size in bytes.
o When evaluating several expressions, the comma operator (,) returns the result of the last expression
that was evaluated.

Conclusion:
In this blog, we have covered the several types of C operators, such as arithmetic, relational, shift, logical,
bitwise, ternary, assignment, and other operators. We also covered their features, syntax, samples, and
what results to expect. By becoming proficient with these operators, you may effectively handle data and
write reliable C programs.

Comments in C
Comments in C language are used to provide information about lines of code. It is widely 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.
1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
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

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. return 0;
8. }
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. return 0;
8. }
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
Escape Sequence in C
Programming languages like C have escape sequences as a standard feature. They enable the inclusion
of special characters and control patterns in strings and character constants that are difficult to represent
or write directly. In this blog post, we will explore escape sequences in C, their syntax, usage,
and examples with matching outputs. Therefore, let's start this adventure to understanding escape
sequences in C.

An escape sequence in the C programming language consists of a backslash () and a character that stands
in for a special character or control sequence. During the compilation process, the C compiler substitutes
any escape sequences it comes across with the relevant character or control sequence. It enables the use
of difficult-to-represent characters like newlines, tabs, quotations, and backslashes. It is composed of two
or more characters starting with backslash \. For example: \n represents new line.

Regular Escape Sequences:


There are several escape sequence in C programming languages.

Escape S equence 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
Now that we have a thorough understanding of each escape sequence in C,

Alarm or Beep (\a):


The alarm or beep escape sequence (a) produces an audible alert or beep sound.
1. #include <stdio.h>
2. int main() {
3. printf("This is an alarm sound: \a");
4. return 0;
5. }
Output:
This is an alarm sound:

Backspace (\b):
The cursor can be advanced by one character with the backspace escape key (b).
1. #include <stdio.h>
2. int main() {
3. printf("Hello\b\b\bWorld!");
4. return 0;
5. }
Output:
HelloWorld!
Form Feed (\f):
The form feed escape sequence (f) is used to mimic a page break or advance to the next page
1. #include <stdio.h>
2. int main() {
3. printf("This is before the form feed.\fThis is after the form feed.");
4. return 0;
5. }
Output:
This is before the form feed.
This is after the form feed.

New Line (\n):


The new line escape sequence (n) is used to insert a newline character and move the cursor to the start of
the following line.
1. #include <stdio.h>
2. int main() {
3. printf("Line 1\nLine 2");
4. return 0;
5. }

Output:

Line 1
Line 2
Carriage Return (\r):
The cursor can be moved to the start of the current line by using the carriage return escape sequence (r).
1. #include <stdio.h>
2. int main() {
3. printf("Hello\rWorld!");
4. return 0;
5. }

Output:

World!

Tab (Horizontal) (\t):


The tab escape sequence (t) is used to insert a horizontal tab character and shift the cursor to the following
tab stop.
1. #include <stdio.h>
2. int main() {
3. printf("Name:\tJohn\tAge:\t25");
4. return 0;
5. }

Output:

Name: John Age: 25


Vertical Tab (\v):
The vertical tab escape sequence (v) is used to simulate a vertical tab or shift the mouse to the following
vertical tab location.
1. #include <stdio.h>
2. int main() {
3. printf("Hello\vWorld!");
4. return 0;
5. }

Output:

Hello
World!
Backslash (\):
A backslash character is inserted using the backslash escape sequence (\).
1. #include <stdio.h>
2. int main() {
3. printf("This is a backslash: \\Hello");
4. return 0;
5. }
Output:
This is a backslash: \Hello
Single Quote ('):
The single quote escape sequence (') is used to insert a single quote character.
1. #include <stdio.h>
2. int main() {
3. printf("This is a single quote: \'Hello\'");
4. return 0;
5. }

Output:

This is a single quote: 'Hello'

Double Quote ("):


A double quotation character is inserted using the double quote escape sequence (").
1. #include <stdio.h>
2. int main() {
3. printf("This is a double quote: \"Hello\"");
4. return 0;
5. }

Output:

This is a double quote: "Hello"

Question Mark (?):


The question mark escape sequence (?) is used to insert a question mark character.
1. #include <stdio.h>
2. int main() {
3. printf("This is a question mark: \?");
4. return 0;
5. }

Output:

This is a question mark: ?

Octal Number (\nnn):


The character's octal value can be inserted using the octal number escape sequence (nnn).
1. #include <stdio.h>
2. int main() {
3. printf("This is an octal value: \101");
4. return 0;
5. }

Output:

This is an octal value: A


Hexadecimal Number (\xhh):
A character's hexadecimal value can be inserted using the hexadecimal number escape sequence (xhh).
1. #include <stdio.h>
2. int main() {
3. printf("This is a hexadecimal value: \x41");
4. return 0;
5. }

Output:

This is a hexadecimal value: A

Null (\0):
The null character, denoted by "0", is inserted using the null escape sequence (0).
1. #include <stdio.h>
2. int main() {
3. char myString[] = "Hello\0World!";
4. printf("String: %s", myString);
5. return 0;
6. }

Output:

String: Hello

Conclusion:
In conclusion, escape sequences are a crucial component of C programming that enables us to
successfully handle special characters and control sequences. We may put characters into strings and
character variables that are challenging to directly express using escape sequences.

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 chara cter 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 i n
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. int main()
3. {
4. char ch; // variable declaration
5. printf("Enter a character");
6. scanf("%c",&ch); // user input
7. printf("\n The ascii value of the ch variable is : %d", ch);
8. return 0;
9. }

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
In programming languages like C, constants are essential because they give you a
mechanism to store unchanging values that hold true throughout the course of the program. These
numbers may be used for several things, such as creating mathematical constants or giving variables
set values. We will discuss the idea of constants in C, their syntax, how to declare and use them and give
illustrated examples along with their anticipated results in this blog article. By the end of this article, you'll
have a firm grasp of constants and their importance in C programming.
A constant in C is a value that doesn't change as the program runs. Integers, floating-point numbers,
characters, and strings are just a few of the several types of constants that may be employed. When a
constant has a value, it cannot be changed, unlike variables. They may be utilized in various operations and
computations and serve as the program's representation of fixed values.
Advantages of C Constants:
There are several advantages of C Constants. Some main advantages of C Constants are as fol lows:
1. Programmers may use constants to provide names that have meaning to fixed numbers, which makes
the code simpler to comprehend and update.
2. Constants assist in avoiding the usage of magic numbers, which are hard -coded values, in the code.
Instead, constants offer named representations of such values, enhancing the code's readability.
3. Constants are reusable throughout the program, allowing for constant values in various locations and
lowering the possibility of errors brought on by typos or inconsistent values.
4. Calculations or processes inside the program can be optimized by using certain constants, such as
mathematical or physical constants.
5. 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.

Types of constant:
There are different types of Constants in C. Some of them are as follows:

Decimal Constant
A whole number represented in base 10 is known as a decimal constant. It has digits that range
from 0 to 9. Declaring a decimal constant has a simple syntax that just requires the value to be written.

Example:
1. #include <stdio.h>
2. int main() {
3. int decimal = 42;
4. printf("The decimal constant is: %d\n", decimal);
5. return 0;
6. }

Output:
The decimal constant is: 42

Real or Floating-Point Constant:


A fractional component or exponentiation of a number is represented by a real or floating-point
constant. It can be expressed with a decimal point, the letter "E", or the symbol "e" in exponential or
decimal notation.

Example:
1. #include <stdio.h>
2. int main() {
3. float real = 3.14;
4. printf("The real constant is: %f\n", real);
5. return 0;
6. }
Output:
The real constant is: 3.140000

Octal Constant:
A base 8 value is represented by an octal constant. It is prefixed with a '0' (zero) to show that it is an octal
constant and has digits ranging from 0 to 7.

Example:
1. #include <stdio.h>
2. int main() {
3. int octal = 052; // Octal representation of decimal 42
4. printf("The octal constant is: %o\n", octal);
5. return 0;
6. }

Output:
The octal constant is: 52

Hexadecimal Constant:
A base-16 value is represented by a hexadecimal constant. It uses letters A to F (or a to f) and
numbers 0 to 9 to represent values from 10 to 15. It is prefixed with '0x' or '0X' to identify it as a
hexadecimal constant.

Example:
1. #include <stdio.h>
2. int main() {
3. int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42
4. printf("The hexadecimal constant is: %x\n", hexadecimal);
5. return 0;
6. }

Output:
The hexadecimal constant is: 2a

Character Constant
A character constant represents a single character that is enclosed in single quotes.

Example:
1. #include <stdio.h>
2. int main() {
3. char character = 'A';
4. printf("The character constant is: %c\n", character);
5. return 0;
6. }

Output:
The character constant is: A
String Constant:
A series of characters wrapped in double quotes is represented by a string constant. It is a character array
that ends with the null character \0.

Example:
1. #include <stdio.h>
2. int main() {
3. char string[] = "Hello, World!";
4. printf("The string constant is: %s\n", string);
5. return 0;
6. }

Output:
The string constant is: Hello, World!

Rules for constructing constants:


The creation of constants must follow specified guidelines. These guidelines specify the format that
constants of various kinds must follow in order for the compiler to accept them as legitimate. The guidelines
for creating constants in C are as follows:

Integer Constants:
1. The digits of an integer constant can range from 0 to 9.
2. A decimal point should not be present in an integer constant.
3. Positive or negative integer constants are also possible.
4. You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for unsigned,
'L' or 'l' for long, or 'LL' or 'll' for long long.

Floating-Point Constants:
1. A decimal point, an exponent, or digits can all be found in floating-point constants.
2. Either exponential notation or decimal notation can be used to write them.
3. 'E' or 'e' can be used to denote an exponent.
4. You can add a suffix to a constant's name to define its type. For instance, "F" or "f" stands
for float and "L" or "l" for long double.

Octagonal Constants
1. Base 8 is used for writing octal constants.
2. They are made up of the numerals 0 through 7.
3. A '0' (zero) should come before any octal constants.

Hexadecimal Constants:
1. Constants in hexadecimal are expressed in base 16.
2. To represent numbers from 10 to 15, they are made up of numerals 0 to 9 and letters A to F (or a
to f).
3. Prefixing a hexadecimal constant with '0x' or '0X' is appropriate.
Character Constants:
1. Individual characters are represented as character constants when they are in single quotes.
2. A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be used as these
characters.

String Constants:
1. A series of characters surrounded in double quotes is represented by string constants.
2. They are essentially character arrays that are closed with the null character "0".

Conclusion:
As a result of their representation of fixed values that don't change during the course of the program,
constants are crucial in C programming. By following the rules for making constants, programmers may
create reliable and practical representations of data in their programs .

By giving descriptive names to fixed values, minimizing the usage of "magic numbers", and encouraging
self-documenting code, constants improve the readability of code. By offering a central area to edit
constant values, facilitating simple modifications, and lowering the possibility of mistakes, they also aid in
the maintainability of the code.

As constants may be used and referenced several times throughout the program, using them in C
programs also increases code reuse. When utilizing the same value again, it assures consistency and lessens
the possibility of adding errors or mistakes.

Constants can also improve computations and processes, particularly when physical or mathematica l
constants are involved. Programmers can create code that is more effective and optimized by utilizing
constants rather than hard-coding variables.

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.
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 Operators in C
o Identifiers in C o Constant in C
o Strings 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 Bitwise Operators


o Relational Operators o Conditional Operators
o Shift Operators o Assignment Operator
o Logical Operators 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
o Using #define pre-processor

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 multidimensiona l
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.
C Boolean
I C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value
represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents
true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1. We do not require to use any
header file to use the Boolean data type in C++, but in C, we have to use the header file, i.e., stdbool.h. If
we do not use the header file, then the program will not compile.

Syntax
1. bool variable_name;
In the above syntax, bool is the data type of the variable, and variable_name is the name of the variable.
Let's understand through an example.
1. #include <stdio.h>
2. #include<stdbool.h>
3. int main()
4. {
5. bool x=false; // variable initialization.
6. if(x==true) // conditional statements
7. {
8. printf("The value of x is true");
9. }
10. else
11. printf("The value of x is FALSE");
12. return 0;
13. }
In the above code, we have used <stdbool.h> header file so that we can use the bool type variable in our
program. After the declaration of the header file, we create the bool type variable ' x' and assigns a 'false'
value to it. Then, we add the conditional statements, i.e., if..else, to determine whether the value of 'x' is
true or not.

Output
The value of x is FALSE
Boolean Array
Now, we create a bool type array. The Boolean array can contain either true or false value, and the values
of the array can be accessed with the help of indexing.

Let's understand this scenario through an example.


1. #include <stdio.h>
2. #include<stdbool.h>
3. int main()
4. {
5. bool b[2]={true,false}; // Boolean type array
6. for(int i=0;i<2;i++) // for loop
7. {
8. printf("%d,",b[i]); // printf statement
9. }
10. return 0;
11. }
In the above code, we have declared a Boolean type ar ray containing two values, i.e., true and false.

Output
1,0,

Typedef
There is another way of using Boolean value, i.e., typedef. Basically, typedef is a keyword in C language,
which is used to assign the name to the already existing datatype.

Let's see a simple example of typedef.


1. #include <stdio.h>
2. typedef enum{false,true} b;
3. int main()
4. {
5. b x=false; // variable initialization
6. if(x==true) // conditional statements
7. {
8. printf("The value of x is true");
9. }
10. else
11. {
12. printf("The value of x is false");
13. }
14. return 0;
15. }

In the above code, we use the Boolean values, i.e., true and false, but we have not used the bool type. We
use the Boolean values by creating a new name of the 'bool' type. In order to achieve this, the
typedef keyword is used in the program.

1. typedef enum{false,true} b;
The above statement creates a new name for the 'bool' type, i.e., 'b' as 'b' can contain either true or false
value. We use the 'b' type in our program and create the 'x' variable of type 'b'.

Output
The value of x is false

Boolean with Logical Operators


The Boolean type value is associated with logical operators. There are three types of logical operators in
the C language:

&&(AND Operator): It is a logical operator that takes two operands. If the value of both the operands are
true, then this operator returns true otherwise false

||(OR Operator): It is a logical operator that takes two operands. If the value of both the operands is false,
then it returns false otherwise true.
!(NOT Operator): It is a NOT operator that takes one operand. If the value of the operand is false, then it
returns true, and if the value of the operand is true, then it returns false.

Let's understand through an example.


1. #include <stdio.h>
2. #include<stdbool.h>
3. int main()
4. {
5. bool x=false;
6. bool y=true;
7. printf("The value of x&&y is %d", x&&y);
8. printf("\nThe value of x||y is %d", x||y);
9. printf("\nThe value of !x is %d", !x);
10. }

Output
The value of x&&y is 0
The value of x||y is 1
The value of !x is 1

Static in C
Static is a keyword used in C programming language. It can be used with both variables and functions, i.e.,
we can declare a static variable and static function as well. An ordinary variable is limited to the scope in
which it is defined, while the scope of the static variable is throughout the program.

Static keyword can be used in the following situations:


o Static global variable
When a global variable is declared with a static keyword, then it is known as a static global
variable. It is declared at the top of the program, and its visibility is throughout the program.
o Static function
When a function is declared with a static keyword known as a static function. Its lifetime is
throughout the program.
o Static local variable
When a local variable is declared with a static keyword, then it is known as a static local variable.
The memory of a static local variable is valid throughout the program, but the scope of visibility
of a variable is the same as the automatic local variables. However, when the function modifies
the static local variable during the first function call, then this modified value will be available for
the next function call also.
o Static member variables
When the member variables are declared with a static keyword in a class, then it is known as static
member variables. They can be accessed by all the instances of a class, not with a specific
instance.
o Static method
The member function of a class declared with a static keyword is known as a static method. It is
accessible by all the instances of a class, not with a specific instance.
Let's understand through an example.
1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6. return 0;
7. }
8. int func()
9. {
10. int count=0; // variable initialization
11. count++; // incrementing counter variable
12. return count; }

In the above code, the func() function is called. In func(), count variable gets updated. As soon as the functio n
completes its execution, the memory of the count variable will be removed. If we do not want to remove
the count from memory, then we need to use the count variable as static. If we declare the variable as static,
then the variable will not be removed from the memory even when the function completes its execution.

Output
1
1
Static variable
A static variable is a variable that persists its value across the various function calls.

Syntax
The syntax of a static variable is given below:
1. static data_type variable_name;
Let's look at a simple example of static variable.
1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6. return 0;
7. }
8. int func()
9. {
10. static int count=0;
11. count++;
12. return count;
13. }

In the above code, we have declared the count variable as static. When the func() is called, the value of
count gets updated to 1, and during the next function call, the value of the count variable becomes 2.
Therefore, we can say that the value of the static variable persists within the function call.
Output
1
2
Static Function
As we know that non-static functions are global by default means that the function can be accessed outside
the file also, but if we declare the function as static, then it limits the function scope. The static function can
be accessed within a file only.

The static function would look like as:

1. static void func()


2. {
3. printf("Hello javaTpoint");
4. }

Differences b/w static and global variable


Global variables are the variables that are declared outside the function. These global variables exist at the
beginning of the program, and its scope remains till the end of the program. It can be accessed outside the
program also.
Static variables are limited to the source file in which they are defined, i.e., they are not accessible by the
other source files.

Both the static and global variables have static initialization. Here, static initialization means if we do not
assign any value to the variable then by default, 0 value will be assigned to the variable.

Differences b/w static local and static global variable


Static global variable
If the variable declared with a static keyword outside the function, then it is known as a static global variable.
It is accessible throughout the program.

Static local variable


The variable with a static keyword is declared inside a function is known as a static local variable. The scope
of the static local variable will be the same as the automatic local variables, but its memory will be available
throughout the program execution. When the function modifies the value of the static local variable during
one function call, then it will remain the same even during the next function call.

Properties of a static variable

The following are the properties of a static variable:

o The memory of a static variable is allocated within a static variable.


o Its memory is available throughout the program, but the scope will remain the same as the automatic
local variables. Its
o value will persist across the various function calls.
o If we do not assign any value to the variable, then the default value will be 0.
o A global static variable cannot be accessed outside the program, while a global variable can be accessed
by other source files.
Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the behavior of the progr am
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 e rror 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
Compile time vs Runtime
Compile-time and Runtime are the two programming terms used in the software
development. Compile-time is the time at which the source code is converted into an
executable code while the run time is the time at which the executable code is started
running. Both the compile-time and runtime refer to different types of error.

Compile-time errors
Compile-time errors are the errors that occurred when we write the wrong syntax. If we
write the wrong syntax or semantics of any programming language, then the compile-
time errors will be thrown by the compiler. The compiler will not allow to run the program
until all the errors are removed from the program. When all the errors are removed from
the program, then the compiler will generate the executable file.

The compile-time errors can be:

ADVERTISEMENT

o Syntax errors
o Semantic errors

Syntax errors

When the programmer does not follow the syntax of any programming language, then
the compiler will throw the syntax error.

ADVERT ISEMENT

For example,
int a, b:

The above declaration generates the compile-time error as in C, every statement ends
with the semicolon, but we put a colon (:) at the end of the statement.

Semantic errors

The semantic errors exist when the statements are not meaningful to the compiler.

For example,

a+b=c;

The above statement throws a compile-time errors. In the above statement, we are
assigning the value of 'c' to the summation of 'a' and 'b' which is not possible in C
programming language as it can contain only one variable on the left of the assignment
operator while right of the assignment operator can contain more than one variable.

The above statement can be re-written as:

c=a+b;

Runtime errors
The runtime errors are the errors that occur during the execution and after compilation.
The examples of runtime errors are division by zero, etc. These errors are not easy to
detect as the compiler does not point to these errors.

Let's explore some typical C runtime error types, cases, and their possible effects.

Division by Zero:
Since division by zero is mathematically undefinable, attempting to divide an integer
by zero leads to a runtime error. This mistake causes the program to crash or produce
an exception. Here's an example:

1. #include <stdio.h>
2.
3. int main() {
4. int a = 10;
5. int b = 0;
6. int result = a / b; // Division by zero
7. printf("Result: %d\n", result);
8. return 0;
9. }

Output:

Floating point exception (core dumped)

Explanation:

A "Floating point exception" error message is produced when the program encounters
a runtime issue because of division by zero.

Accessing Array Out of Bounds:


A runtime error occurs when an array element is accessed outside of certain limits. An
error happens when an index is larger than the array's size and memory access laws are
broken. Here's an example:

1. #include <stdio.h>
2.
3. int main() {
4. int arr[5] = {1, 2, 3, 4, 5};
5. int index = 10;
6. int value = arr[index]; // Accessing array out of bounds
7. printf("Value: %d\n", value);
8. return 0;
9. }

Output:

Segmentation fault (core dumped)

Explanation:

The element at index 10 is beyond the bounds of the array when the program tries to
access it. As a result, a segmentation fault occurs, and the program ends with an error.
Null Pointer Dereference:
A runtime error happens when you try to access a null pointer's memory address, which
is known as dereferencing a null pointer. Accessing null pointers results in unpredictable
behavior because they do not point to legitimate memory locations. Here's an example:

1. #include <stdio.h>
2.
3. int main() {
4. int* ptr = NULL; // Null pointer
5. int value = *ptr; // Null pointer dereference
6. printf("Value: %d\n", value);
7. return 0;
8. }

Output:

Segmentation fault (core dumped)

Explanation:

The attempt to dereference a null pointer results in a segmentation fault, which causes
the program to crash with an error message.

Stack Overflow:
A stack overflow happens when the call stack grows larger than intended, containing
information about function calls. An infinite recursion usually results when recursive
functions lack appropriate termination criteria. Here's an example:

1. #include <stdio.h>
2.
3. void recursiveFunction() {
4. recursiveFunction(); // Recursive call without termination condition
5. }
6.
7. int main() {
8. recursiveFunction();
9. return 0;
10. }

Output:

Segmentation fault (core dumped)

Explanation:

The program starts an endless recursion, which overflows the stack and causes a
segmentation fault.

Unused variables:
Because uninitialized variables have undefined values, using them might result in
runtime errors. The program could provide surprising results or crash, depending on the
circumstance. Here's an example:

1. #include <stdio.h>
2.
3. int main() {
4. int uninitializedVariable;
5. printf("Value: %d\n", uninitializedVariable); // Using uninitialized variable
6. return 0;
7. }

Output:

Some random value (varies each time)

Explanation:

In this example, the value of an uninitialized variable can be any random value chosen
randomly from the memory region designated to that variable.

Let's look at the differences between compile-time and runtime:


Compile-time Runtime

The compile-time errors are the errors which The runtime errors are the errors which are no
are produced at the compile-time, and they are generated by the compiler and produce a
detected by the compiler. unpredictable result at the execution time.

In this case, the compiler prevents the code In this case, the compiler does not detect the error, s
from execution if it detects an error in the it cannot prevent the code from the execution.
program.

It contains the syntax and semantic errors such It contains the errors such as division by zer
as missing semicolon at the end of the determining the square root of a negative number.
statement.

Example of Compile-time error

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

In the above code, we have tried to print the value of 'a', but it throws an error. We put
the colon at the end of the statement instead of a semicolon, so this code generates a
compile-time error.

Output
Example of runtime error

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

In the above code, we try to divide the value of 'b' by zero, and this throws a runtime
error.

Output
Conclusion:
In conclusion, the periods of software development known as compile-
time and runtime errors are separate, and each has a unique set of faults that might
occur. Compile-time errors happen when the code is converted into executable form
during the compilation step. These errors include semantic errors, which
produce illogical or absurd code, and syntax faults, which go against the laws of the
programming language. These errors are identified by the compiler and
reported, blocking the execution of the code until they are fixed.

On the other hand, runtime errors occur when a program is running and are not caught
by the compiler. They can result from several conditions, including division by zero,
erroneous memory access, or other unforeseen events. Runtime errors are more
difficult to discover and debug since they frequently result in program crashes or
unexpected behavior. To elegantly manage runtime errors and guarantee the program's
stability, developers use error-handling techniques like exception handling.

Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depends upon the output of the expression. It
is represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary


operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.

Syntax of a conditional operator

1. Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:


Meaning of the above syntax.

ADVERTISEMENT

o In the above syntax, the expression1 is a Boolean condition that can be either true
or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int age; // variable declaration
5. printf("Enter your age");
6. scanf("%d",&age); // taking user input for age variable
7. (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditio
nal operator
8. return 0;
9. }
In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator. In this condition, we are checking
the age of the user. If the age of the user is greater than or equal to 18, then the
statement1 will execute, i.e., (printf("eligible for voting")) otherwise, statement2 will
execute, i.e., (printf("not eligible for voting")).

Let's observe the output of the above program.

If we provide the age of user below 18, then the output would be:

If we provide the age of user above 18, then the output would be:

As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.

Till now, we have observed that how conditional operator checks the condition and based
on condition, it executes the statements. Now, we will see how a conditional operator is
used to assign the value to a variable.

Let's understand this scenario through an example.


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

In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to
the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using
the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value
otherwise 2.

Output

The above output shows that the value of 'b' variable is 3 because the value of 'a' variable
is equal to 5.

As we know that the behavior of conditional operator and 'if-else' is similar but they have
some differences. Let's look at their differences.

o A conditional operator is a single programming statement, while the 'if-else'


statement is a programming block in which statements come under the
parenthesis.
o A conditional operator can also be used for assigning a value to the variable,
whereas the 'if-else' statement cannot be used for the assignment purpose.
o It is not useful for executing the statements when the statements are multiple,
whereas the 'if-else' statement proves more suitable when executing multiple
statements.
o The nested ternary operator is more complex and cannot be easily debugged, while
the nested 'if-else' statement is easy to read and maintain.

Bitwise Operator in C
The bitwise operators are the operators used to perform the operations on the data at
the bit-level. When we perform the bitwise operations, then it is also known as bit-level
programming. It consists of two digits, either 0 or 1. It is mainly used in numerical
computations to make the calculations faster.

We have different types of bitwise operators in the C programming language. The


following is the list of the bitwise operators:

Operator Meaning of operator

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ One's complement operator (unary operator)

<< Left shift operator

>> Right shift operator

Let's look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y

0 0 0 0 0
0 1 0 1 1

1 0 0 1 1

1 1 1 1 1

Bitwise AND operator


Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands
are written on both sides of the (&) operator. If the corresponding bits of both the
operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output
would be 0.

For example,

1. We have two variables a and b.


2. a =6;
3. b=4;
4. The binary representation of the above two variables are given below:
5. a = 0110
6. b = 0100
7. When we apply the bitwise AND operation in the above two variables, i.e., a&b, the outp
ut would be:
8. Result = 0100

As we can observe from the above result that bits of both the variables are compared one
by one. If the bit of both the variables is 1 then the output would be 1, otherwise 0.

Let's understand the bitwise AND operator through the program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=6, b=14; // variable declarations
5. printf("The output of the Bitwise AND operator a&b is %d",a&b);
6. return 0;
7. }
In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b'
are 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively.
When we apply the AND operator between these two variables,

a AND b = 0110 && 1110 = 0110

Output

Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands
are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then
the output would be 1, otherwise 0.

For example,

1. We consider two variables,


2. a = 23;
3. b = 10;
4. The binary representation of the above two variables would be:
5. a = 0001 0111
6. b = 0000 1010
7. When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the ou
tput would be:
8. Result = 0001 1111

As we can observe from the above result that the bits of both the operands are compared
one by one; if the value of either bit is 1, then the output would be 1 otherwise 0.
Let's understand the bitwise OR operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=23,b=10; // variable declarations
5. printf("The output of the Bitwise OR operator a|b is %d",a|b);
6. return 0;
7. }

Output

Bitwise exclusive OR operator


Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.

For example,

ADVERT ISEMENT

1. We consider two variables a and b,


2. a = 12;
3. b = 10;
4. The binary representation of the above two variables would be:
5. a = 0000 1100
6. b = 0000 1010
7. When we apply the bitwise exclusive OR operator in the above two variables (a^b), then
the result would be:
8. Result = 0000 1110

As we can observe from the above result that the bits of both the operands are compared
one by one; if the corresponding bit value of any of the operand is 1, then the output
would be 1 otherwise 0.

Let's understand the bitwise exclusive OR operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=12,b=10; // variable declarations
5. printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
6. return 0;
7. }

Output

ADVERT ISEMENT
ADVERT ISEMENT

Bitwise complement operator


The bitwise complement operator is also known as one's complement operator. It is
represented by the symbol tilde (~). It takes only one operand or variable and performs
complement operation on an operand. When we apply the complement operation on any
bits, then 0 becomes 1 and 1 becomes 0.
For example,

1. If we have a variable named 'a',


2. a = 8;
3. The binary representation of the above variable is given below:
4. a = 1000
5. When we apply the bitwise complement operator to the operand, then the output woul
d be:
6. Result = 0111
ADVERTISEMENT

As we can observe from the above result that if the bit is 1, then it gets changed to 0 else
1.

Let's understand the complement operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=8; // variable declarations
5. printf("The output of the Bitwise complement operator ~a is %d",~a);
6. return 0;
7. }

Output

Bitwise shift operators


Two types of bitwise shift operators exist in C programming. The bitwise shift operators
will shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise
shift operator is divided into two categories:

ADVERTISEMENT

o Left-shift operator
o Right-shift operator

Left-shift operator

It is an operator that shifts the number of bits to the left-side.

ADVERTISEMENT
ADVERTISEMENT

Syntax of the left-shift operator is given below:

1. Operand << n

Where,

Operand is an integer expression on which we apply the left-shift operation.

n is the number of bits to be shifted.

In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the
left side will be popped out, and 'n' bits on the right-side are filled with 0.

For example,

1. Suppose we have a statement:


2. int a = 5;
3. The binary representation of 'a' is given below:
4. a = 0101
5. If we want to left-shift the above representation by 2, then the statement would be:
6. a << 2;
7. 0101<<2 = 00010100

Let's understand through a program.


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

Output

Right-shift operator

It is an operator that shifts the number of bits to the right side.

Syntax of the right-shift operator is given below:

1. Operand >> n;

Where,

Operand is an integer expression on which we apply the right-shift operation.

N is the number of bits to be shifted.

In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits
on the right-side will be popped out, and 'n' bits on the left-side are filled with 0.

For example,
1. Suppose we have a statement,
2. int a = 7;
3. The binary representation of the above variable would be:
4. a = 0111
5. If we want to right-shift the above representation by 2, then the statement would be:
6. a>>2;
7. 0000 0111 >> 2 = 0000 0001

Let's understand through a program.

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

Output

What is the 2s complement in C?


The 2s complement in C is generated from the 1s complement in C. As we know that the
1s complement of a binary number is created by transforming bit 1 to 0 and 0 to 1; the
2s complement of a binary number is generated by adding one to the 1s complement of
a binary number.

In short, we can say that the 2s complement in C is defined as the sum of the one's
complement in C and one.

In the above figure, the binary number is equal to 00010100, and its one's complement is
calculated by transforming the bit 1 to 0 and 0 to 1 vice versa. Therefore, one's
complement becomes 11101011. After calculating one's complement, we calculate the
two's complement by adding 1 to the one's complement, and its result is 11101100.

Let's create a program of 2s complement.

ADVERT ISEMENT

1. #include <stdio.h>
2. int main()
3. {
4. int n; // variable declaration
5. printf("Enter the number of bits do you want to enter :");
6. scanf("%d",&n);
7. char binary[n+1]; // binary array declaration;
8. char onescomplement[n+1]; // onescomplement array declaration
9. char twoscomplement[n+1]; // twoscomplement array declaration
10. int carry=1; // variable initialization
11. printf("\nEnter the binary number : ");
12. scanf("%s", binary);
13. printf("%s", binary);
14. printf("\nThe ones complement of the binary number is :");
15.
16. // Finding onescomplement in C
17. for(int i=0;i<n;i++)
18. {
19. if(binary[i]=='0')
20. onescomplement[i]='1';
21. else if(binary[i]=='1')
22. onescomplement[i]='0';
23. }
24. onescomplement[n]='\0';
25. printf("%s",onescomplement);
26.
27.
28. printf("\nThe twos complement of a binary number is : ");
29.
30. // Finding twoscomplement in C
31. for(int i=n-1; i>=0; i--)
32. {
33. if(onescomplement[i] == '1' && carry == 1)
34. {
35. twoscomplement[i] = '0';
36. }
37. else if(onescomplement[i] == '0' && carry == 1)
38. {
39. twoscomplement[i] = '1';
40. carry = 0;
41. }
42. else
43. {
44. twoscomplement[i] = onescomplement[i];
45. }
46. }
47. twoscomplement[n]='\0';
48. printf("%s",twoscomplement);
49. return 0;
50. }

Output

Analysis of the above program,


ADVERTISEMENT

o First, we input the number of bits, and it gets stored in the 'n' variable.
o After entering the number of bits, we declare character array, i.e., char
binary[n+1], which holds the binary number. The 'n' is the number of bits which
we entered in the previous step; it basically defines the size of the array.
o We declare two more arrays, i.e., onescomplement[n+1],
and twoscomplement[n+1]. The onescomplement[n+1] array holds the ones
complement of a binary number while the twoscomplement[n+1] array holds the
two's complement of a binary number.
o Initialize the carry variable and assign 1 value to this variable.
o After declarations, we input the binary number.
o Now, we simply calculate the one's complement of a binary number. To do this, we
create a loop that iterates throughout the binary array, for(int i=0;i<n;i++). In for
loop, the condition is checked whether the bit is 1 or 0. If the bit is 1
then onescomplement[i]=0 else onescomplement[i]=1. In this way, one's
complement of a binary number is generated.
o After calculating one's complement, we generate the 2s complement of a binary
number. To do this, we create a loop that iterates from the last element to the
starting element. In for loop, we have three conditions:
o If the bit of onescomplement[i] is 1 and the value of carry is 1 then we put
0 in twocomplement[i].
o If the bit of onescomplement[i] is 0 and the value of carry is 1 then we put
1 in twoscomplement[i] and 0 in carry.
o If the above two conditions are false, then onescomplement[i] is equal to
twoscomplement[i].

Signed integers are frequently represented in C using the two's complement notation.
Using the same binary representation offers a mechanism to express
both positive and negative integers. The most significant bit (MSB) is used as the sign
bit in a two's complement representation, where 0 denotes a positive integer,
and 1 denotes a negative number.

Starting with a negative number's absolute value in binary form, you may take the one's
complement (bitwise negation) of that value to get the two's
complement representation of the negative integer. You add 1 to the resultant
value to acquire the representation of the two's complement.

The two's complement encoding in C can represent signed integers and can perform
fast arithmetic operations. One benefit of employing two's complement is the ability to
do addition and subtraction using the same binary operations as for unsigned numbers.

The binary numbers are added together like unsigned integers when adding two's
complement. A carry-out from the location of the main critical bit is just disregarded.
Due to this fact, handling signed numbers differently is not necessary, and addition
becomes simple.
Consider adding -5 and -3 using the 8-bit two's complement representation, for
instance:

Binary number for -5 is 11111011.

Binary number for -3 is 11111101.

carrying out the addition:

1. 11111011 (-5)
2. 11111101 (-3)
3. -------------
4. 111110100 (-8)

The answer is 111110100, which in two's complement is equal to -8.

Similar to addition, subtraction may be done by treating the second operand's two's
complement as if it were addition. In other words, you add the two's complement of a
negative number to the first operand to remove it.

For instance, when -3 is subtracted from -5:

In binary, -5 is represented by 11111011 and -(-3) by 00000011 (two's complement of -


3)

Carrying out the subtraction

1. 11111011 (-5)
2. 00000011 (+3)
3. -------------
4. 11111110 (-8)

The outcome is 11111110, which in two's complement is equal to -8.

Conclusion:
In C, the 2s complement is a binary representation of a negative number that is created
by adding one to the 1s complement. Computer systems frequently employ this idea to
represent signed numbers and efficiently carry out arithmetic operations.
To get the 2s complement of a binary integer, one must first determine the 1s
complement of the number by flipping the bits. After that, the representation of the 2s
complement is obtained by adding one to the 1s complement. The most significant
bit (MSB) will function as a sign bit by expressing whether a number
is positive or negative.

The computation of the 2s complement for a given binary integer is shown in the
attached C program. The user is prompted to input both the binary number and the
number of bits. After that, the program does the required procedures to acquire the 1s
complement, and then the 2s complement. The findings are then shown.

In computer science and programming, it's crucial to comprehend the 2s


complement representation since it makes it possible to handle negative values
expressed in binary effectively. It makes addition, subtraction, and logical
operations simpler on both positive and negative numbers. The range
of representable integers is symmetric about zero due to the 2s
complement representation, making it appropriate for various numerical operations.

Programmers may conduct arithmetic operations, work with binary data, and design
algorithms using signed integers in C and other programming languages by
understanding the idea of 2s complement and properly utilizing it.

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.

ADVERTISEMENT
ADVERTISEMENT

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.

ADVERT ISEMENT
ADVERT ISEMENT

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

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

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.

How does C switch statement work?


Let's go through the step-by-step process of how the switch statement works in C:

Consider the following switch statement:

C Program:

1. #include <stdio.h>
2.
3. int main() {
4. int num = 2;
5. switch (num) {
6. case 1:
7. printf("Value is 1\n");
8. break;
9. case 2:
10. printf("Value is 2\n");
11. break;
12. case 3:
13. printf("Value is 3\n");
14. break;
15. default:
16. printf("Value is not 1, 2, or 3\n");
17. break;
18. }
19.
20. return 0;
21. }

Output

Value is 2

Step-by-step Process:

1. The switch variable num is evaluated. In this case, num is initialized with
the value 2.
2. The evaluated num (2) value is compared with the constants specified in each
case label inside the switch block.
3. The switch statement matches the evaluated value (2) with the constant
specified in the second case (case 2). Since there is a match, the program jumps
to the code block associated with the matching case (case 2).
4. The code block associated with case 2 is executed, which prints "Value is 2" to
the console.
5. The "break" keyword is present in the code block of case 2. As a result, the
program breaks out of the switch statement immediately after executing the code
block.
6. The program control continues after the switch statement, and any statements
following the switch statement are executed. In this case, there are no statements
after the switch, so the program terminates.
7. The switch statement evaluated the value of the variable num, found a match
with case 2, executed the corresponding code block, and then exited the switch
block due to the presence of the "break" statement.

Example of a switch statement in C


Let us see a simple example of a C language switch statement.

ADVERT ISEMENT
ADVERT ISEMENT
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }

Output

enter a number:4
number is not equal to 10, 50 or 100

enter a number:50
number is equal to 50

Switch case example 2

1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }

Output

hi

Break and Default keyword in Switch statement


Let us explain and define the "break" and "default" keywords in the context of the
switch statement, along with example code and output.

1. Break Keyword:
The "break" keyword is used within the code block of each case to terminate the switch
statement prematurely. When the program encounters a "break" statement inside a case
block, it immediately exits the switch statement, preventing the execution of subsequent
case blocks. The "break" statement is crucial for avoiding switch statements' "fall-
through" behavior.

Example:

Let's take a program to understand the use of the break keyword in C.

1. #include <stdio.h>
2. int main() {
3. int num = 3;
4.
5. switch (num) {
6. case 1:
7. printf("Value is 1\n");
8. break; // Exit the switch statement after executing this case block
9. case 2:
10. printf("Value is 2\n");
11. break; // Exit the switch statement after executing this case block
12. case 3:
13. printf("Value is 3\n");
14. break; // Exit the switch statement after executing this case block
15. default:
16. printf("Value is not 1, 2, or 3\n");
17. break; // Exit the switch statement after executing the default case block
18. }
19.
20. return 0;
21. }

Output

ADVERT ISEMENT
ADVERT ISEMENT

Value is 3

Explanation:

In this example, the switch statement evaluates the value of the variable num (which
is 3) and matches it with case 3. The code block associated with case 3 is executed,
printing "Value is 3" to the console. The "break" statement within case 3 ensures that
the program exits the switch statement immediately after executing this case block,
preventing the execution of any other cases.

2. Default Keyword:
When none of the case constants match the evaluated expression, it operates as
a catch-all case. If no matching case exists and a "default" case exists, the code block
associated with the "default" case is run. It is often used to handle circumstances where
none of the stated situations apply to the provided input.

ADVERT ISEMENT
ADVERT ISEMENT

Example:

Let's take a program to understand the use of the default keyword in C.

1. #include <stdio.h>
2. int main() {
3. int num = 5;
4.
5. switch (num) {
6. case 1:
7. printf("Value is 1\n");
8. break;
9. case 2:
10. printf("Value is 2\n");
11. break;
12. case 3:
13. printf("Value is 3\n");
14. break;
15. default:
16. printf("Value is not 1, 2, or 3\n");
17. break; // Exit the switch statement after executing the default case block
18. }
19.
20. return 0;
21. }
ADVERTISEMENT
ADVERTISEMENT

Output

Value is not 1, 2, or 3
Explanation:

In this example, the switch statement examines the value of the variable num (which
is 5). Because no case matches the num, the program performs the code block associated
with the "default" case. The "break" statement inside the "default" case ensures that
the program exits the switch statement after executing the "default" case block.

Both the "break" and "default" keywords play essential roles in controlling the flow of
execution within a switch statement. The "break" statement helps prevent the fall-
through behavior, while the "default" case provides a way to handle unmatched cases.

C Switch statement is fall-through


In C language, the switch statement is fall through; it means if you don't use a break
statement in the switch case, all the cases after the matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given
below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
ADVERTISEMENT
ADVERTISEMENT

Output

enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Output

enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Nested switch case statement


We can use as many switch statement as we want inside a switch statement. Such type of
statements is called nested switch case statements. Consider the following example.

1. #include <stdio.h>
2. int main () {
3.
4. int i = 10;
5. int j = 20;
6.
7. switch(i) {
8.
9. case 10:
10. printf("the value of i evaluated in outer switch: %d\n",i);
11. case 20:
12. switch(j) {
13. case 20:
14. printf("The value of j evaluated in nested switch: %d\n",j);
15. }
16. }
17.
18. printf("Exact value of i is : %d\n", i );
19. printf("Exact value of j is : %d\n", j );
20.
21. return 0;
22. }

Output

the value of i evaluated in outer switch: 10


The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20

Advantages of the switch statement:


There are several advantages of the switch statement in C. Some main advantages of the
switch statement are as follows:

ADVERTISEMENT
ADVERTISEMENT

o Readability and clarity: The switch statement provides a concise and


straightforward way to express multiway branching in the code. Dealing with
multiple cases can make the code more organized and easier to read than
multiple nested if-else statements.
o Efficiency: The switch statement is generally more efficient than a series of if-
else statements when dealing with multiple conditions. It works as a direct jump
table, which makes it faster and more optimized in terms of execution time.
o Case-based logic: The switch statement naturally fits scenarios where the
program needs to make decisions based on specific values of a single variable. It
is an intuitive and straightforward way to implement case-based logic.

The switch statement supports using a default case which serves as a catch-all
option for values that do not match any provided cases. This default case handles
unusual inputs or circumstances that are not expressly stated.

Disadvantages of the switch statement:


There are several disadvantages of the switch statement in C. Some main disadvantages
of the switch statement are as follows:

ADVERT ISEMENT
ADVERT ISEMENT

o Limited expressions: The expression used in the switch statement must result in
an integral value (char, int, enum) or a compatible data type. It cannot handle
more complex or non-constant expressions, limiting its flexibility in some
scenarios.
o Inability to compare ranges: Unlike if-else statements, the switch
statement cannot handle ranges of values directly. Each case in the switch
statement represents a specific constant value, making it challenging to handle a
range of values efficiently.
o No support for floating-point numbers: The switch statement only
accepts integral types (integers) and values from enums; it does not accept
floating-point numbers. It does not handle non-integral data types like floating-
point integers, which might be problematic in some circumstances.
o Fall-through behavior: Switch statements have "fall-through" behavior by
default which implies that if a case does not include a "break" statement,
execution will "fall through" to the following case block. If not managed
appropriately, this might result in unwanted behavior.
o Duplicate code: Using a switch statement might result in duplicate code in some
circumstances, especially when numerous cases demand the same actions. If not
properly managed, this might result in code duplication.
o Nested switches can become complex: When dealing with nested switch
statements, the code can become complex and less readable. It may require
additional effort to understand and maintain such nested structures.

if-else vs switch
What is an if-else statement?
An if-else statement in C programming is a conditional statement that executes a different
set of statements based on the condition that is true or false. The 'if' block will be executed
only when the specified condition is true, and if the specified condition is false, then the
else block will be executed.

Syntax of if-else statement is given below:

1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }

What is a switch statement?


A switch statement is a conditional statement used in C programming to check the value
of a variable and compare it with all the cases. If the value is matched with any case, then
its corresponding statements will be executed. Each case has some name or number
known as the identifier. The value entered by the user will be compared with all the cases
until the case is found. If the value entered by the user is not matched with any case, then
the default statement will be executed.

Syntax of the switch statement is given below:

1. switch(expression)
2. {
3. case constant 1:
4. // statements;
5. break;
6. case constant 2:
7. // statements;
8. break;
9. case constant n:
10. // statements;
11. break;
12. default:
13. // statements;
14. }

Similarity b/w if-else and switch


Both the if-else and switch are the decision-making statements. Here, decision-making
statements mean that the output of the expression will decide which statements are to
be executed.

Differences b/w if-else and switch statement

The following are the differences between if-else and switch statement are:

o Definition

if-else

Based on the result of the expression in the 'if-else' statement, the block of statements
will be executed. If the condition is true, then the 'if' block will be executed otherwise 'else'
block will execute.

Switch statement

The switch statement contains multiple cases or choices. The user will decide the case,
which is to execute.
o Expression

If-else

It can contain a single expression or multiple expressions for multiple choices. In this, an
expression is evaluated based on the range of values or conditions. It checks both equality
and logical expressions.

Switch

It contains only a single expression, and this expression is either a single integer object or
a string object. It checks only equality expression.

o Evaluation

If-else

An if-else statement can evaluate almost all the types of data such as integer, floating-
point, character, pointer, or Boolean.

Switch

A switch statement can evaluate either an integer or a character.

o Sequence of Execution

If-else

In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed
based on the condition.

Switch

In the case of the 'switch' statement, one case after another will be executed until
the break keyword is not found, or the default statement is executed.

o Default Execution

If-else
If the condition is not true within the 'if' statement, then by default, the else block
statements will be executed.

Switch

If the expression specified within the switch statement is not matched with any of the
cases, then the default statement, if defined, will be executed.

o Values

If-else

Values are based on the condition specified inside the 'if' statement. The value will decide
either the 'if' or 'else' block is to be executed.

Switch

In this case, value is decided by the user. Based on the choice of the user, the case will be
executed.

o Use

If-else

It evaluates a condition to be true or false.

Switch

A switch statement compares the value of the variable with multiple cases. If the value is
matched with any of the cases, then the block of statements associated with this case will
be executed.

o Editing

If-else

Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will
create the havoc.

Switch
Editing in switch statement is easier as compared to the 'if-else' statement. If we remove
any of the cases from the switch, then it will not interrupt the execution of other cases.
Therefore, we can say that the switch statement is easy to modify and maintain.

o Speed

If-else

If the choices are multiple, then the speed of the execution of 'if-else' statements is slow.

Switch

The case constants in the switch statement create a jump table at the compile time. This
jump table chooses the path of the execution based on the value of the expression. If we
have a multiple choice, then the execution of the switch statement will be much faster
than the equivalent logic of 'if-else' statement.

Let's summarize the above differences in a tabular form.

If-else switch

Definition Depending on the condition in the The user will decide which statement is to b
'if' statement, 'if' and 'else' blocks executed.
are executed.

Expression It contains either logical or equality It contains a single expression which can b
expression. either a character or integer variable.

Evaluation It evaluates all types of data, such It evaluates either an integer, or character.
as integer, floating-point, character
or Boolean.

Sequence of First, the condition is checked. If the It executes one case after another till the brea
execution condition is true then 'if' block is keyword is not found, or the default statement
executed otherwise 'else' block executed.

Default If the condition is not true, then by If the value does not match with any case, the
execution default, else block will be executed. by default, default statement is executed.
Editing Editing is not easy in the 'if-else' Cases in a switch statement are easy to mainta
statement. and modify. Therefore, we can say that th
removal or editing of any case will not interrup
the execution of other cases.

Speed If there are multiple choices If we have multiple choices then the switc
implemented through 'if-else', then statement is the best option as the speed of th
the speed of the execution will be execution will be much higher than 'if-else'.
slow.

C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of
the tutorial, we are going to learn all the aspects of C loops.

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.

ADVERT ISEMENT
ADVERT ISEMENT

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
A loop is a programming control structure that allows you to execute a block of
code indefinitely if a specific condition is met. Loops are used to execute repeating
activities and boost programming performance. There are multiple loops in the C
programming language, one of which is the "do-while" loop.

A "do-while" loop is a form of a loop in C that executes the code block first, followed by
the condition. If the condition is true, the loop continues to run; else, it stops. However,
whether the condition is originally true, it ensures that the code block is performed at
least once.

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

The components are divided into the following:

ADVERTISEMENT
ADVERTISEMENT

o The do keyword marks the beginning of the Loop.


o The code block within curly braces {} is the body of the loop, which contains the
code you want to repeat.
o The while keyword is followed by a condition enclosed in parentheses (). After the
code block has been run, this condition is verified. If the condition is true, the loop
continues else, the loop ends.

Working of do while Loop in C


Let us look at an example of how a do-while loop works in C. In this example, we will
write a simple program that questions the user for a password and keeps asking until the
right password is input.

Example:

1. #include <stdio.h>
2. #include <string.h>
3. int main() {
4. char password[] = "secret";
5. char input[20];
6. do {
7. printf("Enter the password: ");
8. scanf("%s", input);
9. } while (strcmp(input, password) != 0);
10. printf("Access granted!\n");
11. return 0;
12. }

The program runs as follows:

1. The following header files are included: <stdio.h> for


standard input and output routines and <string.h> for string manipulation
functions.
2. The correct password is defined as a character array (char password[]) with the
value "secret"
3. After that, we define another character array input to store the user's input.
4. The do keyword indicates that the code block included within the loop will be
performed at least once.
5. Using the printf() function, we display a prompt requesting the user to input their
password inside the Loop.
6. Next, we read the user's input using the scanf() function and store it in the input
array.
7. After reading the input, we use the strcmp() function to compare the input with
the correct password. If the strings are equal, the strcmp function returns 0. So,
we continue looping as long as the input and the password are not equal.
8. Once the correct password is entered, the loop terminates, and we print "Access
granted!" using the printf() function.
9. After that, the program returns 0 to indicate successful execution.

Output:

Let us walk through a possible scenario:

Enter the password: 123


Enter the password: abc
Enter the password: secret
Access Granted!

Explanation:

ADVERT ISEMENT
ADVERT ISEMENT

In this example, the user initially enters the wrong passwords, "123" and "abc". The loop
prompts the user until the correct password "secret" is entered. Once the correct
password is provided, the loop terminates, and the "Access granted!" message is
displayed.

Example of do while loop in C:


Example 1:

Here is a simple example of a "do-while" loop in C that prints numbers from 1 to 5:

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

Output:

1
2
3
4
5

Explanation:

In this example, the code block within the do loop will be executed at least once, printing
numbers from 1 to 5. After each iteration, the i value is incremented, and the
condition i<= 5 is checked. If the condition is still true, the loop continues; otherwise, it
terminates.

Example 2:

ADVERT ISEMENT
ADVERT ISEMENT

Program to print table for the given number using do while Loop

1. #include<stdio.h>
2. intmain(){
3. inti=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

Example 3:

ADVERT ISEMENT
ADVERT ISEMENT

Let's take a program that prints the multiplication table of a given number N using
a do...while Loop:

1. #include <stdio.h>
2. int main() {
3. int N;
4. printf("Enter a number to generate its multiplication table: ");
5. scanf("%d", &N);
6. inti = 1;
7. do {
8. printf("%d x %d = %d\n", N, i, N * i);
9. i++;
10. } while (i<= 10);
11. return 0;
12. }

Output:

ADVERTISEMENT
ADVERTISEMENT

Let us say you enter the number 7 as input:

Please enter a number to generate its multiplication table: 7


7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

The program calculates and prints the multiplication table for 7 from 1 to 10.

Infinite do while loop


An infinite loop is a loop that runs indefinitely as its condition is always true or it lacks a
terminating condition. Here is an example of an infinite do...while loop in C:

Example:

1. #include <stdio.h>
2. int main() {
3. inti = 1;
4. do {
5. printf("Iteration %d\n", i);
6. i++;
7. } while (1); // Condition is always true
8.
9. return 0;
10. }
In this example, the loop will keep running indefinitely because condition 1 is
always true.

Output:

ADVERTISEMENT
ADVERTISEMENT

When you run the program, you will see that it continues printing "Iteration x", where x
is the iteration number without stopping:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
... (and so on)

To interrupt an infinite loop like this, you generally use a break statement within
the loop or some external condition you can control, such as hitting a specific key
combination. In most desktop settings, the keyboard shortcut Ctrl+C can escape the
Loop.

Nested do while loop in C


In C, we take an example of a nested do...while loop. In this example, we will write a
program that uses nested do...while loops to create a numerical pattern.

Example:

1. #include <stdio.h>
2. int main() {
3. int rows, i = 1;
4. printf("Enter the number of rows: ");
5. scanf("%d", &rows);
6. do {
7. int j = 1;
8. do {
9. printf("%d ", j);
10. j++;
11. } while (j <= i);
12. printf("\n");
13. i++;
14. } while (i<= rows);
15. return 0;
16. }

In this program, we use nested do...while loops to generate a pattern of numbers.


The outer loop controls the number of rows, and the inner loop generates the numbers
for each row.

Output:

Let us say you input five as the number of rows:

ADVERT ISEMENT
ADVERT ISEMENT

Enter the number of rows: 5


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Explanation:

In this example, the program generates a pattern of numbers in a triangular shape.


The outer loop iterates over the rows, and the inner loop iterates within each row,
printing the numbers from 1 up to the current row number.

Difference between while and do while Loop


Here is a tabular comparison between the while loop and the do-while Loop in C:

Aspect while loop do-while loop

Syntax while (condition) { ... } do { ... } while (condition);

Loop Body Condition is checked before The body is executed before th


Execution execution. condition.

First Execution The condition must be true initially. The body is executed at least once.
Loop Execution May execute zero or more times. Will execute at least once.

Example while (i< 5) { printf("%d\n", i); i++; } do { printf("%d\n", i); i++; } while (i< 5);

Common Use Cases When the loop may not run at all. When you want the loop to run at lea
once.

While Loop: The loop body is executed before the condition is checked. If the condition
is initially false, the loop may not execute.

Do-while Loop: The loop body is executed at least once before the condition is checked.
This guarantees that the loop completes at least one iteration.

When you want the loop to run based on a condition that may be false at first, use
the while loop, and when you want the loop to run at least once regardless of the starting
state, use the do-while loop.

ADVERT ISEMENT
ADVERT ISEMENT

Features of do while loop


The do-while loop in C has several fundamental characteristics that make it an effective
programming technique in certain situations. The following are the significant
characteristics of the do-while loop:

o Guaranteed Execution: Unlike other loop structures, the do-while oop ensures
that the loop body is executed at least once. Because the condition is assessed
after the loop body, the code within the loop is performed before the condition is
verified.
o Loop after testing: The do-while loop is a post-tested loop which implies that
the loop condition is assessed after the loop body has been executed. If the
condition is true, the loop body is run once again. This behavior allows you to verify
the condition for repetition before ensuring that a given activity is completed.
o Conditionally Controlled: The loop continues to execute as long as the condition
specified after the while keyword remains true. When the condition evaluates
to false, the loop is terminated, and control shifts to the sentence after the loop.
o Flexibility: The do-while loop may be utilized in several contexts. It is typically
used in cases where a piece of code must be executed at least once, such as menu-
driven programs, input validation, or repetitive computations.
o Nesting Capability: Similar to other loop constructs, the do-while loop can
be nested inside other loops or control structures to create more complex
control flow patterns. It allows for the creation of nested loops and the
implementation of intricate repetitive tasks.
o Break and Continue: The break statement can be used within a do-while loop to
terminate the loop execution and exit the loop prematurely. The continue
statement can skip the remaining code in the current iteration and jump to the
next iteration of the loop.
o Local Scope: Variables declared inside the do-while loop body have local scope
and are accessible only within the loop block. They cannot be accessed outside
the loop or by other loops or control structures.
o Infinite Loop Control: It is crucial to ensure that the loop's condition is eventually
modified within the loop body. This modification is necessary to prevent infinite
loops where the condition continually evaluates to true. Modifying the condition
ensures that the loop terminates at some point.

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


ADVERTISEMENT
ADVERTISEMENT

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

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

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

ADVERT ISEMENT
ADVERT ISEMENT

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

ADVERT ISEMENT
ADVERT ISEMENT

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.

ADVERT ISEMENT
ADVERT ISEMENT

1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }

If you run this program, you will see above statement infinite times.

Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the
looping of statements inside another loop. Let's observe an example of nesting loops in
C.

Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times. You can define
any type of loop inside another loop; for example, you can define 'while' loop inside a
'for' loop.

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

ADVERTISEMENT

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.

ADVERT ISEMENT

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.

ADVERT ISEMENT

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(;;)'.

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

Infinite loops can cause problems if it is not properly controlled or designed, leading to
excessive CPU resource consumption and unresponsiveness in programs or
systems. Implementing mechanisms to break out of infinite loops is crucial when
necessary.

It is advisable to include exit conditions within the loop to prevent unintentional infinite
loops. These conditions can be based on user input, specific events or flags, or time
limits. The loop will terminate by incorporating appropriate exit conditions after
fulfilling its purpose or meeting specific criteria.

Techniques for Preventing Infinite Loops:


Although infinite loops can occasionally be intended, they are
frequently unintended and can cause program freezes or crashes. Programmers can use
the following strategies to avoid inadvertent infinite loops:

Add a termination condition: Make sure the loop has a condition that can ultimately
evaluate to false, allowing it to end.

Employ a counter: Establish a cap on the number of iterations and implement a counter
that increases with each loop iteration. Thus, even if the required condition is not satisfied,
the loop will ultimately come to an end.

Introduce a timeout system: If the time limit is reached, the loop will be stopped. Use a
timer or system functions to measure the amount of time that has passed.

Use external or user-provided triggers: Design the loop to end in response to certain
user input or outside events.

In certain cases, infinite loops may be intentionally employed in specialized algorithms


or system-level operations. For instance, real-time systems or embedded systems utilize
infinite loops to monitor inputs or execute specific tasks continuously. However, care must
be taken to manage such loops properly, avoiding any adverse effects on system
performance or responsiveness.

Modern programming languages and development frameworks often offer built-in


mechanisms to handle infinite loops more efficiently. For example, Graphical user
interface (GUI) frameworks provide event-driven architectures where programs wait for
user input or system events, eliminating the need for explicit infinite loops.

It is essential to exercise caution and discretion when using infinite loops. They should
only be employed when there is a clear and valid reason for an indefinite running loop,
and adequate safeguards must be implemented to prevent any negative impact on the
program or system.

Conclusion:
In conclusion, an infinite loop in C constitutes a looping construct that never ends and
keeps running forever. Different loop structures, such as the for loop, while loop, do-
while loop, goto statement, or C macros, can be used to produce it. Operating systems,
servers, and video games all frequently employ infinite loops since they demand constant
human input and output until manual termination. On the other hand, the unintentional
infinite loops might happen because of code flaws, which are difficult to identify,
especially for newcomers.

Careful consideration of semicolons, logical criteria, and loop


termination requirements is required to prevent inadvertent infinite loops. Infinite loops
can result from improper semicolon placement or the use of assignment operators in
place of relational operators. False loop conditions that always evaluate to true may
likewise result in an infinite loop. Furthermore, since the break keyword only ends the
closest loop, caution must be used when using it in nested loops. Furthermore, as they
may make the loop termination condition impossible to meet, floating-point mistakes
should be considered while working with floating-point numbers.

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

How does the break statement work?


The "break" statement works similarly to other programming languages in C
programming. A control flow statement is used to exit a loop or switch statement early
when a specific condition is met. The "break" statement is beneficial when you want to
terminate a loop early or exit a switch block before it ends. The process of the "break"
statement works in C is the same as in other programming languages:

ADVERTISEMENT
ADVERTISEMENT

o The loop (while or for) or the switch (or a series of "if-else" statements) begins
execution.
o The program analyzes the condition within the "if" statement that includes
the "break" statement throughout each iteration of the loop or each check in
the switch.
o If the condition is "true", the "break" statement is performed.
o When a "break" statement is found, the program immediately quits the loop
or switch block, skipping any remaining iterations or checks.
o The program continues to execute the code following the loop or switch

Note: The "break" statement only affects the innermost loop or switch block which is
contained within the statement. If there are nested loops or switch statements, the nearest
one that includes the "break" statement will be broken out of.

Without the "break" statement, the loop or switch would continue its normal execution
and process all the remaining iterations or checks, even if the desired condition has
already been met. The "break" statement provides an efficient way to
exit loops or switch blocks when you no longer need to perform further iterations or
checks.

Use of break statements in different cases with their


examples:
Let us go through each use case of the "break" statement in C with detailed explanations
and examples:
o Simple Loops
o Nested Loops
o Infinite Loops
o Switch case

1. Simple Loops:

When a specific condition is fulfilled, the "break" statement is widely used in simple loops
like "while" and "for" to stop the loop early. It is helpful when you wish to terminate the
loop early due to a condition.

Syntax:

It has the following syntax:

While loop

ADVERT ISEMENT
ADVERT ISEMENT

1. while (condition) {
2. // Code block inside the loop
3. if (some_condition) {
4. break; // Exit the loop if this condition is met
5. }
6. // Rest of the loop's code
7. }

For loop

1. for (initialization; condition; increment) {


2. // Code block inside the loop
3. if (some_condition) {
4. break; // Exit the loop if this condition is met
5. }
6. // Rest of the loop's code
7. }
Example:

Let's take an example to understand the use of the break statement in simple loops in
C:

1. // Using break in a while loop


2. #include <stdio.h>
3. int main() {
4. inti = 1;
5. while (i<= 10) {
6. if (i == 5) {
7. break; // Exit the loop when i becomes 5
8. }
9. printf("%d ", i);
10. i++;
11. }
12. printf("\n");
13. return 0;
14. }

Output

1 2 3 4

Explanation:

In this example, the "while" loop outputs the digits 1 through 4. When i equals 5,
the "if" condition if (i == 5) is true, and the "break" expression is performed, forcing
the loop to finish early.

2. Nested Loops:
The break statement can be applied in nested loops to break out of
the inner and outer loops simultaneously when a specific condition is met. It allows you
to stop processing further iterations in multiple loops at once.

ADVERT ISEMENT
ADVERT ISEMENT
Syntax:

It has the following syntax:

1. for (outer_loop_initialization; outer_loop_condition; outer_loop_increment) {


2. // Code block of the outer loop
3. for (inner_loop_initialization; inner_loop_condition; inner_loop_increment) {
4. // Code block of the inner loop
5. if (some_condition) {
6. break; // Exit both inner and outer loops if this condition is met
7. }
8. // Rest of the inner loop's code
9. }
10. // Rest of the outer loop's code
11. }

Example:

ADVERT ISEMENT
ADVERT ISEMENT

Let's take an example to understand the use of the break statement in nested loops in
C:

1. // Using break in nested loops


2. #include <stdio.h>
3. int main() {
4. for (inti = 1; i<= 3; i++) {
5. for (int j = 1; j <= 3; j++) {
6. if (i == 2 && j == 2) {
7. break; // Exit both loops when i=2 and j=2
8. }
9. printf("(%d, %d) ", i, j);
10. }
11. }
12. printf("\n");
13. return 0;
14. }

Output

(1, 1) (1, 2) (1, 3)


ADVERTISEMENT
ADVERTISEMENT

Explanation:

In this example, the nested loops output pairs of integers ranging from 1 to
3. When i equals 2 and j equals 2, the "if" condition if (i == 2 && j == 2) is true, and
the "break" statement is run, causing both loops to end at the same time.

3. Infinite Loops:
An infinite loop runs continuously unless terminated by a "break" statement or another
condition within the loop. In infinite loops, the "break" statement is typically used to
give a means to leave the loop based on specified criteria.

Syntax:

It has the following syntax:

1. while (1) { // Infinite loop using a true condition


2. // Code block inside the loop
3. if (some_condition) {
4. break; // Exit the loop if this condition is met
5. }
6. // Rest of the loop's code
7. }

Example:

ADVERTISEMENT
ADVERTISEMENT

Let's take an example to understand the use of the break statement in infinite loops in
C:

1. // Using break in an infinite loop


2. #include <stdio.h>
3. int main() {
4. int number;
5. while (1) {
6. printf("Enter a number (0 to exit): ");
7. scanf("%d", &number);
8. if (number == 0) {
9. break; // Exit the loop when the user enters 0
10. }
11. printf("You entered: %d\n", number);
12. }
13. return 0;
14. }

Output

Enter a number (0 to exit): 7


You entered: 7
Enter a number (0 to exit): 5
You entered: 5
Enter a number (0 to exit): 0

Explanation:

In this example, the program keeps asking the user to enter a number in an infinite loop.
If the user enters 0, the "if" condition if (number == 0) is true, and
the "break" statement is executed, ending the loop and terminating the program.

4. Switch Case:
The "break" statement is used in a "switch" statement to exit the switch block after a
particular case is executed. Without the "break" statement, the program would continue
executing the code for all the subsequent cases, potentially leading to unexpected
behavior.

Syntax:

It has the following syntax:

ADVERT ISEMENT
ADVERT ISEMENT

1. switch (expression) {
2. case value1:
3. // Code block for case value1
4. break; // Exit the switch block after executing this case
5. case value2:
6. // Code block for case value2
7. break; // Exit the switch block after executing this case
8. // More cases...
9. default:
10. // Code block for the default case
11. break; // Exit the switch block after executing this case
12. }

Example:

Let's take an example to understand the use of the break statement in the switch case in
C:

1. // Using break in a switch statement


2. #include <stdio.h>
3. int main() {
4. int choice;
5. printf("Menu:\n");
6. printf("1. Option 1\n");
7. printf("2. Option 2\n");
8. printf("3. Quit\n");
9. printf("Enter your choice: ");
10. scanf("%d", &choice);
11.
12. switch (choice) {
13. case 1:
14. printf("You selected Option 1\n");
15. break;
16. case 2:
17. printf("You selected Option 2\n");
18. break;
19. case 3:
20. printf("Quitting the menu...\n");
21. break;
22. default:
23.
24. printf("Invalid choice. Try one more time.\n");
25. break;
26. }
27. return 0;
28. }

Output (Example 1):

Menu:
Option 1
Option 2
Quit
Enter your choice: 2
You selected Option 2

Output (Example 2):

Menu:
Option 1
Option 2
Quit
Enter your choice: 4
Invalid choice. Try one more time.

Explanation:

In this case, the program presents a menu & prompts the user to select an option. The
matching "case" block is run based on the user's input. After the execution of the
corresponding "case" block, the "break" statement exits the switch block, preventing
the program from executing the code for other cases.

ADVERT ISEMENT
ADVERT ISEMENT
These are the different ways you can use the "break" statement in C to control the flow
of your program within loops and switch statements. The "break" statement provides a
powerful mechanism to exit loops and switch blocks when certain conditions are met,
making your code more efficient and functional.

Features of the Break Statement


When a loop or switch statement is executed, the break statement in the C programming
language is used to stop it. It offers several features:

o Loop termination: The break statement allows you to exit a loop prematurely
based on a specific condition. It can help you save execution time by avoiding
unnecessary iterations when the desired condition has been met. It provides a way
to break out of nested loops as well.
o Switch statement termination: In C, the break statement is commonly used
within a switch statement to terminate the execution of the entire switch block.
Without the break statement, execution would continue to the next case,
potentially leading to unintended behavior.
o Enhanced control flow: By using the break statement, you have fine-grained
control over the flow of your program. It allows you to conditionally exit loops or
switch statements based on specific criteria, providing flexibility and control.
o Code organization and readability: Properly using break statements can lead to
cleaner & more readable code. It lets you convey your goal by exiting a loop when
a given condition is fulfilled, making the code easier to understand & maintain.
o Error handling: The break statement can be helpful in error-handling scenarios.
For example, if an error condition arises during a loop iteration, you may use the
break to quit the loop and handle the problem correctly.
o Efficiency: When dealing with large loops or switch statements, using the break
statement can improve the efficiency of your code. Terminating the loop or
switching early unnecessary computations can be avoided, leading to faster
execution.
Note: Excessive use of break statements can sometimes make code harder to understand
and maintain, mainly when it is used in nested loops. It's essential to use break judiciously
and consider other control flow options, such as continuing or restructuring your code when
appropriate.

C continue statement
The continue statement in C language is used to bring the program control to the
beginning of the loop. The continue statement skips some lines of code inside the loop
and continues with the next iteration. It is mainly used for a condition so that we can skip
some code for a particular condition.

Syntax:

1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped

Continue statement example 1

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

Output

infinite loop

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

Output

1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

ADVERT ISEMENT

C continue statement with inner loop


In such case, C continue statement continues only inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }

Output

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2
and j==2.

C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used
to transfer the program control to a predefined label. The goto statment can be used to
repeat some part of the code for a particular condition. It can also be used to break the
multiple loops which can't be done by using a single break statement. However, using
goto is avoided these days since it makes the program less readable and complecated.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

goto example
Let's see a simple example to use goto statement in C language.
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }

Output:

ADVERT ISEMENT

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

When should we use goto?


The only condition in which using goto is preferable is when we need to break the multiple
loops using a single statement at the same time. Consider the following example.

1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

Type Casting in C
Data types are crucial in determining the nature and behavior of variables in the realm
of programming. Typecasting allows us to convert one data type into another. This
procedure is called type casting, and the C programming language offers it as a useful
tool. In this blog, we will examine the syntax, practical applications, and advantages of
typecasting in C.

The procedure of changing a variable's data type is known as type casting. It can be
helpful in a variety of situations, for as when processing user input, doing mathematical
calculations, or interacting with other libraries that need data types. In C language, we
use cast operator for typecasting which is denoted by (type).

Syntax:

1. (type)value;

Note: It is always recommended to convert the lower value to higher to avoid data loss.

Without Type Casting:

int f= 9/4;

printf("f: %d\n", f) ;//Output: 2

With Type Casting:

float f=(float) 9/4;

printf("f: %f\n", f) ;//Output: 2.250000

Types of Type Casting


Type casting may be done in several ways in C, including implicit and explicit casting.

Implicit Casting:
When the compiler automatically transforms the data from one type to another, it is
referred to as implicit casting or automated type conversion. This casting is based on
a set of guidelines that outline how various kinds of data can coexist. As an illustration,
the automated conversion of an integer to a float, which occurs without any explicit
instructions, is an example of an implicit cast.

ADVERT ISEMENT

Implicit casting doesn't require any special syntax because the compiler takes care of it.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. int num1 = 10;
5. float num2 = 5.5;
6. float result;
7.
8. result = num1 + num2; // Implicit cast from int to float
9.
10. printf("The result is: %f\n", result);
11.
12. return 0;
13. }

Output:

The result is: 15.500000

Explanation:

In the example above, the integer value num1 is added to the float variable num2 after
being implicitly cast to a float. The result variable contains a float value representing the
outcome.

Explicit Casting:
Using the cast operator, explicit casting entails explicitly changing one data type to
another. It needs explicit instructions in the code and allows the programmer control over
type conversion.

Syntax:

1. (type) expression

Here, expression is the value or variable that is to be cast, and (type) stands for the
required data type.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. float num1 = 15.6;
5. int num2;
6.
7. num2 = (int) num1; // Explicit cast from float to int
8.
9. printf("The result is: %d\n", num2);
10.
11. return 0;
12. }

Output:

The result is: 15

Explanation:

This example uses the (int) syntax to explicitly cast the float variable num1 to an integer.
After truncating the fractional portion, we get the integer value and that value is
assigned to the num2 variable.

Narrowing Conversion:
ADVERTISEMENT
ADVERTISEMENT

When a value is converted to a data type with a narrower range or precision, it is said
to be narrowing transformed, which may result in data loss. If it is not handled
appropriately, it may lead to unexpected behavior and needs explicit casting.

Example:

1. #include <stdio.h>
2.
3. int main() {
4. double num1 = 1234.56789;
5. int num2;
6.
7. num2 = (int) num1; // Narrowing conversion from double to int
8.
9. printf("The result is: %d\n", num2);
10.
11. return 0;
12. }

Output:

The result is: 1234

Explanation:

This example narrows the conversion by explicitly casting the double value num1 to
an integer. The integer value is sent to the num2 variable, and the fractional portion is
eliminated.

Widening Conversion:
When a value is converted to a data type with a wider range or greater accuracy, this
process is called widening conversion. Since it occurs implicitly, casting is not necessary.

ADVERTISEMENT
ADVERTISEMENT

Example:

1. #include <stdio.h>
2.
3. int main() {
4. int num1 = 10;
5. double num2;
6.
7. num2 = num1; // Widening conversion from int to double
8. printf("The result is: %f\n", num2);
9.
10.
11.
12. return 0;
13.
14. }

Output:

The result is: 10.000000

Explanation:

In this example, the assignment to the num2 variable results in an implicit


conversion of the integer value num1 to a double. A double with the same numerical
value as the initial integer is the outcome.

Advantages of Type Casting


Its numerous advantages make type casting in C a useful feature for programmers. Let's
examine a few of the main advantages:

Precision Control:

Type casting enables programmers to exert precise control over the accuracy of
calculations. They can alter the decimal places, eliminate the fractional component, or
get more precise answers by converting variables to various data types.

ADVERT ISEMENT
ADVERT ISEMENT

Data Compatibility:

When using external libraries or APIs, type casting is essential for assuring data
compatibility. Specific data types are expected as input arguments by many libraries or
functions. Programmers may easily link their code with these external components using
type casting, facilitating effective data transmission and interoperability.

Greater Flexibility:

Type casting allows for greater adaptability when managing user input. Programmers can
convert a string to the necessary data type for additional processing or validation, for
instance, when accepting input as a string. With more robust input processing and
improved error checking made possible by this flexibility, programs are more dependable.

Effective Memory Usage:

By downsizing variables to smaller data types where it is feasible, type casting enables
programmers to efficiently use memory. For instance, type casting can assist conserve
memory if an integer value can be securely stored in a smaller data type like char or short.
This benefit becomes more significant in systems with limited resources when memory
efficiency is crucial.

ADVERT ISEMENT
ADVERT ISEMENT

Code Reusability:

By enabling programmers to employ functions or components created for a single data


type with various data types, type casting enhances code reusability. They may reuse
existing code and prevent duplication by casting variables effectively, cutting down on
development time and effort.

Error Handling:

Error management and detection can benefit from type casting. An error or exception
can be produced. For example, if a conversion fails owing to incompatible data types,
giving the chance to resolve the circumstance graciously. During the development and
testing phases, this error detection technique aids in locating and fixing any problems.

Keeping Data Safe:

Casting explicitly in C serves as a reminder of the possibility of data loss during


conversions. Programmers must be mindful of the destination type's constrained range
or precision when converting a variable to a smaller data type. They can assess the effect
on data integrity and, if necessary, create suitable error handling procedures by explicitly
casting the variable.

Enhancing Performance:

By executing some processes more efficiently, type casting can occasionally increase
performance. For instance, explicit casting can aid the compiler in producing more
effective machine code, leading to quicker execution, when dealing with complicated
expressions containing mixed data types.

Conclusion:
As a result, type casting in C is a potent feature that provides accuracy control,
data compatibility, flexibility, memory optimization, code reuse, error handling,
protection of data loss, and possible speed gains. Programmers may fine-tune
computations, interact with external components, manage user input, optimize memory
use, ensure code reuse, find mistakes, avoid data loss, and boost efficiency by changing
variables from one data type to another. Type casting must be used carefully to guarantee
data integrity and program stability. Programmers can improve the functionality and
performance of their programs by having a solid grasp of typecasting in C.

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 procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.

ADVERTISEMENT

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.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

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:

ADVERT ISEMENT

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. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }

Output

Hello Javatpoint

Example 2

1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }

Output

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 sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }

Output

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


ADVERTISEMENT
ADVERTISEMENT

Example 1

1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

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);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

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

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

1 stdio.h This is a standard input/output header file. It contains all the library function
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.

Additional details regarding C functions are provided below:


There are several additional information related to C functions. Some of them are as
follows:

Modular Programming: The ability to divide a huge program into smaller, more
manageable modules is one of the main benefits of utilizing functions in C. Each function
might contain a particular job or component of functionality, which streamlines and
clarifies the overall program structure. This modular strategy improves code reuse and
makes maintenance and debugging easier.

Code reuse: By using functions, you may create a certain algorithm or piece of logic only
once and utilize it repeatedly throughout your program. You may just call the function
anytime you need to run the code, saving you from having to duplicate it elsewhere. It
not only speeds up development but also assures consistency and lessens the possibility
of making mistakes.

ADVERT ISEMENT
ADVERT ISEMENT

Encapsulation and Abstraction: By obscuring the specifics of functionality's


implementation, functions offer a level of abstraction. A function prototype's interface can
be defined in a header file, while the actual implementation can be provided in a different
source file. Other portions of the program can utilize the function without needing to
understand how it is internally implemented because of the separation of interface and
implementation.

Easy Program Maintenance: A program may be understood and maintained more easily
if it is divided into smaller functions. The ability to assign a specific responsibility to each
function makes code more readable and makes troubleshooting and debugging easier.
You may concentrate on the necessary function without impacting other portions of the
program if an error is found or a modification is needed.

Improved Collaboration: Functions allow developers working on the same project to


collaborate. The program may be divided into functions so that several team members
can work on different functions at once. Developers may smoothly integrate their work
into the functions if the interfaces are well specified, which improves productivity and
promotes effective development.

Passing the parameter: You can send arguments or data to a function in C so that it can
process them. The function can carry out actions and generate outcomes using these
inputs. You may increase the flexibility and adaptability of functions by passing
parameters, which will increase your program's overall versatility.

Return Values: Functions can send values back to the code that called them, allowing for
the communication of the function's execution results. You can utilize the returned value
in other areas of the program after doing calculations or data manipulation within the
function. Return values are especially helpful when you need to calculate a result or
establish a condition depending on the function's output.
Conclusion:
In conclusion, functions are essential to C programming because they give
program organization, reusability, and modularity. Developers can avoid repeatedly
creating the same code by breaking up huge programs into smaller functions, making the
code more effective and simpler to maintain. Anywhere in the program can call a function,
providing flexibility and improving control flow.

ADVERT ISEMENT
ADVERT ISEMENT

The declaration, call, and definition of functions are only a few of their many
characteristics. The compiler is informed by the function declaration of the name,
arguments, and return type. It is possible to call a function with or
without parameters and with or without a return value. Programmers construct user-
defined functions to improve the readability and optimization of their code, whereas C
library functions like printf() and scanf() provide preset capabilities.

Overall, functions are crucial building blocks in C programming, providing benefits


including increased organization, code reuse, and simple tracking of huge programs.
Function calls could add some overhead, but their advantages outweigh the minimal
performance hit. Programmers may write effective and modular C programs by
comprehending and using functions.

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
Let's understand call by value and call by reference in c language one by one.

Call by value in C
ADVERTISEMENT

o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by
the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given
below:

1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables

1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual pa
rameters do not change by changing the formal parameters in call by value, a = 10, b =
20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters
, a = 20, b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
o In call by reference, the address of the variable is passed into the function call as
the actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value gets
stored at the same address.

Consider the following example for the call by reference.


1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Call by reference Example: Swapping the values of the two variables

1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual p
arameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal paramet
ers, a = 20, b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference


in c

No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the functio

2 Changes made inside the function is limited to Changes made inside the function validat
the function only. The values of the actual outside of the function also. The values of th
parameters do not change by changing the actual parameters do change by changing th
formal parameters. formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created at th
different memory location same memory location

Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself
to work on a smaller problem. Any function which calls itself is called recursive function,
and such function calls are called recursive calls. Recursion involves several numbers of
recursive calls. However, it is important to impose a termination condition of recursion.
Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can
be defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example, tower
of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }

Output
Enter the number whose factorial you want to calculate?5
factorial = 120

We can understand the above program of the recursive method call by the figure given
below:

Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn't recur is called the base case whereas the instances
where the function keeps calling itself to perform a subtask, is called the recursive case.
All the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.


1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }

Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.

1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }

Output
Enter the value of n?12
144

Memory allocation of Recursive method


Each recursive call creates a new copy of that method in the memory. Once some data is
returned by the method, the copy is removed from the memory. Since all the variables
and other stuff declared inside function get stored in the stack, therefore a separate stack
is maintained at each recursive call. Once the value is returned from the corresponding
function, the stack gets destroyed. Recursion involves so much complexity in resolving
and tracking the values at each recursive call. Therefore we need to maintain the stack
and track the values of the variables defined in the stack.

ADVERT ISEMENT

Let us consider the following example to understand the memory allocation of the
recursive functions.

1. int display (int n)


2. {
3. if(n == 0)
4. return 0; // terminating condition
5. else
6. {
7. printf("%d",n);
8. return display(n-1); // recursive call
9. }
10. }

Explanation

Let us examine this recursive function for n = 4. First, all the stacks are maintained which
prints the corresponding value of n until n becomes 0, Once the termination condition is
reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider
the following image for more information regarding the stack trace for the recursive
functions.

Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C

ADVERTISEMENT
ADVERTISEMENT

o Automatic
o External
o Static
o Register

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program Mayb
declared anywhere in the program

static RAM Zero Local Till the end of the main program, Retains valu
between multiple functions call

register Register Garbage Local Within the function


Value

Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.

The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.

8. return 0;
9. }

Output:

garbage garbage garbage

Example 2

1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:

11 20 20 20 11

Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Example 1

1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }

Output:

0 0 0.000000 (null)

Example 2

1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }

Output:

10 24
11 25
12 26

Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for
the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be
stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default va
lue of a is 0.
5. printf("%d",a);
6. }

Output:

Example 2

1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the addres
s of a register variable.
6. }

Output:

main.c:5:5: error: address of register variable ?a? requested


printf("%u",&a);
^~~~~~

External
o The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to
be initialized somewhere in the program which may be extern or static. If it is not,
then the compiler will show an error.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }

Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status

Example 2

1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }
Output

Example 3

1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and initial
izer at same time
6. printf("%d",a);
7. }

Output

ADVERT ISEMENT
ADVERT ISEMENT

compile time error


main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;

Example 4

1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized somewh
ere in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;

Output

20

Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line

Output

compile time error

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.

ADVERT ISEMENT

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

ADVERT ISEMENT
ADVERT ISEMENT

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.

ADVERT ISEMENT
ADVERT ISEMENT

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
C Array Example: 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[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
ADVERTISEMENT

Program to print the largest and second largest element of the


array.

1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }

ADVERTISEMENT

Next →← Prev

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized
as matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database lookalike data structure. It provides
ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.

1. int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

ADVERT ISEMENT

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define at least the second dimension of the array. The two-dimensional
array can be declared and defined in the following way.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C

1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

C 2D array example: Storing elements in a matrix and printing it.

1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection
of data. In short, we can say that array is a collection of variables of the same type.

For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these
variables individually, then it becomes a very tedious task. In such a case, we create an
array of variables having the same type. Each element of an array can be accessed using
an index of the element.

Let's first see how to pass a single-dimensional array to a function.

Passing array to a function


1. #include <stdio.h>
2. void getarray(int arr[])
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. }
10. int main()
11. {
12. int arr[5]={45,67,34,78,90};
13. getarray(arr);
14. return 0;
15. }

In the above program, we have first created the array arr[] and then we pass this array to
the function getarray(). The getarray() function prints all the elements of the array arr[].

Output

Passing array to a function as a pointer

Now, we will see how to pass an array to a function as a pointer.

1. #include <stdio.h>
2. void printarray(char *arr)
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%c ", arr[i]);
8. }
9. }
10. int main()
11. {
12. char arr[5]={'A','B','C','D','E'};
13. printarray(arr);
14. return 0;
15. }

In the above code, we have passed the array to the function as a pointer. The
function printarray() prints the elements of an array.

Output

Note: From the above examples, we observe that array is passed to a function as a reference
which means that array also persist outside the function.

How to return an array from a function

Returning pointer pointing to the array

1. #include <stdio.h>
2. int *getarray()
3. {
4. int arr[5];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
10. return arr;
11. }
12. int main()
13. {
14. int *n;
15. n=getarray();
16. printf("\nElements of array are :");
17. for(int i=0;i<5;i++)
18. {
19. printf("%d", n[i]);
20. }
21. return 0;
22. }

In the above program, getarray() function returns a variable 'arr'. It returns a local
variable, but it is an illegal memory location to be returned, which is allocated within a
function in the stack. Since the program control comes back to the main() function, and
all the variables in a stack are freed. Therefore, we can say that this program is returning
memory location, which is already de-allocated, so the output of the program is
a segmentation fault.

Output
There are three right ways of returning an array to a function:

ADVERTISEMENT

o Using dynamically allocated array


o Using static array
o Using structure

Returning array by passing an array which is to be returned as a parameter to the


function.

1. #include <stdio.h>
2. int *getarray(int *a)
3. {
4.
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &a[i]);
9. }
10. return a;
11. }
12. int main()
13. {
14. int *n;
15. int a[5];
16. n=getarray(a);
17. printf("\nElements of array are :");
18. for(int i=0;i<5;i++)
19. {
20. printf("%d", n[i]);
21. }
22. return 0;
23. }

Output

ADVERT ISEMENT
Returning array using malloc() function.

1. #include <stdio.h>
2. #include<malloc.h>
3. int *getarray()
4. {
5. int size;
6. printf("Enter the size of the array : ");
7. scanf("%d",&size);
8. int *p= malloc(sizeof(size));
9. printf("\nEnter the elements in an array");
10. for(int i=0;i<size;i++)
11. {
12. scanf("%d",&p[i]);
13. }
14. return p;
15. }
16. int main()
17. {
18. int *ptr;
19. ptr=getarray();
20. int length=sizeof(*ptr);
21. printf("Elements that you have entered are : ");
22. for(int i=0;ptr[i]!='\0';i++)
23. {
24. printf("%d ", ptr[i]);
25. }
26. return 0;
27. }

Output

Using Static Variable

ADVERT ISEMENT

1. #include <stdio.h>
2. int *getarray()
3. {
4. static int arr[7];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<7;i++)
7. {
8. scanf("%d",&arr[i]);
9. }
10. return arr;
11.
12. }
13. int main()
14. {
15. int *ptr;
16. ptr=getarray();
17. printf("\nElements that you have entered are :");
18. for(int i=0;i<7;i++)
19. {
20. printf("%d ", ptr[i]);
21. }
22. }

In the above code, we have created the variable arr[] as static in getarray() function,
which is available throughout the program. Therefore, the function getarray() returns the
actual memory location of the variable 'arr'.

Output

Using Structure

The structure is a user-defined data type that can contain a collection of items of
different types. Now, we will create a program that returns an array by using structure.
1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
7. struct array getarray()
8. {
9. struct array y;
10. printf("Enter the elements in an array : ");
11. for(int i=0;i<8;i++)
12. {
13. scanf("%d",&y.arr[i]);
14. }
15. return y;
16. }
17. int main()
18. {
19. struct array x=getarray();
20. printf("Elements that you have entered are :");
21. for(int i=0;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26. }

Output

Passing Array to Function in C


In C, there are various general problems which requires passing more than one variable
of the same type to a function. For example, consider a function which sorts the 10
elements in ascending order. Such a function requires 10 numbers to be passed as the
actual parameters from the main function. Here, instead of declaring 10 different numbers
and then passing into the function, we can declare and initialize an array and pass that
into the function. This will resolve all the complexity since the function will now work for
any number of values.

As we know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended
to accept an array. The array defined as the formal parameter will automatically refer to
the array specified by the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

1. functionname(arrayname);//passing array

Methods to declare a function that receives an array as an


argument
There are 3 ways to declare the function which is intended to receive an array as an
argument.

First way:

1. return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

1. return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

1. return_type function(type *arrayname)

You can also use the concept of a pointer. In pointer chapter, we will learn about it.
ADVERT ISEMENT

C language passing an array to function example

1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }

Output

minimum number is 3

C function to sort the array


1. #include<stdio.h>
2. void Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. Bubble_Sort(arr);
7. }
8. void Bubble_Sort(int a[]) //array a[] points to arr.
9. {
10. int i, j,temp;
11. for(i = 0; i<10; i++)
12. {
13. for(j = i+1; j<10; j++)
14. {
15. if(a[j] < a[i])
16. {
17. temp = a[i];
18. a[i] = a[j];
19. a[j] = temp;
20. }
21. }
22. }
23. printf("Printing Sorted Element List ...\n");
24. for(i = 0; i<10; i++)
25. {
26. printf("%d\n",a[i]);
27. }
28. }

Output

Printing Sorted Element List ...


7
9
10
12
23
23
34
44
78
101
Returning array from the function
As we know that, a function can not return more than one value. However, if we try to
write the return statement as return a, b, c; to return three values (a,b,c), the function will
return the last mentioned value which is c in our case. In some problems, we may need to
return multiple values from a function. In such cases, an array is returned from the
function.

Returning an array is similar to passing the array into the function. The name of the array
is returned from the function. To make a function returning an array, the following syntax
is used.

1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }

To store the array returned from the function, we can define a pointer which points to
that array. We can traverse the array by increasing that pointer since pointer initially points
to the base address of the array. Consider the following example that contains a function
returning the sorted array.

1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }

Output

Printing Sorted Element List ...


7
9
10
12
23
23
34
44
78
101

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 t
ype 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 theref
ore printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a po
inter therefore if we print *p, we will get the value stored at the address 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 arr
ay 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.

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.

ADVERT ISEMENT
ADVERT ISEMENT

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

ADVERT ISEMENT
ADVERT ISEMENT

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
ADVERTISEMENT

Reading complex pointers


There are several things which must be taken into the consideration while reading the
complex pointers in C. Lets see the precedence and associativity of the operators which
are used regarding pointers.

Operator Precedence Associativity

(), [] 1 Left to right

*, identifier 2 Right to left

Data type 3 -
ADVERTISEMENT
ADVERTISEMENT

Here,we must notice that,

ADVERTISEMENT

o (): This operator is a bracket operator used to declare and define the function.
o []: This operator is an array subscript operator
o * : This operator is a pointer operator.
o Identifier: It is the name of the pointer. The priority will always be assigned to this.
o Data type: Data type is the type of the variable to which the pointer is intended to
point. It also includes the modifier like signed int, long, etc).

How to read the pointer: int (*p)[10].

To read the pointer, we must see that () and [] have the equal precedence. Therefore, their
associativity must be considered here. The associativity is left to right, so the priority goes
to ().

Inside the bracket (), pointer operator * and pointer name (identifier) p have the same
precedence. Therefore, their associativity must be considered here which is right to left,
so the priority goes to p, and the second priority goes to *.
Assign the 3rd priority to [] since the data type has the last precedence. Therefore the
pointer will look like following.

o char -> 4
o * -> 2
o p -> 1
o [10] -> 3

The pointer will be read as p is a pointer to an array of integers of size 10.

ADVERTISEMENT
ADVERTISEMENT

Example

How to read the following pointer?

1. int (*p)(int (*)[2], int (*)void))

Explanation
This pointer will be read as p is a pointer to such function which accepts the first parameter
as the pointer to a one-dimensional array of integers of size two and the second
parameter as the pointer to a function which parameter is void and return type is the
integer.

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 contained by p i.e. 1
0 will be printed
12. printf("value stored at pp: %d\n",**pp); // value stored at the address contained by th
e 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",*p);
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 of **p variable is 50

Q. What will be the output of the following program?


1. #include<stdio.h>
2. void main ()
3. {
4. int a[10] = {100, 206, 300, 409, 509, 601}; //Line 1
5. int *p[] = {a, a+1, a+2, a+3, a+4, a+5}; //Line 2
6. int **pp = p; //Line 3
7. pp++; // Line 4
8. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 5
9. *pp++; // Line 6
10. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 7
11. ++*pp; // Line 8
12. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 9
13. ++**pp; // Line 10
14. printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 11
15. }

Explanation
In the above question, the pointer arithmetic is used with the double pointer. An array of
6 elements is defined which is pointed by an array of pointer p. The pointer array p is
pointed by a double pointer pp. However, the above image gives you a brief idea about
how the memory is being allocated to the array a and the pointer array p. The elements
of p are the pointers that are pointing to every element of the array a. Since we know that
the array name contains the base address of the array hence, it will work as a pointer and
can the value can be traversed by using *(a), *(a+1), etc. As shown in the image, a[0] can
be accessed in the following ways.

ADVERTISEMENT

o a[0]: it is the simplest way to access the first element of the array
o *(a): since a store the address of the first element of the array, we can access its
value by using indirection pointer on it.
o *p[0]: if a[0] is to be accessed by using a pointer p to it, then we can use indirection
operator (*) on the first element of the pointer array p, i.e., *p[0].
o **(pp): as pp stores the base address of the pointer array, *pp will give the value of
the first element of the pointer array that is the address of the first element of the
integer array. **p will give the actual value of the first element of the integer array.

Coming to the program, Line 1 and 2 declare the integer and pointer array relatively. Line
3 initializes the double pointer to the pointer array p. As shown in the image, if the address
of the array starts from 200 and the size of the integer is 2, then the pointer array will
contain the values as 200, 202, 204, 206, 208, 210. Let us consider that the base address
of the pointer array is 300; the double pointer pp contains the address of pointer array,
i.e., 300. Line number 4 increases the value of pp by 1, i.e., pp will now point to address
302.

Line number 5 contains an expression which prints three values, i.e., pp - p, *pp - a, **pp.
Let's calculate them each one of them.

o pp = 302, p = 300 => pp-p = (302-300)/2 => pp-p = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, a = 200 => *pp - a = 202 - 200 = 2/2 = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, *(*pp) = 206, i.e., 206 will be printed.

Therefore as the result of line 5, The output 1, 1, 206 will be printed on the console. On
line 6, *pp++ is written. Here, we must notice that two unary operators * and ++ will have
the same precedence. Therefore, by the rule of associativity, it will be evaluated from right
to left. Therefore the expression *pp++ can be rewritten as (*(pp++)). Since, pp = 302
which will now become, 304. *pp will give 204.

On line 7, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.

o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, a = 200 => *pp-a = (204 - 200)/2 = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, *(*pp) = 300, i.e., 300 will be printed.

Therefore, as the result of line 7, The output 2, 2, 300 will be printed on the console. On
line 8, ++*pp is written. According to the rule of associativity, this can be rewritten as,
(++(*(pp))). Since, pp = 304, *pp = 204, the value of *pp = *(p[2]) = 206 which will now
point to a[3].

On line 9, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.

o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o pp = 304, *pp = 206, *(*pp) = 409, i.e., 409 will be printed.

Therefore, as the result of line 9, the output 2, 3, 409 will be printed on the console. On
line 10, ++**pp is writen. according to the rule of associativity, this can be rewritten as,
(++(*(*(pp)))). pp = 304, *pp = 206, **pp = 409, ++**pp => *pp = *pp + 1 = 410. In other
words, a[3] = 410.

On line 11, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.

o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o On line 8, **pp = 410.

Therefore as the result of line 9, the output 2, 3, 410 will be printed on the console.

At last, the output of the complete program will be given as:


Output

1 1 206
2 2 300
2 3 409
2 3 410

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic
operation performed on the pointer will also be a pointer if the other operand is of type
integer. In pointer-from-pointer subtraction, the result will be an integer value. Following
arithmetic operations are possible on the pointer in C language:

ADVERTISEMENT

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 incre
mented 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 im
midiate 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:

ADVERT ISEMENT

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.

ADVERT ISEMENT

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.

C Pointer Subtraction
ADVERTISEMENT

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.

ADVERTISEMENT

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 which pointer p


oints

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

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

ADVERT ISEMENT

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

Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild
pointers. Sometimes the programmer fails to initialize the pointer with a valid address,
then this type of initialized pointer is known as a dangling pointer in C.

Dangling pointer occurs at the time of the object destruction when the object is deleted
or de-allocated from memory without modifying the value of the pointer. In this case, the
pointer is pointing to the memory, which is de-allocated. The dangling pointer can point
to the memory, which contains either the program code or the code of the operating
system. If we assign the value to this pointer, then it overwrites the value of the program
code or operating system instructions; in such cases, the program will show the
undesirable result or may even crash. If the memory is re-allocated to some other process,
then we dereference the dangling pointer will cause the segmentation faults.

Let's observe the following examples.


In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer
1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and
Object 2, respectively. Pointer 3 is a dangling pointer as it points to the de-allocated
object.

Let's understand the dangling pointer through some C programs.

Using free() function to de-allocate the memory.

1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }

In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer
and 'a' is a integer variable. The *ptr is a pointer variable which is created with the help
of malloc() function. As we know that malloc() function returns void, so we use int * to
convert void pointer into int pointer.
The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes
shown in the below image:

The statement free(ptr) de-allocates the memory as shown in the below image with a
cross sign, and 'ptr' pointer becomes dangling as it is pointing to the de-allocated
memory.

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory.
Therefore, we can say that ptr is not a dangling pointer, as shown in the below image:

Variable goes out of the scope

When the variable goes out of the scope then the pointer pointing to the variable
becomes a dangling pointer.

1. #include<stdio.h>
2. int main()
3. {
4. char *str;
5. {
6. char a = ?A?;
7. str = &a;
8. }
9. // a falls out of scope
10. // str is now a dangling pointer
11. printf("%s", *str);
12. }

In the above code, we did the following steps:

ADVERTISEMENT

o First, we declare the pointer variable named 'str'.


o In the inner scope, we declare a character variable. The str pointer contains the
address of the variable 'a'.
o When the control comes out of the inner scope, 'a' variable will no longer be
available, so str points to the de-allocated memory. It means that the str pointer
becomes the dangling pointer.

Function call

Now, we will see how the pointer becomes dangling when we call the function.

Let's understand through an example.

1. #include <stdio.h>
2. int *fun(){
3. int y=10;
4. return &y;
5. }
6. int main()
7. {
8. int *p=fun();
9. printf("%d", *p);
10. return 0;
11. }
In the above code, we did the following steps:

o First, we create the main() function in which we have declared 'p' pointer that
contains the return value of the fun().
o When the fun() is called, then the control moves to the context of the int
*fun(), the fun() returns the address of the 'y' variable.
o When control comes back to the context of the main() function, it means the
variable 'y' is no longer available. Therefore, we can say that the 'p' pointer is a
dangling pointer as it points to the de-allocated memory.

Output

Let's represent the working of the above code diagrammatically.

Let's consider another example of a dangling pointer.

ADVERT ISEMENT

1. #include <stdio.h>
2. int *fun()
3. {
4. static int y=10;
5. return &y;
6. }
7. int main()
8. {
9. int *p=fun();
10. printf("%d", *p);
11. return 0;
12. }

The above code is similar to the previous one but the only difference is that the variable
'y' is static. We know that static variable stores in the global memory.

Output

Now, we represent the working of the above code diagrammatically.

The above diagram shows the stack memory. First, the fun() function is called, then the
control moves to the context of the int *fun(). As 'y' is a static variable, so it stores in the
global memory; Its scope is available throughout the program. When the address value is
returned, then the control comes back to the context of the main(). The pointer 'p'
contains the address of 'y', i.e., 100. When we print the value of '*p', then it prints the value
of 'y', i.e., 10. Therefore, we can say that the pointer 'p' is not a dangling pointer as it
contains the address of the variable which is stored in the global memory.

Avoiding Dangling Pointer Errors

The dangling pointer errors can be avoided by initializing the pointer to the NULL value.
If we assign the NULL value to the pointer, then the pointer will not point to the de-
allocated memory. Assigning NULL value to the pointer means that the pointer is not
pointing to any memory location.

sizeof() operator in C
The sizeof() operator is commonly used in C. It determines the size of the expression or
the data type specified in the number of char-sized storage units. The sizeof() operator
contains a single operand which can be either an expression or a data typecast where the
cast is data type enclosed within parenthesis. The data type cannot only be primitive data
types such as integer or floating data types, but it can also be pointer data types and
compound data types such as unions and structs.

Need of sizeof() operator


Mainly, programs know the storage size of the primitive data types. Though the storage
size of the data type is constant, it varies when implemented in different platforms. For
example, we dynamically allocate the array space by using sizeof() operator:

1. int *ptr=malloc(10*sizeof(int));

In the above example, we use the sizeof() operator, which is applied to the cast of type
int. We use malloc() function to allocate the memory and returns the pointer which is
pointing to this allocated memory. The memory space is equal to the number of bytes
occupied by the int data type and multiplied by 10.

Note:
The output can vary on different machines such as on 32-bit operating system will show
different output, and the 64-bit operating system will show the different outputs of the same
data types.
The sizeof() operator behaves differently according to the type of the operand.

ADVERTISEMENT

o Operand is a data type


o Operand is an expression

When operand is a data type.

1. #include <stdio.h>
2. int main()
3. {
4. int x=89; // variable declaration.
5. printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable.
6. printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integ
er data type.
7. printf("\nsize of the character data type is %d",sizeof(char)); //Displaying the size of c
haracter data type.
8.
9. printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of flo
ating data type.
10. return 0;
11. }

In the above code, we are printing the size of different data types such as int, char, float
with the help of sizeof() operator.

Output
When operand is an expression

1. #include <stdio.h>
2. int main()
3. {
4. double i=78.0; //variable initialization.
5. float j=6.78; //variable initialization.
6. printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expressio
n (i+j).
7. return 0;
8. }

In the above code, we have created two variables 'i' and 'j' of type double and float
respectively, and then we print the size of the expression by using sizeof(i+j) operator.

Output

size of (i+j) expression is : 8

Handling Arrays and Structures


The sizeof() operator is highly helpful when working with arrays and structures in
addition to the above usage cases. Contiguous blocks of memory are known as arrays,
and understanding their size is crucial for a few tasks.

For example:

1. #include <stdio.h>
2.
3. int main() {
4. int arr[] = {1, 2, 3, 4, 5};
5. int arrSize = sizeof(arr) / sizeof(arr[0]);
6.
7. printf("Size of the array arr is: %d\n", sizeof(arr));
8. printf("Number of elements in arr is: %d\n", arrSize);
9.
10. return 0;
11. }

Output

Size of the array arr is: 20


Number of elements in arr is: 5

Sizeof(arr) returns the array's overall size in bytes, whereas sizeof(arr[0]) returns the
array's smallest element's size. The number of items in the array is determined by dividing
the overall size by the size of a single element (arrSize). By using this technique, the
code will continue to be flexible in the face of changing array sizes.

Similarly, you can use the sizeof() operator to figure out the size of structures:

1. #include <stdio.h>
2.
3. struct Person {
4. char name[30];
5. int age;
6. float salary;
7. };
8.
9. int main() {
10. struct Person p;
11.
12. printf("Size of the structure Person is: %d bytes\n", sizeof(p));
13.
14. return 0;
15. }

Output

Size of the structure Person is: 40 bytes

Allocation of dynamic memory and pointer arithmetic


Other applications of the sizeof() operator include pointer arithmetic and dynamic
memory allocation. Knowing the size of data types becomes essential when working
with arrays and pointers for correct memory allocation and element access.

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main() {
5. int *ptr;
6. int numElements = 5;
7.
8. ptr = (int*)malloc(numElements * sizeof(int));
9. if (ptr == NULL) {
10. printf("Memory allocation failed!\n");
11. return 1;
12. }
13.
14. for (int i = 0; i < numElements; i++) {
15. ptr[i] = i + 1;
16. }
17.
18. printf("Dynamic array elements: ");
19. for (int i = 0; i < numElements; i++) {
20. printf("%d ", ptr[i]);
21. }
22.
23. free(ptr); // Release allocated memory.
24.
25. return 0;
26. }

Output

Dynamic array elements: 1 2 3 4 5


Explanation:

In this example, a size numElements integer array has a memory that is dynamically
allocated. numElements * sizeof(int) bytes represent the total amount of memory
allocated. By doing this, the array is guaranteed to have enough room to accommodate
the desired amount of integers.

Sizeof() for Unions


Unions and the sizeof() operator are compatible. Unions are comparable
to structures, except only one member can be active at once, and all its members share
memory.

1. #include <stdio.h>
2.
3. union Data {
4. int i;
5. float f;
6. char str[20];
7. };
8.
9. int main() {
10. union Data data;
11.
12. printf("Size of the union Data is: %d bytes\n", sizeof(data));
13.
14. return 0;
15. }

Output

Size of the union Data is: 20 bytes

The sizeof() operator is extremely important since it's essential for memory
management, portability, and effective data handling. The sizeof() operator is crucial
in C for the reasons listed in the list below:
Memory Allocation: When working with arrays and dynamic memory allocation ,
the sizeof() operator is frequently used in memory allocation. Knowing the size of data
types when allocating memory for arrays or structures guarantees that the correct
amount of memory is reserved, reducing memory overflows and improving memory
utilization.

Portability: Since C is a popular programming language, code frequently has to


operate on several systems with differing architectures and data type sizes. As it specifies
the size of data types at compile-time, the sizeof() operator aids in designing portable
code by enabling programs to adapt automatically to various platforms.

Pointer Arithmetic: When dealing with pointers, the sizeof() operator aids in figuring
out memory offsets, allowing accurate movement within data structures, arrays, and
other memory regions. It is extremely helpful when iterating across arrays or dynamically
allocated memory.

Handling Binary Data: The sizeof() operator guarantees that the right amount of data
is read or written when working with binary data or files, eliminating mistakes brought on
by inaccurate data size assumptions.

Unions and Structures: The sizeof() operator is essential when


managing structures and unions, especially when utilizing them to build complicated
data structures. Memory allocation and access become effective and error-free when
you are aware of the size of structures and unions.

Safe Buffer Management: The sizeof() operator helps make sure that the buffer is big
enough to hold the data being processed while working with character arrays (strings),
preventing buffer overflows and potential security flaws.

Data Serialization and Deserialization: The sizeof() operator guarantees that the right
amount of data is handled, maintaining data integrity throughout data transfer or
storage, in situations where data needs to be serialized (converted to a byte stream) or
deserialized (retrieved from a byte stream).

Code Improvement: Knowing the size of various data formats might occasionally aid
in code optimization. For instance, it enables the compiler to more effectively align data
structures, reducing memory waste and enhancing cache performance.

Sizeof() Operator Requirement in C


The sizeof() operator is a key component in C programming due to its need in different
elements of memory management and data processing. Understanding data type sizes
is essential for effectively allocating memory, especially when working with arrays and
dynamic memory allocation. By ensuring that the appropriate amount of memory is
reserved, this information helps to avoid memory overflows and optimize memory use.
The sizeof() operator is also essential for creating portable code, which may execute
without error on several systems with differing architectures and data type sizes.

The program can adapt to many platforms without the need for manual modifications
since it supplies the size of data types at compile-time. Additionally, the sizeof()
operator makes it possible to navigate precisely around data structures and arrays while
working with pointers, facilitating safe and effective pointer arithmetic. Another
application for the sizeof() operator is handling unions and structures. It ensures
precise memory allocation and access within intricate data structures, preventing
mistakes and inefficiencies. The sizeof() operator is a basic tool that enables C
programmers to develop effective, portable, and resilient code while optimizing
performance and data integrity. It ensures safe buffer management and makes data
serialization and deserialization easier.

Conclusion:
In summary, the C sizeof() operator is a useful tool for calculating the size of many sorts
of objects, including data types, expressions, arrays, structures, unions, and more. As
it offers the size of data types at compile-time, catering to multiple platforms and settings,
it enables programmers to create portable and flexible code. Developers may effectively
handle memory allocation, pointer arithmetic, and dynamic memory allocation in
their programs by being aware of the storage needs of various data types.

When working with arrays and structures, the sizeof() operator is very helpful since it
ensures proper memory allocation and makes it simple to retrieve elements.
Additionally, it facilitates pointer arithmetic, making it simpler to move between memory
regions. However, because of operator precedence, programmers should be cautious
when utilizing complicated expressions with sizeof() operator.

Overall, learning the sizeof() operator equips C programmers to create stable and
adaptable software solutions by enabling them to write efficient, dependable, and
platform-independent code.

const Pointer in C
Constant Pointers
A constant pointer in C cannot change the address of the variable to which it is pointing,
i.e., the address will remain constant. Therefore, we can say that if a constant pointer is
pointing to some variable, then it cannot point to any other variable.

Syntax of Constant Pointer

1. <type of pointer> *const <name of pointer>;

Declaration of a constant pointer is given below:

1. int *const ptr;

Let's understand the constant pointer through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=1;
5. int b=2;
6. int *const ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }

In the above code:

Backward Skip 10sPlay VideoForward Skip 10s


ADVERTISEMENT

o We declare two variables, i.e., a and b with values 1 and 2, respectively.


o We declare a constant pointer.
o First, we assign the address of variable 'a' to the pointer 'ptr'.
o Then, we assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we try to print the value of the variable pointed by the 'ptr'.

Output

In the above output, we can observe that the above code produces the error "assignment
of read-only variable 'ptr'". It means that the value of the variable 'ptr' which 'ptr' is
holding cannot be changed. In the above code, we are changing the value of 'ptr' from
&a to &b, which is not possible with constant pointers. Therefore, we can say that the
constant pointer, which points to some variable, cannot point to another variable.

Pointer to Constant
A pointer to constant is a pointer through which the value of the variable that the pointer
points cannot be changed. The address of these pointers can be changed, but the value
of the variable that the pointer points cannot be changed.

Syntax of Pointer to Constant

1. const <type of pointer>* <name of pointer>

Declaration of a pointer to constant is given below:

1. const int* ptr;

Let's understand through an example.

o First, we write the code where we are changing the value of a pointer

1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%u",ptr);
10. return 0;
11. }

In the above code:

o We declare two variables, i.e., a and b with the values 100 and 200 respectively.
o We declare a pointer to constant.
o First, we assign the address of variable 'a' to the pointer 'ptr'.
o Then, we assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we try to print the value of 'ptr'.

Output

The above code runs successfully, and it shows the value of 'ptr' in the output.

o Now, we write the code in which we are changing the value of the variable to which
the pointer points.

1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&b;
8. *ptr=300;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }

In the above code:

o We declare two variables, i.e., 'a' and 'b' with the values 100 and 200 respectively.
o We declare a pointer to constant.
o We assign the address of the variable 'b' to the pointer 'ptr'.
o Then, we try to modify the value of the variable 'b' through the pointer 'ptr'.
o Lastly, we try to print the value of the variable which is pointed by the pointer 'ptr'.

Output

The above code shows the error "assignment of read-only location '*ptr'". This error
means that we cannot change the value of the variable to which the pointer is pointing.

Constant Pointer to a Constant


A constant pointer to a constant is a pointer, which is a combination of the above two
pointers. It can neither change the address of the variable to which it is pointing nor it can
change the value placed at this address.

Syntax

1. const <type of pointer>* const <name of the pointer>;

Declaration for a constant pointer to a constant is given below:

1. const int* const ptr;


Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int b=90;
6. const int* const ptr=&a;
7. *ptr=12;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }

In the above code:

o We declare two variables, i.e., 'a' and 'b' with the values 10 and 90, respectively.
o We declare a constant pointer to a constant and then assign the address of 'a'.
o We try to change the value of the variable 'a' through the pointer 'ptr'.
o Then we try to assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we print the value of the variable, which is pointed by the pointer 'ptr'.

Output
The above code shows the error "assignment of read-only location '*ptr'" and "assignment
of read-only variable 'ptr'". Therefore, we conclude that the constant pointer to a constant
can change neither address nor value, which is pointing by this pointer.

void pointer in C
Till now, we have studied that the address assigned to a pointer should be of the same
type as specified in the pointer declaration. For example, if we declare the int pointer, then
this int pointer cannot point to the float variable or some other type of variable, i.e., it can
point to only int type variable. To overcome this problem, we use a pointer to void. A
pointer to void means a generic pointer that can point to any data type. We can assign
the address of any data type to the void pointer, and a void pointer can be assigned to
any type of the pointer without performing any explicit typecasting.

Syntax of void pointer

1. void *pointer name;

Declaration of the void pointer is given below:

1. void *ptr;

In the above declaration, the void is the type of the pointer, and 'ptr' is the name of the
pointer.

Let us consider some examples:

ADVERT ISEMENT

int i=9; // integer variable initialization.

int *p; // integer pointer declaration.

float *fp; // floating pointer declaration.

void *ptr; // void pointer declaration.

p=fp; // incorrect.

fp=&i; // incorrect
ptr=p; // correct

ptr=fp; // correct

ptr=&i; // correct

Size of the void pointer in C


The size of the void pointer in C is the same as the size of the pointer of character type.
According to C perception, the representation of a pointer to void is the same as the
pointer of character type. The size of the pointer will vary depending on the platform that
you are using.

Let's look at the below example:

1. #include <stdio.h>
2. int main()
3. {
4. void *ptr = NULL; //void pointer
5. int *p = NULL;// integer pointer
6. char *cp = NULL;//character pointer
7. float *fp = NULL;//float pointer
8. //size of void pointer
9. printf("size of void pointer = %d\n\n",sizeof(ptr));
10. //size of integer pointer
11. printf("size of integer pointer = %d\n\n",sizeof(p));
12. //size of character pointer
13. printf("size of character pointer = %d\n\n",sizeof(cp));
14. //size of float pointer
15. printf("size of float pointer = %d\n\n",sizeof(fp));
16. return 0;
17. }

Output
Advantages of void pointer
Following are the advantages of a void pointer:

ADVERTISEMENT

o The malloc() and calloc() function return the void pointer, so these functions can
be used to allocate the memory of any data type.

1. #include <stdio.h>
2. #include<malloc.h>
3. int main()
4. {
5. int a=90;
6.
7. int *x = (int*)malloc(sizeof(int)) ;
8. x=&a;
9. printf("Value which is pointed by x pointer : %d",*x);
10. return 0;
11. }

Output

o The void pointer in C can also be used to implement the generic functions in C.
Some important points related to void pointer are:

o Dereferencing a void pointer in C

The void pointer in C cannot be dereferenced directly. Let's see the below example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. void *ptr;
6. ptr=&a;
7. printf("Value which is pointed by ptr pointer : %d",*ptr);
8. return 0;
9. }

In the above code, *ptr is a void pointer which is pointing to the integer variable 'a'. As
we already know that the void pointer cannot be dereferenced, so the above code will
give the compile-time error because we are printing the value of the variable pointed by
the pointer 'ptr' directly.

Output

ADVERTISEMENT

Now, we rewrite the above code to remove the error.

1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. void *ptr;
6. ptr=&a;
7. printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
8. return 0;
9. }

In the above code, we typecast the void pointer to the integer pointer by using the
statement given below:

(int*)ptr;

Then, we print the value of the variable which is pointed by the void pointer 'ptr' by using
the statement given below:

*(int*)ptr;

Output

o Arithmetic operation on void pointers

We cannot apply the arithmetic operations on void pointers in C directly. We need to


apply the proper typecasting so that we can perform the arithmetic operations on the
void pointers.

Let's see the below example:

1. #include<stdio.h>
2. int main()
3. {
4. float a[4]={6.1,2.3,7.8,9.0};
5. void *ptr;
6. ptr=a;
7. for(int i=0;i<4;i++)
8. {
9. printf("%f,",*ptr);
10. ptr=ptr+1; // Incorrect.
11.
12. }}

The above code shows the compile-time error that "invalid use of void expression" as
we cannot apply the arithmetic operations on void pointer directly, i.e., ptr=ptr+1.

Let's rewrite the above code to remove the error.

1. #include<stdio.h>
2. int main()
3. {
4. float a[4]={6.1,2.3,7.8,9.0};
5. void *ptr;
6. ptr=a;
7. for(int i=0;i<4;i++)
8. {
9. printf("%f,",*((float*)ptr+i));
10. }}

The above code runs successfully as we applied the proper casting to the void pointer,
i.e., (float*)ptr and then we apply the arithmetic operation, i.e., *((float*)ptr+i).

Output

Why we use void pointers?


We use void pointers because of its reusability. Void pointers can store the object of any
type, and we can retrieve the object of any type by using the indirection operator with
proper typecasting.

Let's understand through an example.

1. #include<stdio.h>
2. int main()
3. {
4. int a=56; // initialization of a integer variable 'a'.
5. float b=4.5; // initialization of a float variable 'b'.
6. char c='k'; // initialization of a char variable 'c'.
7. void *ptr; // declaration of void pointer.
8. // assigning the address of variable 'a'.
9. ptr=&a;
10. printf("value of 'a' is : %d",*((int*)ptr));
11. // assigning the address of variable 'b'.
12. ptr=&b;
13. printf("\nvalue of 'b' is : %f",*((float*)ptr));
14. // assigning the address of variable 'c'.
15. ptr=&c;
16. printf("\nvalue of 'c' is : %c",*((char*)ptr));
17. return 0;
18. }

Output

C dereference pointer
As we already know that "what is a pointer", a pointer is a variable that stores the address
of another variable. The dereference operator is also known as an indirection operator,
which is represented by (*). When indirection operator (*) is used with the pointer variable,
then it is known as dereferencing a pointer. When we dereference a pointer, then the
value of the variable pointed by this pointer will be returned.

Why we use dereferencing pointer?


Dereference a pointer is used because of the following reasons:

ADVERTISEMENT
ADVERTISEMENT

o It can be used to access or manipulate the data stored at the memory location,
which is pointed by the pointer.
o Any operation applied to the dereferenced pointer will directly affect the value of
the variable that it points to.

Let's observe the following steps to dereference a pointer.

o First, we declare the integer variable to which the pointer points.

1. int x =9;

o Now, we declare the integer pointer variable.

1. int *ptr;

o After the declaration of an integer pointer variable, we store the address of 'x'
variable to the pointer variable 'ptr'.

1. ptr=&x;

o We can change the value of 'x' variable by dereferencing a pointer 'ptr' as given
below:

1. *ptr =8;

The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to the 'x'
location and dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.
Let's combine all the above steps:

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

Output

Let's consider another example.

1. #include <stdio.h>
2. int main()
3. {
4. int x=4;
5. int y;
6. int *ptr;
7. ptr=&x;
8. y=*ptr;
9. *ptr=5;
10. printf("The value of x is : %d",x);
11. printf("\n The value of y is : %d",y);
12. return 0;
13. }

In the above code:

o We declare two variables 'x' and 'y' where 'x' is holding a '4' value.
o We declare a pointer variable 'ptr'.
o After the declaration of a pointer variable, we assign the address of the 'x' variable
to the pointer 'ptr'.
o As we know that the 'ptr' contains the address of 'x' variable, so '*ptr' is the same
as 'x'.
o We assign the value of 'x' to 'y' with the help of 'ptr' variable, i.e., y=*ptr instead of
using the 'x' variable.

Note: According to us, if we change the value of 'x', then the value of 'y' will also get changed
as the pointer 'ptr' holds the address of the 'x' variable. But this does not happen, as 'y' is
storing the local copy of value '5'.

Output

Let's consider another scenario.

ADVERT ISEMENT
ADVERT ISEMENT

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

In the above code:

o First, we declare an 'a' variable.


o Then we declare two pointers, i.e., ptr1 and ptr2.
o Both the pointers contain the address of 'a' variable.
o We assign the '7' value to the *ptr1 and '6' to the *ptr2. The final value of 'a' would
be '6'.

Note: If we have more than one pointer pointing to the same location, then the change made
by one pointer will be the same as another pointer.

Output

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

ADVERT ISEMENT
ADVERT ISEMENT

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

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.

ADVERT ISEMENT
ADVERT ISEMENT

1. ptr=realloc(ptr, new-size)

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

1. free(ptr)

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.

ADVERTISEMENT

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

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

It is clear from the output that, the above code will not work for space separated strings.
To make this code working for the space separated strings, the minor changed required
in the scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s)
which instructs the compiler to store the string s while the new line (\n) is encountered.
Let's consider the following example to store the space-separated strings.

ADVERT ISEMENT

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

Enter the string?javatpoint is the best


You entered javatpoint is the best

Here we must also notice that we do not need to use address of (&) operator in scanf to
store a string since string s is an array of characters and the name of the array, i.e., s
indicates the base address of the string (character array) therefore we need not use &
with it.

Some important points


ADVERTISEMENT

However, there are the following points which must be noticed while entering the strings
by using scanf.

o The compiler doesn't perform bounds checking on the character array. Hence,
there can be a case where the length of the string can exceed the dimension of the
character array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a
header file string.h. The gets() is capable of receiving only one string at a time.

Pointers with strings


We have used pointers with the array, functions, and primitive data types so far. However,
pointers can be used to point to the strings. There are various advantages of using
pointers to point strings. Let us consider the following example to access the string via
the pointer.

1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. char *p = s; // pointer p is pointing to string s.
6. printf("%s",p); // the string javatpoint is printed if we print p.
7. }
Output

javatpoint

As we know that string is an array of characters, the pointers can be used in the same way
they were used with arrays. In the above example, p is declared as a pointer to the array
of characters s. P affects similar to s since s is the base address of the string and treated
as a pointer internally. However, we can not change the content of s or copy the content
of s into another string directly. For this purpose, we need to use the pointers to store the
strings. In the following example, we have shown the use of pointers to copy the content
of a string into another.

1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("String p: %s\n",p);
6. char *q;
7. printf("copying the content of p into q...\n");
8. q = p;
9. printf("String q: %s\n",q);
10. }
Output

String p: hello javatpoint


copying the content of p into q...
String q: hello javatpoint

Once a string is defined, it cannot be reassigned to another set of characters. However,


using pointers, we can assign the set of characters to the string. Consider the following
example.

1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("Before assigning: %s\n",p);
6. p = "hello";
7. printf("After assigning: %s\n",p);
8. }

Output

Before assigning: hello javatpoint


After assigning: hello

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: Sonoo Jaiswal
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, source) copies the contents of source string to destination string.

3) strcat(first_string, concats or joins first string with second string. The result of th
second_string) is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) returns 0.

5) strrev(string) returns reverse string.

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

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

C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }

Output:

Length of string is: 10

C Copy String: strcpy()


The strcpy(destination, source) function copies the source string in destination.

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

Output:

Value of second string is: javatpoint

Strcat() function in C
Programmers may easily concatenate two strings using the strcat() function in C, which
is a potent tool for manipulating strings. This function accepts two input strings and
appends the second string's content to the end of the first string. A single, longer string
made up of the characters from both input strings is the outcome. You must include
the string.h header file to use strcat(). But to prevent buffer
overflow and unpredictable behavior, it is essential to make sure the first string has
enough memory to hold the concatenated content. In this article, we'll study several
crucial string concatenation principles in C and go in-depth on the strcat() method.

Concatenating strings is a fundamental programming process, particularly when


working with text-based data. Strings in C are character arrays that are ended by the null
character "0". You may produce longer and more insightful text outputs by adding one
string to another with the strcat() method.

The strcat(first_string, second_string) function concatenates two strings and result is


returned to first_string.

first_string: The concatenated result will be saved in this string, which is a reference to
the target string. The second_string's content is added to the end of the first_string by
the function. Making ensuring that the first_string has adequate memory to store the
concatenated information is crucial.
Second_string: It is a reference to the source string that will be added to the end of
the first_string. During concatenation, the initial second_string is not modified.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }

Output

Value of first string is: helloc

Explanation:

The required header files are included in the source code, stdio.h for
standard input/output routines and string.h for string manipulation operations
like strcat().

There are two declared character arrays (ch and ch2). The first array, ch, begins with the
letters "hello" and ends with the specifically specified null character "0". The letter "c" is
found in the second array, ch2, followed by the null character "0".

The two strings are concatenated using the strcat(ch, ch2) function. The characters
from ch2 will be added to the end of ch in accordance with the behavior of the function.
The adjusted ch array will appear as follows concatenation: "helloc0" (remember
that "0" stands for the null terminator).

ADVERT ISEMENT

The changed ch array is then displayed using the printf() function, producing the
following output: "Value of the first string is: helloc".

Conclusion:
In conclusion, developers may effectively deal with character arrays due to the C
programming language's robust string manipulation capabilities like strcat().
The strcat() method is designed to join two strings together by merging the end of
the second string with the contents of the first. Care must be taken while utilizing this
function to prevent buffer overflow and undefinable behavior.

The strcat() function successfully combined the strings "hello" and "c" in the supplied
code sample, producing the output "helloc". It emphasizes how crucial it is to check that
the destination string has enough room to hold the combined result.

When working with unknown or dynamic data, developers should always evaluate the
sizes of the source and destination arrays before using strcat() and may want to
use strncat() with a set maximum length.

There are several string manipulation functions available in the C language, each with
special benefits and applications. The creation of reliable and secure software will be
facilitated by understanding these functions and using safe coding techniques.
Understanding string handling, a fundamental programming component, enables
programmers to build more complex and dependable systems across various industries.
As their exploration of C programming progresses, aspiring programmers should get
more familiar with the language's features and gain proficiency in it.

Strcmp() function in C
The C standard library includes the strcmp() function for string comparison. In C
programming, it is frequently used to compare two strings and is a component of
the <string.h> header. A connection between the two strings is shown by the
function's return value, which is an integer value.

The strcmp(first_string, second_string) function compares two strings and returns 0 if both
strings are equal.

Pointer to the first string that will be compared, str1.

Pointer to the second string that will be compared, str2.

If str1 is lexicographically superior to str2, it returns an integer number larger than 0.

If str1 is lexicographically smaller to str2, it returns an integer value that is less than 0.
It returns 0 if str1 and str2 are equal.

Here, we are using gets()function, which reads string from the console.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }

Output

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

Explanation:

ADVERT ISEMENT
ADVERT ISEMENT

The program comes with the appropriate header files, including "stdio.h" for functions
that deal with standard input/output and "string.h" for functions that deal with strings,
including strcmp().

Two-character arrays str1 and str2 of size 20 are declared to hold the input
strings supplied by the user.

Using the printf() method, the program asks the user to input the first string.
The input string is read from the console using the gets() method. However, it is
significant to highlight that due to its susceptibility to buffer overflow attacks, gets() is
deprecated and not advised. In a similar manner, the program asks the user to enter
the second string before using gets() to read it.

After that, the two strings str1 and str2 are put to a comparison using the strcmp()
method.

Since the two strings are equal if strcmp() returns 0, the program writes "Strings are
equal" using printf().

Otherwise, the program outputs "Strings are not equal" if strcmp() returns a non-zero
result.

ADVERT ISEMENT
ADVERT ISEMENT

Lastly, the main function returns 0, indicating that the program has successfully run.

Two strings are character-by-character compared using the strcmp() method. The
comparison process begins with each string's first characters. If they are equal, it advances
to the subsequent characters until either:

It decides which string is lexicographically bigger or smaller based on the differences


between the matching characters, or it reaches the end of one or both strings.

ADVERT ISEMENT
ADVERT ISEMENT

The ASCII values of the characters are used in the comparison.

Uppercase and lowercase letters are viewed differently in the comparison since it takes
the case into account.

ADVERTISEMENT
ADVERTISEMENT

The function presupposes that the strings handed in as input are null-terminated. A
string that ends with the null character ('0') is known as a null-terminated string.

In this example, the gets() function is used to read strings from the console. It is
important to note that the gets() method has been deprecated in the C programming
language and is strongly discouraged. The main cause of the issue is that gets() has no
method to control how many characters are read from the input, rendering it vulnerable
to buffer overflow attacks that can result in security flaws.

It is advised to use fgets() in place of the console to safely read strings. To avoid buffer
overflows, the fgets() function lets you set the maximum number of characters to read.

C Reverse String: strrev()


The C standard library does not contain the strrev() function, which is not a standard
library function. However, it has long been a well-liked utility function for C programmers
to reverse strings. Despite being widely used, strrev() should not be used owing to
potential hazards and its inherent restrictions.

The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }

Output

Enter string: javatpoint


String is: javatpoint
Reverse String is: tnioptavaj

Explanation:

The provided C code accepts a string as input, uses the strrev() function to reverse it,
and outputs both the original and reversed texts. Using the strrev() method, the
text "javatpoint" is reversed to become "tnioptavaj".
Let's talk about the drawbacks of strrev() and why it is not advised:
There are various drawbacks of the strrev() function. Some main drawbacks are as
follows:

ADVERTISEMENT
ADVERTISEMENT

o Security Risks: It is inherently dangerous because the strrev() method changes


the original string in place. If the target buffer is not big enough to accommodate
the reversed string, it might result in buffer overflows. Attackers may use buffer
overflows to run malicious code, potentially resulting in security flaws.
o Lack of Standard Library Support: Since strrev() is not supported by the C
standard library, its behavior may change between systems and compilers. As a
result, code that uses strrev() might not run on different platforms.
o Strrev Is Not a Safe Replacement for strdup(): Some programmers could try to
use strrev() in place of the string duplication method strdup(). Strrev() alters the
old string; it does not produce a new reversed string. Therefore, it is not a reliable
alternative to strdup().
o Strrev() is not a standard function, as was previously indicated, and current C
programming conventions encourage the use of safer and more dependable
alternatives.

If you want to reverse a string in C instead of using strrev(), you should think about
the following alternatives:

Using a Loop: Until you reach the center of the string, you can traverse it using a
loop, switching characters from the beginning with characters from the end.

Using a Temporary Array: If you want to produce a reversed string, copy the characters
from the original string into a temporary array in the opposite sequence and then null-
terminate the array.

Using Standard Library methods: If you are familiar with C++, you can quickly reverse
a string by using the standard library's std::string and std::reverse methods.

ADVERT ISEMENT
ADVERT ISEMENT
The strrev() function in C is not a recommended method for string manipulation due
to several significant restrictions and possible hazards, despite its popularity among
developers for reversing strings. It is not portable because it is not a part of the C standard
library and because of its unsafe behavior, which might result in buffer overflows and
expose security flaws in the code.

Using strrev() is discouraged in modern C programming practices, which emphasize safe


and dependable string manipulation approaches. Developers are urged to choose other
approaches, such as traversing and swapping characters in the string using loops or
temporarily storing the reversed text in an array.

Developers may ensure their code is resistant to vulnerabilities and can be reliably
executed across many platforms and compilers by using more secure ways.

The standard library's string manipulation methods, such


as std::string and std::reverse, which provide a safer and more user-friendly way to
reverse strings, are also available to developers using C++.

In conclusion, avoiding the use of strrev() and implementing safer ways for string
reversing conforms with contemporary best practices for programming and contributes
to the development of C code that is more dependable, secure, and manageable.

Strlwr() function in C
Working with strings is a regular activity while programming in the C programming
language. It is frequently necessary to transform strings to lowercase or uppercase to
ensure uniform processing and comparisons. The strlwr() function is very crucial in this
situation. It is a string manipulation function that can be found in the C Standard Library
(string.h) and is used to change the case of characters in a string. In-depth explanations
of the strlwr() function and a practical application example are provided in this article.

Every capital letter in a C-style string is changed to its corresponding lowercase


character using the strlwr() function. One input, a reference to the string that must be
transformed, is all that is required. The function makes the necessary modifications to
the initial string while still returning the same pointer. It's crucial to remember that this
method isn't standardized and cannot be accessible on all C implementations.

Syntax:
It has the following syntax:
1. char* strlwr(char* str);

str: It is a reference to the string that must be lowercase and has a null ending.

Value Returned:
The same pointer str is returned by the strlwr() method, which now points to the altered
lowercase text.

The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }

Output

Enter string: JAVATpoint


String is: JAVATpoint
Lower String is: javatpoint

Explanation:

The relevant header files are first included in the


code: stdio.h for input/output operations and string.h for functions involving string
manipulation.

The input string will be saved in a 20-character array named str.

ADVERT ISEMENT
ADVERT ISEMENT
The printf() method asks the user to provide a string.

The gets() method reads the input string. It's crucial to remember that the gets()
method is insecure and should be swapped out with fgets() to prevent buffer overflow.
The printf() function prints the original input string.

After that, the str pointer is sent as an argument when using the strlwr() method. The
method returns the changed text after changing all capital letters in the string
to lowercase.

After that, the printf() function is used to output the lowercase string.

Problems with Safer Input Reading and gets()


The example's use of the gets() method brings up a serious issue with buffer overflow
vulnerability. The function does not verify the input size, which might result in memory
corruption. It is strongly advised to switch from gets() to fgets() for safer input reading.
The updated code would seem as follows:

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main() {
5. char str[20];
6.
7. printf("Enter string: ");
8. fgets(str, sizeof(str), stdin);
9.
10. // Rest of the code remains unchanged.
11. }

Output

Enter string: HELLOworld


String is: HELLOworld
Lower String is: helloworld

Conclusion:
In conclusion, the C language's strlwr() function offers an easy way to
change uppercase to lowercase letters within a string, enabling case-insensitive
operations and reliable string processing. Despite being frequently used, the function is
non-standard and may not be included in all C implementations, which raises questions
regarding portability.

ADVERT ISEMENT
ADVERT ISEMENT

The example code was advised against using gets(), and the safer substitute fgets() was
suggested instead to solve potential security flaws. It is essential to ensure safe input
handling to avoid buffer overflow and memory corruption problems.

Although strlwr() can effectively accomplish its goal, programmers should be aware of
its limits and consider other standard-compliant approaches to string manipulation. It
may be more portable to use bespoke functions in various C environments when
converting lowercase strings.

Overall, being proficient with string manipulation in C, especially the proper application
of methods like strlwr(), equips programmers to deal with strings quickly and write
reliable, safe, and portable programs.

C String Uppercase: strupr()


In C programming, the strupr() method is used to make all the characters in a string
uppercase. The <string.h> header file contains the strupr() function, and it is a
component of the C Standard Library. A pointer to the null-terminated string (an array
of characters) is the only argument required by the function. When the strupr()
function is used, all alphabetic characters in the string are transformed to uppercase,
while non-alphabetic characters are left alone.

The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }

Output

Enter string: javatpoint


String is: javatpoint
Upper String is: JAVATPOINT

Explanation:

The program begins by incorporating the required header files: string.h for functions
related to strings and stdio.h for input/output operations. It defines a 20-
character str array as its size. The user-provided input string will be kept in this array.

A prompt message asking the user to enter a string is shown using the printf() function.

The user-input string is received from the console and stored in the str array using
the gets() method. It is crucial to remember that using gets() function might result in
buffer overflow problems, making it dangerous. It is preferable to utilize fgets() to
reliably read input in real-world applications.

After that, the original input string is shown by the program using printf() function.
The intriguing portion is about to start. The str array is sent as an argument when
the strupr() method is used. All alphabetic characters in the string will be converted
to uppercase using this function, which makes the changes in-place.

After that, the updated (uppercase) string is printed by the program using the printf()
function.

Benefits of strupr() function:


1. Simple Uppercase Conversion: Using the strupr() method, every character in a
string may be easily converted to uppercase without the need for any additional
character manipulation.
2. By modifying the original string while it is still in existence, the function avoids the
need to create a new string specifically to hold the transformed result.
3. Convenience in Text Processing: It is very helpful when case-insensitive text
comparisons or operations are needed.

Cautions:
1. As previously explained, the gets () method is unsafe to employ since it doesn't
verify the size of the buffer and can result in buffer overflows. Use fgets() to safely
read input instead.
2. Locale Consideration: Since different locales may have rules for case conversions,
the behavior of strupr() may vary depending on the current locale settings. It's
crucial to confirm that your locale settings are acceptable for your use case if you
see unexpected behavior.
3. It's important to note that the strupr() function is not a part of the C standard
library. It may not be present in all C contexts, despite being often accessible on
many C compilers (such as Borland C, Turbo C, etc.).

Conclusion:
In conclusion, the C strupr() function provides a practical and simple method for
changing all the characters in each string to uppercase. Although it is not a part of the
standard C library, it is frequently present in many C settings and can be handy for case-
insensitive string manipulation. Nevertheless, the feature must be used with caution.

ADVERT ISEMENT
ADVERT ISEMENT

The unsafe gets() function, which can result in buffer overflows, is one of the main issues
with the presented code example. It is advised to utilize methods like fgets() to
read input with a designated buffer size to ensure secure input handling.

Additionally, strupr()'s behavior could be impacted by the current locale settings, which
may have an impact on the conversion process based on certain language regulations.
For better control over case conversion, it's recommended to select the proper locale or
make use of common character manipulation methods like toupper() function.
Strstr() function in C
The strstr() function in C is a part of the string.h library and is used to find the first
occurrence of a substring within a given string. If the substring is found in the string, it
returns a pointer to the first character of the first occurrence of the substring. The function
returns a NULL pointer if the substring is not present in the given string.

Syntax:
It has the following syntax:

1. char *strstr(const char *string, const char *match);

Here is an explanation of each heading or aspect related to the strstr() function:

Function Name:
The strstr() function stands for "string search". It is a built-in C library function that
searches for a substring within a larger string.

Return Type:
The function returns a pointer to the substring ('match')'s first occurrence within the
text ('string'). If the substring cannot be found, the method returns NULL.

Parameters:
ADVERTISEMENT

o 'string' (const char *): It is the input string in which the substring should be found.
o 'match' (const char *): It is the substring you want to search for within the string.

Function Behavior:
The strstr() function looks for the first instance of the substring ('match') inside the
more extensive string ('string').

It returns a reference to the haystack place where the substring begins or NULL if it
cannot be found.
Case Sensitivity:
By default, strstr() is case-sensitive. It differentiates
between uppercase and lowercase characters in both the string and the match.

Example Usage:

1. #include <stdio.h>
2. #include <string.h>
3.
4. intmain() {
5. char str[100] = "this is javatpoint with c and java";
6. char *sub;
7.
8. sub = strstr(str, "java");
9.
10. if (sub != NULL) {
11. printf("Substring is: %s", sub);
12. } else {
13. printf("Substring not found.");
14. }
15.
16. return 0;
17. }

Output:

Substring is: javatpoint with c and java

Complexity:

Time Complexity: O((n - m + 1) * m)

Auxiliary Space Complexity: O(1)

Explanation:
In the example above, the strstr() function searches for the first occurrence of the
substring "java" in the string str. Since "java" is present in the string, the function
returns a pointer to the beginning of the matched substring "javatpoint with c and
java", which is then printed using the printf() function. The strstr() function returns a
pointer to the first occurrence of the matched string in the given string. It returns the
substring from the first match to the last character.

Application:
Searching for a specific word within a given text.

Example Code:

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main() {
5. const char *text = "The quick brown fox leaps over the sleepy dog.";
6. const char *word = "fox";
7.
8. char *result = strstr(text, word);
9.
10. if (result != NULL) {
11. printf("Word '%s' found at index: %ld\n", word, result - text);
12. } else {
13. printf("Word '%s' not found.\n", word);
14. }
15.
16. return 0;
17. }

Output:

Word' fox' found at index: 16

Complexity:
Time Complexity: O((n - m + 1) * m)

Auxiliary Space Complexity: O(1)

Features of the strstr() function in c


The strstr() function has several useful capabilities for searching and manipulating
strings in C. Here are a few of its key characteristics:

o Substring Search:

The primary purpose of the strstr() function is to search for the first occurrence of a
substring within a larger string (match).

o Pointer Return:

It gives back a pointer to the substring's leading character that was located in
the haystack. A NULL reference is returned if the substring is not found.

o Case Sensitivity:

By default, the strstr() function performs a case-sensitive search. It considers the exact
sequence of characters in the needle and haystack.

o Customizable Search:

While the strstr() function is case-sensitive by default, you can implement case-insensitive
searching by converting the haystack and the needle to lowercase or uppercase before
performing the search.

o String Manipulation:

The returned pointer can be used to manipulate the string, such as extracting the
substring, modifying it, or performing other operations.

o Text Processing:

The strstr() function is commonly used in text processing tasks, such as finding keywords
or phrases within text, highlighting search terms, and performing basic string-based
operations.
o Efficiency:

Although the worst-case time complexity of the strstr() function is not always
optimal (O((n - m + 1) * m)), where n is the length of the haystack & m is the length of
the needle, it still performs well for many practical use cases.

o Library Function:

The strstr() function can be found in the string.h header of the C Standard Library. It
indicates that it can be used without extra libraries or dependencies in any C environment.

The strstr() function works with null-terminated strings, like most C string methods. It
indicates that it expects strings ending with a null character ('0').

o Character Set Agnostic:

The strstr() function operates on individual bytes and does not depend on the
character encoding used for the strings. It's suitable for various character sets,
including ASCII and Unicode.

o Usage with Other Functions:

The strstr() fucntion can be supplemented with additional string functions like altering
substrings, counting occurrences, and separating strings.

o Portability

As the strstr() function is a component of the C Standard Library, it is accessible on many


platforms and compilers, enhancing the portability of your work.

Although strstr() is flexible and effective for many applications, there may be occasions
where other string manipulation methods or libraries are more appropriate. This is
especially true if you need to perform more in-depth text processing or pattern matching.

ADVERT ISEMENT
ADVERT ISEMENT

Advantages and disadvantages of strstr() function in C:


Like any other tool, the strstr() function in C has its advantages and disadvantages. Let
us explore these aspects:

Advantages:

o Simplicity: The strstr() function is straightforward, especially for basic substring


search operations. Its interface is simple and doesn't require complex
configurations.
o Built-in Functionality: It is part of the C Standard Library and is available in
virtually every C environment without requiring additional libraries or
dependencies.
o Portability: Since it is a standard library function, code using the strstr() function
tends to be more portable across different systems and compilers.
o Efficiency for Many Use Cases: While its worst-case time complexity isn't
optimal (O((n - m + 1) * m)), it performs well for many practical scenarios, making
it suitable for basic text processing tasks.
o Text Processing: It is especially useful for searching for keywords, extracting
substrings, and basic string manipulations.
o Pointer Manipulation: The returned pointer can be used to directly manipulate
the string or perform further operations without needing extra memory allocation.

Disadvantages:

o Limited to First Occurrence: The strstr() function only finds the first occurrence
of the substring within the haystack. If you need to find all occurrences, you'll need
to implement additional logic.
o Inefficiency in Some Cases: The worst-case time complexity of the strstr()
function can be inefficient for large strings or when searching for long substrings
within long haystacks.
o Case Sensitivity: By default, the strstr() function is case-sensitive. If you require
case-insensitive searching, you must convert strings to lowercase or uppercase,
which might be time-consuming.
o Advanced Features Missing: While the strstr() function is adequate for basic
jobs, it lacks complex features such as regular expressions and more complicated
pattern matching.
o Not Suitable for Binary Data: It's designed for null-terminated strings, so it might
not work well for searching within binary data containing null bytes.
o Memory Manipulation: While the returned pointer can be used to manipulate
the string, improper usage could lead to buffer overflows or memory corruption.
o Limited Error Reporting: If the substring is not found in the string, the strstr()
function primarily returns a pointer to the substring or NULL. It doesn't provide
detailed error messages, making debugging more challenging.

Conclusion:
The strstr() function is useful for searching and extracting substrings within C strings. It
is widely used in various applications that involve string processing and manipulation.
However, it's essential to be mindful of case sensitivity, edge cases, and the potential
performance impact when dealing with large strings.

C Math
C Programming allows us to perform mathematical operations through the functions
defined in <math.h> header file. The <math.h> header file contains various methods for
performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value which is greate
than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value which is les
than or equal to given number.
3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

C Math Example
Let's see a simple example of math functions found in math.h header file.

1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }

Output:

4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
C Structure
Why use structure?
In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only. It can have different
attributes of different data types. For example, an entity Student may have its name
(string), roll number (int), marks (float). To store such type of information regarding an
entity student, we have the following approaches:

ADVERTISEMENT
ADVERTISEMENT

o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.

Let's look at the first approach in detail.

1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }

Output

Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69

Printing the Student details...


Arun 90 91.000000
Varun 91 56.000000
Sham 89 69.000000

The above program may fulfill our requirement of storing the information of an entity
student. However, the program is very complex, and the complexity increase with the
amount of the input. The elements of each of the array are stored contiguously, but all
the arrays may not be stored contiguously in the memory. C provides you with an
additional and simpler approach where you can use a special data structure, i.e., structure,
in which, you can group all the information of different data type regarding an entity.

What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member. Structures ca; simulate the use
of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

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:

ADVERT ISEMENT
ADVERT ISEMENT

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.

ADVERT ISEMENT
ADVERT ISEMENT

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

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.

ADVERT ISEMENT
ADVERT ISEMENT

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:

employee 1 id : 101
employee 1 name : Sonoo Jaiswal
ADVERTISEMENT
ADVERTISEMENT

Let's see another example of the structure in C language to store many employees
information.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
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

typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to
the already existing variable in the C program. It behaves similarly as we define the alias
for the commands. In short, we can say that this keyword is used to redefine the name of
an already existing variable.

Syntax of typedef
1. typedef <existing_name> <alias_name>

In the above syntax, 'existing_name' is the name of an already existing variable while
'alias name' is another name given to the existing variable.

For example, suppose we want to create a variable of type unsigned int, then it becomes
a tedious task if we want to declare multiple variables of this type. To overcome the
problem, we use a typedef keyword.

1. typedef unsigned int unit;

In the above statements, we have declared the unit variable of type unsigned int by
using a typedef keyword.

Now, we can create the variables of type unsigned int by writing the following statement:

1. unit a, b;

instead of writing:

1. unsigned int a, b;

Till now, we have observed that the typedef keyword provides a nice shortcut by
providing an alternative name for an already existing variable. This keyword is useful when
we are dealing with the long data type especially, structure declarations.

Let's understand through a simple example.

1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10. return 0;
11. }

Output

Value of i is :10
Value of j is :20

Using typedef with structures


Consider the below structure declaration:

ADVERT ISEMENT
ADVERT ISEMENT

1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. struct student s1;

In the above structure declaration, we have created the variable of student type by
writing the following statement:

1. struct student s1;

The above statement shows the creation of a variable, i.e., s1, but the statement is quite
big. To avoid such a big statement, we use the typedef keyword to create the variable of
type student.

1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. typedef struct student stud;
7. stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now,
we can use the stud variable in a program to create the variables of type struct student.

The above typedef can be written as:

1. typedef struct student


2. {
3. char name[20];
4. int age;
5. } stud;
6. stud s1,s2;

From the above declarations, we conclude that typedef keyword reduces the length of
the code and complexity of data types. It also helps in understanding the program.

Let's see another example where we typedef the structure declaration.

1. #include <stdio.h>
2. typedef struct student
3. {
4. char name[20];
5. int age;
6. }stud;
7. int main()
8. {
9. stud s1;
10. printf("Enter the details of student s1: ");
11. printf("\nEnter the name of the student:");
12. scanf("%s",&s1.name);
13. printf("\nEnter the age of student:");
14. scanf("%d",&s1.age);
15. printf("\n Name of the student is : %s", s1.name);
16. printf("\n Age of the student is : %d", s1.age);
17. return 0;
18. }
Output

ADVERT ISEMENT
ADVERT ISEMENT

Enter the details of student s1:


Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28

Using typedef with pointers


We can also provide another name or alias name to the pointer variables with the help
of the typedef.

For example, we normally declare a pointer, as shown below:

1. int* ptr;

We can rename the above pointer variable as given below:

ADVERT ISEMENT
ADVERT ISEMENT

1. typedef int* ptr;

In the above statement, we have declared the variable of type int*. Now, we can create
the variable of type int* by simply using the 'ptr' variable as shown in the below
statement:

1. ptr p1, p2 ;

In the above statement, p1 and p2 are the variables of type 'ptr'.

C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using
the structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25. }

Output

Enter the name, id, and marks of student 1 James 90 90


Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will
have to declare 20 different structure variables and store them one by one. This will always
be tough since we will have to declare a variable every time we add a student.
Remembering the name of all the variables is also a very tricky task. However, c enables
us to declare an array of structures by using which, we can avoid declaring the different
structure variables; instead we can make a collection containing all the structures that
store the information of different entities.

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.a
dd.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,e
1.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.

ADVERT ISEMENT
ADVERT ISEMENT

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

Structure Padding in C
Structure padding is a concept in C that adds the one or more empty bytes between the
memory addresses to align the data in memory.

Let's first understand the structure padding in C through a simple scenario which is
given below:

Suppose we create a user-defined structure. When we create an object of this structure,


then the contiguous memory will be allocated to the structure members.
1. struct student
2. {
3. char a;
4. char b;
5. int c;
6. } stud1;

In the above example, we have created a structure of type student. We have declared the
object of this structure named as 'stud1'. After the creation of an object, a contiguous
block of memory is allocated to its structure members. First, the memory will be allocated
to the 'a' variable, then 'b' variable, and then 'c' variable.

What is the size of the struct student?

Now, we calculate the size of the struct student. We assume that the size of the int is 4
bytes, and the size of the char is 1 byte.

1. struct student
2. {
3. char a; // 1 byte
4. char b; // 1 byte
5. int c; // 4 bytes
6. }

In the above case, when we calculate the size of the struct student, size comes to be 6
bytes. But this answer is wrong. Now, we will understand why this answer is wrong? We
need to understand the concept of structure padding.

Structure Padding
The processor does not read 1 byte at a time. It reads 1 word at a time.

What does the 1 word mean?

If we have a 32-bit processor, then the processor reads 4 bytes at a time, which means
that 1 word is equal to 4 bytes.

1. 1 word = 4 bytes
If we have a 64-bit processor, then the processor reads 8 bytes at a time, which means
that 1 word is equal to 8 bytes.

ADVERT ISEMENT
ADVERT ISEMENT

1. 1 word = 8 bytes

Therefore, we can say that a 32-bit processor is capable of accessing 4 bytes at a time,
whereas a 64-bit processor is capable of accessing 8 bytes at a time. It depends upon the
architecture that what would be the size of the word.

Why structure padding?

1. struct student
2. {
3. char a; // 1 byte
4. char b; // 1 byte
5. int c; // 4 bytes
6. }

If we have a 32-bit processor (4 bytes at a time), then the pictorial representation of the
memory for the above structure would be:

As we know that structure occupies the contiguous block of memory as shown in the
above diagram, i.e., 1 byte for char a, 1 byte for char b, and 4 bytes for int c, then what
problem do we face in this case.

What's the problem?

The 4-bytes can be accessed at a time as we are considering the 32-bit architecture. The
problem is that in one CPU cycle, one byte of char a, one byte of char b, and 2 bytes
of int c can be accessed. We will not face any problem while accessing the char
a and char b as both the variables can be accessed in one CPU cycle, but we will face the
problem when we access the int c variable as 2 CPU cycles are required to access the
value of the 'c' variable. In the first CPU cycle, the first two bytes are accessed, and in the
second cycle, the other two bytes are accessed.
Suppose we do not want to access the 'a' and 'b' variable, we only want to access the
variable 'c', which requires two cycles. The variable 'c' is of 4 bytes, so it can be accessed
in one cycle also, but in this scenario, it is utilizing 2 cycles. This is an unnecessary wastage
of CPU cycles. Due to this reason, the structure padding concept was introduced to save
the number of CPU cycles. The structure padding is done automatically by the compiler.
Now, we will see how structure padding is done.

How is structure padding done?

In order to achieve the structure padding, an empty row is created on the left, as shown
in the above diagram, and the two bytes which are occupied by the 'c' variable on the left
are shifted to the right. So, all the four bytes of 'c' variable are on the right. Now, the 'c'
variable can be accessed in a single CPU cycle. After structure padding, the total memory
occupied by the structure is 8 bytes (1 byte+1 byte+2 bytes+4 bytes), which is greater
than the previous one. Although the memory is wasted in this case, the variable can be
accessed within a single cycle.

Let's create a simple program of structures.

1. #include <stdio.h>
2. struct student
3. {
4. char a;
5. char b;
6. int c;
7. };
8. int main()
9. {
10. struct student stud1; // variable declaration of the student type..
11. // Displaying the size of the structure student.
12. printf("The size of the student structure is %d", sizeof(stud1));
13. return 0;
14. }
In the above code, we have created a structure named 'student'. Inside
the main() method, we declare a variable of student type, i.e., stud1, and then we
calculate the size of the student by using the sizeof() operator. The output would be 8
bytes due to the concept of structure padding, which we have already discussed in the
above.

Output

Changing order of the variables


Now, we will see what happens when we change the order of the variables, does it affect
the output of the program. Let's consider the same program.

ADVERT ISEMENT
ADVERT ISEMENT

1. #include <stdio.h>
2. struct student
3. {
4. char a;
5. int b;
6. char c;
7. };
8. int main()
9. {
10. struct student stud1; // variable declaration of the student type..
11. // Displaying the size of the structure student.
12. printf("The size of the student structure is %d", sizeof(stud1));
13. return 0;
14. }
The above code is similar to the previous code; the only thing we change is the order of
the variables inside the structure student. Due to the change in the order, the output
would be different in both the cases. In the previous case, the output was 8 bytes, but in
this case, the output is 12 bytes, as we can observe in the below screenshot.

Output

ADVERTISEMENT
ADVERTISEMENT

Now, we need to understand "why the output is different in this case".

ADVERTISEMENT
ADVERTISEMENT

o First, memory is allocated to the char a variable, i.e., 1 byte.

o Now, the memory will be allocated to the int b Since the int variable occupies 4
bytes, but on the left, only 3 bytes are available. The empty row will be created on
these 3 bytes, and the int variable would occupy the other 4 bytes so that the
integer variable can be accessed in a single CPU cycle.

o Now, the memory will be given to the char c At a time, CPU can access 1 word,
which is equal to 4 bytes, so CPU will use 4 bytes to access a 'c' variable. Therefore,
the total memory required is 12 bytes (4 bytes +4 bytes +4 bytes), i.e., 4 bytes
required to access char a variable, 4 bytes required to access int b variable, and
other 4 bytes required to access a single character of 'c' variable.

How to avoid the structure padding in C?


The structural padding is an in-built process that is automatically done by the compiler.
Sometimes it required to avoid the structure padding in C as it makes the size of the
structure greater than the size of the structure members.

We can avoid the structure padding in C in two ways:

o Using #pragma pack(1) directive


o Using attribute
Using #pragma pack(1) directive

1. #include <stdio.h>
2. #pragma pack(1)
3. struct base
4. {
5. int a;
6. char b;
7. double c;
8. };
9. int main()
10. {
11. struct base var; // variable declaration of type base
12. // Displaying the size of the structure base
13. printf("The size of the var is : %d", sizeof(var));
14. return 0;
15. }

In the above code, we have used the #pragma pack(1) directive to avoid the structure
padding. If we do not use this directive, then the output of the above program would be
16 bytes. But the actual size of the structure members is 13 bytes, so 3 bytes are wasted.
To avoid the wastage of memory, we use the #pragma pack(1) directive to provide the
1-byte packaging.

Output

o By using attribute

1. #include <stdio.h>
2.
3. struct base
4. {
5. int a;
6. char b;
7. double c;
8. }__attribute__((packed)); ;
9. int main()
10. {
11. struct base var; // variable declaration of type base
12. // Displaying the size of the structure base
13. printf("The size of the var is : %d", sizeof(var));
14.
15. return 0;
16. }
ADVERTISEMENT
ADVERTISEMENT

Output

Next Topic C Union

← PrevNext →

ADVERTISEMENT

Union in C
Union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also be
defined as many members, but only one member can contain a value at a particular point
in time.
Union is a user-defined data type, but unlike structures, they share the same memory
location.

Let's understand this through an example.

1. struct abc
2. {
3. int a;
4. char b;
5. }

The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we found
that their addresses are different. Therefore, we conclude that the members in the
structure do not share the same memory location.

When we define the union, then we found that union is defined in the same way as the
structure is defined but the difference is that union keyword is used for defining the union
data type, whereas the struct keyword is used for defining the structure. The union
contains the data members, i.e., 'a' and 'b', when we check the addresses of both the
variables then we found that both have the same addresses. It means that the union
members share the same memory location.

Let's have a look at the pictorial representation of the memory allocation.

The below figure shows the pictorial representation of the structure. The structure has
two members; i.e., one is of integer type, and the another one is of character type. Since
1 block is equal to 1 byte; therefore, 'a' variable will be allocated 4 blocks of memory while
'b' variable will be allocated 1 block of memory.

The below figure shows the pictorial representation of union members. Both the variables
are sharing the same memory location and having the same initial address.

In union, members will share the memory location. If we try to make changes in any of
the member then it will be reflected to the other member as well. Let's understand this
concept through an example.

1. union abc
2. {
3. int a;
4. char b;
5. }var;
6. int main()
7. {
8. var.a = 66;
9. printf("\n a = %d", var.a);
10. printf("\n b = %d", var.b);
11. }

In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union
abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on
the screen. Since both 'a' and 'b' share the memory location, var.b will print 'B' (ascii code
of 66).

ADVERT ISEMENT
ADVERT ISEMENT

Deciding the size of the union


The size of the union is based on the size of the largest member of the union.

Let's understand through an example.

1. union abc{
2. int a;
3. char b;
4. float c;
5. double d;
6. };
7. int main()
8. {
9. printf("Size of union abc is %d", sizeof(union abc));
10. return 0;
11. }
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the
size of double is 8 bytes. Since the double variable occupies the largest memory among
all the four variables, so total 8 bytes will be allocated in the memory. Therefore, the
output of the above program would be 8 bytes.

Accessing members of union using pointers


We can access the members of the union through pointers by using the (->) arrow
operator.

Let's understand through an example.

1. #include <stdio.h>
2. union abc
3. {
4. int a;
5. char b;
6. };
7. int main()
8. {
9. union abc *ptr; // pointer variable declaration
10. union abc var;
11. var.a= 90;
12. ptr = &var;
13. printf("The value of a is : %d", ptr->a);
14. return 0;
15. }

In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of
var variable. Now, ptr can access the variable 'a' by using the (->) operator. Hence the
output of the above code would be 90.

Why do we need C unions?


Consider one example to understand the need for C unions. Let's consider a store that
has two items:

ADVERT ISEMENT
ADVERT ISEMENT

ADVERTISEMENT
ADVERTISEMENT

o Books
o Shirts

Store owners want to store the records of the above-mentioned two items along with the
relevant information. For example, Books include Title, Author, no of pages, price, and
Shirts include Color, design, size, and price. The 'price' property is common in both items.
The Store owner wants to store the properties, then how he/she will store the records.

Initially, they decided to store the records in a structure as shown below:

1. struct store
2. {
3. double price;
4. char *title;
5. char *author;
6. int number_pages;
7. int color;
8. int size;
9. char *design;
10. };

The above structure consists of all the items that store owner wants to store. The above
structure is completely usable but the price is common property in both the items and
the rest of the items are individual. The properties like price, *title, *author, and
number_pages belong to Books while color, size, *design belongs to Shirt.

ADVERT ISEMENT
ADVERT ISEMENT

Let's see how can we access the members of the structure.

1. int main()
2. {
3. struct store book;
4. book.title = "C programming";
5. book.author = "Paulo Cohelo";
6. book.number_pages = 190;
7. book.price = 205;
8. printf("Size is : %ld bytes", sizeof(book));
9. return 0;
10. }

In the above code, we have created a variable of type store. We have assigned the values
to the variables, title, author, number_pages, price but the book variable does not possess
the properties such as size, color, and design. Hence, it's a wastage of memory. The size
of the above structure would be 44 bytes.

ADVERTISEMENT
ADVERTISEMENT

We can save lots of space if we use unions.

1. #include <stdio.h>
2. struct store
3. {
4. double price;
5. union
6. {
7. struct{
8. char *title;
9. char *author;
10. int number_pages;
11. } book;
12.
13. struct {
14. int color;
15. int size;
16. char *design;
17. } shirt;
18. }item;
19. };
20. int main()
21. {
22. struct store s;
23. s.item.book.title = "C programming";
24. s.item.book.author = "John";
25. s.item.book.number_pages = 189;
26. printf("Size is %ld", sizeof(s));
27. return 0;
28. }

In the above code, we have created a variable of type store. Since we used the unions in
the above code, so the largest memory occupied by the variable would be considered for
the memory allocation. The output of the above program is 32 bytes. In the case of
structures, we obtained 44 bytes, while in the case of unions, the size obtained is 44 bytes.
Hence, 44 bytes is greater than 32 bytes saving lots of memory space.

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.

ADVERTISEMENT
ADVERTISEMENT

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.ext".
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. void 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. }

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:

ADVERT ISEMENT
ADVERT ISEMENT

1. int fclose( FILE *fp );

C fprintf() and fscanf()


C fprintf() and fscanf() example

C fputc() and fgetc()


C fputc() and fgetc() example

C fputs() and fgets()


C fputs() and fgets() example

C fseek()
C fseek() example

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:

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

Example:

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

ADVERT ISEMENT
ADVERT ISEMENT

emp.txt

Id= 1
Name= sonoo
Salary= 120000

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.

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. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }

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

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

Understanding the fseek() Parameters:


Let's understand the input parameters for the fseek() function is essential for complete
use:

File*: The FILE *stream argument is a reference to the file's associated FILE structure. By
utilizing the fopen() method, it is acquired.

Long int offset: The offset parameter specifies how many bytes will relocated to the
whence parameter's location. It may be zero, positive, or negative.

Whence is an integer that indicates the reference place from which the offset is
determined. Any one of the following three constants may be used:

SEEK_SET: It establishes the offset with respect to the file's start.

ADVERT ISEMENT

SEEK_CUR: It modifies the file pointer's offset to its current location.

SEEK_END: It establishes the offset with respect to the file's end.

Detailed Understanding of the fseek() Function


The three main tasks of the fseek() function are used to move the file pointer, write data
to the specified place, and update the file position indication.

The file pointer is being moved: You can shift the file pointer to a specified area of the
file using the fseek() method. You can change the reference point for the offset by
altering the 'whence' parameter to one of the values SEEK_SET, SEEK_CUR,
or SEEK_END.

Putting Data in the Right Place: Using operations like fprintf(), fputs(), fwrite(), etc.,
you may write data after shifting the file reference to the correct spot. The data will be
written beginning at the file pointer's new location.

A file position indicator update: The fseek() method automatically updates the file
position indication to reflect the changed location of the file pointer. By doing this, you
may be confident that the file will always be operated on from the right angle.
Regular Use Cases of fseek()
There are several regular use cases of fseek() function. Some use cases are as follows:

Random Access: The fseek() function allows you random access to a file, enabling you
to read or write data at any point you want inside the file. It is especially beneficial for
huge files or databases when sequential data access is not the most effective method.

Modifying Existing Data: Without rewriting the whole file, fseek() lets you edit data at
specified locations inside a file. You can replace or insert new data while keeping the
present contents by shifting the file pointer to the appropriate spot.

Data Appending: You may relocate the file pointer to the end of the file and add
additional data by using the fseek() function with the SEEK_END constant. It is quite
helpful when working with log files or adding entries to an existing file.

Reading Specific Portions: You can read only the information you need by using
the fseek() function to move to a specific location inside a file. Working with huge files
or structured data can improve file reading procedures.

Metadata updating: In some circumstances, metadata may be present in places in files.


You may access these metadata sections using fseek() and make the necessary changes.
It is typical when working with file formats that include headers or other descriptive
information.

Support for huge Files: The fseek() function is compatible with huge files when given
a file offset of type long int. You may now work with files that are larger than what is
allowed by standard file operations.

Considerations for Performance: Although fseek() function offers flexibility, frequent


use of random-access operations can have an adverse effect on speed, particularly with
big files. Consider the trade-off between convenience and performance when considering
whether to use fseek() for file manipulation.

Here are several examples of how to use the C fseek() function and their accompanying
results:

Example 1:
Consider the following text in a file called "data.txt":
1. Line 1
2. Line 2
3. Line 3
4. Line 4
5. Line 5

Code:

1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.txt", "r");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. char line[100];
11. fseek(file, 4, SEEK_SET); // Move to the beginning of the fourth line
12. fgets(line, sizeof(line), file);
13. printf("Fourth line: %s", line);
14.
15. fclose(file);
16. return 0;
17. }

Output:

Fourth line: Line 4

Example 2:
Let's say we have a binary file called "data.bin" that contains the following information:

1. 1 2 3 4 5
Code:

1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.bin", "r+b");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. int value = 10;
11. fseek(file, 3 * sizeof(int), SEEK_SET); // Move to the fourth integer (zero-based index)
12. fwrite(&value, sizeof(int), 1, file);
13.
14. fclose(file);
15. return 0;
16. }

Output:

File contents after writing: 1 2 3 10 5

Example 3:
Consider the following text in a file called "log.txt":

1. Log entry 1
2. Log entry 2

Code:

1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("log.txt", "a");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. fseek(file, 0, SEEK_END); // Move to the end of the file
11. fputs("\nLog entry 3", file);
12.
13. fclose(file);
14. return 0;
15. }

Output:

Log entry 1
Log entry 2
Log entry 3

Example 4:

1. #include <stdio.h>
2. int main() {
3. FILE *file = fopen("data.txt", "r");
4. if (file == NULL) {
5. printf("Unable to open the file.\n");
6. return 1;
7. }
8.
9. fseek(file, 0, SEEK_END); // Move to the end of the file
10. long size = ftell(file); // Get the file size
11. printf("File size: %ld bytes\n", size);
12.
13. fclose(file);
14. return 0;
15. }
Output:

File size: 28 bytes

The fseek() function in the C language allows programmers to set the file pointer to a
given offset inside a file, making it an essential tool for file manipulation. Developers
may perform various tasks, including random access, adding data, editing existing
material, and reading particular file sections, skillfully utilizing the fseek() function.

For fseek() to operate properly, it is crucial to comprehend its syntax, which comprises
the FILE pointer, offset, and whence arguments. The reference location from which the
offset is computed is determined by the three variables SEEK_SET, SEEK_CUR,
and SEEK_END, enabling precise control over the movement of the file pointer.

Programmers may manage big files, access data structures in binary files, and modify
metadata sections with the help of fseek(). Additionally, the function has error-handling
features that make it possible to identify and fix problems like looking outside of file
boundaries or using closed files.

When using fseek(), it's crucial to consider the compromise between ease and speed.
Performance can be impacted by excessive random-access operations, especially when
dealing with big files. Therefore, it is essential to analyze how to optimize file handling
and reduce pointless carefully seeks.

Developers may improve their ability to manipulate files by understanding the fseek()
method, which will make their programs more effective, adaptable, and resilient.
Programmers can easily handle sophisticated file operations due to fseek(), which
enables file navigation, data modification, and content adding.

fseek() is a useful tool for manipulating file pointers and accessing data at precise points
in the world of file management in C. By embracing and comprehending the potential of
fseek(), developers may handle files with a new degree of precision and control, resulting
in more complex and useful programs.

ADVERT ISEMENT

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. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }

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

ADVERT ISEMENT

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

Output:
Size of file: 21 bytes

Explanation:

Using fseek(fp, 0, SEEK_END), the program accesses the file "file.txt" in read mode and
advances the file pointer to the end. Using ftell(fp), it obtains the file location, which
represents the file size. Finally, the program uses the printf() function to output the file's
size in bytes. The result shows that "file.txt" has 21 bytes in it. You should take note of
the program's use of uncommon functions like clrscr() and getch().

Knowing the file's position and size is crucial for various tasks when working with files in
C programming. As the preceding example shows, the ftell() function is essential in
giving this information. Let's look more closely at some additional crucial file operations
and ideas since file management encompasses more than simply determining the file size.

Modes for Opening Files: In the example, we opened the file in "r" mode. This mode
indicates read-only access. Additional access modes are available, including "w" for
writing (creates a new file or overwrites an existing one), "a" for append (writes at the end
of the file), "rb" for binary read, "wb" for binary write, etc. It is essential to comprehend
and use the proper file modes to guarantee that the correct file actions are carried out.

Error Handling: It's critical to manage potential failures when working with file operations
properly. If the fopen() method cannot open the file, it returns NULL. Therefore, looking
at the return value and responding appropriately is crucial if the file opening doesn't
succeed. Error management helps you find and fix possible problems and prevent
program crashes.

ADVERT ISEMENT
ADVERT ISEMENT

File Reading and Writing: Although the function ftell() is generally used to determine
the size of a file, file handling frequently includes reading data from and writing data to
files. For these uses, C has several methods, including fread(), fwrite(), fgets(), and
fputs(). You may efficiently modify the content of files by becoming familiar with and
using these functions.

File Seeking: The fseek() function is used in conjunction with ftell() to adjust the file
position indication to a particular point inside the file. It is helpful when you want to read
or write data from a specific location in the file. You can traverse a file and perform the
necessary operations with the fseek() function.
Text vs. Binary Mode: Both binary mode and text mode are available for opening files.
While text mode is used for text files, binary mode is appropriate for non-text files.
Different platforms (such as Windows and Unix-like systems) may treat newline
characters differently when opening a file in text mode. In binary mode, there are no such
transformations and data is read, and written just as it is.

Conclusion:
In conclusion, the C ftell() method is a helpful resource for locating the current file
location and retrieving the file size. Programmers may easily search through files and do
actions by combining them with the fseek() function. Successful file handling in C
depends on the understanding and use of file opening modes, error management, and
many file-related functions. Furthermore, understanding the differences between binary
and text modes guarantees precise data handling. C programmers who are skilled in file
handling can read, write, and modify files efficiently, enabling the creation of various
programs with exact file operations.

C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.


All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.

ADVERT ISEMENT
ADVERT ISEMENT

o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
What is Macro
Please visit next page.

C Macros
C macros provide a potent method for code reuse and simplification. They let
programmers construct symbolic names or phrases that are changed to certain values
before the compilation process begins. The use of more macros makes code easier
to comprehend, maintain, and makes mistakes less likely. In this article, we'll delve
deeper into the concept of C macros and cover their advantages, ideal usage scenarios,
and potential hazards.

A macro is a segment of code which is replaced by the value of macro. Macro is defined
by #define directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros

Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to
represent numeric constants. For example:

1. #define PI 3.14

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros
The function-like macro looks like function call. For example:

1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.

No. Macro Description

1 _DATE_ represents current date in "MMM DD YYYY" format.

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line number.

5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example


File: simple.c

1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }

Output:

ADVERT ISEMENT
ADVERT ISEMENT

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
ADVERTISEMENT
Advantages of Using Macros:
There are various advantages of Macros in C. Some main advantages of C macros are as
follows:

Code reuse: By allowing developers to declare a piece of code just once and use it several
times, macros help to promote modular programming and minimize code duplication.

Code abbreviation: Macros make it possible to write clear, expressive code that is
simpler to read and comprehend the intentions of the programmer.

Performance Optimization: By minimizing function call overhead, macros may be


utilized to optimize code execution. For instance, it is possible to inline brief pieces of
code using function-like macros.

Using macros, conditional compilation enables distinct sections of the code to


be included or removed based on predetermined circumstances.
Debugging or platform-specific code both benefit from this functionality.

When Using Macros, Exercise Caution:


Use caution while constructing function-like macros in brackets. Always use brackets to
contain parameters and the full macro body to avoid unexpected outcomes brought on
by operator precedence.

Macro Side consequences: Steer clear of macros with negative consequences.


Multiple evaluations of macro arguments may result in surprising results since macros
are directly substituted.

ADVERT ISEMENT
ADVERT ISEMENT

Use capital letters to distinguish macro names from standard C identifiers and to make
the code easier to understand.

ADVERTISEMENT

Macros' best practices:


There are various practices of C macros. Some of them are as follows:
For object-like macros, use constants: If possible, use object-like macros for constants
to make the code more readable and make any necessary adjustments simpler.

ADVERT ISEMENT
ADVERT ISEMENT

Macros with Functions for Basic Operations: Use macros that resemble functions for
straightforward, one-line operations. Use normal functions in their place for more
intricate processes.

Use Predefined Macros Wisely: While predefined macros like __DATE__, __TIME__, and
__FILE__ are useful for debugging and logging, don't rely on them for essential functions.

ADVERTISEMENT

Macros and Conditional Compilation:


ADVERTISEMENT
ADVERTISEMENT

When conditional compilation is used, macros significantly contribute utilizing


the #ifdef, #ifndef, #else, and #endif directives. It gives the compiler the ability to
include or reject code blocks depending on precise criteria.

Using Inline Functions vs. Macros:


Inline functions offer comparable advantages to macros while avoiding some of the
possible drawbacks of macros. Macros can enhance speed since they directly replace
code. Modern compilers may frequently inline appropriate functions, making them a safer
option in many circumstances.

Using macros for debugging:


As shown in the example above, macros can be helpful in debugging by supplying extra
details like file names, line numbers, and timestamps.

Conclusion:
As a result, C macros are a crucial component of the C programming language and give
programmers a strong tool for code reuse and optimization. Object-like macros act
as symbolic constants and improve code readability by giving numerical values names
that make sense. The cost of function calls has decreased, and efficiency is increased
through function-like macros, which operate as in lined code snippets.

Code reuse, code simplification, and conditional compilation are a few advantages of
using macros in C. Programmers can build modular code structures and streamline
complicated procedures by designing macros. Additionally, conditional
compilation facilitates platform-specific functions and debugging by enabling
developers to include or remove code blocks based on certain criteria.

C #include
The #include preprocessor directive is used to paste code of given file into current file. It
is used include system-defined and user-defined header files. If included file is not found,
compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to


look for the header files. There are two variants to use #include directive.

1. #include <filename>
2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system
header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where
program is running.

#include directive example


Let's see a simple example of #include directive. In this program, we are including stdio.h
file because printf() function is defined in this file.

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

Hello C

#include notes:
Note 1: In #include directive, comments are not recognized. So in case of #include
<a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence.
So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define
The C programming language's #define preprocessor directive provides a strong and
flexible tool for declaring constants and producing macros. It conducts textual
replacement before actual compilation during the pre-processing phase of C programs,
where it plays a significant role. By using this functionality, developers may improve their
code's readability, maintainability, and effectiveness.

Developers may give meaningful names to fixed values when declaring constants
using #define, which makes the code easier to understand and maintain. Programmers
can avoid hard coding values throughout the code by using constants, which reduces
errors and ensures consistency.

Additionally, #define makes it possible to create macros, which serve as code blocks. As
they substitute function calls and sometimes provide more control over program
behavior, macros aid in constructing short, effective lines of code. However, macros must
be used carefully since they are directly substituted in the code and, if incorrectly
specified, might have unexpected outcomes.

The #define preprocessor directive is used to define constant or micro substitution. It can
use any basic data type.

Syntax:

1. #define token value


Let's see an example of #define to define a constant.

1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }

Output:

3.140000

Explanation:

In this example, we define a constant PI with a value of 3.14. After that, the printf()
function uses the PI constant to display the value. This program's output after
compilation and execution is as follows:

Let's see an example of #define to create a macro.

1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }

Output:

ADVERT ISEMENT
ADVERT ISEMENT

Minimum between 10 and 20 is: 10

Explanation:

In this example, we develop a MIN macro that accepts the two inputs a and b. The
macro's definition returns the lowest value between the two inputs. The preprocessor
replaces the MIN macro with the actual code implementation when it is used with
the inputs (10, 20), resulting in ((10) (20)? (10): (20)). It is equal to 10, which shows in
the output.
Uses:
There are several uses of #define preproceesor directive in C. Some of the uses are as
follows:

Constant Definition: The #define is widely used in C programs to declare constants.


Developers can improve the readability and maintainability of their code by giving fixed
values names that make sense.

Making macros: Making macros enables programmers to define code snippets that
may be used repeatedly throughout the program. By minimizing function calls and
minimizing code duplication, this feature facilitates the construction of more effective
and concise code.

Conditional Compilation: The directives #ifdef, #ifndef, #if, and #elif are frequently
used in combination with the directive #define. It gives developers the ability to include
or omit code blocks depending on predetermined criteria.

Configuration management: The #define can be used in big software projects to


control configuration settings and switch between them quickly during development or
deployment.

ADVERT ISEMENT
ADVERT ISEMENT

Feature Toggles: In the code, you may toggle individual features or functions by using
the #define statement. Developers can activate or disable sections of the codebase by
declaring or undefining symbols.

Debugging and logging: The #define is used to activate or disable debugging


statements or logging messages throughout the software. It aids
in finding and fixing problems throughout the development and testing phases.

Math and Scientific Constants: Mathematical constants like PI, E, and other numbers
may be declared using #define, making their use in computations simple and reliable.

ADVERT ISEMENT
ADVERT ISEMENT

Conclusion:
In conclusion, the C #define preprocessor directive is a flexible and effective tool that
programmers may use to declare constants, build macros, and control code settings. C
programmers may improve code readability, maintainability, and efficiency by giving
constants meaningful names and creating reusable code blocks using macros.
Customizing code behavior for various contexts is made easier by #define's conditional
compilation capabilities and feature toggles. When utilizing macros, care must be taken
to avoid potential problems and undesirable outcomes. Overall, #define is very important
to the C programming language and helps it become popular and widely used in a variety
of software development projects.

C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by
#define.

Syntax:

1. #undef token

Let's see a simple example to define and undefine a constant.

1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so
that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before
being undefined, it was used by square variable.

1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }

Output:

225

C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes
the code otherwise #else code is executed, if present.

Syntax:

1. #ifdef MACRO
2. //code
3. #endif

Syntax with #else:

1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif

C #ifdef example
Let's see a simple example to use #ifdef preprocessor directive.

ADVERT ISEMENT
1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:

Enter a:5
Value of a: 5

C #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.

Syntax:

1. #ifndef MACRO
2. //code
3. #endif

Syntax with #else:

1. #ifndef MACRO
2. //successful code
3. #else
4. //else code
5. #endif

C #ifndef example
Let's see a simple example to use #ifndef preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define INPUT
4. void main() {
5. int a=0;
6. #ifndef INPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifndef INPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11. printf("Value of a: %d\n", a);
12. getch();
13. }

Output:

Value of a: 2

C #if
The #if preprocessor directive evaluates the expression or condition. If condition is true,
it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:
1. #if expression
2. //code
3. #endif

Syntax with #else:

1. #if expression
2. //if code
3. #else
4. //else code
5. #endif

Syntax with #elif and #else:

1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif

C #if example
Let's see a simple example to use #if preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 0
4. void main() {
5. #if (NUMBER==0)
6. printf("Value of Number is: %d",NUMBER);
7. #endif
8. getch();
9. }
Output:

Value of Number is: 0

Let's see another example to understand the #if directive clearly.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. clrscr();
6. #if (NUMBER==0)
7. printf("1 Value of Number is: %d",NUMBER);
8. #endif
9.
10. #if (NUMBER==1)
11. printf("2 Value of Number is: %d",NUMBER);
12. #endif
13. getch();
14. }

Output:

2 Value of Number is: 1

C #else
The #else preprocessor directive evaluates the expression or condition if condition of #if
is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

1. #if expression
2. //if code
3. #else
4. //else code
5. #endif

Syntax with #elif:

1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif

C #else example
Let's see a simple example to use #else preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. #if NUMBER==0
6. printf("Value of Number is: %d",NUMBER);
7. #else
8. print("Value of Number is non-zero");
9. #endif
10. getch();
11. }

Output:

Value of Number is non-zero

C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
C #error example
Let's see a simple example to use #error preprocessor directive.

1. #include<stdio.h>
2. #ifndef __MATH_H
3. #error First include then compile
4. #else
5. void main(){
6. float a;
7. a=sqrt(7);
8. printf("%f",a);
9. }
10. #endif

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

1. #include<stdio.h>
2. #include<math.h>
3. #ifndef __MATH_H
4. #error First include then compile
5. #else
6. void main(){
7. float a;
8. a=sqrt(7);
9. printf("%f",a);
10. }
11. #endif

Output:

2.645751
C #pragma
The #pragma preprocessor directive is used to provide additional information to the
compiler. The #pragma directive is used by the compiler to offer machine or operating -
system feature.

Syntax:

1. #pragma token

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

1. #pragma argsused
2. #pragma exit
3. #pragma hdrfile
4. #pragma hdrstop
5. #pragma inline
6. #pragma option
7. #pragma saveregs
8. #pragma startup
9. #pragma warn

Let's see a simple example to use #pragma preprocessor directive.

1. #include<stdio.h>
2. #include<conio.h>
3.
4. void func() ;
5.
6. #pragma startup func
7. #pragma exit func
8.
9. void main(){
10. printf("\nI am in main");
11. getch();
12. }
13.
14. void func(){
15. printf("\nI am in func");
16. getch();
17. }

Output:

I am in func
I am in main
I am in func

Command Line Arguments in C


The arguments passed from command line are called command line arguments. These
arguments are handled by main() function.

To support command line argument, you need to change the structure of main() function
as given below.

1. int main(int argc, char *argv[] )

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name
always.

Example
Let's see the example of command line arguments where we are passing one argument
with file name.

1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }

Run this program as follows in Linux:

1. ./program hello

Run this program as follows in Windows from command line:

1. program.exe hello

Output:

Program name is: program


First argument is: hello

If you pass many arguments, it will print only one.

1. ./program hello c how r u

Output:

ADVERT ISEMENT
ADVERT ISEMENT

Program name is: program


First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.

1. ./program "hello c how r u"

Output:

Program name is: program


First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing
only argv[1], that is why it is printing only one argument.

C Expressions
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array
element or a constant.

Let's see an example:

1. a-b;

In the above expression, minus character (-) is an operator, and a, and b are the two
operands.

There are four types of expressions exist in C:

ADVERTISEMENT

o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.

For example:

1. x = 9/2 + a-b;

The entire above line is a statement, not an expression. The portion after the equal is an
expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic
operators. An arithmetic expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer
expression when it contains only real operands, it is known as pure real expression, and
when it contains both integral and real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence
and associativity of operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

o When both the operands are of type integer, then arithmetic will be performed,
and the result of the operation would be an integer value. For example, 3/2 will
yield 1 not 1.5 as the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and
the result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0,
not 1.
o If one operand is of type integer and another operand is of type real, then the
mixed arithmetic will be performed. In this case, the first operand is converted into
a real operand, and then arithmetic is performed to produce the real value. For
example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then
arithmetic is performed to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string
value.
o The result of the relational expression can be either zero or non-zero value. Here,
the zero value is equivalent to a false and non-zero value is equivalent to true.
Relational Description
Expression

x%2 = = 0 This condition is used to check whether the x is an even number or not. Th
relational expression results in value 1 if x is an even number otherwise results i
value 0.

a!=b It is used to check whether a is not equal to b. This relational expression results i
1 if a is not equal to b otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression "x+y".

a>=9 It is used to check whether the value of a is greater than or equal to 9.

Let's see a simple example:

1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }

Output
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.

Let's see some example of the logical expressions.

ADVERT ISEMENT

Logical Description
Expressions

( x > 4 ) && ( x < 6 It is a test condition to check whether the x is greater than 4 and x is less than
) The result of the condition is true only when both the conditions are true.

x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 1
The result of the test condition is true if either of the conditions holds true value

! ( x > 10 ) && ( y It is a test condition used to check whether x is not greater than 10 and y is equ
==2) to 2. The result of the condition is true if both the conditions are true.

Let's see a simple program of "&&" operator.

1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }

Output

Let's see a simple example of "| |" operator

ADVERT ISEMENT

1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }

Output

Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true
otherwise 0.
o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

ADVERTISEMENT

Suppose exp1, exp2 and exp3 are three expressions.

exp1 ? exp2 : exp3

The above expression is a conditional expression which is evaluated on the basis of the
value of the exp1 expression. If the condition of the expression exp1 holds true, then the
final conditional expression is represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }

Output

Data Segments
To understand the way our C program works, we need to understand the arrangement of
the memory assigned to our program.

All the variables, functions, and data structures are allocated memory into a special
memory segment known as Data Segment. The data segment is mainly divided into four
different parts which are specifically allocated to different types of data defined in our C
program.
The parts of Data segments are :

1. Data Area
It is the permanent memory area. All static and external variables are stored in the data
area. The variables which are stored in the data area exist until the program exits.

2. Code Area
It is the memory area which can only be accessed by the function pointers. The size of the
code area is fixed.

3. Heap Area
As we know that C supports dynamic memory allocation. C provides the functions like
malloc() and calloc() which are used to allocate the memory dynamically. Therefore, the
heap area is used to store the data structures which are created by using dynamic memory
allocation. The size of the heap area is variable and depends upon the free space in the
memory.

4. Stack Area
Stack area is divided into two parts namely: initialize and non-initialize. Initialize variables
are given priority than non-initialize variables.

1. All the automatic variables get memory into stack area.


2. Constants in c get stored in the stack area.
3. All the local variables of the default storage class get stored in the stack area.
4. Function parameters and return value get stored in the stack area.
5. Stack area is the temporary memory area as the variables stored in the stack area
are deleted whenever the program reaches out of scope.
Flow of C Program
The C program follows many steps in execution. To understand the flow of C program
well, let us see a simple program first.

File: simple.c

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

C Programs
C programs are frequently asked in the interview. These programs can be asked from
basics, array, string, pointer, linked list, file handling etc. Let's see the list of c programs.

1) Fibonacci Series

Write a c program to print fibonacci series without using recursion and using recursion.

Input: 10

Output: 0 1 1 2 3 5 8 13 21 34

Backward Skip 10sPlay VideoForward Skip 10s

2) Prime number

Write a c program to check prime number.

Input: 44

Output: not prime number

Input: 7
Output: prime number

3) Palindrome number

Write a c program to check palindrome number.

Input: 329

Output: not palindrome number

Input: 12321

Output: palindrome number

4) Factorial

Write a c program to print factorial of a number.

Input: 5

Output: 120

Input: 6

Output: 720

5) Armstrong number

Write a c program to check armstrong number.

Input: 153

Output: armstrong

Input: 22
Output: not armstrong

6) Sum of Digits

Write a c program to print sum of digits.

Input: 234

Output: 9

Input: 12345

Output: 15

7) Reverse Number

Write a c program to reverse given number.

Input: 123

Output: 321

8) Swap two numbers without using third variable

Write a c program to swap two numbers without using third variable.

Input: a=10 b=20

Output: a=20 b=10

9) Print "hello" without using semicolon

Write a c program to print "hello" without using semicolon


10) Assembly Program in C

Write a c program to add two numbers using assembly code.

11) C Program without main() function

Write a c program to print "Hello" without using main() function.

12) Matrix Multiplication

Write a c program to print multiplication of 2 matrices.

Input:

first matrix elements:


1 1 1
2 2 2
3 3 3
second matrix elements
1 1 1
2 2 2
3 3 3

Output:

multiplication of the matrix:


6 6 6
12 12 12
18 18 18

13) Decimal to Binary

ADVERTISEMENT

Write a c program to convert decimal number to binary.

Input: 5

Output: 101
Input: 20

Output: 10100

14) Alphabet Triangle

Write a c program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

15) Number Triangle

Write a c program to print number triangle.

Input: 7

Output:

enter the range= 6


1
121
12321
1234321
123454321
12345654321

16) Fibonacci Triangle

Write a c program to generate fibonacci triangle.

Input: 5

Output:

1
1 1
1 1 2
1 1 2 3
1 1 2 3 5

17) Number in Characters

Write a c program to convert number in characters.

Input: 5

Output: five

Input: 203

Output: two zero three

Fibonacci Series in C
Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two
numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series
are 0 and 1.

There are two ways to write the fibonacci series program:

ADVERTISEMENT

o Fibonacci Series without recursion


o Fibonacci Series using recursion

Fibonacci Series in C without recursion


Let's see the fibonacci series program in c without recursion.

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

Fibonacci Series using recursion in C


Let's see the fibonacci series program in c using recursion.

1. #include<stdio.h>
2. void printFibonacci(int n){
3. static int n1=0,n2=1,n3;
4. if(n>0){
5. n3 = n1 + n2;
6. n1 = n2;
7. n2 = n3;
8. printf("%d ",n3);
9. printFibonacci(n-1);
10. }
11. }
12. int main(){
13. int n;
14. printf("Enter the number of elements: ");
15. scanf("%d",&n);
16. printf("Fibonacci Series: ");
17. printf("%d %d ",0,1);
18. printFibonacci(n-2);//n-2 because 2 numbers are already printed
19. return 0;
20. }

Output:

Enter the number of elements:15


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

Prime Number program in C


Prime number in C: Prime number is a number that is greater than 1 and divided by 1 or
itself. In other words, prime numbers can't be divided by other numbers than itself or 1.
For example 2, 3, 5, 7, 11, 13, 17, 19, 23.... are the prime numbers.

Note: Zero (0) and 1 are not considered as prime numbers. Two (2) is the only one even
prime number because all the numbers can be divided by 2.

Let's see the prime number program in C. In this c program, we will take an input from
the user and check whether the number is prime or not.

1. #include<stdio.h>
2. int main(){
3. int n,i,m=0,flag=0;
4. printf("Enter the number to check prime:");
5. scanf("%d",&n);
6. m=n/2;
7. for(i=2;i<=m;i++)
8. {
9. if(n%i==0)
10. {
11. printf("Number is not prime");
12. flag=1;
13. break;
14. }
15. }
16. if(flag==0)
17. printf("Number is prime");
18. return 0;
19. }

Output:

Enter the number to check prime:56


Number is not prime

Enter the number to check prime:23


Number is prime

Palindrome program in C
Palindrome number in c: A palindrome number is a number that is same after reverse.
For example 121, 34543, 343, 131, 48984 are the palindrome numbers.

Palindrome number algorithm


ADVERTISEMENT
ADVERTISEMENT

o Get the number from user


o Hold the number in temporary variable
o Reverse the number
o Compare the temporary number with reversed number
o If both numbers are same, print palindrome number
o Else print not palindrome number

Let's see the palindrome program in C. In this c program, we will get an input from the
user and check whether number is palindrome or not.

1. #include<stdio.h>
2. int main()
3. {
4. int n,r,sum=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=(sum*10)+r;
12. n=n/10;
13. }
14. if(temp==sum)
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

Factorial Program in C
Factorial Program in C: Factorial of n is the product of all positive descending integers.
Factorial of n is denoted by n!. For example:

1. 5! = 5*4*3*2*1 = 120
2. 3! = 3*2*1 = 6

Here, 5! is pronounced as "5 factorial", it is also called "5 bang" or "5 shriek".

The factorial is normally used in Combinations and Permutations (mathematics).


There are many ways to write the factorial program in c language. Let's see the 2 ways to
write the factorial program.

ADVERTISEMENT

o Factorial Program using loop


o Factorial Program using recursion

Factorial Program using loop


Let's see the factorial Program using loop.

1. #include<stdio.h>
2. int main()
3. {
4. int i,fact=1,number;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. for(i=1;i<=number;i++){
8. fact=fact*i;
9. }
10. printf("Factorial of %d is: %d",number,fact);
11. return 0;
12. }

Output:

Enter a number: 5
Factorial of 5 is: 120

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

Armstrong Number in C
Before going to write the c program to check whether the number is Armstrong or not,
let's understand what is Armstrong number.

Armstrong number is a number that is equal to the sum of cubes of its digits. For example
0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

Let's try to understand why 153 is an Armstrong number.

1. 153 = (1*1*1)+(5*5*5)+(3*3*3)
2. where:
3. (1*1*1)=1
4. (5*5*5)=125
5. (3*3*3)=27
6. So:
7. 1+125+27=153

Let's try to understand why 371 is an Armstrong number.

ADVERT ISEMENT

1. 371 = (3*3*3)+(7*7*7)+(1*1*1)
2. where:
3. (3*3*3)=27
4. (7*7*7)=343
5. (1*1*1)=1
6. So:
7. 27+343+1=371

Let's see the c program to check Armstrong Number in C.

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

Output:

enter the number=153


armstrong number

enter the number=5


not armstrong number

Sum of digits program in C


C program to sum each digit: We can write the sum of digits program in c language by
the help of loop and mathematical operation only.

Sum of digits algorithm


To get sum of each digits by c program, use the following algorithm:

ADVERTISEMENT
ADVERTISEMENT

o Step 1: Get number by user


o Step 2: Get the modulus/remainder of the number
o Step 3: sum the remainder of the number
o Step 4: Divide the number by 10
o Step 5: Repeat the step 2 while number is greater than 0.

Let's see the 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. printf("Sum is=%d",sum);
14. return 0;
15. }

Output:

Enter a number:654
Sum is=15

Enter a number:123
Sum is=6

C Program to reverse number


We can reverse a number in c using loop and arithmetic operators. In this program, we
are getting number as input from the user and reversing that number. Let's see a simple
c example to reverse a given number.

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

Output:

Enter a number: 123


Reversed Number: 321

C Program to reverse number


We can reverse a number in c using loop and arithmetic operators. In this program, we
are getting number as input from the user and reversing that number. Let's see a simple
c example to reverse a given number.

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

Output:

Enter a number: 123


Reversed Number: 321
Execution Flow
Let's try to understand the flow of above program by the figure given below.

1) C program (source code) is sent to preprocessor first. The preprocessor is responsible


to convert preprocessor directives into their respective values. The preprocessor
generates an expanded source code.

ADVERTISEMENT

2) Expanded source code is sent to compiler which compiles the code and converts it into
assembly code.

3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files. Then
it is converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.

You might also like