0% found this document useful (0 votes)
15 views209 pages

DS - Unit - 1

The document provides an overview of variables and data types in the C programming language, explaining the definition, declaration, and initialization of variables. It outlines the rules for naming variables, types of variables (local, global, static, automatic, external), and basic data types (int, char, float, double) along with derived data types (arrays, pointers). The document emphasizes the importance of following naming conventions and the role of data types in determining the kind of data a variable can store.

Uploaded by

manju.patnaik136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views209 pages

DS - Unit - 1

The document provides an overview of variables and data types in the C programming language, explaining the definition, declaration, and initialization of variables. It outlines the rules for naming variables, types of variables (local, global, static, automatic, external), and basic data types (int, char, float, double) along with derived data types (arrays, pointers). The document emphasizes the importance of following naming conventions and the role of data types in determining the kind of data a variable can store.

Uploaded by

manju.patnaik136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 209

AITAM Data Structures I-I MCA (AR-24)

UNIT – 1
INTRODUCTION TO C
VARIABLES AND DATA TYPES
Variables:
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: data_type variable_name;

Here,

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)

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

int count = 0;

Here, the variable count is declared an integer and initialized with 0.

Syntax:

Let us see the syntax to declare a

variable: type variable_list;

Jayavardhanarao Sahukaru @ aitam 1


AITAM Data Structures I-I MCA (AR-24)

An example of declaring the variable is given

below: int a;
float
b;
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:

int a=20,b=30; //declaring 2 variable of integer

type float f=20.9;

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:

Allowed Characters:

Variable names include letters ( uppercase and lowercase ), digits, and underscores.
They must start with a letter (uppercase or lowercase) or an underscore.

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.

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.

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.

Spaces and Special Characters:

Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, C,


*, (, ), -, +, =, [,
], {, }, |, \, /, <, >,., ?;, ', or ").
Jayavardhanarao Sahukaru @ aitam 2
AITAM Data Structures I-I MCA (AR-24)
Underscores are the only allowed special characters in variable names.

Jayavardhanarao Sahukaru @ aitam 3


AITAM Data Structures I-I MCA (AR-24)

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:

int age;
float salary;
char _status;
double
average_score; int
studentCount;

Invalid examples of variable names:

int 1stNumber; // Starts with a digit


float my-salary; // Contains a
hyphen (-) char int; // Same as a
C keyword
int double; // Same as a C keyword
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 data_type

variable_name;

Jayavardhanarao Sahukaru @ aitam 4


AITAM Data Structures I-I MCA (AR-24)

Example of variable declaration:

include <stdio.h>
int main() {
// Variable declaration
int age;
float salary;
char initial;
return 0;
}

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:

include <stdio.h>
int main() {
// Variable definition
int age = 25;
float salary = 2500.5;
char initial = 'J';
return 0;
}

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:

include <stdio.h>
int main() {
// Variable definition and initialization
int age = 25;
float salary = 2500.5;
char initial = 'J';
// Later in the program, you can change the value of the variable
age = 30;
Jayavardhanarao Sahukaru @ aitam 5
AITAM Data Structures I-I MCA (AR-24)

salary = 3000.0;
return 0;
}
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:

 local variable
 global variable
 static variable
 automatic variable
 external variable
 Local 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.

void function1(){

int x=10;//local variable

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. int value=20;//global variable

void function1(){

int x=10;//local variable

Static Variable

A variable that is declared with the static keyword is called static variable. It retains its
value between multiple function calls.

Jayavardhanarao Sahukaru @ aitam 6


AITAM Data Structures I-I MCA (AR-24)

void function1(){

int x=10;//local variable

static int y=10;//static

variable x=x+1;

y=y+1;

printf("%d,%d",x,y);

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.

void main(){

int x=10;//local variable (also

automatic) auto int y=20;//automatic

variable

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
extern int x=10;//external variable (also global)
program1.c
include "myfile.h"
include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}

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:

 Declaring the data type.


Jayavardhanarao Sahukaru @ aitam 7
AITAM Data Structures I-I MCA (AR-24)
 Specifying the data that the variable may carry.
 Giving the variable a unique name.

Jayavardhanarao Sahukaru @ aitam 8


AITAM Data Structures I-I MCA (AR-24)

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.

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.

Jayavardhanarao Sahukaru @ aitam 9


AITAM Data Structures I-I MCA (AR-24)

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.

Jayavardhanarao Sahukaru @ aitam 10


AITAM Data Structures I-I MCA (AR-24)

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.

int age = 25;

char grade =

'A';

float temperature = 98.6;

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

Jayavardhanarao Sahukaru @ aitam 11


AITAM Data Structures I-I MCA (AR-24)
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.

Jayavardhanarao Sahukaru @ aitam 12


AITAM Data Structures I-I MCA (AR-24)

Here is an example of declaring and utilizing an array:

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

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:

include <stdio.h>
int main() {
int num = 42; // An integer variable
int *ptr; // Declares a pointer to an integer
ptr = // Assigns the address of 'num' to the pointer
// Accessing the value of 'num' using the pointer
printf("Value of num: %d\n", *ptr);
return 0;
}

Output:
Value of num: 42
Jayavardhanarao Sahukaru @ aitam 13
AITAM Data Structures I-I MCA (AR-24)

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.

 A structure's members or fields are used to refer to each variable within it.
 Any data type, including different structures, can be a member of a structure.
 A structure's members can be accessed by using the dot (.)

operator. A declaration and use of a structure is demonstrated

here:

include <stdio.h>
include <string.h>
// Define a structure representing a person
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare a variable of type struct Person
struct Person person1;
// Assign values to the structure members
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 1.8;
// Accessing the structure members
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n", person1.height);
return 0;
}

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 same
memory 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
Jayavardhanarao Sahukaru @ aitam 14
AITAM Data Structures I-I MCA (AR-24)
members of a union by using the dot (.) operator.

Jayavardhanarao Sahukaru @ aitam 15


AITAM Data Structures I-I MCA (AR-24)

Here is an example of a union being declared and used:

include <stdio.h>
// Define a union representing a numeric value
union NumericValue {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Declare a variable of type union NumericValue
union NumericValue value;
// Assign a value to the union
value.intValue = 42;
// Accessing the union members
printf("Integer Value: %d\n", value.intValue);
// Assigning a different value to the union
value.floatValue = 3.14;
// Accessing the union members
printf("Float Value: %.2f\n", value.floatValue);
return 0;
}

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:

include <stdio.h>
// Define an enumeration for days of the week
enum DaysOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
Jayavardhanarao Sahukaru @ aitam 16
AITAM Data Structures I-I MCA (AR-24)

// Declare a variable of type enum DaysOfWeek


enum DaysOfWeek today;
// Assign a value from the enumeration
today = Wednesday;
// Accessing the enumeration value
printf("Today is %d\n", today);
return 0;
}

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:

void printHello() { printf("Hello, world!\n"); }

Function Parameters:

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

Example:

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:

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.

Jayavardhanarao Sahukaru @ aitam 17


AITAM Data Structures I-I MCA (AR-24)

Here is a sample of code that shows how to utilize void in various situations:

include <stdio.h>
// Function with void return type
void printHello() {
printf("Hello, world!\n");
}
// Function with void parameter
void processInput(void) {
printf("Processing input...\n");
}
int main() {
// Calling a void function
printHello();
// Calling a function with void parameter
processInput();
// Using a void pointer
int number = 10;
void* dataPtr = &number;
printf("Value of number: %d\n", *(int*)dataPtr);
return 0;
}

Output:

Hello, world!
Processing input...
Value of number:
10

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

Jayavardhanarao Sahukaru @ aitam 18


AITAM Data Structures I-I MCA (AR-24)
the meaningful representation of related data. The void data type indicates the lack of a
particular type. It is used as a

Jayavardhanarao Sahukaru @ aitam 19


AITAM Data Structures I-I MCA (AR-24)

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.

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.

1. Arithmetic Operators
2. Relational Operators
3. Shift Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary or Conditional Operators
7. Assignment Operator
8. 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: int value=10+20*10;

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

Jayavardhanarao Sahukaru @ aitam 20


AITAM Data Structures I-I MCA (AR-24)

The precedence and associativity of C operators is given below:

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:

result = operand1 +
operand2; Example:
int a =
5; int b
= 3;
int result = a + b;
Output:
result = 8
Jayavardhanarao Sahukaru @ aitam 21
AITAM Data Structures I-I MCA (AR-24)

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

Syntax:

result = operand1 -
operand2; Example:
int a =
8; int b
= 3;
int result = a
- b; Output:
result = 5

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

Syntax:

result = operand1 *
operand2; Example:
int a =
4; int b
= 5;
int result = a
* b; Output:
result = 20

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

Syntax:

result = operand1 /
operand2; Example:
int a =
10; int b
= 2;
int result = a / b;
Output:
result = 5

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

Syntax:

result = operand1 %
operand2; Example:
int a =
10; int
Jayavardhanarao Sahukaru @ aitam 22
AITAM Data Structures I-I MCA (AR-24)
b = 3;
int result = a
% b; Output:
result = 1

Jayavardhanarao Sahukaru @ aitam 23


AITAM Data Structures I-I MCA (AR-24)

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:

result = operand1 ==
operand2; Example:
int a =
5; int b
= 5;
int result = a ==
b; Output:
result=1 (true)

Inequality Operator (!=): The inequality operator determines whether two operands are
equal or not.

Syntax:

result = operand1 !=
operand2; Example:
int a =
5; int b
= 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:

result = operand1 >


operand2; Example:
int a =
7; int b
= 4;
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:
Jayavardhanarao Sahukaru @ aitam 24
AITAM Data Structures I-I MCA (AR-24)
result = operand1 < operand2;

Jayavardhanarao Sahukaru @ aitam 25


AITAM Data Structures I-I MCA (AR-24)

Example:
int a =
2; int b
= 6;
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:

result = operand1 >=


operand2; Example:
int a =
5; int b
= 5;
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:

result = operand1 <=


operand2; Example:
int a =
3; int b
= 6;
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:

result = operand1 <<


operand2; Example:
unsigned int a = 5; // 0000 0101 in
Jayavardhanarao Sahukaru @ aitam 26
AITAM Data Structures I-I MCA (AR-24)
binary int result = a << 2;
Output:
result = 20 // 0001 0100 in binary

Jayavardhanarao Sahukaru @ aitam 27


AITAM Data Structures I-I MCA (AR-24)

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:

result = operand1 >>


operand2; Example:
unsigned int a = 20; // 0001 0100 in
binary 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 (CC): The logical AND operator returns true if both operands are
true.

Syntax:

result = operand1 CC

operand2; Example:
int a =
5; int b
= 3;
int result = (a > 3) CC (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:

result = operand1 ||
operand2; Example:
int a =
5; int b
= 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:

result = !
Jayavardhanarao Sahukaru @ aitam 28
AITAM Data Structures I-I MCA (AR-24)
operand;
Example:

int a = 5;

Jayavardhanarao Sahukaru @ aitam 29


AITAM Data Structures I-I MCA (AR-24)

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 (s): The bitwise AND operator performs a bitwise AND
operation on the corresponding bits of the operands.

Syntax:

result = operand1 C
operand2; Example:
unsigned int a = 5; // 0000 0101 in
binary unsigned int b = 3; // 0000
0011 in binary int result = a C 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:

result = operand1 |
operand2; Example:
unsigned int a = 5; // 0000 0101 in
binary unsigned int b = 3; // 0000
0011 in binary 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:

result = operand1 ^
operand2; Example:
unsigned int a = 5; // 0000 0101 in
binary unsigned int b = 3; // 0000
0011 in binary int result = a ^ b;
Output:
result = 6 // 0000 0110 in binary

Jayavardhanarao Sahukaru @ aitam 30


AITAM Data Structures I-I MCA (AR-24)

Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.

Syntax:

result = ~operand;
Example:
unsigned int a = 5; // 0000 0101 in
binary 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:

result = condition ? value1 : value2;


Example:
int a =
5; int b
= 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:

variable =
value;
Example:
int
a; 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. sizeof Operator: The sizeof operator returns the size, in bytes, of a

Jayavardhanarao Sahukaru @ aitam 31


AITAM Data Structures I-I MCA (AR-24)
variable or a data type.

Syntax:

result = sizeof(variable / data type);

Jayavardhanarao Sahukaru @ aitam 32


AITAM Data Structures I-I MCA (AR-24)

Example:
int a;
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:

makefileCopy code
result = (expression1, expression2,...,
expressionN); Example:
int a = 5, b = 3;
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:
 Calculations in fundamental mathematics are performed using the addition and
subtraction operators (+ and -).
 If the user wants to do some multiplication and division operations, utilize the
multiplication and division operators (* and /).
 The remainder of a division operation is obtained using the modulus operator (%).
 Equality and inequality operators (== and!=) are needed to compare values
and determine whether they are equal or not.
 Use the greater than and less than operators (>and <) to compare values and
determine if one value is larger than or less than
 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 <=).
 A binary number's bits are shifted to the left using the left shift operator (<<).
 A binary number's bits can be shifted to the right using the right shift operator
(>>).
 Use the logical AND operator (CC) to combine many criteria and determine if each
condition is true.
 When combining several criteria, the logical OR operator (||) is used to determine if
at least one of the conditions is true.
 The logical NOT operator (!) is used to negate a condition's value.
 When two numbers' individual bits are involved, the bitwise AND operator (C) is
utilized to accomplish the action.
 The bitwise OR operator (|) is employed when two numbers' individual bits are
involved.

Jayavardhanarao Sahukaru @ aitam 33


AITAM Data Structures I-I MCA (AR-24)

 Bitwise exclusive OR operator is performed on individual bits of two integers using


the bitwise XOR operator ().
 Use the bitwise NOT operator () to flip or invert the bits of an integer.
 Use the ternary operator (?:) to assign a value depending on a condition in a
compact form.
 A value is assigned to a variable using the simple assignment operator (=).
 The sizeof operator is used to calculate a variable's or data type's size in bytes.
 When evaluating several expressions, the comma operator (,) returns the result
of the last expression that was evaluated.

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.

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

1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. 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:

x = 9/2 + a-b;

The entire above line is a statement, not an expression. The portion after the equal is an
expression.

Jayavardhanarao Sahukaru @ aitam 34


AITAM Data Structures I-I MCA (AR-24)

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

Jayavardhanarao Sahukaru @ aitam 35


AITAM Data Structures I-I MCA (AR-24)
example. 6*2/ (2+1 * 2/3 + 6) +

8 * (8/4)

Jayavardhanarao Sahukaru @ aitam 36


AITAM Data Structures I-I MCA (AR-24)

Relational Expressions
 A relational expression is an expression used to compare two operands.
 It is a condition which is used to decide whether the action should be taken or not.
 In relational expressions, a numeric value cannot be compared with the string
value.
 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.

Let's see a simple example:

include <stdio.h>
int main()
{
int x=4; if(x
%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}

Output

Jayavardhanarao Sahukaru @ aitam 37


AITAM Data Structures I-I MCA (AR-24)

Logical Expressions
A logical expression is an expression that computes either a zero or non-zero value. It is
a complex test condition to take a decision.

Let's see some example of the logical expressions.

Let's see a simple program of "CC" operator.

include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output

Jayavardhanarao Sahukaru @ aitam 38


AITAM Data Structures I-I MCA (AR-24)

Let's see a simple example of "| |" operator

include <stdio.h>
int main()
{
int x = 4;
int y = 6;
if ( (x <6) || (y>10))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}

Output

Conditional Expressions

A conditional expression is an expression that returns 1 if the condition is true


otherwise 0. A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

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.

Jayavardhanarao Sahukaru @ aitam 39


AITAM Data Structures I-I MCA (AR-24)

Let's understand through a simple example.

include<stdio.h>
include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}

Output

Managing Input and Output


C Input
In C programming, scanf() is one of the commonly used function to take input from the
user. The scanf() function reads formatted input from the standard input such as
keyboards.

Example : Integer Input/Output

include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output

Enter an integer: 4
Number = 4
Jayavardhanarao Sahukaru @ aitam 40
AITAM Data Structures I-I MCA (AR-24)

Here, we have used %d format specifier inside the scanf() function to take int input from
the user. When the user enters an integer, it is stored in the testInteger variable.

Notice, that we have used CtestInteger inside scanf(). It is because CtestInteger gets
the address of testInteger, and the value entered by the user is stored in that address.

Example : Float and Double Input/Output

include <stdio.h>
int main()
{
float num1;
double num2;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2);
return 0;
}

Output

Enter a number: 12.523


Enter another number:
10.2 num1 =
12.523000
num2 = 10.200000
We use %f and %lf format specifier for float and double respectively.

Example: C Character I/O

include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}

Output

Enter a

character: g You

entered g
Jayavardhanarao Sahukaru @ aitam 41
AITAM Data Structures I-I MCA (AR-24)

When a character is entered by the user in the above program, the character itself is not
stored. Instead, an integer value (ASCII value) is stored.

And when we display that value using %c text format, the entered character is displayed.
If we use %d to display the character, it's ASCII value is printed.

Example: ASCII Value

include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
// When %c is used, a character is displayed
printf("You entered %c.\n",chr);
// When %d is used, ASCII value is displayed
printf("ASCII value is %d.", chr);
return 0;
}
Output

Enter a
character: g You
entered g.
ASCII value is 103.

I/O Multiple Values

Here's how you can take multiple inputs from the user and

display them. #include <stdio.h>


int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", Ca, Cb);
printf("You entered %d and %f",
a, b); return 0;
}

Output

Enter integer and then a

float: -3 3.4

You entered -3 and 3.400000

Jayavardhanarao Sahukaru @ aitam 42


AITAM Data Structures I-I MCA (AR-24)

Format Specifiers for I/O

As you can see from the above examples, we use

%d for int

%f for float

%lf for double

%c for char

Here's a list of commonly used C data types and their format specifiers.

Jayavardhanarao Sahukaru @ aitam 43


AITAM Data Structures I-I MCA (AR-24)

Decision making
Branching statements in C
The capacity to decide what to do and how to run distinct pieces of code based on
specific circumstances is essential in the realm of programming. This ability to manage
the execution flow is provided by branching statements in the C programming
language. We'll examine the different branching statements in C in this blog article,
going through their syntax, giving examples, and showcasing the results they
produce.

Branching statements are mainly categorized as follows.

 Conditional Branching Statements


 Unconditional Branching Statements

Conditional Branching Statements:


In C, conditional branching statements are used to execute code blocks based on a
condition (as needed). These branching instructions in C allow programmers to run
the code only when specific conditions are met. The various categories of conditional
branching statements in C are as follows:

1. if Statement
2. if-else Statement
3. nested if-else Statement
4. switch Statement

The if Statement:

The most fundamental branching construct in C is the "if" statement. If a given


condition is met, it permits the execution of a block of code. The "if" statement has the
following syntax:

if (condition) {

// Code to execute if condition is true

Example:

include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}

Jayavardhanarao Sahukaru @ aitam 44


AITAM Data Structures I-I MCA (AR-24)
Output:

The number is positive.

Jayavardhanarao Sahukaru @ aitam 45


AITAM Data Structures I-I MCA (AR-24)

The if-else Statement:

By offering a different block of code to run when the condition is false, the "if-else"
statement builds on the "if" statement. The "if-else" expression has the following syntax:

if (condition) {

// Code to execute if condition is true

else {

// Code to execute if condition is false

Example:

include <stdio.h>
int main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is non-positive.\n");
}
return 0;
}

Output:

The number is non-positive.

The nested if-else Statement:

You can have an "if-else" statement within another "if" or "else" block in C since it
supports the nesting of "if-else" statements. It allows for adaptability when managing
various environments. The nested "if- else" statement has the following syntax:

if (condition1) {

// Code to execute if condition1 is

true if (condition2) {

// Code to execute if condition2 is true

else {

Jayavardhanarao Sahukaru @ aitam 46


AITAM Data Structures I-I MCA (AR-24)

// Code to execute if condition2 is false

else {

// Code to execute if condition1 is false

Example:

include <stdio.h>
int main() {
int num = 0;
if (num > 0) {
printf("The number is positive.\n");
}
else if (num < 0) {
printf("The number is negative.\n");
}
else {
printf("The number is zero.\n");
}
return 0;
}

Output:

The number is zero.

The switch Statement:

Multiple actions can be taken using the "switch" statement based on the value of a
variable or expression. When managing several instances, it is especially helpful. The
"switch" statement has the following syntax:

switch

(expression) {

case constant1:

// Code to execute if expression matches

constant1 break;

case constant2:

// Code to execute if expression matches

constant2 break;
Jayavardhanarao Sahukaru @ aitam 47
AITAM Data Structures I-I MCA (AR-24)

// More cases...

default:

// Code to execute if expression doesn't match any constant

Example:

include <stdio.h>
int main() {
int day = 3;
switch (day)
{ case 1:
printf("Monday\n");
break;
case 2: printf("Tuesday\
n"); break;
case 3:
printf("Wednesday\n");
break;
case 4: printf("Thursday\
n"); break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}

Output:

Wednesday

Jayavardhanarao Sahukaru @ aitam 48


AITAM Data Structures I-I MCA (AR-24)

Unconditional Branching Statements:


C uses unconditional branching statements to alter the typical course of program
execution. These statements give programmers the freedom to jump to a specific
location in their code under any circumstance. The various categories of unconditional
branching statements in C are as follows:

1. goto Statement
2. break Statement
3. continue Statement

goto Statement:

The "goto" command enables programmers to leap directly to a designated labelled


statement within their code. It is an unconditional branching statement.

Syntax of goto Statement

in C: goto label;

...

label:

// code to be executed

The "goto" statement executes the code in the block following a jump to the "label"-
labeled statement. Any legal identifier can be used as the "label" after a colon (:).

Example:

It is an illustration of a goto

statement. #include <stdio.h>


int main() {
int num =
1;
if (num ==
1) { goto
label;
}
printf("This statement is skipped.\n");
label:
printf("The value of num is
1.\n"); return 0;
}

Output:
Jayavardhanarao Sahukaru @ aitam 49
AITAM Data Structures I-I MCA (AR-24)
The value of num is 1.

Jayavardhanarao Sahukaru @ aitam 50


AITAM Data Structures I-I MCA (AR-24)

Explanation:

In this example, the 'goto' statement switches control to the labelled statement 'label',
skipping the succeeding printf statement, when the condition num == 1 is true. Only the
line "The value of num is 1" is printed consequently

The 'break' Statement:

The "break" statement is frequently employed in switch statements as well as looping


constructions like "for", "while", and "do-while". It enables you to skip the statement
that follows the loop or switch and end the execution of the closest enclosing loop or
switch statement.

The "break" statement in C is written in the following

syntax. break;

Example:

Look at the following illustration of the 'break' statement in use within a

loop: #include <stdio.h>


int main() {
int i;
for (i = 1; i<= 5;
i++) { if (i ==
3) {
break;
}
printf("%d ", i);
}
return 0;
}

Output:

12

Explanation:

In this illustration, the 'for' loop iterates from 1 to 5. However, the 'break' statement is
encountered when i equals 3, ending the loop early. Only the numerals 1 and 2 are
printed as a result.

continue Statement

In the C programming language, the continue statement is used to go to the next


iteration of a loop while skipping the current iteration. Usually, this statement is used in
loops like for or while.

Syntax of continue statement in C is as follows:

Jayavardhanarao Sahukaru @ aitam 51


AITAM Data Structures I-I MCA (AR-24)
continue;

When a loop encounters the continue statement, the current iteration of the loop is
ended, and control is returned to the top of the loop to begin the subsequent iteration.

Jayavardhanarao Sahukaru @ aitam 52


AITAM Data Structures I-I MCA (AR-24)

Example:

This sample demonstrates how the C continues Statement

functions. #include <stdio.h>


int main() {
int i;
for (i = 0; i< 10;
i++) { if (i % 2
== 0) {
continue; // skip even numbers
}
printf("%d ", i);
}
return 0;
}

Output:

13579

Explanation:

In the above example, the for loop iterates from 0 to 9, and when the loop variable i is even,
the continue statement is executed and control is transferred to the following iteration of
the loop. As a result, the printf statement only prints odd integers and skips over even
values.

Advantages and Disadvantages of Branching Statements

There are various advantages and disadvantages of the branching statements. Some
main advantages and disadvantages of the branching statements are as follows:

Advantages of Branching Statements:

Better Decision Making: Branching statements give programmers the ability to decide
what to do next in their code depending on certain circumstances. It improves the
program's functionality and versatility by allowing it to respond and adapt to various
conditions.

Readability of the code: Branching statements make the logic of the code clearer
and simpler to understand. For other developers to understand and maintain the
codebase, the conditional statements provide distinct signs of the program's decision-
making process.

Code effectiveness: Branching statements optimize program execution by only running


the necessary code blocks in accordance with the predetermined circumstances. It can
make programs run more quickly and effectively, especially when employing the
"switch" statement to process big sets of cases or complex decision trees.

Flexibility: Programming flexibility is provided through branching statements, which


Jayavardhanarao Sahukaru @ aitam 53
AITAM Data Structures I-I MCA (AR-24)
enables several code paths to be performed in response to diverse circumstances.
This adaptability is especially helpful when the program needs to react quickly to
altering inputs or outside influences.

Jayavardhanarao Sahukaru @ aitam 54


AITAM Data Structures I-I MCA (AR-24)

Code Reusability: Branching statements make it easier to reuse code by enabling


the execution of code blocks in response to various situations. Programmers can
create modular code that can be easily reused in various portions of the program by
utilizing branching statements efficiently.

Disadvantages of Branching Statements:

Code Complexity: When branching statements are overused or deeply nested, the
code may become clearer and easier to comprehend. It may result in maintenance
problems, defects, and poorer-quality code. It's crucial to utilize branching statements
sparingly and aim for simplicity.

Readability Issues: Although branching statements can sometimes make code easier
to comprehend, they can also cause issues if used carelessly. The code may become
more difficult to read and understand if there are too many nested levels, complex
conditional expressions, or duplicative sections of code.

Potential for Logical Mistakes: If the conditions are not adequately established
and validated, branching statements run the danger of logical mistakes.

Code Maintenance: The intricacy of branching statements makes it more difficult to


maintain the code. It can be difficult to comprehend the logic of the code and make
the necessary adjustments without adding problems when there are numerous
branching statements and nested conditions present.

Let's look at a few more instances to see how branching statements are used in various
contexts:

Example 1: Finding the Maximum Number

include <stdio.h>
int main() {
int num1 = 10;
int num2 = 20;
int max;
if (num1 > num2)
{ max = num1;
}
else {
max = num2;
}
printf("The maximum number is: %d\n", max);
return 0;
}
Output:

The maximum number is:

20 Explanation:

Jayavardhanarao Sahukaru @ aitam 55


AITAM Data Structures I-I MCA (AR-24)
In this illustration, the maximum value is established by comparing two numbers
(num1 and num2) using the "if-else" expression. The program sets the variable max
to its maximum value before displaying it on the terminal.

Jayavardhanarao Sahukaru @ aitam 56


AITAM Data Structures I-I MCA (AR-24)

Example 2: Grade Classification

include <stdio.h>
int main() {
int marks;
printf("Enter the marks: ");
scanf("%d", &marks);
if (marks >= 60)
{ printf("Grade: A\n");
}
else if (marks >= 80)
{ printf("Grade: B\n");
}
else if (marks >= 70)
{ printf("Grade: C\n");
}
else if (marks >= 60)
{ printf("Grade: D\n");
}
else {
printf("Grade: F\n");
}
return 0;
}

Output (for input 78):

Grade: C

Explanatio

n:

In this illustration, the program accepts the user's marks as input and determines the
grade level using the "if-else if" ladder. The program prints the corresponding grade on
the console based on the input marks.

Example 3: Month Name

include <stdio.h>
int main() {
int monthNumber;
printf("Enter the month number (1-12): ");
scanf("%d", &monthNumber);
switch (monthNumber)
{ case 1:
printf("January\n");
break;
case 2: printf("February\
n"); break;
Jayavardhanarao Sahukaru @ aitam 57
AITAM Data Structures I-I MCA (AR-24)

case 3:
printf("March\n");
break;
case 4:
printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");
break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");
break;
case 6:
printf("September\n");
break;
case 10:
printf("October\n");
break;
case 11:
printf("November\n");
break;
case 12:
printf("December\n");
break;
default:
printf("Invalid month number\n");
}
return 0;
}

Output (for input 8):

August

Explanatio

n:

In this illustration, the computer receives the user's input as the month number and
then utilizes the "switch" statement to get the name of the matching month. The
program prints the corresponding month name on the console based on the input.

Jayavardhanarao Sahukaru @ aitam 58


AITAM Data Structures I-I MCA (AR-24)

Example 4: Leap Year Check

include <stdio.h>
int main() {
int year;
printf("Enter the year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{ printf("%d is a leap year.\n", year);
}
else {
printf("%d is not a leap year.\n", year);
}
return 0;
}

Output (for input 2024):

2024 is a leap

year. Explanation:

In the above example, the for loop iterates from 0 to 9, and when the loop variable i is even,
the continue statement is executed and control is transferred to the following iteration of
the loop. As a result, the printf statement only prints odd integers and skips over even
values.

Programmers often use branching statements because they give them the power to
modify how code is executed based on certain criteria. In this blog post, we focused on the
"if", "if-else", nested "if-else", and "switch" expressions to examine the fundamental
branching statements in the C programming language.

The "if-else" statement expands on the "if" statement's ability to execute code conditionally
by offering an additional code block for when the condition is false. Decision-making is
more flexible because numerous criteria may be handled within nested blocks due to the
nested "if-else" statement. Finally, the "switch" statement simplifies managing many
situations by enabling alternative actions to be carried out depending on the value of
a variable or expression.

Learning how to use these branching statements gives programmers more control
over how their programs run, allowing them to create applications that are more
intelligent and dynamic. It is crucial to experiment with various conditions and
scenarios to gain a deeper grasp of and increase one's expertise with branching
statements efficiently.

As you advance in your understanding of C programming, keep in mind that branching


statements are effective tools that improve the flexibility and logic of the code. With time and
practice, you will develop the abilities needed to make the best decisions and build solid,
effective programs.
Jayavardhanarao Sahukaru @ aitam 59
AITAM Data Structures I-I MCA (AR-24)

Loops in C
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:

do{

//code to be executed

}while(condition);

while loop in C

The while loop in c is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the condition
specified in the while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given

below: while(condition){
Jayavardhanarao Sahukaru @ aitam 60
AITAM Data Structures I-I MCA (AR-24)
//code to be executed }

Jayavardhanarao Sahukaru @ aitam 61


AITAM Data Structures I-I MCA (AR-24)

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:

for(initialization;condition;incr/decr){

//code to be executed

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:

do{

//code to be executed

}while(condition);

The components are divided into the following:

 The do keyword marks the beginning of the Loop.


 The code block within curly braces {} is the body of the loop, which contains the
code you want to repeat.
 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:

include <stdio.h>
include <string.h>
Jayavardhanarao Sahukaru @ aitam 62
AITAM Data Structures I-I MCA (AR-24)
int main() {

Jayavardhanarao Sahukaru @ aitam 63


AITAM Data Structures I-I MCA (AR-24)

char password[] = "secret";


char input[20];
do {
printf("Enter the password: ");
scanf("%s", input);
} while (strcmp(input, password) != 0);
printf("Access granted!\n");
return 0;
}
The program runs as follows:

The following header files are included: <stdio.h> for standard input and output routines
and <string.h> for string manipulation functions.

The correct password is defined as a character array (char password[]) with the

value "secret" After that, we define another character array input to store the

user's input.

The do keyword indicates that the code block included within the loop will be performed
at least once.

Using the printf() function, we display a prompt requesting the user to input their
password inside the Loop.

Next, we read the user's input using the scanf() function and store it in the input array.

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.

Once the correct password is entered, the loop terminates, and we print "Access
granted!" using the printf() function.

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:

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
Jayavardhanarao Sahukaru @ aitam 64
AITAM Data Structures I-I MCA (AR-24)
password is provided, the loop terminates, and the "Access granted!" message is
displayed.

Jayavardhanarao Sahukaru @ aitam 65


AITAM Data Structures I-I MCA (AR-24)

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:

include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i<= 5);
return 0;
}
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:

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

include<stdio.h>
Int main(){
inti=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
Output:

Enter a
number: 5 5
10
15
Jayavardhanarao Sahukaru @ aitam 66
AITAM Data Structures I-I MCA (AR-24)

20
25
30
35
40
45
50
Enter a number:
10 10
20
30
40
50
60
70
80
90
100

Example 3:

Let's take a program that prints the multiplication table of a given number N using a

do...while Loop: #include <stdio.h>


int main() {
int N;
printf("Enter a number to generate its multiplication
table: "); scanf("%d", CN);
inti =
1; do
{
printf("%d x %d = %d\n", N, i,
N * i); i++;
} while (i<=
10); return 0;
}

Output:
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
Jayavardhanarao Sahukaru @ aitam 67
AITAM Data Structures I-I MCA (AR-24)

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:

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

always true. Output:

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:

include <stdio.h>
int main() {
int rows, i = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Jayavardhanarao Sahukaru @ aitam 68
AITAM Data Structures I-I MCA (AR-24)

do {
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= i);
printf("\n");
i++;
} while (i<= rows);
return 0;
}
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:

Enter the number of

rows: 5 1
12
123
1234
12345

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:

Jayavardhanarao Sahukaru @ aitam 69


AITAM Data Structures I-I MCA (AR-24)

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.

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:

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.

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.

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.

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.

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.

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.

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.

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
Jayavardhanarao Sahukaru @ aitam 70
AITAM Data Structures I-I MCA (AR-24)
the loop terminates at some point.

Jayavardhanarao Sahukaru @ aitam 71


AITAM Data Structures I-I MCA (AR-24)

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

Test it Now

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.

include<stdio.h>
int main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;

Jayavardhanarao Sahukaru @ aitam 72


AITAM Data Structures I-I MCA (AR-24)

}
return 0;
}

Outpu

t1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while loop in C

include<stdio.h>
int main(){
int i=1,number=0,b=6;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
return 0;
}
Output

Enter a number:

50 50
100
150
200
250
300
350
400
450
500
Enter a number:
100 100
200
300
400
Jayavardhanarao Sahukaru @ aitam 73
AITAM Data Structures I-I MCA (AR-24)

500
600
700
800
900
1000

Properties of while loop

 A conditional expression is used to check the condition. The statements


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

Example 1
include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
Output

3 5 7 9 11

Example 2

include<stdio.h>
void main ()
{
while()
{
printf("hello Jayavardhan");
}
}
Output

compile time error: while loop can't be empty

Jayavardhanarao Sahukaru @ aitam 74


AITAM Data Structures I-I MCA (AR-24)

Example 3

include<stdio.h>
void main ()
{
int x = 10, y = 2;
while(x+y-1)
{
printf("%d %d",x--,y--);
}
}
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.

while(1){

//statement

for loop in C
The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and
linked list.

Syntax of for loop in C

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

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

2. //code to be executed

3. }

Flowchart of for loop in C

Jayavardhanarao Sahukaru @ aitam 75


AITAM Data Structures I-I MCA (AR-24)

C for loop Examples

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

include<stdio.h>
int main(){
int i=0; for(i=1;i<=5;i+
+){ printf("%d \n",i);
}
return 0;
}

Outpu

t1
2
3
4
5

Jayavardhanarao Sahukaru @ aitam 76


AITAM Data Structures I-I MCA (AR-24)

C Program: Print table for the given number using C for loop

include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
return 0;
}

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

The expression represents the initialization of the loop

variable. We can initialize more than one variable in

Expression 1.

Expression 1 is optional.

In C, we cannot declare the variables in Expression 1. However, it can be an exception

Jayavardhanarao Sahukaru @ aitam 77


AITAM Data Structures I-I MCA (AR-24)
in some compilers.

Jayavardhanarao Sahukaru @ aitam 78


AITAM Data Structures I-I MCA (AR-24)

Example
1
include <stdio.h>
int main()
{
int a,b,c;
for(a=0,b=12,c=23;a<2;a++)
{
printf("%d ",a+b+c);
}
}
Outpu

t 35

36

Example 2

include <stdio.h>
int main()
{
int i=1;
for(;i<5;i++)
{
printf("%d ",i);
}
}
Outpu

t12

34

Properties of Expression 2

Expression 2 is a conditional expression. It checks for a specific condition to be satisfied.


If it is not, the loop is terminated.

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.

Expression 2 is optional.

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.

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.

Jayavardhanarao Sahukaru @ aitam 79


AITAM Data Structures I-I MCA (AR-24)

Example
1
include <stdio.h>
int main()
{
int i;
for(i=0;i<=4;i++)
{
printf("%d ",i);
}
}
Output

0123

Example 2

include <stdio.h>
int main()
{
int i,j,k;
for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
{
printf("%d %d %d\n",i,j,k);
j+=2;
k+=3;
}
}

Output

0 0 0
1 2 3
2 4 6
3 6 9
4 8 12

Example 3

include <stdio.h>
int main()
{
int i;
for(i=0;;i++)
{
printf("%d",i);
}
}
Jayavardhanarao Sahukaru @ aitam 80
AITAM Data Structures I-I MCA (AR-24)

Outpu
t
infinite loop

Properties of Expression 3

Expression 3 is used to update the loop variable.

We can update more than one variable at the

same time. Expression 3 is optional.

Example 1

#include<stdio.h>
void main ()
{
int i=0,j=2;
for(i = 0;i<5;i++,j=j+2)
{
printf("%d %d\n",i,j);
}
}

Output

0 2
1 4
2 6
3 8
4 10

Loop body

The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The
braces work as a block separator, i.e., the value variable declared inside for loop is valid
only for that block and not outside. Consider the following example.

#include<stdio.h>
void main ()
{
int i;
for(i=0;i<10;i
++)
{
int i = 20;
printf("%d ",i);
}
}

Jayavardhanarao Sahukaru @ aitam 81


AITAM Data Structures I-I MCA (AR-24)

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

#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to javatpoint");
}
}

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 Outer_loop

Inner_loop

// inner loop statements.

// outer loop statements.

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.

Jayavardhanarao Sahukaru @ aitam 82


AITAM Data Structures I-I MCA (AR-24)

Nested for loop

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

'for' loop. for (initialization; condition; update)

for(initialization; condition; update)

// inner loop statements.

// outer loop statements.

Example of nested for loop

#include <stdio.h>
int main()
{
int n;// variable
declaration printf("Enter
the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

Explanation of the above code

 First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
 The program control checks whether the condition 'i<=n' is true or not.
 If the condition is true, then the program control passes to the inner loop.
 The inner loop will get executed until the condition is true.
 After the execution of the inner loop, the control moves back to the update of the
outer loop, i.e., i++.
 After incrementing the value of the loop counter, the condition is checked again, i.e.,
i<=n.
 If the condition is true, then the inner loop will be executed again.
 This process will continue until the condition of the outer loop is true.

Jayavardhanarao Sahukaru @ aitam 83


AITAM Data Structures I-I MCA (AR-24)

Output:

Nested while loop

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

loop. while(condition)

while(condition)

// inner loop statements.

// outer loop statements.

Example of nested while

loop #include <stdio.h>


int main()
{
int rows; // variable declaration
int columns; // variable
declaration int k=1; // variable
initialization
printf("Enter the number of rows :"); // input the number of
rows. scanf("%d",Crows);
printf("\nEnter the number of columns :"); // input the number of
columns. scanf("%d",Ccolumns);
int a[rows][columns]; //2d array
declaration int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.
Jayavardhanarao Sahukaru @ aitam 84
AITAM Data Structures I-I MCA (AR-24)

k++; // increment
counter j++;
}
i++;
printf("\n");
}
}

Explanation of the above code.

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


 The program initializes the 'i' variable by 1.
 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.
 After the execution of the inner loop, the control moves to the update of the outer loop,
i.e., i++.
 After incrementing the value of 'i', the condition (i<=rows) is checked.
 If the condition is true, the control then again moves to the inner loop.
 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. do

do

// inner loop statements.

Jayavardhanarao Sahukaru @ aitam 85


AITAM Data Structures I-I MCA (AR-24)
}while(condition);

Jayavardhanarao Sahukaru @ aitam 86


AITAM Data Structures I-I MCA (AR-24)

// outer loop statements.

}while(condition);

Example of nested do..while loop.

#include <stdio.h>
int main()
{
/*printing the pattern
********
********
********
********
*/ int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}

Output:

Explanation of the above code.

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


 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.
 After the execution of the inner loop, the control moves to the update of the i++.
 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.

Jayavardhanarao Sahukaru @ aitam 87


AITAM Data Structures I-I MCA (AR-24)

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

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.

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.

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:

1. for loop
2. while loop
3. do-while loop
4. go to statement
5. C macros

For loop

Let's see the infinite 'for' loop. The following is the definition for the

infinite for loop: for(; ;)

// body of the for loop.

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.

Jayavardhanarao Sahukaru @ aitam 88


AITAM Data Structures I-I MCA (AR-24)
#include
<stdio.h> int
main()
{

Jayavardhanarao Sahukaru @ aitam 89


AITAM Data Structures I-I MCA (AR-24)

for(;;)
{
printf("Hello javatpoint");
}
return 0;
}
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:

while(1)

// body of the loop..

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.

#include <stdio.h>
int main()
{
int i=0;
while(1)
{
i++;
printf("i is :%d",i);
Jayavardhanarao Sahukaru @ aitam 90
AITAM Data Structures I-I MCA (AR-24)

}
return 0;
}

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.

do

// body of the loop..

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

// body statements.

goto infinite_loop;

In the above code, the goto statement transfers the control to the infinite loop.

Jayavardhanarao Sahukaru @ aitam 91


AITAM Data Structures I-I MCA (AR-24)

Macros

We can also create the infinite loop with the help of a macro constant. Let's understand
through an example.

#include
<stdio.h> #define
infinite for(;;) int
main()
{
infinite
{
printf("hello");
}
return 0;
}

In the above code, we have defined a macro named as 'infinite', and its value is 'for(;;)'.
Whenever the word 'infinite' comes in a program then it will be replaced with a 'for(;;)'.

Output

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

#include
<stdio.h> int
main()
{
char
ch;
while(1
)
{
Jayavardhanarao Sahukaru @ aitam 92
AITAM Data Structures I-I MCA (AR-24)
ch=getchar();
if(ch=='n')
{
break;
}

Jayavardhanarao Sahukaru @ aitam 93


AITAM Data Structures I-I MCA (AR-24)

printf("hello");
}
return 0;
}

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:

We should examine the semicolons carefully. Sometimes we put the semicolon at the
wrong place, which leads to the infinite loop.

include <stdio.h>
int main()
{
int i=1;
while(i<=10);
{
printf("%d", i);
i++;
}
return 0;
}
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.

We should check the logical conditions carefully. Sometimes by mistake, we place the
assignment operator (=) instead of a relational operator (= =).

#include
<stdio.h> int
main()
{
char
ch='n';
while(ch='
y')
{
printf("hello");
}
return 0;
Jayavardhanarao Sahukaru @ aitam 94
AITAM Data Structures I-I MCA (AR-24)
}
In the above code, we use the assignment operator (ch='y') which leads to the
execution of loop infinite number of times.

Jayavardhanarao Sahukaru @ aitam 95


AITAM Data Structures I-I MCA (AR-24)

We use the wrong loop condition which causes the loop to be executed

indefinitely. #include <stdio.h>


int main()
{
for(int i=1;i>=1;i++)
{
printf("hello");
}
return 0;
}
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.

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.

#include
<stdio.h> int
main()
{
while(1)
{
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
break;
}
}
}
return 0;
}

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.

We should be very careful when we are using the floating-point value inside the loop
as we cannot underestimate the floating-point errors.

#include
<stdio.h> int
main()
{
float x = 3.0;
while (x != 4.0) {
printf("x = %f\n",
x); x += 0.1;
Jayavardhanarao Sahukaru @ aitam 96
AITAM Data Structures I-I MCA (AR-24)
}
return 0;

Jayavardhanarao Sahukaru @ aitam 97


AITAM Data Structures I-I MCA (AR-24)

}
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

Jayavardhanarao Sahukaru @ aitam 98


AITAM Data Structures I-I MCA (AR-24)
on the program or system.

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

Jayavardhanarao Sahukaru @ aitam 99


AITAM Data Structures I-I MCA (AR-24)

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.

Branching in C:
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:

//loop or switch case

break;

Flowchart of break in c

Jayavardhanarao Sahukaru @ aitam 10


0
AITAM Data Structures I-I MCA (AR-24)

Example

#include<stdio.
h>
#include<stdlib
.h> void main
()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d
",i); if(i ==
5)
break;
}
printf("came outside of loop i = %d",i);
}

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:

The loop (while or for) or the switch (or a series of "if-else" statements) begins execution.

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.

If the condition is "true", the "break" statement is performed.

When a "break" statement is found, the program immediately quits the loop or switch
block, skipping any remaining iterations or checks.

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.
Jayavardhanarao Sahukaru @ aitam 10
1
AITAM Data Structures I-I MCA (AR-24)

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:

1. Simple Loops
2. Nested Loops
3. Infinite Loops
4. 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:

While loop

while (condition) {

// Code block inside the

loop if (some_condition)

break; // Exit the loop if this condition is met

// Rest of the loop's code

For loop

for (initialization; condition; increment) {

// Code block inside the

loop if (some_condition)

break; // Exit the loop if this condition is met

// Rest of the loop's code

Jayavardhanarao Sahukaru @ aitam 10


2
AITAM Data Structures I-I MCA (AR-24)

Example:

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

// Using break in a while loop

include <stdio.h>
int main() {
inti = 1;
while (i<= 10) {
if (i == 5) {
break; // Exit the loop when i becomes 5
}
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}

Outpu

t12

34

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.

Syntax:

It has the following syntax:

for (outer_loop_initialization; outer_loop_condition; outer_loop_increment) {

// Code block of the outer loop

for (inner_loop_initialization; inner_loop_condition; inner_loop_increment) {

// Code block of the inner

loop if (some_condition) {

break; // Exit both inner and outer loops if this condition is met

Jayavardhanarao Sahukaru @ aitam 10


3
AITAM Data Structures I-I MCA (AR-24)
}

// Rest of the inner loop's code

Jayavardhanarao Sahukaru @ aitam 10


4
AITAM Data Structures I-I MCA (AR-24)

// Rest of the outer loop's code

Example:

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

// Using break in nested

loops #include <stdio.h>


int main() {
for (inti = 1; i<= 3;
i++) { for (int j = 1; j
<= 3; j++) { if (i ==
2 CC j == 2) {
break; // Exit both loops when i=2 and j=2
}
printf("(%d, %d) ", i, j);
}
}
printf("\n");
return 0;
}

Output

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

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

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

// Code block inside the

loop if (some_condition)

{
Jayavardhanarao Sahukaru @ aitam 10
5
AITAM Data Structures I-I MCA (AR-24)
break; // Exit the loop if this condition is met

Jayavardhanarao Sahukaru @ aitam 10


6
AITAM Data Structures I-I MCA (AR-24)

// Rest of the loop's code

Example:

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

// Using break in an infinite loop

include <stdio.h>
int main() {
int number;
while (1) {
printf("Enter a number (0 to exit): ");
scanf("%d", &number);
if (number == 0) {
break; // Exit the loop when the user enters 0
}
printf("You entered: %d\n", number);
}
return 0;
}
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:

Jayavardhanarao Sahukaru @ aitam 107


AITAM Data Structures I-I MCA (AR-24)

switch (expression)

{ case value1:

// Code block for case value1

break; // Exit the switch block after executing this

case case value2:

// Code block for case value2

break; // Exit the switch block after executing this case

// More cases...

default:

// Code block for the default case

break; // Exit the switch block after executing this case

Example:

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

// Using break in a switch statement

#include <stdio.h>
int main() {
int choice;
printf("Menu:\n");
printf("1. Option 1\
n"); printf("2.
Option 2\n");
printf("3. Quit\n");
printf("Enter your choice: ");
scanf("%d", Cchoice);

switch
(choice) {
case 1:
printf("You selected Option 1\
n"); break;
case 2:
printf("You selected Option 2\
n"); break;
case 3:
printf("Quitting the menu...\
n"); break;
default:
Jayavardhanarao Sahukaru @ aitam 108
AITAM Data Structures I-I MCA (AR-24)

printf("Invalid choice. Try one more time.\


n"); break;

Jayavardhanarao Sahukaru @ aitam 109


AITAM Data Structures I-I MCA (AR-24)

}
return 0;
}

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

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:

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.

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.

Jayavardhanarao Sahukaru @ aitam 110


AITAM Data Structures I-I MCA (AR-24)
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.

Jayavardhanarao Sahukaru @ aitam 111


AITAM Data Structures I-I MCA (AR-24)

Code organization and readability: Properly using break statements can lead to
cleaner C 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 C maintain.

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.

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:

//loop

statements

continue;

//some lines of the code which is to be

skipped Continue statement example 1

#include<stdio.h>
void main ()
{
int i = 0;
while(i!=10)
{
printf("%d",
i); continue;
i++;
}
}

Output

Jayavardhanarao Sahukaru @ aitam 112


AITAM Data Structures I-I MCA (AR-24)
infinite loop

Jayavardhanarao Sahukaru @ aitam 113


AITAM Data Structures I-I MCA (AR-24)

Continue statement example 2

#include<stdio.h>

int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for
loop return 0;
}

Outpu

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

C continue statement with inner loop

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

include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d %d\n",i,j);
}
}//end of for loop
return 0;
}

Jayavardhanarao Sahukaru @ aitam 114


AITAM Data Structures I-I MCA (AR-24)

Outpu

t11
12
13
21
23
31
32
33
As you can see, 2 2 is not printed on the console because inner loop is continued at
i==2 and j==2.

C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statement 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 complicated.

Syntax:

label:

//some part of the code;

goto label;

goto example

Let's see a simple example to use goto statement in C language.

include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i); i+
+;
if(i<=10)
goto table;
}
Output
:

Enter the number whose table you want to


print?10 10 x 1 = 10
10 x 2 = 20
Jayavardhanarao Sahukaru @ aitam 115
AITAM Data Structures I-I MCA (AR-24)
10 x 3 = 30
10 x 4 = 40

Jayavardhanarao Sahukaru @ aitam 116


AITAM Data Structures I-I MCA (AR-24)

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.

#include
<stdio.h> int
main()
{
int i, j, k;
for(i=0;i<10;i++)
{
for(j=0;j<5;j++)
{
for(k=0;k<3;k++)
{
printf("%d %d %d\
n",i,j,k); if(j == 3)
{
goto out;
}
}
}
}
out:
printf("came out of the loop");
}
Output:

000
001
002
010
011
012
020
021
022
030
came out of the loop
Jayavardhanarao Sahukaru @ aitam 117
AITAM Data Structures I-I MCA (AR-24)

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


• Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
• 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

• Code Optimization: Less code to access the data.


• Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
• Ease of sorting: To sort the elements of the array, we need a few lines of code only.
• Random Access: We can access any element randomly using the array.

Disadvantage of C Array
• 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.
There are two types of arrays.
1. Singe Dimensional Arrays
2. Multi-Dimensional Arrays
Single Dimensional Arrays:
Declaration of C Array
data_type array_name[array_size];
Eg: int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array

Jayavardhanarao Sahukaru @ aitam 118


AITAM Data Structures I-I MCA (AR-24)

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.
marks[0]=80;//initialization of
array marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Example – 1:
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \t",marks[i]);
}//end of for loop
return 0;

}
Output:
80 60 70 85 75
Example – 2:

Jayavardhanarao Sahukaru @ aitam 119


AITAM Data Structures I-I MCA (AR-24)

#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \t",marks[i]);

}
return 0;
}
Output:
20 30 40 50 60
Example – 3: Program to accept students marks and print number of first classes, second classes
and third classes.
#include<stdio.h>
int main(){
int i=0,n,a[10],n1=0,n2=0,n3=0;
printf("Enter number of students: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter student marks: ");
scanf("%d",&a[i]);
if(a[i] >= 60)
n1++;
else if(a[i] >= 50)
n2++;
else if(a[i] >=35)
n3++;
}
printf("\n\nFirst Classes: %d\n",n1);

Jayavardhanarao Sahukaru @ aitam 120


AITAM Data Structures I-I MCA (AR-24)

printf("Second Classes: %d\n",n2);


printf("Third Classes: %d\n",n3);
return 0;
}
Output:
Enter number of studens: 4
Enter student marks: 34
Enter student marks: 67
Enter student marks: 45
Enter student marks: 76
First Classes: 2
Second Classes: 0
Third Classes: 1
Example – 4: Program to accept students marks and calculate the average of first class students,
second class students and third class students.
#include<stdio.h>
int main(){

int i=0,n,a[10],n1=0,n2=0,n3=0,s1=0,s2=0,s3=0;
printf("Enter number of studens: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter student marks: ");
scanf("%d",&a[i]);
if(a[i] >= 60){
n1++;
s1+=a[i];}
else if(a[i] >= 50){
n2++;

s2+=a[i];}
else if(a[i] >=35){
n3++;

Jayavardhanarao Sahukaru @ aitam 121


AITAM Data Structures I-I MCA (AR-24)

s3+=a[i];}
}
printf("\n\nAverage marks of First Class students: %d\n",s1/n1);
printf("Average marks of Second Class students: %d\n",s2/n2);
printf("Average marks of Third Class students: %d\n",s3/n3);
return 0;

}
Output:
Enter number of studens: 9
Enter student marks: 78
Enter student marks: 90
Enter student marks: 37
Enter student marks: 45
Enter student marks: 56
Enter student marks: 58
Enter student marks: 79
Enter student marks: 47
Enter student marks: 36
Average marks of First Class students: 82
Average marks of Second Class students: 57
Average marks of Third Class students: 41

Jayavardhanarao Sahukaru @ aitam 122


AITAM Data Structures I-I MCA (AR-24)

Example – 5: Program to accept n number and print those numbers in reverse order.
#include <stdio.h>
int main() {
int a[20],i,n;
printf("How many numbers you want: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number a[%d]: ",i);
scanf("%d",&a[i]);
}
printf("The numbers in reverse order is:\n");
for(i=n-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
return 0;
}

Output:
How many numbers you want: 5
Enter number a[0]: 3
Enter number a[1]:
4 Enter number
a[2]: 5 Enter
number a[3]: 6
Enter number a[4]:
8
The numbers in reverse order is:
8 6 5 4 3

Jayavardhanarao Sahukaru @ aitam 123


AITAM Data Structures I-I MCA (AR-24)

Example – 6: Program to check whether any of the digits in a number appears more than once.
// Online C compiler to run C program online
#include <stdio.h>
int main() {
int a[10]={0},n,r;
printf("Enter a number: ");
scanf("%d",&n);
while (n>0){
r = n % 10;
if (a[r] == 1)
break;
a[r] = 1;
n = n / 10;
}
if(n>0)
printf("YES");
else
printf("NO");
return 0;
}

Output:
Enter a number: 7656
YES
Enter a number: 1234
NO

Multi-dimensional arrays:
Multidimensional arrays are one of the most powerful features of the C programming language. They
allow you to store data in a table-like format, where each row and column can be accessed using an
index. In this blog post, we'll look at multidimensional arrays in C, including their syntax, example
usage, and output.
Syntax of Multidimensional Arrays in C
To create a multidimensional array in C, you need to specify the number of dimensions and the size of
each dimension. The general syntax for declaring a multidimensional array is as follows:
type array_name[size1][size2]...[sizeN];
Here, type is the data type of the elements that will be stored in the array, array_name is the name of
the array, and size1, size2, ..., sizeN are the sizes of each dimension of the array.
For example, the following code declares a 2-dimensional array of integers with 3 rows and 4 columns:
int my_array[3][4];
It creates an array with 3 rows and 4 columns, for a total of 12 elements. Each element is of type int.

Jayavardhanarao Sahukaru @ aitam 124


AITAM Data Structures I-I MCA (AR-24)

Accessing Elements of Multidimensional Arrays


To access an element of a multidimensional array, you need to specify the indices for each dimension.
For example, to access the element in the second row and third column of my_array, you would use
the following syntax:
int element = my_array[1][2];
Note that the indices start at 0, so the first row is my_array[0], the second row is my_array[1], and so
on. Similarly, the first column of each row is my_array[i][0], and so on.
Initializing Multidimensional Arrays
You can initialize a multidimensional array when you declare it by specifying the values for each
element in the array. For example, the following code declares and initializes a 2-dimensional array of
integers with 2 rows and 3 columns:
int my_array[2][3] = { {1, 2, 3}, {4, 5, 6} };
It creates an array with 2 rows and 3 columns and initializes the elements to the specified values.
Iterating Over Multidimensional Arrays
You can iterate over the elements of a multidimensional array using nested loops. For example, the
following code iterates over the elements of my_array and prints their values:
for (int i = 0; i< 2; i++)
{ for (int j = 0; j < 3; j++)
{
printf("%d ", my_array[i][j]);
}
printf("\n");
}
This code loops through each row and column of my_array, and prints each element with a space
between them. The printf("\n") statement is used to print a newline character after each row.
2-D arrays:
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. However, 2D arrays are created to
implement a relational database lookalike data structure. It provides ease of holding the bulk of data
at once which can be passed to any number of functions wherever required.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
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

Jayavardhanarao Sahukaru @ aitam 125


AITAM Data Structures I-I MCA (AR-24)

the second dimension of the array. The two-dimensional array can be declared and defined in the
following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example – 1: Program print 2D array elements.
int main()
{ int
i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array for(i=0;i<4;i+
+){
for(j=0;j<3;j++){ printf("%d\
t",arr[i][j]);
}//end of j
printf("\n");
}//end of i
return 0;
}

Output:
1 2 3
2 3 4
3 4 5
4 5 6

Example – 2: Program read the values in to 2D array and print 2D array elements.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter value for a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n\n The elements in the matrix are:");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
Jayavardhanarao Sahukaru @ aitam 126
AITAM Data Structures I-I MCA (AR-24)

}
}
}

Output:
Enter value for a[0][0]:
1 Enter value for a[0]
[1]: 2 Enter value for
a[0][2]: 3 Enter value
for a[1][0]: 4 Enter
value for a[1][1]: 5
Enter value for a[1][2]:
6 Enter value for a[2]
[0]: 7 Enter value for
a[2][1]: 8 Enter value
for a[2][2]: 9
The elements in the matrix are:
1 2 3
4 5 6
7 8 9

Example – 3: Program read the size of the 2D array, accept array elements and print the array
values.
#include <stdio.h>
int main() {
// Define the dimensions of the 2D array
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare a 2D array with the specified dimensions
int array[rows][cols];
// Read elements of the 2D array
printf("Enter the elements of the array:\n");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("Enter element at position [%d][%d]: ", i, j);
scanf("%d", &array[i][j]);
Jayavardhanarao Sahukaru @ aitam 127
AITAM Data Structures I-I MCA (AR-24)
}
}

Jayavardhanarao Sahukaru @ aitam 128


AITAM Data Structures I-I MCA (AR-24)

// Print the elements of the 2D array


printf("\nElements of the array are:\n");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) { printf("%d\
t", array[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of the array:
Enter element at position [0][0]: 2
Enter element at position [0][1]: 3
Enter element at position [1][0]: 4
Enter element at position [1][1]: 5
Elements of the array are:
2 3
4 5

Example – 4: Program to perform matrix addition.


#include <stdio.h>
int main() {
int rows, cols;
// Get the number of rows and columns for the matrices
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

// Declare matrices A and B with the given dimensions


Int matrixA[rows][cols], matrixB[rows][cols],
resultMatrix[rows][cols];

// Input elements of matrix A


printf("Enter elements of matrix A:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{ printf("Enter element A[%d][%d]: ", i,
j);
scanf("%d", &matrixA[i][j]);
}
}
Jayavardhanarao Sahukaru @ aitam 129
AITAM Data Structures I-I MCA (AR-24)

// Input elements of matrix B


printf("Enter elements of matrix B:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{ printf("Enter element B[%d][%d]: ", i,
j);
scanf("%d", &matrixB[i][j]);
}
}
// Perform matrix addition
for (int i = 0; i < rows; i++)
{ for (int j = 0; j < cols; j++)
{
resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}

// Display the result matrix printf("\


nResultant Matrix (A + B):\n"); for (int
i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{ printf("%d \t", resultMatrix[i]
[j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 3
Enter the number of columns: 3
Enter elements of matrix A:
Enter element A[0][0]: 2
Enter element A[0][1]: 3
Enter element A[0][2]: 4
Enter element A[1][0]: 5
Enter element A[1][1]: 6
Enter element A[1][2]: 7
Enter element A[2][0]: 8
Enter element A[2][1]: 9
Enter element A[2][2]: 8
Enter elements of matrix B:
Enter element B[0][0]: 2
Enter element B[0][1]: 3
Enter element B[0][2]: 4
Enter element B[1][0]: 5
Enter element B[1][1]: 6
Jayavardhanarao Sahukaru @ aitam 130
AITAM Data Structures I-I MCA (AR-24)
Enter element B[1][2]: 7
Enter element B[2][0]: 8

Jayavardhanarao Sahukaru @ aitam 131


AITAM Data Structures I-I MCA (AR-24)

Enter element B[2][1]: 5


Enter element B[2][2]: 4

Resultant Matrix (A + B):


4 6 8
10 12 14
16 14 12

Example – 5: Program to perform matrix multiplication.


#include <stdio.h>
int main() {
int i, j, k, rows1, cols1, rows2, cols2;
// Read the size of the first matrix
printf("Enter the number of rows and columns for the first matrix:\
n");
scanf("%d %d", &rows1, &cols1);
// Read the size of the second matrix
printf("Enter the number of rows and columns for the second matrix:\
n");
scanf("%d %d", &rows2, &cols2);

// Check if multiplication is possible


if (cols1 != rows2) {
printf("Matrix multiplication is not possible. Number of columns
in the first matrix must be equal to the number of rows in the second
matrix.\n");
return 1; // Exit the program with an error code
}
// Declare matrices
int matrix1[rows1][cols1], matrix2[rows2][cols2], result[rows1]
[cols2];
// Read elements of the first matrix
printf("Enter elements of the first matrix:\n");
for (i = 0; i < rows1; ++i) {
for (j = 0; j < cols1; ++j)
{ scanf("%d", &matrix1[i]
[j]);
}
}
// Read elements of the second matrix
printf("Enter elements of the second matrix:\n");
for (i = 0; i < rows2; ++i) {
for (j = 0; j < cols2; ++j)
{ scanf("%d", &matrix2[i]
[j]);
}

Jayavardhanarao Sahukaru @ aitam 132


AITAM Data Structures I-I MCA (AR-24)
}
// Perform matrix multiplication

Jayavardhanarao Sahukaru @ aitam 133


AITAM Data Structures I-I MCA (AR-24)

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


{ for (j = 0; j < cols2; ++j)
{
result[i][j] = 0;
for (k = 0; k < cols1; ++k) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display the result
printf("Result of matrix multiplication:\n");
for (i = 0; i < rows1; ++i) {
for (j = 0; j < cols2; ++j)
{ printf("%d ", result[i]
[j]);
}
printf("\n");
}
return 0; // Exit the program with success code
}

Output:
Enter the number of rows and columns for the first matrix:
22
Enter the number of rows and columns for the second matrix:
33
Matrix multiplication is not possible. Number of columns in the first matrix must be equal to the
number of rows in the second matrix.

C:\Users\JAYAVARDHANARAO S\Desktop>a
Enter the number of rows and columns for the first matrix:
22
Enter the number of rows and columns for the second matrix:
22
Enter elements of the first matrix:
34 45 23 54
Enter elements of the second matrix:
23 34 45 53
Result of matrix
multiplication: 2807
3541
2959 3644

Jayavardhanarao Sahukaru @ aitam 134


AITAM Data Structures I-I MCA (AR-24)

Example – 6: Program to perform Transpose of a matrix.


#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10
int main() {
int matrix[MAX_ROWS][MAX_COLS], transpose[MAX_COLS][MAX_ROWS];
int rows, cols;
// Input the matrix size (rows and columns)
printf("Enter the number of rows (max %d): ", MAX_ROWS);
scanf("%d", &rows);
printf("Enter the number of columns (max %d): ", MAX_COLS);
scanf("%d", &cols);
// Input the elements of the matrix
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j)
{ printf("Enter element [%d][%d]: ", i ,
j);
scanf("%d", &matrix[i][j]);
}
}
// Transpose the matrix
for (int i = 0; i < rows; ++i)
{ for (int j = 0; j < cols; ++j)
{
transpose[j][i] = matrix[i][j];
}
}
// Display the original matrix
printf("\nOriginal Matrix:\n");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) { printf("%d\
t", matrix[i][j]);
}
printf("\n");
}
// Display the transposed matrix
printf("\nTransposed Matrix:\n");
for (int i = 0; i < cols; ++i) {
for (int j = 0; j < rows; ++j) { printf("%d\
t", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Jayavardhanarao Sahukaru @ aitam 135
AITAM Data Structures I-I MCA (AR-24)

Output:
C:\Users\JAYAVARDHANARAO S\Desktop>a
Enter the number of rows (max 10): 4
Enter the number of columns (max 10): 5
Enter the elements of the matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [0][3]: 4
Enter element [0][4]: 5
Enter element [1][0]: 6
Enter element [1][1]: 7
Enter element [1][2]: 8
Enter element [1][3]: 9
Enter element [1][4]: 0
Enter element [2][0]: 9
Enter element [2][1]: 8
Enter element [2][2]: 7
Enter element [2][3]: 6
Enter element [2][4]: 5
Enter element [3][0]: 4
Enter element [3][1]: 3
Enter element [3][2]: 2
Enter element [3][3]: 1
Enter element [3][4]: 2

Original Matrix:
1 2 3 4 5
6 7 8 9 0
9 8 7 6 5
4 3 2 1 2

Transposed Matrix:
1 6 9 4
2 7 8 3
3 8 7 2
4 9 6 1
5 0 5 2

Jayavardhanarao Sahukaru @ aitam 136


AITAM Data Structures I-I MCA (AR-24)

3D Arrays:
In C programming, you can create an array of arrays. These arrays are known as multidimensional
arrays.
you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
Here, the array y can hold 24 elements.
Initialization of a 3d array
You can initialize a three-dimensional array in a similar way to a two-dimensional array. Here's an
example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example – 1: C Program to read and print 3D array.


#include <stdio.h>
int main()
{
int test[2][3][2];

printf("Enter values for 3D array: \n");

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


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("Enter values for test[%d][%d][%d]: ",i,k,j);
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with the proper index.

printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)

Jayavardhanarao Sahukaru @ aitam 137


AITAM Data Structures I-I MCA (AR-24)

{
printf("%d\t",test[i][j][k]);
}
printf("\n");
}
printf("\n");
}

return 0;
}

Output:
Enter values for 3D array:
Enter values for test[0][0][0]: 1
Enter values for test[0][1][0]: 2
Enter values for test[0][0][1]: 3
Enter values for test[0][1][1]: 4
Enter values for test[0][0][2]: 5
Enter values for test[0][1][2]: 6
Enter values for test[1][0][0]: 7
Enter values for test[1][1][0]: 8
Enter values for test[1][0][1]: 9
Enter values for test[1][1][1]: 10
Enter values for test[1][0][2]: 11
Enter values for test[1][1][2]: 12
Displaying values:
1 2
3 4
5 6

7 8
9 10
11 12

Jayavardhanarao Sahukaru @ aitam 138


AITAM Data Structures I-I MCA (AR-24)

FUNCTIONS
Definition:
Functions in C are the basic building blocks of a C program. A function is a set of statements enclosed
within curly brackets ({}) that take inputs, do the computation, and provide the resultant output. You
can call a function multiple times, thereby allowing reusability and modularity in C programming. It
means that instead of writing the same code again and again for different arguments, you can simply
enclose the code and make it a function and then call it multiple times by merely passing the various
arguments.
Why Do We Need Functions in C Programming?

We need functions in C programming and even in other programming languages due to the numerous
advantages they provide to the developer. Some of the key benefits of using functions are:

 Enables reusability and reduces redundancy.


 Makes a code modular.
 Provides abstract functionality.
 The program becomes easy to understand and manage.
 Breaks an extensive program into smaller and simpler pieces.
Function Aspects:

There are three aspects of a C function.

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.

return_type function_name (argument list);

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.

function_name (argument_list)

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.

return_type function_name (argument list)


{
function body;
}
Declaration:
The syntax of creating function in c language is

return_type function_name(data_type parameter1, data_type parameter2....)

Jayavardhanarao Sahukaru @ aitam 139


AITAM Data Structures I-I MCA (AR-24)

//code to be executed

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

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.

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.

Example without return value:

void hello()

{ printf("hello

c");

Example with return value:

int get()

{ return

10;

Jayavardhanarao Sahukaru @ aitam 140


AITAM Data Structures I-I MCA (AR-24)

Parameter Passing:

In programming, argument refers to the variable passed to the function. In the above example, two
variables n1 and n2 are passed during the function call.

The parameters a and b accepts the passed arguments in the function definition. These arguments are
called formal parameters of the function.

The type of arguments passed to a function and the formal parameters must match, otherwise, the
compiler will throw an error.

If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of
float type.

A function can also be called without passing an argument.

Jayavardhanarao Sahukaru @ aitam 141


AITAM Data Structures I-I MCA (AR-24)

Example-1: C program to display maximum of two numbers using function.


#include <stdio.h>
// Function declaration
int max_Num(int i, int j)
{
// Function definition

if (i > j)
return i;
else
return j;
}
// The main function.

int main()
{
int x,y,m;
printf("Enter two numbers: ");
scanf("%d%d",&x,&y);
// Calling the function to find the greater number among the two
m = max_Num(x, y);
printf("The bigger number is %d", m);
return 0;
}

Output:

Enter two numbers: 89 10


The bigger number is 89
Enter two numbers: 67 89
The bigger number is 89
Example-2: C program to perform addition of two numbers using function.
#include <stdio.h>
// Function declaration
int add(int i, int j){
// Function definition
return i+j;
}
// The main function. We will discuss about it later
int main(){
int x,y,result;
printf("Enter two numbers to perform addition: ");
scanf("%d%d",&x,&y);
// Calling the function to find the greater number among the two
result = add(x, y);
printf("The sum of %d and %d is %d", x,y,result);
return 0;
}
Output:

Enter two numbers to perform addition: 34 89


The sum of 34 and 89 is 123

Jayavardhanarao Sahukaru @ aitam 142


AITAM Data Structures I-I MCA (AR-24)

Example-3: C program to perform addition, subtraction and multiplication of two numbers


using function.

#include <stdio.h>

int add(int i, int j){


// Function definition
return i+j;
}

int sub(int i, int j){


// Function definition
return i-j;
}

int mul(int i, int j){


// Function definition
return i*j;
}

// The main function. We will discuss about it later


int main(){
int x,y,s,d,m;
printf("Enter two numbers to perform operations: "); scanf("%d
%d",&x,&y);
// Calling the function to find the greater number among the two
s = add(x, y);
d = sub(x, y);
m = mul(x, y);
printf("The sum of %d and %d is %d", x,y,s); printf("\
nThe difference of %d and %d is %d", x,y,d); printf("\
nThe product of %d and %d is %d", x,y,m); return 0;
}

Output:

Enter two numbers to perform operations: 23 20


The sum of 23 and 20 is 43
The difference of 23 and 20 is 3
The product of 23 and 20 is 460

Jayavardhanarao Sahukaru @ aitam 143


AITAM Data Structures I-I MCA (AR-24)

Example-4: C program to demonstrate the inclusion of a function from stored file.

int add(int i, int j){


// Function definition
return i+j;
}
Store the above code with “filename.c”, Eg: a.c and use the above stored
file like below

#include <stdio.h>
#include “a.c”

int sub(int i, int j){


// Function definition
return i-j;
}

int mul(int i, int j){


// Function definition
return i*j;
}

// The main function. We will discuss about it later


int main(){
int x,y,s,d,m;
printf("Enter two numbers to perform operations: "); scanf("%d
%d",&x,&y);
// Calling the function to find the greater number among the two
s = add(x, y);
d = sub(x, y);
m = mul(x, y);
printf("The sum of %d and %d is %d", x,y,s); printf("\
nThe difference of %d and %d is %d", x,y,d); printf("\
nThe product of %d and %d is %d", x,y,m); return 0;
}

Output:

Enter two numbers to perform operations: 23 20


The sum of 23 and 20 is 43
The difference of 23 and 20 is 3
The product of 23 and 20 is 460

Jayavardhanarao Sahukaru @ aitam 144


AITAM Data Structures I-I MCA (AR-24)

Example-5: C program which takes an integer and returns reverse of it.

#include <stdio.h>
int rev(int n)
{
int s=0;
while(n)
{
s=(s*10)+(n%10);
n=n/10;
}
return s;
}
int main() {
int n,r;
printf("Enter an integer: ");
scanf("%d",&n);
r=rev(n);
printf("%d reverse no is %d", n,r);
return 0;
}

Output:
Enter an integer: 87654
87654 reverse no is 45678

Example-6: C program which takes an integer and returns the factorial of the same.

#include <stdio.h>
int fact(int n)
{
int f=1;
while(n>=1)
{
f=f*n;
n--;
}
return f;
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d",&num);
printf("%d! = %d", num,fact(num));
return 0;
}

Jayavardhanarao Sahukaru @ aitam 145


AITAM Data Structures I-I MCA (AR-24)

Output:
Enter an integer: 7
7! = 5040

Example-7: C program which takes a string and returns reverse of it.

#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string: ");
scanf("%s",&s);
// Calculating string length
while (s[count] != '\0')
count++;
end = count - 1;
for (begin = 0; begin < count; begin++)
{ r[begin] = s[end];
end--;
}
//r[begin] = '\0';
printf("\nThe reverse string is %s\n", r);
return 0;
}

Output:

Input a string: sahukaru

The reverse string is urakuhas

Jayavardhanarao Sahukaru @ aitam 146


AITAM Data Structures I-I MCA (AR-24)

Example-8: Write a program in C to check whether a number is a prime or not using the
function.

//3.a. program in C to check whether a number is a prime or not using the function

include<stdio.h>
int main()
{
int n,i,count=0;
printf("Enter a number: ");
scanf("%d",&n);
if (n <= 1)
{
count++; // Not prime
}
for(i=2; i<n; i++)
{
if(n%2==0)
{
count++;
break;
}
}
if(count==0)
printf("%d is a prime number\n",n);
else
printf("%d is not a prime number\n",n);
return 0;
}

Output:

Jayavardhanarao Sahukaru @ aitam 147


AITAM Data Structures I-I MCA (AR-24)

Example-9: Write recursive program which computes the nth Fibonacci number, for
appropriate values of n.

// 3.b. recursive program which computes the nth Fibonacci number,


for appropriate values
of n.
include<stdio.h>
int fib(int n)
{
if(n==1)
return 0;
if(n==2)
return 1;
else
return fib(n-1) + fib(n-2);
}
int main()
{
int x;
printf("Enter value of n: ");
scanf("%d",&x);
if(x<=0)
printf("Fibonacci is not defined for zero or negative
numbers.\n");
else
printf("The %dth Fibonacci number is %d",x,fib(x));
return 0;
}
Output:

Jayavardhanarao Sahukaru @ aitam 148


AITAM Data Structures I-I MCA (AR-24)

Call by value and Call by reference:


There are two methods to pass the arguments into the function in C language, i.e., call by value and call
by reference.

Call by value in C

• 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.
• In call by value method, we cannot modify the value of the actual parameter by the formal
parameter.
• 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.
• 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.
Example:

#include<stdio.h>
void swap(int n1, int n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
int main() {
int x,y;
printf("Enter two numbers: ");
scanf("%d%d",&x,&y);
printf("The numbers before swapping n1=%d and n2=%d\n",x, y);
swap(x, y);
printf("The numbers after swapping n1=%d and n2=%d\n",x, y);
return 0;
}
Jayavardhanarao Sahukaru @ aitam 149
AITAM Data Structures I-I MCA (AR-24)

Output:
Enter two numbers: 20 60
The numbers before swapping n1=20 and n2=60
The numbers after swapping n1=20 and n2=60

Call by reference in C
• In call by reference, the address of the variable is passed into the function call as the actual
parameter.
• The value of the actual parameters can be modified by changing the formal parameters since
the address of the actual parameters is passed.
• 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.
Example:
#include<stdio.h>
void swap(int *n1 ,int *n2)
{
int temp = *n1;
*n1 = *n2;
*n2 = temp;
}
int main() {
int n1,n2;
printf("Enter two numbers: ");
scanf("%d%d",&n1,&n2);
printf("The numbers before swapping n1=%d and n2=%d\n",n1, n2);
swap(&n1, &n2);
printf("The numbers after swapping n1=%d and n2=%d",n1, n2);
return 0;
}

Output:
Enter two numbers: 10 30
The numbers before swapping n1=10 and n2=30
The numbers after swapping n1=30 and n2=10

Jayavardhanarao Sahukaru @ aitam 150


AITAM Data Structures I-I MCA (AR-24)

Scope and lifetime of variables


The scope of a variable in C is the block or the region in the program where a variable is declared,
defined, and used. Outside this region, we cannot access the variable and it is treated as an undeclared
identifier.
 The scope is the area under which a variable is visible.
 The scope of an identifier is the part of the program where the identifier may directly be
accessible.
 We can only refer to a variable in its scope.
Example:

// C program to illustrate the scope of a variable


#include <stdio.h>
int main()
{
// Scope of this variable is within main() function
// only.
int var = 34;
printf("%d", var);
return 0;
}
// function where we try to access the var defined in main()
void func()
{
printf("%d", var);
}

Output:
It will display error, because we cannot access variable named ‘var’ out side of the main function i,e in
‘void func()’ as it is local variable to main().

Types of Scope Rules in C

C scope rules can be covered under the following two categories:


1. Global Scope
2. Local Scope
1. Global Scope in C

The global scope refers to the region outside any block or function.

• The variables declared in the global scope are called global variables.
• Global variables are visible in every part of the program.
• Global is also called File Scope as the scope of an identifier starts at the beginning of the file
and ends at the end of the file.

Jayavardhanarao Sahukaru @ aitam 151


AITAM Data Structures I-I MCA (AR-24)

Example:

// C program to illustrate the global scope


#include <stdio.h>
// variable declared in global scope
int global = 5;
// global variable accessed from
// within a function
void display()
{
printf("%d\n", global);
}
// main function
int main()
{
printf("Before change within main: ");
display();

// changing value of global


// variable from main function
printf("After change within main: ");
global = 10;
display();
}

Output:
Before change within main: 5
After change within main: 10

2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space enclosed between the { }
braces.

The variables declared within the local scope are called local variables.
Local variables are visible in the block they are declared in and other blocks nested inside that block.
Local scope is also called Block scope.
Local variables have internal linkage.

Jayavardhanarao Sahukaru @ aitam 152


AITAM Data Structures I-I MCA (AR-24)

Example:

// C program to illustrate the local scope


#include <stdio.h>
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains
// declaration of x and
// y, so following statement
// is valid and prints
// 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again,
// so outer block y is
// not accessible in this block
int y = 40;

// Changes the outer block


// variable x to 11
x++;

// Changes this block's


// variable y to 41
y++;

printf("x = %d, y = %d\n", x, y);


}

// This statement accesses


// only outer block's
// variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}

Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20

Jayavardhanarao Sahukaru @ aitam 153


AITAM Data Structures I-I MCA (AR-24)

Passing Arrays to functions:

In C programming, you can pass an entire array to functions. Before we learn that, let’s see how you
can pass individual elements of an array to functions.

Pass Individual Array Elements

Passing array elements to a function is similar to passing variables to a function.

Example 1: Pass Individual Array Elements

#include <stdio.h>
void display(int age1, int age2)
{ printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int age[] = {20, 18, 14, 22};

// pass second and third elements to display()


display(age[1], age[2]);
return 0;
}

Output:
18
14

Here, we have passed array parameters to the display() function in the same way we pass variables to
a function.

Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
Jayavardhanarao Sahukaru @ aitam 154
AITAM Data Structures I-I MCA (AR-24)

float calculateSum(float num[])


{ float sum = 0.0;

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


{ sum += num[i];
}

return sum;
}

Output:
Result = 162.50

To pass an entire array to a function, only the name of the array is passed as an argument.

Pass Multidimensional Arrays to a Function

To pass multidimensional arrays to a function, only the name of the array is passed to the function
(similar to one-dimensional arrays).

Example 3: Pass two-dimensional arrays

#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j)
{ scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);

return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
{ for (int j = 0; j < 2; ++j)
{
printf("%d\n", num[i][j]);
}
}
}

Jayavardhanarao Sahukaru @ aitam 155


AITAM Data Structures I-I MCA (AR-24)

Output:
Enter 4 numbers:
12
45
89
47
Displaying:
12
45
89
47
Notice the parameter int num[2][2] in the function prototype and function definition:

// function prototype
void displayNumbers(int num[2][2]);

This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays
with more than 2 dimensions as a function argument.
When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.

For example,
void displayNumbers(int num[][2]) {
// code
}

Recursion:
Recursion is a process in which a function calls itself repeatedly until some specified condition is
satisfied.

How recursion works?

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

Jayavardhanarao Sahukaru @ aitam 156


AITAM Data Structures I-I MCA (AR-24)

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call, and other doesn't.

Example - 1: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n)
{
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Output:

Enter a positive integer: 10


sum = 55

Jayavardhanarao Sahukaru @ aitam 157


AITAM Data Structures I-I MCA (AR-24)

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to the sum()
function. This process continues until n is equal to 0.

When n is equal to 0, the if condition fails and the else part is executed returning the sum of integers
ultimately to the main() function.

Jayavardhanarao Sahukaru @ aitam 158


AITAM Data Structures I-I MCA (AR-24)

Example-2: Create a program that computes the factorial of a number. (Calculating factorial
using recirsion)
 Take an input number from the user
 Create a function that takes the number as a parameter.
 Inside the function check if the number is greater than 0.
 If true, return number multiplied by a recursive call to the function with parameter 1 less than
number
 Else, return 1
#include <stdio.h>
int fact (int n);
int main()
{
int number;
printf("Enter any number: ");
scanf("%d", &number);
if(number >= 0)
{
int result = fact(number);
printf("The Factorial is : %d", result);
}
else
{
printf("Enter positive value");
}
return 0;
}
int fact (int n)
{
if(n == 1 || n==0)
{
return 1;
}
else
{
return n * fact(n-1);
}
}
Output:

Enter any number: 6


The Factorial is : 720

Enter any number: 0


The Factorial is : 1

Enter any number: -2


Enter positive value
Jayavardhanarao Sahukaru @ aitam 159
AITAM Data Structures I-I MCA (AR-24)

Example-3: C program to find sum of digits of a given number using recursion.

#include <stdio.h>
int sumOfDigits(int num)
{
if (num < 10)
{
return num;
}
else
{
return num % 10 + sumOfDigits(num / 10);
}
}
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
int sum = sumOfDigits(number);
printf("Sum of digits: %d\n", sum);
return 0;
}

Output:

Enter a number: 3454


Sum of digits: 16

Enter a number: 9
Sum of digits: 9

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is
usually much slower.
That being said, recursion is an important concept. It is frequently used in data structure and
algorithms. For example, it is common to use recursion in problems such as tree traversal.

Jayavardhanarao Sahukaru @ aitam 160


AITAM Data Structures I-I MCA (AR-24)

Command line arguments

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.

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.

#include <stdio.h>
int main(int argc, char *argv[]) {
// Write C code here
printf("Number of arguments %d\n", argc);
printf("first arguement %s", argv[0]);
return 0;
}

Output:

Example: C program to calculate factorial using command line arguments.

#include <stdio.h>
#include <stdlib.h>
int factorial(int n) {
if (n == 0 || n == 1)
{ return 1;
} else {
return n * factorial(n - 1);
}
}
int main(int argc, char *argv[])
{ if (argc != 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1; // Return error code
}
int number = atoi(argv[1]);
if (number < 0) {
printf("Please enter a non-negative integer.\n");

Jayavardhanarao Sahukaru @ aitam 161


AITAM Data Structures I-I MCA (AR-24)

return 1; // Return error code


}
printf("The factorial of %d is: %d\n", number, factorial(number));
return 0; // Return success code
}

Output:

Storage classes

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

 Automatic
 External
 Static
 Register

Automatic
• Automatic variables are allocated memory automatically at runtime.
• 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.
• The automatic variables are initialized to garbage by default.

Jayavardhanarao Sahukaru @ aitam 162


AITAM Data Structures I-I MCA (AR-24)

• The memory assigned to automatic variables gets freed upon exiting from the block.
• The keyword used for defining automatic variables is auto.
• Every local variable is automatic in C by default.

Example-1:

#include <stdio.h>
int main()
{
int a;
//auto char
b; float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic
variables a, b, and c.
return 0;
}

Output:

Example-2:

#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local
value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is
ended.
}

Output:
11 20 20 20 11

Jayavardhanarao Sahukaru @ aitam 163


AITAM Data Structures I-I MCA (AR-24)

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

Example:

#include <stdio.h>
void display();

int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}

Output:
6 11

Register
• 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.
• We can not dereference the register variables, i.e., we can not use &operator for the register
variable.
• The access time of the register variables is faster than the automatic variables.
• The initial default value of the register local variables is 0.
• 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.
• We can store pointers into the register, i.e., a register can store the address of a variable.
• Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.

Jayavardhanarao Sahukaru @ aitam 164


AITAM Data Structures I-I MCA (AR-24)

Example:

#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register.
The initial default value of a is 0.
printf("%d",a);
}

Output:
0

External
• 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.
• 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.
• The default initial value of external integral type is 0 otherwise null.
• We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
• An external variable can be declared many times but can be initialized at only once.
• 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:

#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and
initialized somewhere in the pogram or not.
printf("%d",a);
}
int a = 20;

Output:
20

Jayavardhanarao Sahukaru @ aitam 165


AITAM Data Structures I-I MCA (AR-24)

Structures:
Definition:
In C programming, a struct (or structure) is a collection of variables (can be of different types) under a
single name.

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:

 Construct individual arrays for storing names, roll numbers, and marks.
 Use a special data structure to store the collection of different data types.
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.

Declaration:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Example:

struct employee

{ int id;

char name[20];

float salary;

};

The following image shows the memory allocation of the structure employee that is defined in the
above example.

Jayavardhanarao Sahukaru @ aitam 166


AITAM Data Structures I-I MCA (AR-24)

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:

By struct keyword within main() function

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.

struct employee

{ int id;

char name[50];

float salary;

Jayavardhanarao Sahukaru @ aitam 167


AITAM Data Structures I-I MCA (AR-24)

};

Now write given code inside the main() function.

struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

struct employee

{ int id;

char name[50];

float salary;

}e1,e2;

Which approach is good

 If number of variables are not fixed, use the 1st approach. It provides you the flexibility
to declare the structure variable many times.
 If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in
main() function.

Accessing Structure Elements:


There are two ways to access structure members:

By . (member or dot operator)

By -> (structure pointer operator)

Example: (Accessing using dot operator)

#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1;

// Accessing structure members


strcpy(person1.name, "Jayavardhan");
person1.age = 35;
person1.height = 5.10;

// Printing structure member values

Jayavardhanarao Sahukaru @ aitam 168


AITAM Data Structures I-I MCA (AR-24)

printf("Name: %s\n", person1.name);


printf("Age: %d\n", person1.age);
printf("Height: %.2f \n", person1.height);

return 0;
}

Output:

Name: Jayavardhan

Age: 35

Height: 5.10

Example: Accessing Structure Members through Pointers

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

struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1;

// Declare a pointer to a structure


struct Person *personPtr;

// Assign the address of person1 to the pointer


personPtr = &person1;

// Accessing structure members through


pointer strcpy(personPtr->name,
"Jayavardhan");
personPtr->age = 35;
personPtr->height = 5.10;

// Printing structure member values


printf("Name: %s\n", personPtr->name);
printf("Age: %d\n", personPtr->age);
printf("Height: %.2f \n", personPtr->height);

return 0;
}
Output:

Name: Jayavardhan

Age: 35
Jayavardhanarao Sahukaru @ aitam 169
AITAM Data Structures I-I MCA (AR-24)

Height: 5.10

Array of structures:
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.

Example of an array of structures that stores information of 5 students and prints it.

#include<stdio.h>
#include
<string.h> struct
student{ int
rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno); printf("\
nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
Jayavardhanarao Sahukaru @ aitam 170
AITAM Data Structures I-I MCA (AR-24)

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:

Enter Records of 5 students

Enter Rollno:1

Enter Name:Jayavardhan

Enter Rollno:2

Enter Name:Teja

Enter Rollno:3

Enter Name:Sakuntala

Enter Rollno:4

Enter Name:Raghav

Enter Rollno:5

Enter Name:Saritha

Student Information List:

Rollno:1, Name:Jayavardhan

Rollno:2, Name:Teja

Rollno:3, Name:Sakuntala

Rollno:4, Name:Raghav

Rollno:5, Name:Saritha

Jayavardhanarao Sahukaru @ aitam 171


AITAM Data Structures I-I MCA (AR-24)

Array within Structure:


The structure is a collection of the different data types. Like normal data types, It can also store an
array as well. In arrays within the structure, the member of the structure is an array.

Syntax:

struct struct-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
----------
datatype varN;
};
struct struct-name obj;

Example:

#include<stdio.h>
#include<string.h>
struct Student
{
int Roll;
char Name[10];
int Marks[3]; //array of marks
int Total;
float Avg;
};
void main()
{
int i;
struct Student S;
printf("\n\nEnter Student Roll : ");
scanf("%d",&S.Roll); printf("\n\
nEnter Student Name : ");
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
{
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3; printf("\
nRoll : %d",S.Roll); printf("\
nName : %s",S.Name); printf("\
nTotal : %d",S.Total);

Jayavardhanarao Sahukaru @ aitam 172


AITAM Data Structures I-I MCA (AR-24)

printf("\nAverage : %f",S.Avg);
}

Output:

Enter Student Roll : 101

Enter Student Name : Jayavardhan

Enter Marks 1 : 90

Enter Marks 2 : 56

Enter Marks 3 : 85

Roll : 101

Name : Jayavardhan

Total : 231

Average : 77.000000

Pointer to structure:
The structure pointer points to the address of a memory block where the Structure is being stored.
Like a pointer that tells the address of another variable of any data type (int, char, float) in memory.
And here, we use a structure pointer which tells the address of a structure in memory by pointing
pointer variable ptr to the structure variable.

Declare a Structure Pointer

The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can
declare the structure pointer and variable inside and outside of the main() function. To declare a
pointer variable in C, we use the asterisk (*) symbol before the variable's name.

struct structure_name *ptr;

After defining the structure pointer, we need to initialize it, as the code is shown:

Initialization of the Structure Pointer

ptr = &structure_variable;

We can also initialize a Structure Pointer directly during the declaration of a pointer.

struct structure_name *ptr = &structure_variable;

As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.

Access Structure member using pointer:

There are two ways to access the member of the structure using Structure pointer:

 Using ( * ) asterisk or indirection operator and dot ( . ) operator.

Jayavardhanarao Sahukaru @ aitam 173


AITAM Data Structures I-I MCA (AR-24)

 Using arrow ( -> ) operator or membership operator.


Example – 1:

Program to access the structure member using structure pointer and the dot operator.

#include <stdio.h>
#include <string.h>
// create a structure Subject using the struct keyword
struct Subject
{
// declare the member of the Course structure
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};
int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = &sub; /* ptr variable pointing to the address of the structure
variable sub */
strcpy (sub.sub_name, " Computer Science");
sub.sub_id = 1201;
strcpy (sub.sub_duration, "6 Months");
strcpy (sub.sub_type, " Multiple Choice question");
// print the details of the Subject;
printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
printf (" \n Duration of the Subject: %s\t ",
(*ptr).sub_duration);
printf (" \n Type of the Subject: %s\t ", (*ptr).sub_type);
return 0;
}

Output:

Subject Name: Computer Science

Subject Id: 1201

Duration of the Subject: 6 Months

Type of the Subject: Multiple Choice Question

In the above program, we have created the Subject structure that contains different data elements like
sub_name (char), sub_id (int), sub_duration (char), and sub_type (char). In this, the sub is the structure

Jayavardhanarao Sahukaru @ aitam 174


AITAM Data Structures I-I MCA (AR-24)

variable, and ptr is the structure pointer variable that points to the address of the sub variable like ptr
= &sub. In this way, each *ptr is accessing the address of the Subject structure's member.

Example – 2:

Program to access the structure member using structure pointer and arrow (->) operator

#include <stdio.h>
// create Employee structure
struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
// define the variables of the Structure with pointers
struct Employee emp1, emp2, *ptr1, *ptr2;
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;
printf (" Enter the name of the Employee (emp1): ");
scanf (" %s", &ptr1->name);
printf (" Enter the id of the Employee (emp1): ");
scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
printf (" Enter the gender of the Employee (emp1): ");
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);
printf (" \n Second Employee: \n");
printf (" Enter the name of the Employee (emp2): ");
scanf (" %s", &ptr2->name);
printf (" Enter the id of the Employee (emp2): ");
scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2): ");
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);

Jayavardhanarao Sahukaru @ aitam 175


AITAM Data Structures I-I MCA (AR-24)

printf ("\n Display the Details of the Employee using Structure


Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);
printf ("\n Details of the Employee (emp2) \n");
printf(" Name: %s\n", ptr2->name);
printf(" Id: %d\n", ptr2->id);
printf(" Age: %d\n", ptr2->age);
printf(" Gender: %s\n", ptr2->gender);
printf(" City: %s\n", ptr2->city);
return 0;
}

Output:

Enter the name of the Employee (emp1): Jayavardhan


Enter the id of the Employee (emp1): 101
Enter the age of the Employee (emp1): 35
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): Tekkali
Second Employee:
Enter the name of the Employee (emp2): Teja
Enter the id of the Employee (emp2): 102
Enter the age of the Employee (emp2): 33
Enter the gender of the Employee (emp2): Male
Enter the city of the Employee (emp2): Vizag
Display the Details of the Employee using Structure Pointer
Details of the Employee (emp1)
Name: Jayavardhan
Id: 101
Age: 35
Gender: Male
City: Tekkali

Details of the Employee


(emp2) Name: Teja
Id: 102
Age: 33
Gender: Male
City: Vizag

Jayavardhanarao Sahukaru @ aitam 176


AITAM Data Structures I-I MCA (AR-24)

Self-referential structure:
Self-Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-referential in nature.

Example:

struct node {
int data1;
char data2;
struct node*
link;
};

int main()
{
struct node ob;
return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is
a self-referential structure with ‘link’ as the referencing pointer.

An important point to consider is that the pointer should be initialized properly before accessing, as
by default it contains garbage value.

Jayavardhanarao Sahukaru @ aitam 177


AITAM Data Structures I-I MCA (AR-24)

Types of Self Referential Structures

 Self Referential Structure with Single Link


 Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-pointer as
their member. The following example will show us how to connect the objects of a self-referential
structure with the single link and access the corresponding data members. The connection formed is
shown in
the following figure.

#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1

// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1); printf("\n
%d", ob1.link->data2);
return 0;
}
Output:

30
Jayavardhanarao Sahukaru @ aitam 178
AITAM Data Structures I-I MCA (AR-24)

40
Self Referential Structure with Multiple Links: Self referential structures with multiple links can
have more than one self-pointers. Many complicated data structures can be easily constructed using
these structures. Such structures can easily connect to more than one nodes at a time. The following
example shows one such structure with more than one links.

The connections made in the above example can be understood using the following figure.

Example:

#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
struct node ob2; // Node2
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
struct node ob3; // Node3

// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

Jayavardhanarao Sahukaru @ aitam 179


AITAM Data Structures I-I MCA (AR-24)

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

Output:

10 20 30

10 20 30

10 20 30

Passing Structure to a function:


 A structure can be passed to any function from main function or from any sub function.
 Structure definition will be available within the function only.
 It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
 Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the
functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:

It can be done in below 3 ways.

 Passing structure to a function by value


 Passing structure to a function by address(reference)
 No need to pass a structure – Declare structure variable as global
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY VALUE:

In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.

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

Jayavardhanarao Sahukaru @ aitam 180


AITAM Data Structures I-I MCA (AR-24)

{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Jayavardhan");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Output:

Id is: 1

Name is: Jayavardhan

Percentage is: 86.500000

EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:

In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function by
its address.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);

Jayavardhanarao Sahukaru @ aitam 181


AITAM Data Structures I-I MCA (AR-24)

int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Jayavardhan");
record.percentage = 86.5;
func(&record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Output:

Id is: 1

Name is: Jayavardhan

Percentage is: 86.500000

EXAMPLE PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL IN C:

Structure variables also can be declared as global variables as we declare other variables in C. So,
When a structure variable is declared as global, then it is visible to all the functions in a program. In
this scenario, we don’t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Jayavardhan");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()

Jayavardhanarao Sahukaru @ aitam 182


AITAM Data Structures I-I MCA (AR-24)

{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Output:

Id is: 1

Name is: Jayavardhan

Percentage is: 86.500000

Nested structures:
C provides us with 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.
Example:

#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee Name, City, Pin and Phone Number?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin,
emp.add.phone);
printf("Printing the employee information........\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:
%s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}

Jayavardhanarao Sahukaru @ aitam 183


AITAM Data Structures I-I MCA (AR-24)

Output:

Enter employee Name, City, Pin and Phone Number?

Jayavardhan Tekkali 532201 9999999999

Printing the employee information. name: Jayavardhan

City: Tekkali

Pincode: 532201

Phone: 9999999999

The structure can be nested in the following ways.

 By separate structure
 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.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}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.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;

Jayavardhanarao Sahukaru @ aitam 184


AITAM Data Structures I-I MCA (AR-24)

int yyyy;
}doj;
}emp1;

Accessing Nested Structure

We can access the member of the nested structure by Outer_Structure.Nested_Structure.member as


given below:

e1.doj.dd

e1.doj.mm

e1.doj.yyyy

Example:

#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Jayavardhanarao");//copying string into char array
e1.doj.dd=29;
e1.doj.mm=12;
e1.doj.yyyy=2021;

//printing first employee information


printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",
e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}

Jayavardhanarao Sahukaru @ aitam 185


AITAM Data Structures I-I MCA (AR-24)

Output:

employee id : 101

employee name : Jayavardhanarao

employee date of joining (dd/mm/yyyy) : 29/12/2021

Unions in C:
A union is a user-defined type similar to structs in C except for one key difference.

Structures allocate enough space to store all their members, whereas unions can only hold one
member value at a time.

How to define a union?

We use the union keyword to define unions. Here's an example:

union car

char name[50];

int price;

};

The above code defines a derived type union car.

Create union variables

When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate
memory for a given union type and work with it, we need to create variables.

Here's how we create union variables.

union car

char name[50];

int price;

};

int main()

union car car1, car2, *car3;

return 0;

Jayavardhanarao Sahukaru @ aitam 186


AITAM Data Structures I-I MCA (AR-24)

Another way of creating union variables is:

union car

char name[50];

int price;

} car1, car2, *car3;

In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.

Access members of a union

We use the . operator to access members of a union. And to access pointer variables, we use the ->
operator.

In the above example,

To access price for car1, car1.price is used.

To access price using car3, either (*car3).price or car3->price can be used.

Difference between unions and structures

Let's take an example to demonstrate the difference between unions and structures:

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}

Output:

size of union = 32 bytes

Jayavardhanarao Sahukaru @ aitam 187


AITAM Data Structures I-I MCA (AR-24)

size of structure = 40 bytes

Why this difference in the size of union and structure variables?

Here, the size of sJob is 40 bytes because

the size of name[32] is 32 bytes

the size of salary is 4 bytes

the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of
its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes.

With a union, all members share the same memory.

Example: Accessing Union Members:

#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f \n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}

Output:

Salary = 0.0

Number of workers = 100

Jayavardhanarao Sahukaru @ aitam 188


AITAM Data Structures I-I MCA (AR-24)

Dynamic memory allocation:


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.

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:

ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
Jayavardhanarao Sahukaru @ aitam 189
AITAM Data Structures I-I MCA (AR-24)
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc

Jayavardhanarao Sahukaru @ aitam 190


AITAM Data Structures I-I MCA (AR-24)

if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
for(i=1;i<=n;++i)
{
printf("Enter element %d of the array: ",i);
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

Output:

Enter number of elements: 6

Enter element 1 of the array: 12

Enter element 2 of the array: 23

Enter element 3 of the array: 23

Enter element 4 of the array: 45

Enter element 5 of the array: 65

Enter element 6 of the array: 43

Sum=211
calloc() function in C

 The calloc() function allocates multiple block of requested memory.


 It initially initialize all bytes to zero.
 It returns NULL if memory is not
sufficient. The syntax of calloc() function is given
below:
ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
Jayavardhanarao Sahukaru @ aitam 191
AITAM Data Structures I-I MCA (AR-24)

ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc


if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
for(i=1;i<=n;++i)
{
printf("Enter element %d of the array: ",i);
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

Output:

Enter number of elements: 6

Enter element 1 of the array: 12

Enter element 2 of the array: 34

Enter element 3 of the array: 45

Enter element 4 of the array: 56

Enter element 5 of the array: 67

Enter element 6 of the array: 78

Sum=292
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.

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.

free(ptr)

Jayavardhanarao Sahukaru @ aitam 192


AITAM Data Structures I-I MCA (AR-24)

POINTERS
Definition:
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. int n = 10;

int* p = &n; // p is of type pointer is pointing to the address of the variable n of type integer.

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to char

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.

Initializing a pointer:
When we declare a pointer variable, it does not automatically point to any particular memory
location. To initialize a pointer to point to a specific variable or memory location, we use the
ampersand & operator to get the address of that variable.

For example, to initialize the pointer p to point to an integer variable called x, we would

write: int x = 42;

int *p = &x;

This sets the value of p to be the memory address of x.

Jayavardhanarao Sahukaru @ aitam 193


AITAM Data Structures I-I MCA (AR-24)

Changing values pointed by pointers:

#include <stdio.h>
int main()
{
int *p, a;
a = 5;
p = &a;
a=1;
printf("%d\t%d", *p,p);
}

Output:

1 -1575739708

Identify errors in the following code statements.

Int *p,c;

p=c //Error

*p=&c //Error

p=&c; // No Error

*p=c //No Error

Example:

#include <stdio.h>
int main()
{
int *p, a;
a = 5;
p = &a;
printf("%d", *p); // Output: 5
}

Output:
5

Application of Pointers:

Finding the largest and smallest elements in the array using pointers

Jayavardhanarao Sahukaru @ aitam 194


AITAM Data Structures I-I MCA (AR-24)

Pointer arithmetic:
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:

Increment

Decrement

Addition

Subtraction

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:

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.

#include<stdio.h>

int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in
our case, p will get incremented by 4 bytes.

Jayavardhanarao Sahukaru @ aitam 195


AITAM Data Structures I-I MCA (AR-24)

return 0;
}
Output:

Address of p variable is 3749542724


After increment: Address of p variable is 3749542728

Traversing an array by using

pointer: Example-1:

#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}
Output:

printing array elements...

12345

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:

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.

#include <stdio.h>
void main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable

Jayavardhanarao Sahukaru @ aitam 196


AITAM Data Structures I-I MCA (AR-24)

printf("Address of p variable is %u \n",p);


p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P
will now point to the immidiate previous location.
}

Output:

Address of p variable is 1845100660

After decrement: Address of p variable is 1845100656

C Pointer Addition:
We can add a value to the pointer variable. The formula of adding value to pointer is given below:

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.

Example of adding value to pointer variable on 64-bit architecture.

#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output:
Address of p variable is 1597179572
After adding 3: Address of p variable is 1597179584

C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from
a pointer will give an address. The formula of subtracting value from the pointer variable is given
below:
new_address= current_address - (number * size_of(data type))

32-bit
Jayavardhanarao Sahukaru @ aitam 197
AITAM Data Structures I-I MCA (AR-24)

For 32-bit int variable, it will subtract 2 *

number. 64-bit
For 64-bit int variable, it will subtract 4 * number.

Example of subtracting value from the pointer variable on 64-bit architecture.


#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}

Output:
Address of p variable is 3505922836
After subtracting 3: Address of p variable is 3505922824

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,

Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points

Example to subtract one pointer from an another

#include<stdio.h>
void main ()
{
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
}

Output:
Pointer Subtraction: 1747757608 - 1747757596 = 3

Jayavardhanarao Sahukaru @ aitam 198


AITAM Data Structures I-I MCA (AR-24)

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.

 Address + Address = illegal


 Address * Address = illegal
 Address % Address = illegal
 Address / Address = illegal
 Address & Address = illegal
 Address ^ Address = illegal
 Address | Address = illegal
 ~Address = illegal

Functions and pointers:


We know that we can create a pointer of any data type such as int, char, float, we can also create a
pointer pointing to a function. The code of a function always resides in memory, which means that the
function has some address. We can get the address of memory by using the function pointer.

Example:

#include <stdio.h>
int main()
{
printf("Address of main() function is %p",main);
return 0;
}
Output:

Address of main() function is 0x401126

In the above output, we observe that the main() function has some address. Therefore, we conclude
that every function has some address.

Declaration of a function pointer

Syntax of function pointer

return type (*ptr_name)(type1, type2…);

For example:

int (*ip) (int);

In the above declaration, *ip is a pointer that points to a function which returns an int value and
accepts an integer value as an argument.

float (*fp) (float);

In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts
a float value as an argument.

Jayavardhanarao Sahukaru @ aitam 199


AITAM Data Structures I-I MCA (AR-24)

We can observe that the declaration of a function is similar to the declaration of a function pointer
except that the pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function
rather than a pointer.

float (*fp) (int , int); // Declaration of a function

pointer. float func( int , int ); // Declaration of

function.

fp = func; // Assigning address of func to the fp pointer.

Calling a function through a function pointer

We already know how to call a function in the usual way. Now, we will see how to call a function using
a function pointer.

Suppose we declare a function as given below:

float func(int , int); // Declaration of a function.

Calling an above function using a usual way is given

below:

result = func(a , b); // Calling a function using usual ways.

Calling a function using a function pointer is given below:

result = (*fp)( a , b); // Calling a function using function pointer.

Or

result = fp(a , b); // Calling a function using function pointer

Example:

#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add; result=(*ip)
(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
Jayavardhanarao Sahukaru @ aitam 200
AITAM Data Structures I-I MCA (AR-24)
return c;
}

Jayavardhanarao Sahukaru @ aitam 201


AITAM Data Structures I-I MCA (AR-24)

Output:

Enter the values of a and b : 10

20 Value after addition is : 30

Passing a function's address as an argument to other function

We can pass the function's address as an argument to other functions in the same way we send other
arguments to the function.

Example:

#include <stdio.h>
void func1(void (*ptr)());
void func2();
int main()
{
func1(func2);
return 0;
}
void func1(void (*ptr)())
{
printf("Function1 is called");
(*ptr)();
}
void func2()
{
printf("\nFunction2 is called");
}

Output:

Function1 is called

Function2 is called

Array and Function Pointers:


Function pointers are used in those applications where we do not know in advance which function
will be called. In an array of function pointers, array takes the addresses of different functions, and the
appropriate function will be called based on the index number.

Example:

#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()

Jayavardhanarao Sahukaru @ aitam 202


AITAM Data Structures I-I MCA (AR-24)

{
float x; // variable declaration.
int y;
float (*fp[4]) (float,int); // function pointer declaration.
fp[0]=add; // assigning addresses to the elements of an
array of a function pointer.
fp[1]=sub;
fp[2]=mul;
fp[3]=div;
printf("Enter the values of x and y :");
scanf("%f %d",&x,&y);
float r=(*fp[0]) (x,y); // Calling add() function.
printf("\nSum of two values is : %f",r);
r=(*fp[1]) (x,y); // Calling sub() function.
printf("\nDifference of two values is : %f",r);
r=(*fp[2]) (x,y); // Calliung sub() function.
printf("\nMultiplication of two values is : %f",r);
r=(*fp[3]) (x,y); // Calling div() function.
printf("\nDivision of two values is : %f",r);
return 0;
}

float add(float x,int y)


{
float a=x+y;
return a;
}
float sub(float x,int y)
{
float a=x-y;
return a;
}
float mul(float x,int y)
{
float a=x*y;
return a;
}
float div(float x,int y)
{
float a=x/y;
return a;
}

Output:

Enter the values of x and y :7 9

Jayavardhanarao Sahukaru @ aitam 203


AITAM Data Structures I-I MCA (AR-24)

Sum of two values is : 16.000000

Difference of two values is : -2.000000

Multiplication of two values is :

63.000000 Division of two values is :

0.777778

In the above code, we have created an array of function pointers that contain the addresses of four
functions. After storing the addresses of functions in an array of function pointers, we call the
functions using the function pointer.

Pointer to pointer (Double Pointer):


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.

int **p; // pointer to a pointer which is pointing to an integer.

Example:

#include<stdio.h>
void main ()
{
int a =
10; int
*p; int
**pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of
pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address
contained by p i.e. 10 will be printed
printf("value stored at pp: %d\n",**pp); // value stored at the
address contained by the pointer stoyred at pp
}

Jayavardhanarao Sahukaru @ aitam 204


AITAM Data Structures I-I MCA (AR-24)
Output:

Jayavardhanarao Sahukaru @ aitam 205


AITAM Data Structures I-I MCA (AR-24)

address of a: 88965f34

address of p:

88965f28 value stored

at p: 10

value stored at pp: 10

C double pointer

Example-1:

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",*p);
return 0;
}
Output:

Address of number variable is 1d8ec5e4


Address of p variable is 1d8ec5e4
Value of *p variable is 50 Address of p2 variable is 1d8ec5d8
Value of **p2 variable is 50

Example-2:

#include<stdio.h>
void main ()
{
int a[10] = {100, 206, 300, 409, 509, 601}; //Line 1
int *p[] = {a, a+1, a+2, a+3, a+4, a+5}; //Line 2
Jayavardhanarao Sahukaru @ aitam 206
AITAM Data Structures I-I MCA (AR-24)

int **pp = p; //Line 3 pp+


+; // Line 4
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 5
*pp++; // Line 6
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 7
++*pp; // Line 8
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 9
++**pp; // Line 10
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 11
}

Output:

1 1 206

2 2 300

2 3 409

2 3 410

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.

 a[0]: it is the simplest way to access the first element of the array
 *(a): since a store the address of the first element of the array, we can access its value by using
indirection pointer on it.
 *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].

Jayavardhanarao Sahukaru @ aitam 207


AITAM Data Structures I-I MCA (AR-24)

 **(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.

 pp = 302, p = 300 => pp-p = (302-300)/2 => pp-p = 1, i.e., 1 will be printed.
 pp = 302, *pp = 202, a = 200 => *pp - a = 202 - 200 = 2/2 = 1, i.e., 1 will be printed.
 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.

 pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
 pp = 304, *pp = 204, a = 200 => *pp-a = (204 - 200)/2 = 2, i.e., 2 will be printed.
 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.

 pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
 pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
 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.

 pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
 pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
Jayavardhanarao Sahukaru @ aitam 208
AITAM Data Structures I-I MCA (AR-24)

 On line 8, **pp = 410.


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

Features of Pointers:
 Pointers save memory space.
 Execution time with pointers is faster because data are manipulated with the address, that is,
direct access to memory location.
 Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory
as well. Hence it can be said the Memory of pointers is dynamically allocated.
 Pointers are used with data structures. They are useful for representing two-dimensional and
multi-dimensional arrays.
 An array, of any type, can be accessed with the help of pointers, without considering its
subscript range.
 Pointers are used for file handling.
 Pointers are used to allocate memory dynamically.

Uses of pointers:
 To pass arguments by reference
 For accessing array elements
 To return multiple values
 Dynamic memory allocation
 To implement data structures
 To do system-level programming where memory addresses are useful
Drawbacks of Pointers:

 If pointers are pointed to some incorrect location then it may end up reading a wrong value.
 Erroneous input always leads to an erroneous output
 Segmentation fault can occur due to uninitialized pointer.
 Pointers are slower than normal variable
 It requires one additional dereferences step
 If we forgot to deallocate a memory then it will lead to a memory leak.

Jayavardhanarao Sahukaru @ aitam 209

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy