DS - Unit - 1
DS - Unit - 1
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:
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.
int count = 0;
Syntax:
below: int a;
float
b;
char
c;
Here, a, b, and c are variables. The int, float, and char are the
char c='A';
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:
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.
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.
int age;
float salary;
char _status;
double
average_score; int
studentCount;
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.
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.
declaration is data_type
variable_name;
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.
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.
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
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(){
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.
void function1(){
Static Variable
A variable that is declared with the static keyword is called static variable. It retains its
value between multiple function calls.
void function1(){
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(){
variable
External Variable
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:
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.
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.
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them.
An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to hold
ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols, or
commas. There are 256 characters that can be represented by a single char, which
takes up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in
single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to
represent fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not
be very precise. It can store values with an accuracy of about 6 decimal places and a
range of about 3.4 x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is
needed, such as in scientific calculations or financial applications, it provides greater
accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
char grade =
'A';
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.
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
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.
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:
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.
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 (.)
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.
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
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)
Output:
Today is 2
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.
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:
Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
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.
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
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 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.
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.
The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).
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
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:
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;
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:
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:
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:
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:
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;
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
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
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)
Syntax:
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
Syntax:
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.
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.
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.
8 * (8/4)
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.
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
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.
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
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
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.
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
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.
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
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.
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.
Here's how you can take multiple inputs from the user and
Output
float: -3 3.4
%d for int
%f for float
%c for char
Here's a list of commonly used C data types and their format specifiers.
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.
1. if Statement
2. if-else Statement
3. nested if-else Statement
4. switch Statement
The if Statement:
if (condition) {
Example:
include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
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) {
else {
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:
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) {
true if (condition2) {
else {
else {
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:
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:
constant1 break;
case constant2:
constant2 break;
Jayavardhanarao Sahukaru @ aitam 47
AITAM Data Structures I-I MCA (AR-24)
// More cases...
default:
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
1. goto Statement
2. break Statement
3. continue Statement
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
Output:
Jayavardhanarao Sahukaru @ aitam 49
AITAM Data Structures I-I MCA (AR-24)
The value of num is 1.
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
syntax. break;
Example:
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
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.
Example:
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.
There are various advantages and disadvantages of the branching statements. Some
main advantages and disadvantages of the branching statements are as follows:
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 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.
Let's look at a few more instances to see how branching statements are used in various
contexts:
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:
20 Explanation:
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;
}
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.
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;
}
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.
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;
}
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.
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.
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
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or
linked lists).
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested
loop. It is used when it is necessary to execute the loop at least once (mostly menu
driven programs).
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.
below: while(condition){
Jayavardhanarao Sahukaru @ aitam 60
AITAM Data Structures I-I MCA (AR-24)
//code to be executed }
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.
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{
//code to be executed
}while(condition);
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() {
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.
execution. Output:
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.
Example 1:
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
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.
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
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
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.
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:
rows: 5 1
12
123
1234
12345
Explanation:
Here is a tabular comparison between the while loop and the do-while Loop in C:
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.
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.
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.
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.
1. while(condition){
2. //code to be executed
3. }
Test it Now
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++;
}
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
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
Example 3
include<stdio.h>
void main ()
{
int x = 10, y = 2;
while(x+y-1)
{
printf("%d %d",x--,y--);
}
}
Output
infinite loop
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.
2. //code to be executed
3. }
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
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
Expression 1.
Expression 1 is optional.
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 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.
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
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);
}
}
Outpu
t
20 20 20 20 20 20 20 20 20 20
To make a for loop infinite, we need not give any expression in the syntax. Instead of
that, we need to provide two semicolons to validate the syntax of the for loop. This will
work as an infinite for loop.
#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
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.
The nested for loop means any type of loop which is defined inside the
#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");
}
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.
Output:
The nested while loop means any type of loop which is defined inside the 'while'
loop. while(condition)
while(condition)
k++; // increment
counter j++;
}
i++;
printf("\n");
}
}
The nested do..while loop means any type of loop which is defined inside the
'do..while' loop. do
do
}while(condition);
#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:
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.
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
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.
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)
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.
#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
}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
// body statements.
goto infinite_loop;
In the above code, the goto statement transfers the control to the infinite loop.
Macros
We can also create the infinite loop with the help of a macro constant. Let's understand
through an example.
#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.
#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;
}
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.
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.
We use the wrong loop condition which causes the loop to be executed
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;
}
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.
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.
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
In conclusion, an infinite loop in C constitutes a looping construct that never ends and
keeps running forever. Different loop structures, such as the for loop, while loop, do-while
loop, goto statement, or C macros, can be used to produce it. Operating systems,
servers, and video games all frequently employ
infinite loops since they demand constant human input and output until manual
termination. On the other hand, the unintentional infinite loops might happen because of
code flaws, which are difficult to identify, especially for newcomers.
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:
2. With
loop Syntax:
break;
Flowchart of break in c
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
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.
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)
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) {
loop if (some_condition)
For loop
loop if (some_condition)
Example:
Let's take an example to understand the use of the break statement in simple loops in C:
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:
loop if (some_condition) {
break; // Exit both inner and outer loops if this condition is met
Example:
Let's take an example to understand the use of the break statement in nested loops in C:
Output
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:
Syntax:
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
Example:
Let's take an example to understand the use of the break statement in infinite loops in C:
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
Enter a number (0 to
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:
switch (expression)
{ case value1:
// More cases...
default:
Example:
Let's take an example to understand the use of the break statement in the switch case in
C:
#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)
}
return 0;
}
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.
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.
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;
#include<stdio.h>
void main ()
{
int i = 0;
while(i!=10)
{
printf("%d",
i); continue;
i++;
}
}
Output
#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.
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;
}
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:
goto label;
goto example
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
:
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
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
Advantage of C 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
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:
#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);
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++;
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
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
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.
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)
}
}
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
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
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
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}}};
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)
{
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
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:
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.
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.
//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.
void hello()
{ printf("hello
c");
int get()
{ return
10;
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.
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:
#include <stdio.h>
Output:
#include <stdio.h>
#include “a.c”
Output:
#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;
}
Output:
Enter an integer: 7
7! = 5040
#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:
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:
Example-9: Write recursive program which computes the nth Fibonacci number, for
appropriate values of n.
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
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().
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.
Example:
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.
Example:
Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
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.
#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};
Output:
18
14
Here, we have passed array parameters to the display() function in the same way we pass variables to
a function.
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
return sum;
}
Output:
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
To pass multidimensional arrays to a function, only the name of the array is passed to the function
(similar to one-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]);
}
}
}
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.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call, and other doesn't.
#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:
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.
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:
#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: 9
Sum of digits: 9
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.
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.
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:
#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");
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.
• 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
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.
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
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
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.
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:
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;
};
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;
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.
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
return 0;
}
Output:
Name: Jayavardhan
Age: 35
Height: 5.10
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
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 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
Rollno:1, Name:Jayavardhan
Rollno:2, Name:Teja
Rollno:3, Name:Sakuntala
Rollno:4, Name:Raghav
Rollno:5, Name:Saritha
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);
printf("\nAverage : %f",S.Avg);
}
Output:
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.
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.
After defining the structure pointer, we need to initialize it, as the code is shown:
ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.
There are two ways to access the member of the structure using Structure pointer:
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 = ⊂ /* 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:
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
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);
Output:
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.
#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;
Output:
10 20 30
10 20 30
10 20 30
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
{
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
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);
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
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()
{
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
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);
}
Output:
City: Tekkali
Pincode: 532201
Phone: 9999999999
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;
int yyyy;
}doj;
}emp1;
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;
Output:
employee id : 101
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.
union car
char name[50];
int price;
};
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.
union car
char name[50];
int price;
};
int main()
return 0;
union car
char name[50];
int price;
In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.
We use the . operator to access members of a union. And to access pointer variables, we use the ->
operator.
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:
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.
#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
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
ptr=(cast-type*)malloc(byte-size)
#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
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:
Sum=211
calloc() function in C
#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)
Output:
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.
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.
free(ptr)
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
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.
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
int *p = &x;
#include <stdio.h>
int main()
{
int *p, a;
a = 5;
p = &a;
a=1;
printf("%d\t%d", *p,p);
}
Output:
1 -1575739708
Int *p,c;
p=c //Error
*p=&c //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
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.
increased. 32-bit
#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.
return 0;
}
Output:
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:
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:
32-bit
bytes. 64-bit
#include <stdio.h>
void main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
Output:
C Pointer Addition:
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
32-bit
number. 64-bit
#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)
number. 64-bit
For 64-bit int variable, it will subtract 4 * number.
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.
Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points
#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
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.
Example:
#include <stdio.h>
int main()
{
printf("Address of main() function is %p",main);
return 0;
}
Output:
In the above output, we observe that the main() function has some address. Therefore, we conclude
that every function has some address.
For example:
In the above declaration, *ip is a pointer that points to a function which returns an int value and
accepts an integer value as an argument.
In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts
a float value as an argument.
We can observe that the declaration of a function is similar to the declaration of a function pointer
except that the pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function
rather than a pointer.
function.
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.
below:
Or
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;
}
Output:
We can pass the function's address as an argument to other functions in the same way we send other
arguments to the function.
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
Example:
#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
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;
}
Output:
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.
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
}
address of a: 88965f34
address of p:
at p: 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:
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)
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].
**(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)
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.