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

C prog notes-1

A flowchart is a diagram that visually represents a workflow or algorithm, enhancing program readability and simplifying complex processes. It serves various purposes in programming, such as aiding communication among team members and optimizing processes. Flowcharts utilize specific symbols to denote different actions and decisions in the algorithmic flow.

Uploaded by

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

C prog notes-1

A flowchart is a diagram that visually represents a workflow or algorithm, enhancing program readability and simplifying complex processes. It serves various purposes in programming, such as aiding communication among team members and optimizing processes. Flowcharts utilize specific symbols to denote different actions and decisions in the algorithmic flow.

Uploaded by

skushal.mys
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

What is FlowChart?

Uses of Flowcharts in Computer Programming/Algorithms

A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a The following are the uses of a flowchart:

diagrammatic representation of an algorithm, a step-by-step approach to solving a task. 1. It is a pictorial representation of an algorithm that increases the readability of the program.

2. Complex programs can be drawn in a simple way using a flowchart.

Flowchart symbols 3. It helps team members get an insight into the process and use this knowledge to collect data, detect

Different types of boxes are used to make flowcharts flowchart Symbols. All the different kinds of boxes problems, develop software, etc.

are connected by arrow lines. Arrow lines are used to display the flow of control. Let’s learn about each box 4. A flowchart is a basic step for designing a new process or adding extra features.

in detail. 5. Communication with other people becomes easy by drawing flowcharts and sharing them.

Symbol Name Symbol Representation When to Use Flowchart?

Terminal/Terminator Flowcharts are mainly used in the below scenarios:

1. It is most importantly used when programmers make projects. As a flowchart is a basic step to make

Process the design of projects pictorially, it is preferred by many.

2. When the flowcharts of a process are drawn, the programmer understands the non-useful parts of the

Decision process. So flowcharts are used to separate sound logic from the unwanted parts.

3. Since the rules and procedures of drawing a flowchart are universal, a flowchart serves as a

Data or Input/Output communication channel to the people who are working on the same project for better understanding.

4. Optimizing a process becomes easier with flowcharts. The efficiency of the code is improved with the

Flow Arrow flowchart drawing.

Comment or Annotation

On-page connector/reference

Off-page connector/reference

Structure of a C program Errors


#include <stdio.h>
// Definition • Syntax Errors - These are also referred to as compile-time errors. These errors
#define X 20 have occurred when the rule of C writing techniques or syntaxes has been
// Global Declaration broken. These types of errors are typically flagged by the compiler prior to
int sum(int y); compilation.
// Main() Function
int main(void) • Runtime Errors - This type of error occurs while the program is running.
{ Because this is not a compilation error, the compilation will be completed
int y; successfully. These errors occur due to segmentation fault when a number is
Printf(“Enter the value of y:\n”) divided by division operator or modulo division operator. Example: Let us
Scanf(“%d”, &y); 118 1110 consider an array of length 5 i.e. array[5], but during runtime, if we try to
printf("Sum: %d", sum(y)); 30 access 10 elements i.e array[10] then we get segmentation fault errors called
return 0; runtime errors. Giving only an array length of 5
}
// Subprogram • Logical Errors - Even if the syntax and other factors are correct, we may not
10
int sum(int y) get the desired results due to logical issues. These are referred to as logical
{ errors. We sometimes put a semicolon after a loop, which is syntactically
10 120
return y + X; correct but results in one blank loop. In that case, it will display the desired
} output.

Semantic Errors - When a sentence is syntactically correct but has no


meaning, semantic errors occur. This is similar to grammatical errors.
Void main() {
If(a=b)
}
I. CONSTANTS
A constant is a name given to the variable whose values can‘t be altered or changed. A constant
Compiling a C Program: Behind the Scenes is very similar to variables in the C programming language, but it can hold only a single variable
during the execution of a program. It means that once we assign value to the constant, then we
How do we compile and run a C program? can‘t change it throughout the execution of a program- it stays fixed.
We first need a compiler and a code editor to compile and run a C Program. The Use of the Constants in C: A constant is basically a named memory location in a program that
holds a single value throughout the execution of that program. It can be of any data type-
below example is of an Ubuntu machine with GCC compiler. character, floating-point, string and double, integer, etc. There are various types of constants in
Step 1: Creating a C Source File C. It has two major categories- primary and secondary constants. Character constants, real
constants, and integer constants, etc., are types of primary constants. Structure, array, pointer,
We first create a C program using an editor and save the file as filename.c union, etc., are types of secondary constants.

$ vi filename.c What are Literals in C?


Literals are referred to as the values that we assign to the variables that remain constant
We can write a simple hello world program and save it. throughout the execution of a program. Generally, we can use both the terms- literal and
constants interchangeably. For instance, the expression “const int = 7;”, is a type of constant
expression, while we refer to the value 7 as a constant integer literal.
Step 2: Compiling using GCC compiler Types of Constants in C
We use the following command in the terminal for compiling our filename.c
Type of Constants Data type Example of Data type
source file
Integer constants
$ gcc filename.c –o filename int unsigned int 2000u, 5000U, etc.
We can pass many instructions to the GCC compiler to different tasks such as: 23, 738, -1278, etc.
long int, long long int 325,647 1,245,473,940
The option -o is used to specify the output file name. If we do not use this option,
Floating-point or Real
then an output file with the name a.out is generated. constants float 20.987654
doule
If there are no errors in our C program, the executable file of the C program will
500.987654321
be generated.
Octal constant int Example: 013 /*starts with 0 */

Hexadecimal constant int Example: 0x90 /*starts with


0x*/

character constants char Example: „X‟, „Y‟, „Z‟

string constants char Example: “PQRS”, “ABCD”

More About Types of Constants in C


Integer Constants
It can be an octal integer or a decimal integer or even a hexadecimal integer. We specify a
decimal integer value as a direct integer value, while we prefix the octal integer values with ‗o‘.
We also prefix the hexadecimal integer values with ‗0x‘.

The integer constant used in a program can also be of an unsigned type or a long type. We suffix The definition of the same string constant can also occur using white spaces:
the unsigned constant value with ‗u‘ and we suffix the long integer constant value with ‗l‘. Also,
―This‖ ―is‖ ―Cookie‖
we suffix the unsigned long integer constant value using ‗ul‘.
All the three mentioned above define the very same string constant.
Examples,
Rules of Constructing Constants in C
55 —> Decimal Integer Constant
Here is how we construct these constants in a given program:
0x5B —> Hexa Decimal Integer Constant
Integer Constants
O23 —> Octal Integer Constant
68ul —> Unsigned Long Integer Constant  It must have at least one digit.
 There must be no decimal point.
50l —> Long Integer Constant  It does not allow any blanks or commas.
30u —> Unsigned Integer Constant  An integer constant can be both negative or positive.
 We assume an integer constant to be positive if there is no sign in front of that constant.
Floating Point Constants / Real Constants  The allowable range for this type of constant is from -32768 to 32767.
This type of constant must contain both the parts- decimal as well as integers. Sometimes, the Real Constants
floating-point constant may also contain the exponential part. In such a case when the floating-
point constant gets represented in an exponential form, its value must be suffixed using ‗E‘ or  This type of constant must consist of one digit at least.
‗e‘.  There must not be any decimal point.
 This type of constant can be both negative or positive.
Example,
 It does not allow any blanks or commas within.
We represent the floating-point value 3.14 as 3E-14 in its exponent form.  We assume an integer constant to be positive if there is no sign in front of that constant.
Character Constants String and Character Constants
The character constants are symbols that are enclosed in one single quotation. The maximum  This type of constant can be a single digit, a single alphabet, or even a single special
length of a character quotation is of one character only. symbol that stays enclosed within single quotes.
Example,  The string constants get enclosed within double quotes.
 The maximum length of this type of constant is a single character.
‗B‘
Backslash Character Constants
‗5‘
 These are some types of characters that have a special type of meaning in the C language.
‗+‘  These types of constants must be preceded by a backslash symbol so that the program can
Some predefined character constants exist in the C programming language, known as escape use the special function in them.
sequences. Each escape sequence consists of a special functionality of its own, and each of these  Here is a list of all the special characters used in the C language and their purpose:
sequences gets prefixed with a ‗/‘ symbol. We use these escape sequences in output functions
known as ‗printf()‘. Meaning of Character Backslash Character
String Constants
Backspace \b
The string constants are a collection of various special symbols, digits, characters, and escape
sequences that get enclosed in double quotations.
The definition of a string constant occurs in a single line: New line \n

―This is Cookie‖
Form feed \f
We can define this with the use of constant multiple lines as well:
‖ This\ Horizontal tab \t
is\
Cookie‖ Carriage return \r
a = 100 ; // creates an error
Single quote \‘ printf(―q = %d\na = %d‖, q, a ) ;
}
Double quote \‖ The program given above creates an error. It is because we are trying to change the value of the
constant variable (a = 100).

Vertical tab \v Use of the ‘#define’ preprocessor


One can also use the ‗#define‘ preprocessor directive to create the constants. And when we
Backslash \\ create the constants by making use of the preprocessor directive, we must define it in the very
beginning of the program. It is because we must write all the preprocessor directives before the
global declaration.
Question mark \?
Here is the syntax that we must use for creating a constant by making use of the ‗#define‘
preprocessor directive:
Alert or bell \a #define CONSTANTNAME value
Let us look at an example to understand this better,
Hexadecimal constant (Here, N – hex.dcml cnst) \XN
#define PI 3.14

Octal constant (Here, N is an octal constant) \N In this above-mentioned case, PI is a constant, and it has a value of 3.14.
We can run a program for this as follows:
#include<stdio.h>
Creation and Use of Constants in C #include<conio.h>
We can create constants in the C programming language by using two of the concepts mentioned #define PI 3.14
below: void main(){
int a, area ;
 By using the ‗#define‘ preprocessor printf(―Enter the radius of the given circle here : ―) ;
 By using the ‗const‘ keyword. scanf(―%d‖, &a) ;
area = PI * (a * a) ;
Use of the ‘const’ Keyword printf(―The area of the circle is = %d‖, area) ;
The ‗const‘ keyword is used to create a constant of any given datatype in a program. For creating }
a constant, we have to prefix the declaration of the variable with the ‗const‘ keyword. Here is the
general syntax that we follow when using the ‗const‘ keyword:
II. VARIABLES
const datatype constantName = value ;
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
OR variable in C has a specific type, which determines the size and layout of the variable's memory; the
const datatype constantName ; range of values that can be stored within that memory; and the set of operations that can be applied to
the variable.
Let us look at an example to understand this better
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
const int a = 10 ; with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
In this case, a is an integer constant that has a fixed value of 10. sensitive. Based on the basic types explained in the previous chapter, there will be the following basic
variable types −
The program will run as follows:
#include<stdio.h> Sr.No. Type & Description
#include<conio.h>
void main(){
1
int q = 9 ; char
const int a = 10 ; Typically a single octet(one byte). It is an integer type.
q = 15 ;

For definition without an initializer: variables with static storage duration are implicitly initialized with
2
int NULL (all bytes have the value 0); the initial value of all other variables are undefined.
The most natural size of integer for the machine. Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given
3 type and name so that the compiler can proceed for further compilation without requiring the complete
float
detail about the variable. A variable definition has its meaning at the time of compilation only, the
A single-precision floating point value.
compiler needs actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one
4
double of the files which will be available at the time of linking of the program. You will use the
A double-precision floating point value. keyword extern to declare a variable at any place. Though you can declare a variable multiple times in
your C program, it can be defined only once in a file, a function, or a block of code.

5 Example
void
Try the following example, where variables have been declared at the top, but they have been defined
Represents the absence of type. and initialized inside the main function −
#include <stdio.h>
C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us // Variable declaration:
study only basic variable types. extern int a, b;
Variable Definition in C extern int c;
extern float f;
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as int main () {
follows −
type variable_list; /* variable definition: */
int a, b;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user- int c;
defined object; and variable_list may consist of one or more identifier names separated by commas. float f;
Some valid declarations are shown here −
int i, j, k; /* actual initialization */
char c, ch; a = 10;
float f, salary; b = 20;
double d;
c = a + b;
printf("value of c : %d \n", c);
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int. f = 70.0/3.0;
printf("value of f : %f \n", f);
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows − return 0;
type variable_name = value; }

Some examples are − When the above code is compiled and executed, it produces the following result −
extern int d = 3, f = 5; // declaration of d and f. value of c : 30
int d = 3, f = 5; // definition and initializing d and f. value of f : 23.333334
byte z = 22; // definition and initializes z. The same concept applies on function declaration where you provide a function name at the time of its
char x = 'x'; // the variable x has the value 'x'. declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func(); Local Variable: A variable that is declared inside the function or block is called a local variable.

int main() { It must be declared at the start of the block.

// function call void function1(){


int i = func();
} int x=10;//local variable
}
// function definition
int func() { You must have to initialize the local variable before it is used.
return 0;
} 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.
Lvalues and Rvalues in C
There are two kinds of expressions in C − It must be declared at the start of the block.
 lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue
may appear as either the left-hand or right-hand side of an assignment. int value=20;//global variable
 rvalue − The term rvalue refers to a data value that is stored at some address in memory. An void function1(){
rvalue is an expression that cannot have a value assigned to it which means an rvalue may int x=10;//local variable
appear on the right-hand side but not on the left-hand side of an assignment.
}
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the I Variable: A variable that is declared with the static keyword is called static variable.
V Static
following valid and invalid statements −
int g = 20; // valid statement It retains its value between multiple function calls.
12
10 = 20; // invalid statement; would generate compile-time error void function1(){ y
int x=10;//local variable
Rules for defining variables static int y=10;//static variable yet
o A variable can have alphabets, digits, and underscore. x=x+1;
o A variable name can start with the alphabet, and underscore only. It can't start with a digit. y=y+1;
printf("%d,%d",x,y);
o No whitespace is allowed within the variable name.
}
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.
goto
if
If you call this function many times, the local variable will print the same value for each function
Types of Variables in C default 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.
There are many types of variables in c:
Automatic Variable: All variables in C that are declared inside the block, are automatic variables by
1. local variable default. We can explicitly declare an automatic variable using auto keyword.
2. global variable
void main(){
3. static variable
int x=10;//local variable (also automatic)
4. automatic variable
auto int y=20;//automatic variable
5. external variable }

External Variable: We can share a variable in multiple C source files by using an external variable. Below image shows the compilation process with the files created at each step of the
To declare an external variable, you need to use extern keyword. compilation process:

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

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

III. EXECUTION PROCESS OF A C PROGRAM


Whenever a C program file is compiled and executed, the compiler generates some files with the
same name as that of the C program file but with different extensions. So, what are these files
and how are they created?
Every file that contains a C program must be saved with ‗.c‘ extension. This is necessary for the
compiler to understand that this is a C program file. Suppose a program file is named, first.c. The Linker Loader
file first.c is called the source file which keeps the code of the program. Now, when we compile
the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file Linker generates the executable module of Loader loads the executable module to the
as a .obj file of the same name, called the object file. So, here it will create the first.obj. This .obj a source program. main memory for execution.
file is not executable. The process is continued by the Linker which finally gives a .exe file
which is executable.
Linker takes the object code generated by Loader takes executable module generated by
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to an assembler, as input. a linker as input.
convert preprocessor directives into their respective values. The preprocessor generates an
expanded source code.
Linker combines all the object modules of a Loader allocates the addresses to an
2) Expanded source code is sent to compiler which compiles the code and converts it into
source code to generate an executable executable module in main memory for
assembly code.
module. execution.
3) The assembly code is sent to assembler which assembles the code and converts it into object
code. Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it is The types of Loader are Absolute loading,
converted into executable code. A simple.exe file is generated. The types of Linker are Linkage Editor, Relocatable loading and Dynamic Run-time
5) The executable code is sent to loader which loads it into memory and then it is executed. After Dynamic linker. loading.
execution, output is sent to console.

Linker: First of all, let us know that library functions are not a part of any C program but of the IV. STRUCTURE OF C PROGRAM
C software. Thus, the compiler doesn‘t know the operation of any function, whether it be printf
or scanf. The definitions of these functions are stored in their respective library which the The sections of a C program are listed below:
compiler should be able to link. This is what the Linker does. So, when we write #include, it
includes stdio.h library which gives access to Standard Input and Output. The linker links the 1. Documentation section
object files to the library functions and the program becomes a .exe file. Here, first.exe will be
created which is in an executable format. 2. Preprocessor section
Loader: Whenever we give the command to execute a particular program, the loader comes into 3. Definition section
work. The loader will load the .exe file in RAM and inform the CPU with the starting point of
the address where this program is loaded. 4. Global declaration
5. Main function
6. User defined functions

Let's discuss it in detail.

Documentation section: It includes the statement specified at the beginning of a program, such as a
program's name, date, description, and title. It is represented as:

//name of a program

Or
CPU Registers

/*
Instruction Register: It holds the current instructions to be executed by the CPU.
Program Counter: It contains the address of the next instructions to be executed by the CPU. Overview of the code
Accumulator: It stores the information related to calculations. .
The loader informs Program Counter about the first instruction and initiates the execution. Then */
onwards, Program Counter handles the task.
Difference between Linker and Loader

Both methods work as the document section in a program. It provides an overview of the program. We can also use int or main with the main (). The void main() specifies that the program will not
Anything written inside will be considered a part of the documentation section and will not interfere return any value. The int main() specifies that the program can return integer type data.
with the specified code.
int main()
Preprocessor section: The preprocessor section contains all the header files used in a program. It
informs the system to link the header files to the system libraries. It is given by: Or

#include<stdio.h> void main()


#include<conio.h>
Main function is further categorized into local declarations, statements, and expressions.
The #include statement includes the specific file as a part of a function at the time of the compilation.
Thus, the contents of the included file are compiled along with the function being compiled. Local declarations: The variable that is declared inside a given function or block refers to as local
The #include<stdio.h> consists of the contents of the standard input output files, which contains the declarations.
definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr are used in a
function, the statement #include<stdio.h> need to be used. main()
There are various header files available for different purposes. For example, # include <math.h>. It is {
used for mathematic functions in a program. int i = 2;
i++;
Define section: The define section comprises of different constants declared using the define keyword.
}
It is given by:
Statements: The statements refers to if, else, while, do, for, etc. used in a program within the main
#define a = 2 function.

Global declaration: The global section comprises of all the global declarations in the program. It is Expressions: An expression is a type of formula where operands are linked with each other by the use
given by: of operators. It is given by:

float num = 2.54; a - b;


int a = 5; a +b;
char ch ='z';
User defined functions: The user defined functions specified the functions specified as per the
The size of the above global variables is listed as follows: requirements of the user. For example, color(), sum(), division(), etc.

char = 1 byte The program (basic or advance) follows the same sections as listed above.

float = 4 bytes Return function is generally the last section of a code. But, it is not necessary to include. It is used
when we want to return a value. The return function returns a value when the return type other than the
int = 4 bytes void is specified with the function.

We can also declare user defined functions in the global variable section. Return type ends the execution of the function. It further returns control to the specified calling
function. It is given by:
Main function: main() is the first function to be executed by the computer. It is necessary for a code
to include the main(). It is like any other function available in the C library. Parenthesis () are used for return;
passing parameters (if any) to a function.
Or
The main function is declared as:
return expression ;
main()
For example,
{… The curly braces mark the beginning and end of a function. It is mandatory
return 0; } in all the functions.

Examples printf() The printf() prints text on the screen. It is a function for displaying constant
or variables data. Here, 'Enter two numbers to be added' is the parameter
Let's begin with a simple program in C language.
passed to it.
Example 1: To find the sum of two numbers given by the user
scanf() It reads data from the standard input stream and writes the result into the
It is given by:
specified arguments.

/* Sum of two numbers */


sum = a + b The addition of the specified two numbers will be passed to the sum
#include<stdio.h>
parameter in the output.
int main()
{
return 0 A program can also run without a return 0 function. It simply states that a
int a, b, sum;
program is free from error and can be successfully exited.
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum Example 2: To draw a box by accepting a number from the user
sum = a + b;
It is given by:
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum /* a simple code to draw a box by accepting a number from the user */
}
#include<stdio.h> // preprocessor section that contains header files
Output
#include<conio.h>
void main() // main section
{
The detailed explanation of each part of a code is as follows: char num; //local statements
puts(" Enter number of lines of a box (1 to 3) \n");
/* Sum of the two It is the comment section. Any statement described in it is not considered as /* puts accepts, as parameter, a string constant, or a variable enclosed within the double quotes
numbers */ a code. It is a part of the description section in a code. for display on the standard output*/
The comment line is optional. It can be in a separate line or part of an
executable line.
num = getchar(); // getchar() is also equal to getc(stdin) in C programming.
/* It accepts a parameter and allows the character to be read during the program execution. */
#include<stdio.h> It is the standard input-output header file. It is a command of the
fflush(stdin); // clears the buffer
preprocessor section.
if(num=='1') // beginning of if-else condition
{
int main() main() is the first function to be executed in every program. We have used
puts("-----------");
int with the main() in order to return an integer value.
puts("| |");
puts("-----------");

} The steps to create, compile, and execute the code from the beginning have been explained later in the
topic. It will help us compile any type of C code with the help of text editor (Notepad here)
else if(num=='2') /*if- and cmd (Command Prompt).
else performs two different operations depending on the true or false condition of the expressio
n.*/ We can collectively say that the program includes preprocessor commands, variables, functions,
statements, expressions, and comments.
{
puts("-----------"); Compile and execution of a C program: Here, we will discuss the method to compile and run the C
puts("| |"); program with the help of the command prompt.
puts("| |"); The steps involved in a complete program execution are as follows:
puts("-----------");
} 1. Create a program
else if(num=='3') 2. Compile a program
{
3. Run or execute a program
puts("-----------");
4. Output of the program
puts("| |");
puts("| |");
puts("| |");
puts("-----------");
}
else
{
puts("Invalid input");
}
}

We have saved the file with the name boxexample.c. Let's compile and execute the code with the help
of the command prompt. The file was created in the Notepad.

Output
I. DATATYPES IN C Memory Format
Each variable in C has an associated data type. Each data type requires different amounts of Data Type (bytes) Range Specifier
memory and has some specific operations which can be performed over it. It specifies the
type of data that the variable can store like integer, character, floating, double, etc. The data
type is a collection of data with values having fixed values, meaning as well as its
characteristics. short int 2 -32,768 to 32,767 %hd

The data types in C can be classified as follows: unsigned short int 2 0 to 65,535 %hu
Types Description
unsigned int 4 0 to 4,294,967,295 %u
Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.
int -2,147,483,648 to %d
4 2,147,483,647
The data type has no value or operator and it does not provide a result to
Void Types its caller. But void comes under Primitive data types.
long int 4 -2,147,483,648 to %ld
2,147,483,647
User Defined It is mainly used to assign names to integral constants, which make a
DataTypes program easy to read and maintain
unsigned long int 4 0 to 4,294,967,295 %lu

The data types that are derived from the primitive or built-in datatypes are
long long int 8 -(2^63) to (2^63)-1 %lld
Derived types referred to as Derived Data Types.

unsigned long long 0 to


int 8 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

1. Integer Types:
Different data types also have different ranges up to which they can store numbers. These The integer data type in C is used to store the whole numbers without decimal values. Octal
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory values, hexadecimal values, and decimal values can be stored in int data type in C. We can
requirement and format specifiers on the 32-bit GCC compiler. determine the size of the int data type by using the sizeof operator in C. Unsigned int data
type in C is used to store the data values from zero to positive numbers but it can’t store
negative values like signed int. Unsigned int is larger in size than signed int and it uses “%u”

as a format specifier in C programming language. Below is the programming implementation


of the int data type in C. // C program to print Integer data types.
 Range: -2,147,483,648 to 2,147,483,647 #include <stdio.h>
 Size: 2 bytes or 4 bytes
 Format Specifier: %d int main()
Note: The size of an integer data type is compiler-dependent, when processors are 16-bit {
systems, then it shows the output of int as 2 bytes. And when processors are 32-bit then it
shows 2 bytes as well as 4 bytes.
char a = 'a';
char c;
// C program to print Integer data types.
#include <stdio.h> printf("Value of a: %c\n", a);
int main()
{ a++;
// Integer value with positive data. printf("Value of a after increment is: %c\n", a);
int a = 9;
// c is assigned ASCII values
// integer value with negative data. // which corresponds to the
int b = -9; // character 'c'
// a-->97 b-->98 c-->99
// U or u is Used for Unsigned int in C. // here c will be printed
int c = 89U; c = 99;
// L or l is used for long int in C.
long int d = 99998L; printf("Value of c: %c", c);

printf("Integer value with positive data: %d\n", a); return 0;


printf("Integer value with negative data: %d\n", b); }
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d); Output
Value of a: a
return 0; Value of a after increment is: b
Value of c: c
}

Output 3. Floating-Point Types


Integer value with positive data: 9 In C programming float data type is used to store floating-point values. Float in C is used to
Integer value with negative data: -9 store decimal and exponential values. It is used to store decimal numbers (numbers with
Integer value with an unsigned int data: 89 floating point values) with single precision.
Integer value with an long int data: 99998  Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f

// C Program to demonstrate use


2. Character Types // of Floating types
Character data type allows its variable to store only a single character. The storage size of the #include <stdio.h>
character is 1. It is the most basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.
int main()
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte {
 Format Specifier: %c
printf("%lf", c);
float a = 9.0f;
float b = 2.5f; return 0;
}
// 2x10^-4
float c = 2E-4f; Output
printf("%f\n",a); 123123123.000000
12.293123
printf("%f\n",b);
2312312312.123123
printf("%f",c);
1. Void Data types
The void data type in C is used to specify that no value is present. It does not provide a result
return 0; value to its caller. It has no values and no operations. It is used to represent nothing. Void is
} used in multiple ways as function return type, function arguments as void, and pointers to
void.
Output Syntax:
9.000000 // function return type void
2.500000
0.000200 void exit(int check);

// Function without any parameter can accept void.


4. Double Types
5
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
int print(void);
Ed a
decimal values in C. Double data type is basically a precision sort of data type that is capable
of holding 64 bits of decimal numbers or floating points. Since double has more precision as
// memory allocation function which
// returns a pointer to void. pts Had
compared to that float then it is much more obvious that it occupies twice the memory as void *malloc( size_t size);
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or
before a decimal point. // C program to demonstrate
int a 5
 Range: 1.7E-308 to 1.7E+308
// use of void pointers a
 Size: 8 bytes
 Format Specifier: %lf
#include <stdio.h> print adl
// C Program to demonstrate int main() Ra
// use of double data type { a
#include <stdio.h> int val = 30;
void *ptr = &val; pts
int main() printf("%d", *(int *)ptr); 5
{
}
return 0; pts all
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
Output
30
PIE
We can use the sizeof() operator to check the size of a variable. See the following C program
for the usage of the various data types.
printf("%lf\n", a);
// C Program to print size of
printf("%lf\n", b); // different data type in C
#include <stdio.h>

Enumerated Type Declaration:


int main()
When you define an enum type, the blueprint for the variable is created. Here's how you can
{
create variables of enum types.
int size_of_int=sizeof(int);
int size_of_char= sizeof(char); enum boolean {false, true};
int size_of_float=sizeof(float);
int size_of_double=sizeof(double); enum boolean check; // declaring an enum variable

printf("The size of int data type : %d\n",size_of_int ); Here, a variable check of the type enum boolean is created.
printf("The size of char data type : %d\n",size_of_char); You can also declare enum variables like this.
printf("The size of float data type : %d\n",size_of_float);
printf("The size of double data type : %d",size_of_double); enum boolean {false, true} check;

return 0;
Here, the value of false is equal to 0 and the value of true is equal to 1.
}
Example: Enumeration Type
Output
The size of int data type : 4
#include <stdio.h>
The size of char data type : 1
The size of float data type : 4
The size of double data type : 8 enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main()
{
II. ENUMERATION CONSTANTS // creating today variable of enum week type
In C programming, an enumeration type (also called enum) is a data type that consists of enum week today;
integral constants. To define enums, the enum keyword is used. today = Wednesday;
printf("Day %d",today+1);
enum flag {const1, const2, ..., constN}; return 0;
}

By default, const1 is 0, const2 is 1 and so on. You can change default values of enum
elements during declaration (if necessary). Output

// Changing default values of enum constants Day 4

enum suit {
Why enums are used?
An enum variable can take only one value. Here is an example to demonstrate it,
club = 0,

diamonds = 10, #include <stdio.h>

hearts = 20, enum suit {


club = 0,
spades = 3, diamonds = 10,
hearts = 20,
}; spades = 3
} card;
};
int main()
{ int main() {
card = club; int myDesign = BOLD | UNDERLINE;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0; // 00000001
} // | 00000100
// ___________
Output // 00000101

Size of enum variable = 4 bytes printf("%d", myDesign);

Here, we are getting 4 because the size of int is 4 bytes. return 0;


This makes enum a good choice to work with flags. }

How to use enums for flags?


Let us take an example, Output

enum designFlags { 5
ITALICS = 1, When the output is 5, you always know that bold and underline is used.
BOLD = 2, Also, you can add flags according to your requirements.
UNDERLINE = 4
} button; if (myDesign & ITALICS) {
Suppose you are designing a button for Windows application. You can set // code for italics
flags ITALICS, BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are a power of 2 in the above pseudocode. }

// In binary
Here, we have added italics to our design. Note, only code for italics is written inside
the if statement.
You can accomplish almost anything in C programming without using enumerations.
ITALICS = 00000001 However, they can be pretty handy in certain situations.

BOLD = 00000010
III. STORAGE CLASSES
UNDERLINE = 00000100
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
Since the integral constants are a power of 2, you can combine two or more flags at once
without overlapping using bitwise OR | operator. This allows you to choose two or more flags
o Automatic
at once. For example,
o External
#include <stdio.h>
o Static
enum designFlags { o Register
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4

Output:
Storage Storage Default Scope Lifetime
Classes Place Value garbage garbage garbage

Example 2
auto RAM Garbage Local Within function #include <stdio.h>
Value
int main()
{
extern RAM Zero Global Till the end of the main program Maybe
int a = 10,i;
declared anywhere in the program
printf("%d ",++a);
{
static RAM Zero Local Till the end of the main program,
int a = 20;
Retains value between multiple
functions call for (i=0;i<3;i++)
{

register Register Garbage Local Within the function printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
Value }
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
Automatic
}
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are Output:
defined. 11 20 20 20 11
o The scope of the automatic variables is limited to the block in which they are defined.
Static
o The automatic variables are initialized to garbage by default.
o The variables defined as static specifier can hold their value between the multiple
o The memory assigned to automatic variables gets freed upon exiting from the block. function calls.
o The keyword used for defining automatic variables is auto. o Static local variables are visible only to the function or the block in which they are
o Every local variable is automatic in C by default. defined.

Example 1 o A same static variable can be declared many times but can be assigned at only one time.

#include <stdio.h> o Default initial value of the static integral variable is 0 otherwise null.
int main() o The visibility of the static global variable is limited to the file in which it has declared.
{ o The keyword used to define static variable is static.
int a; //auto
Example 1
char b;
float c; #include<stdio.h>
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, an static char c;
d c. static int i;
return 0; static float f;
} static char s[100];
void main () o The register keyword is used for the variable which should be stored in the CPU
{ register. However, it is compiler?s choice whether or not; the variables can be stored in
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed. the register.
} o We can store pointers into the register, i.e., a register can store the address of a variable.

Output: o Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.
0 0 0.000000 (null)
Example 1
Example 2
#include <stdio.h>
#include<stdio.h>
int main()
void sum()
{
{
register int a; // variable a is allocated memory in the CPU register. The initial default v
static int a = 10;
alue of a is 0.
static int b = 24;
printf("%d",a);
printf("%d %d \n",a,b);
}
a++;
b++; Output:
}
0
void main()
Example 2
{
int i; #include <stdio.h>
for(i = 0; i< 3; i++) int main()
{ {
sum(); // The static variables holds their value between multiple function calls. register int a = 0;
} printf("%u",&a); // This will give a compile time error since we can not access the addr
} ess of a register variable.
}
Output:
Output:
10 24
11 25 main.c:5:5: error: address of register variable ?a? requested
12 26 printf("%u",&a);
^~~~~~
Register
External
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU. o The external storage class is used to tell the compiler that the variable defined as extern
is declared with an external linkage elsewhere in the program.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable. o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The access time of the register variables is faster than the automatic variables.
o The default initial value of external integral type is 0 otherwise null.
o The initial default value of the register local variables is 0.

o We can only initialize the extern variable globally, i.e., we can not initialize the external Output
variable within any block or method. compile time error
o An external variable can be declared many times but can be initialized at only once. main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
o If a variable is declared as external then the compiler searches for that variable to be extern int a = 0;
initialized somewhere in the program which may be extern or static. If it is not, then the
Example 4
compiler will show an error.
#include <stdio.h>
Example 1 int main()
#include <stdio.h> {
int main() extern int a; // Compiler will search here for a variable a defined and initialized somew
{ here in the pogram or not.
extern int a; printf("%d",a);
printf("%d",a); }
} int a = 20;

Output Output

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


collect2: error: ld returned 1 exit status
Example 5
Example 2 extern int a;
#include <stdio.h> int a = 10;
int a; #include <stdio.h>
int main() int main()
{ {
extern int a; // variable a is defined globally, the memory will not be allocated to a printf("%d",a);
printf("%d",a); }
} int a = 20; // compiler will show an error at this line

Output Output

0 compile time error


Example 3
#include <stdio.h>
int a;
int main()
{
extern int a = 0; // this will show a compiler error since we can not use extern and initia
lizer at same time
printf("%d",a);
}
10/10/2024, 02:45 operator precedence table.png

What is Typecasting?
Typecasting is the process of converting a variable from one data type to
another. It is used to ensure that operations involving different data types
behave correctly and produce the desired results.
Types of Typecasting
a d
• Implicit Typecasting (Automatic Type Conversion):
Performed by the compiler automatically.
15
Happens when a smaller data type is converted to a larger data type (e.g., int to
float).
No data loss occurs.

• Explicit Typecasting (Type Conversion):


Performed manually by the programmer.
Requires the use of a cast operator.
Can lead to data loss if converting from a larger data type to a smaller data
type (e.g., float to int).

https://classroom.google.com/c/NTA0OTE2MTA0ODgw 1/1

int age;
I. OPERATOR
Expression : // take input from users
printf("Enter your age: ");
 An expression is anything which evaluates to something. scanf("%d", &age);
 Expressions are combinations of operators and operands.
// ternary operator to find if a person can vote or not
Operator : (age >= 18) ? printf("You can vote") : printf("You cannot vote");
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
return 0;
Operator's Categories: } Code

1. Unary : A unary operator is an operator, which operates on one operand. Output 1


2. Binary : A binary operator is an operator, which operates on two operands.
3. Ternary : A ternary operator is an operator, which operates on three operands. Enter your age: 12
You cannot vote
We use the ternary operator in C to run one code when the condition is true and another code
In the above example, we have used a ternary operator that checks whether a user can vote or
when the condition is false. For example,
not based on the input value. Here,
(age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
 age >= 18 - test condition that checks if input value is greater or equal to 18
Here, when the age is greater than or equal to 18, Can Vote is printed. Otherwise, Cannot
 printf("You can vote") - expression1 that is executed if condition is true
Vote is printed.
 printf("You cannot vote") - expression2 that is executed if condition is false
Syntax of Ternary Operator
Here, the user inputs 12, so the condition becomes false. Hence, we get You cannot vote as
The syntax of ternary operator is: output.
Output 2
testCondition ? expression1 : expression 2;
Enter your age: 24
The testCondition is a boolean expression that results in either true or false. If the condition You can vote

is
This time the input value is 24 which is greater than 18. Hence, we get You can vote as
 true - expression1 (before the colon) is executed
output.
 false - expression2 (after the colon) is executed
Assign the ternary operator to a variable
The ternary operator takes 3 operands (condition, expression1 and expression2). Hence, the
name ternary operator. In C programming, we can also assign the expression of the ternary operator to a variable.

Example: C Ternary Operator For example,

Run variable = condition ? expression1 : expression2;


#include <stdio.h>

int main() {

3 3
printf("Even Number");
Here, if the test condition is true, expression1 will be assigned to the variable.
}
Otherwise, expression2 will be assigned. else {
printf("Odd Number");
Let's see an example }

#include <stdio.h> return 0;


}
int main() { Run Code

// create variables #include <stdio.h>


char operator = '+'; int main() {
int num1 = 8;
int num2 = 7; int number = 3;

// using variables in ternary operator (number % 2 == 0) ? printf("Even Number") : printf("Odd Number");


int result = (operator == '+') ? (num1 + num2) : (num1 - num2); return 0;

printf("%d", result); }
We can replace this code with the following code using the ternary operator.
return 0;
}
Run Code
// Output: 15
Here, both the programs are doing the same task, checking even/odd numbers. However, the
Run Code
code using the ternary operator looks clean and concise.
In the above example, the test condition (operator == '+') will always be true. So, the first
expression before the colon i.e the summation of two integers num1 and num2 is assigned to In such cases, where there is only one statement inside the if...else block, we can replace it

the result variable. with a ternary operator.

And, finally the result variable is printed as an output giving out the summation of 8 and 7.
i.e 15.

Ternary Operator Vs. if...else Statement in C

In some of the cases, we can replace the if...else statement with a ternary operator. This will
make our code cleaner and shorter.
Let's see an example:

include <stdio.h>

int main() {
int number = 3;

if (number % 2 == 0) {

3 3

C Arithmetic Operators }

An arithmetic operator performs mathematical operations such as addition, subtraction, Run Code
multiplication, division etc on numerical values (constants and variables). Output

a+b = 13
Operator Meaning of Operator
a-b = 5
a*b = 36
+ addition or unary plus
a/b = 2
Remainder when a divided by b=1
- subtraction or unary minus

The operators +, - and * computes addition, subtraction, and multiplication respectively as


* multiplication
you might have expected.
/ division
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both

% remainder after division (modulo division) the variables a and b are integers. Hence, the output is also an integer. The compiler neglects
the term after the decimal point and shows answer 2 instead of 2.25. The modulo
Example 1: Arithmetic Operators
operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1.
// Working of arithmetic operators The % operator can only be used with integers.
#include <stdio.h> Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
int main()
// Either one of the operands is a floating-point number
{
a/b = 2.5
int a = 9,b = 4, c;
a/d = 2.5

c = a+b; c/b = 2.5

printf("a+b = %d \n",c);
c = a-b;
// Both operands are integers
printf("a-b = %d \n",c);
c/d = 2
c = a*b;
printf("a*b = %d \n",c);
c = a/b; C Increment and Decrement Operators:

printf("a/b = %d \n",c); C programming has two operators increment ++ and decrement -- to change the value of an
c = a%b; operand (constant or variable) by 1.
printf("Remainder when a divided by b = %d \n",c);
return 0;
3 3
/= a /= b a = a/b
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These
two operators are unary operators, meaning they only operate on a single operand.
%= a %= b a = a%b
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators Example 3: Assignment Operators
#include <stdio.h> // Working of assignment operators
int main() #include <stdio.h>
{ int main()
int a = 10, b = 100; {
float c = 10.5, d = 100.5; int a = 5, c;
printf("++a = %d \n", ++a); c = a; // c is 5
printf("--b = %d \n", --b); printf("c = %d\n", c);
printf("++c = %f \n", ++c); c += a; // c is 10
printf("--d = %f \n", --d); printf("c = %d\n", c);
c -= a; // c is 5
return 0; printf("c = %d\n", c);
} c *= a; // c is 25
printf("c = %d\n", c);
Run Code c /= a; // c is 5
Output printf("c = %d\n", c);
c %= a; // c = 0
++a = 11 printf("c = %d\n", c);
--b = 99
return 0;
++c = 11.500000
}
--d = 99.500000
Run Code
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as
Output
postfixes like a++ and a--.
c=5
C Assignment Operators c = 10
c=5
An assignment operator is used for assigning a value to a variable. The most common c = 25
c=5
assignment operator is =
c=0
Operator Example Same as

= a=b a=b
C Relational Operators
+= a += b a = a+b
A relational operator checks the relationship between two operands. If the relation is true, it
-= a -= b a = a-b
returns 1; if the relation is false, it returns value 0.
*= a *= b a = a*b
Relational operators are used in decision making and loops.

3 3

Operator Meaning of Operator Example


5 < 10 is 1
5 != 5 is 0
== Equal to 5 == 3 is evaluated to 0 5 != 10 is 1
5 >= 5 is 1
> Greater than 5 > 3 is evaluated to 1 5 >= 10 is 0
5 <= 5 is 1
< Less than 5 < 3 is evaluated to 0 5 <= 10 is 1

!= Not equal to 5 != 3 is evaluated to 1 C Logical Operators

>= Greater than or equal to 5 >= 3 is evaluated to 1 An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are commonly used in decision making in C
<= Less than or equal to 5 <= 3 is evaluated to 0
programming.
Example 4: Relational Operators
Operator Meaning Example
// Working of relational operators
#include <stdio.h>
Logical AND. True only if If c = 5 and d = 2 then, expression
int main() &&
all operands are true ((c==5) && (d>5)) equals to 0.
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b); Logical OR. True only if If c = 5 and d = 2 then, expression
||
printf("%d == %d is %d \n", a, c, a == c); either one operand is true ((c==5) || (d>5)) equals to 1.
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
Logical NOT. True only if If c = 5 then, expression !(c==5) equals
printf("%d < %d is %d \n", a, b, a < b); !
the operand is 0 to 0.
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
Example 5: Logical Operators
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c); // Working of logical operators
printf("%d <= %d is %d \n", a, b, a <= b); #include <stdio.h>
printf("%d <= %d is %d \n", a, c, a <= c);
int main()
return 0; {
}
Run Code int a = 5, b = 5, c = 10, result;

Output result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);
5 == 5 is 1
5 == 10 is 0 result = (a == b) && (c < b);
5 > 5 is 0
printf("(a == b) && (c < b) is %d \n", result);
5 > 10 is 0
5 < 5 is 0 result = (a == b) || (c < b);

3 3
printf("(a == b) || (c < b) is %d \n", result); & Bitwise AND
result = (a != b) || (c < b);
| Bitwise OR
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b); ^ Bitwise exclusive OR

printf("!(a != b) is %d \n", result); ~ Bitwise complement


result = !(a == b);
<< Shift left
printf("!(a == b) is %d \n", result);
return 0; >> Shift right
}
Run Code Other Operators
Output
Comma Operator
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0 Comma operators are used to link related expressions together.
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0 For example: int a, c = 5, d;
!(a != b) is 1
!(a == b) is 0
1. int a=7,9; //a=7

Explanation of logical operator program


2. int a=(7,9); //a=9
 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false). 3. int i=1;

 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true). while(i=+2,i<=10)

 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false). {

 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true). printf(“%d ”,i);

 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false). }


printf(“%d ”,i); //3 5 7 9 11
The sizeof operator
C Bitwise Operators
The sizeof is a unary operator that returns the size of data (constants, variables, array,
During computation, mathematical operations like: addition, subtraction, multiplication,
structure, etc).
division, etc are converted to bit-level which makes processing faster and saves power.
Example 6: sizeof Operator
Bitwise operators are used in C programming to perform bit-level operations. #include <stdio.h>
int main()
{
Operators Meaning of operators int a;

3 3

float b; Decision-making statements in programming languages decide the direction of the flow of
double c; program execution. Decision-making statements available in C or C++ are:
char d;
1. if statement
printf("Size of int=%lu bytes\n",sizeof(a));
2. if-else statements
printf("Size of float=%lu bytes\n",sizeof(b));
3. nested if statements
printf("Size of double=%lu bytes\n",sizeof(c));
4. if-else-if ladder
printf("Size of char=%lu byte\n",sizeof(d));
5. switch statements
6. Jump Statements:
return 0;
 break
}
 continue
 goto
Run Code
 return
Output 1. if statement in C/C++
if statement is the most simple decision-making statement. It is used to decide whether a
Size of int = 4 bytes certain statement or block of statements will be executed or not i.e if a certain condition is
Size of float = 4 bytes true then a block of statement is executed otherwise not.
Size of double = 8 bytes Syntax:
Size of char = 1 byte if(condition)
{
// Statements to execute if
II. DECISION MAKING
// condition is true
There come situations in real life when we need to make some decisions and based on these }
decisions, we decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the Here, the condition after evaluation will be either true or false. C if statement accepts
next block of code. boolean values – if the value is true then it will execute the block of statements below it
otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by
For example, in C if x occurs then execute y else execute z. There can also be multiple default if statement will consider the first immediately below statement to be inside its
conditions like in C if x occurs then execute p, else if condition y occurs execute q, else block.
execute r. This condition of C else-if is one of the many ways of importing multiple Example:
conditions. if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.

Flowchart

3 3
As the condition present in the if statement is false. So, the block below the if statement is
not executed.
2. if-else in C/C++
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the C else statement. We can use the else statement with
the if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart:

// C program to illustrate If statement


#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}

printf("I am Not in if");


}

Output:
I am Not in if

3 3

Flowchart
// C program to illustrate If statement
#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;
}

Output:
i is greater than 15
The block of code following the else statement is executed as the condition present in
the if statement is false.
3. nested-if in C/C++ Example:
A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, both C and C++ allow us // C program to illustrate nested-if statement
to nested if statements within if statements, i.e, we can place an if statement inside another #include <stdio.h>
if statement.
int main()
Syntax: {
if (condition1) int i = 10;
{
if (i == 10) {
// Executes when condition1 is true // First if statement
if (i < 15)
if (condition2)
printf("i is smaller than 15\n");
{
// Nested - if statement
// Executes when condition2 is true
// Will only be executed if statement above
} // is true
if (i < 12)
} printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}

return 0;
}

Output:
i is smaller than 15
3 3
i is smaller than 12 too // C program to illustrate nested-if statement
#include <stdio.h>
4. if-else-if ladder in C/C++
Here, a user can decide among multiple options. The C if statements are executed from the
int main()
top down. As soon as one of the conditions controlling the if is true, the statement
{
associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none
int i = 20;
of the conditions is true, then the final else statement will be executed.
Syntax: if (i == 10)
if (condition) printf("i is 10");
else if (i == 15)
statement; printf("i is 15");
else if (condition) else if (i == 20)
printf("i is 20");
statement; else
. printf("i is not present");
}
.
Output:
else i is 20

statement; 5. Jump Statements in C/C++


These statements are used in C or C++ for the unconditional flow of control throughout the
functions in a program. They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the
loop immediately to the first statement after the loop.
Syntax:
break;
Basically, break statements are used in situations when we are not sure about the actual
number of iterations for the loop or we want to terminate the loop based on some
condition.

3 3

// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>

void findElement(int arr[], int size, int key)


{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
}
}
}

int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
Example:
// no of elements
int n = 6; // C program to explain the use
// of continue statement
// key to be searched #include <stdio.h>
int key = 3;
int main()
// Calling function to find the key {
findElement(arr, n, key); // loop from 1 to 10
for (int i = 1; i <= 10; i++) {
return 0;
} // If i is equals to 6,
// continue to next iteration
Output: // without printing
Element found at position: 3 if (i == 6)
continue;
B) continue
This loop control statement is just like the break statement. else
The continue statement is opposite to that of the break statement, instead of terminating the // otherwise print the value of i
loop, it forces to execute the next iteration of the loop. printf("%d ", i);
As the name suggests the continue statement forces the loop to continue or execute the next }
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and the next iteration of the loop will return 0;
begin. }
Syntax:
continue; Output:
1 2 3 4 5 7 8 9 10

3 3
If you create a variable in if-else in C/C++, it will be local to that if/else block only. You
can use global variables inside the if/else block. If the name of the variable you created in
if/else is as same as any global variable then priority will be given to `local variable`.

#include <stdio.h>

int main()
{

int gfg = 0; // local variable for main


printf("Before if-else block %d\n", gfg);
if (1) {
int gfg = 100; // new local variable of if block
printf("if block %d\n", gfg);
}
printf("After if block %d", gfg);
return 0;
}

Output:
Before if-else block 0
if block 100
After if block 0
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement can be
Examples:
used to jump from one point to another within a function.
Syntax: // C program to print numbers
Syntax1 | Syntax2 // from 1 to 10 using goto
---------------------------- // statement
#include <stdio.h>
goto label; | label:
. | . // function to print numbers from 1 to 10
void printNumbers()
. | . {
int n = 1;
. | .
label:
label: | goto label; printf("%d ", n);
n++;
In the above syntax, the first line tells the compiler to go to or jump to the statement if (n <= 10)
marked as a label. Here, a label is a user-defined identifier that indicates the target goto label;
statement. The statement immediately followed after ‘label:’ is the destination statement. }
The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
// Driver program to test above function
int main()
{
printNumbers();
return 0;
}

3 3

Output: Loops in programming are used to repeat a block of code until the specified condition is
1 2 3 4 5 6 7 8 9 10 met. A loop statement allows programmers to execute a statement or group of statements
multiple times without repetition of code.
D) return
The return in C or C++ returns the flow of the execution to the function from where it is
called. This statement does not mandatorily need any conditional statements. As soon as the // C program to illustrate need of loops
statement is executed, the flow of the program stops immediately and returns the control #include <stdio.h>
from where it was called. The return statement may or may not return anything for a void
function, but for a non-void function, a return value must be returned. int main()
Syntax: {
return[expression]; printf( "Hello World\n");
printf( "Hello World\n");
Example: printf( "Hello World\n");
printf( "Hello World\n");
// C code to illustrate return printf( "Hello World\n");
// statement printf( "Hello World\n");
#include <stdio.h> printf( "Hello World\n");
printf( "Hello World\n");
// non-void return type printf( "Hello World\n");
// function to calculate sum printf( "Hello World\n");
int SUM(int a, int b)
{ return 0;
int s1 = a + b; }
return s1;
} Output
Hello World
// returns void
// function to print Hello World
void Print(int s2) Hello World
{
printf("The sum is %d", s2); Hello World
return; Hello World
}
Hello World
int main() Hello World
{
int num1 = 10; Hello World
int num2 = 10;
Hello World
int sum_of = SUM(num1, num2);
Print(sum_of); Hello World
return 0;
} There are mainly two types of loops in C Programming:
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
Output: entering the main body of the loop. For Loop and While Loop is Entry-controlled
The sum is 20 loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of whether
the condition is true or false. do-while Loop is Exit Controlled loop.

III. LOOPS

3 3
In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable
with some value, then check its test condition. If the statement is true then control will
move to the body and the body of for loop will be executed. Steps will be repeated till the
exit condition becomes true. If the test condition will be false then it will stop.
 Initialization Expression: In this expression, we assign a loop variable or loop counter
to some value. for example: int i=1;
 Test Expression: In this expression, test conditions are performed. If the condition
evaluates to true then the loop body will be executed and then an update of the loop
variable is done. If the test expression becomes false then the control will exit from the
loop. for example, i<=9;
 Update Expression: After execution of the loop body loop variable is updated by some
value it could be incremented, decremented, multiplied, or divided by any value.
for loop Equivalent Flow Diagram:

Loop Type Description

first Initializes, then condition check, then executes the body and at last, the
for loop update is done.

first Initializes, then condition checks, and then executes the body, and
while loop updating can be inside the body.

do-while
loop do-while first executes the body and then the condition check is done.

for Loop
for loop in C programming is a repetition control structure that allows programmers to
write a loop that will be executed a specific number of times. for loop enables programmers
to perform n number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
Example:
}

3 3

// C program to illustrate for loop }


#include <stdio.h>
Flow Diagram for while loop:
// Driver code
int main()
{
int i = 0;

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


{
printf( "Hello World\n");
}
return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is terminated on
the basis of the test condition. If the test condition will become false then it will break from
the while loop else body will be executed.
Syntax:
initialization_expression;
// C program to illustrate
// while loop
while (test_expression) #include <stdio.h>
{
// Driver code
// body of the while loop int main()
{
// Initialization expression
update_expression; int i = 2;

3 3
// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");

// update expression
i++;
}

return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while
loop test condition which is tested at the end of the body. In the do-while loop, the loop
body will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{ // C program to illustrate
// body of do-while loop // do-while loop
#include <stdio.h>

// Driver code
update_expression;
int main()
{
// Initialization expression
} while (test_expression); int i = 2;

do
{
// loop body
printf( "Hello World\n");

3 3

for ( ; ; )
// Update expression {
i++; printf("This loop will run forever.\n");
}
// Test expression
} while (i < 1); return 0;
}
return 0;
} Output
This loop will run forever.
Output
This loop will run forever.
Hello World
This loop will run forever.
Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the
body will be executed once. ...
Loop Control Statements Using While loop:
Loop control statements in C programming are used to change execution from its normal
sequence. // C program to demonstrate
// infinite loop using while
Name Description // loop
#include <stdio.h>
the break statement is used to terminate the switch and loop statement. It
// Driver code
break transfers the execution to the statement immediately following the loop or
int main()
statement switch.
{
while (1)
continue continue statement skips the remainder body and immediately resets its printf("This loop will run forever.\n");
statement condition before reiterating it. return 0;
}
goto Output
statement goto statement transfers the control to the labeled statement. This loop will run forever.
Infinite Loop This loop will run forever.
An infinite loop is executed when the test expression never becomes false and the body of
This loop will run forever.
the loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is
always true. Mostly this is an error that can be resolved by using Loop Control statements. ...
Using for loop: Using the do-while loop:
// C program to demonstrate infinite // C program to demonstrate
// loops using for loop // infinite loop using do-while
#include <stdio.h> // loop
#include <stdio.h>
// Driver code
int main () // Driver code
{ int main()
int i; {
do
// This is an infinite for loop {
// as the condition expression printf("This loop will run forever.\n");
// is blank } while (1);

3 3
SEARCHING
return 0;
}
Linear search:
Output
This loop will run forever.  Linear search is the simplest method for searching.
This loop will run forever.  In Linear search technique of searching; the element to be found in searching the
elements to be found is searched sequentially in the list.
This loop will run forever.  This method can be performed on a sorted or an unsorted list (usually arrays).
...  In case of a sorted list searching starts from 0th element and continues until the element is
found from the list or the element whose value is greater than (assuming the list is sorted in
ascending order), the value being searched is reached.
 As against this, searching in case of unsorted list also begins from the 0th element and
continues until the element or the end of the list is reached.
 The linear search algorithm searches all elements in the array sequentially.
 Its best execution time is 1, whereas the worst execution time is n, where n is the total
number of items in the search array.
 It is the most simple search algorithm in data structure and checks each item in the set of
elements until it matches the search element until the end of data collection.
 When data is unsorted, a linear search algorithm is preferred.
Linear Search is defined as a sequential search algorithm that starts at one end and goes
through each element of a list until the desired element is found, otherwise the search
continues till the end of the data set. It is the easiest searching algorithm

Linear Search Algorithm


Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the array.
Step 3: If both are matched, display “Target element is found” and terminate the Linear
Search
function.
Step 4: If both are not matched, compare the search element with the next element in the
array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared with
the
last element of the array.
Step 6 – If the last element in the list does not match, the Linear Search Function will be
terminated, and the message “Element is not found” will be displayed.

Given an array arr[] of N elements, the task is to write a function to search a given  Does not require any additional memory.
element x in arr[].  It is a well suited algorithm for small datasets.
Examples: Drawbacks of Linear Search:
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 110;  Linear search has a time complexity of O(n), which in turn makes it slow for large
Output: 6 datasets.
Explanation: Element x is present at index 6  Not suitable for large array.
 Linear search can be less efficient than other algorithms, such as hash tables.
When to use Linear Search:
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 175;
 When we are dealing with a small dataset.
Output: -1
 When you need to find an exact value.
Explanation: Element x is not present in arr[].
 When you are searching a dataset stored in contiguous memory.
// C code to linearly search x in arr[]. If x  When you want to implement a simple algorithm.
// is present then return its location, otherwise Summary:
// return -1  Linear search is a simple and flexible algorithm for finding whether an element is
present within an array.
 It sequentially examines each element of the array.
#include <stdio.h>  The time complexity of linear search is O(n).
 It is used for searching databases, lists, and arrays.
int search(int arr[], int N, int x)
{ Binary Search:
int i; Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the
for (i = 0; i < N; i++) search interval in half. The idea of binary search is to use the information that the array is
if (arr[i] == x) sorted and reduce the time complexity to O(Log n).
return i; Binary Search Algorithm: The basic steps to perform Binary Search are:
return -1;  Sort the array in ascending order.
}  Set the low index to the first element of the array and the high index to the last element.
 Set the middle index to the average of the low and high indices.
 If the element at the middle index is the target element, return the middle index.
// Driver's code
 If the target element is less than the element at the middle index, set the high index to
int main(void) the middle index – 1.
{  If the target element is greater than the element at the middle index, set the low index to
int arr[] = { 2, 3, 4, 10, 40 }; the middle index + 1.
int x = 10;  Repeat steps 3-6 until the element is found or it is clear that the element is not present in
int N = sizeof(arr) / sizeof(arr[0]); the array.

Binary Search Algorithm can be implemented in the following two ways


// Function call
int result = search(arr, N, x); 1. Iterative Method
(result == -1) 2. Recursive Method
1. Iteration Method
? printf("Element is not present in array")
: printf("Element is present at index %d", result); binarySearch(arr, x, low, high)
return 0; repeat till low = high
}
mid = (low + high)/2
Advantages of Linear Search: if (x == arr[mid])
 Linear search is simple to implement and easy to understand. return mid
 Linear search can be used irrespective of whether the array is sorted or not. It can be
used on arrays of any data type.
else if (x > arr[mid]) // x is on the right side int mid = l + (r - l) / 2;
low = mid + 1
// If the element is present at the middle
// itself
else // x is on the left side if (arr[mid] == x)
high = mid - 1 return mid;

2. Recursive Method (The recursive method follows the divide and conquer approach) // If element is smaller than mid, then
binarySearch(arr, x, low, high) // it can only be present in left subarray
if (arr[mid] > x)
if low > high
return binarySearch(arr, l, mid - 1, x);
return False
// Else the element can only be present
// in right subarray
else
return binarySearch(arr, mid + 1, r, x);
mid = (low + high) / 2 }
if x == arr[mid]
// We reach here when element is not
return mid
// present in array
return -1;
else if x > arr[mid] // x is on the right side }
return binarySearch(arr, x, mid + 1, high)
int main(void)
{
else // x is on the left side int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
return binarySearch(arr, x, low, mid - 1)
int x = 10;
Illustration of Binary Search Algorithm: int result = binarySearch(arr, 0, n - 1, x);
Step-by-step Binary Search Algorithm: We basically ignore half of the elements just (result == -1)
after one comparison.
? printf("Element is not present in array")
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index. : printf("Element is present at index %d", result);
3. Else If x is greater than the mid element, then x can only lie in the right half subarray return 0;
after the mid element. So we recur for the right half. }
4. Else (x is smaller) recur for the left half.
Advantages of Binary Search:
// C program to implement recursive Binary Search  Binary search is faster than linear search, especially for large arrays. As the size of the
#include <stdio.h> array increases, the time it takes to perform a linear search increases linearly, while the
time it takes to perform a binary search increases logarithmically.
// A recursive binary search function. It returns  Binary search is more efficient than other searching algorithms that have a similar time
// location of x in given array arr[l..r] is present, complexity, such as interpolation search or exponential search.
 Binary search is relatively simple to implement and easy to understand, making it a
// otherwise -1
good choice for many applications.
int binarySearch(int arr[], int l, int r, int x)  Binary search can be used on both sorted arrays and sorted linked lists, making it a
{ flexible algorithm.
if (r >= l) {

 Binary search is well-suited for searching large datasets that are stored in external
memory, such as on a hard drive or in the cloud. Linear search performs equality
 Binary search can be used as a building block for more complex algorithms, such as comparisons Binary search performs ordering comparisons
those used in computer graphics and machine learning.
Drawbacks of Binary Search:
It is less complex. It is more complex.
 We require the array to be sorted. If the array is not sorted, we must first sort it before
performing the search. This adds an additional O(n log n) time complexity for the
sorting step, which can make binary search less efficient for very small arrays. It is very slow process. It is very fast process.
 Binary search requires that the array being searched be stored in contiguous memory
locations. This can be a problem if the array is too large to fit in memory, or if the array
is stored on external memory such as a hard drive or in the cloud. SORTING
 Binary search requires that the elements of the array be comparable, meaning that they
must be able to be ordered. This can be a problem if the elements of the array are not Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting
naturally ordered, or if the ordering is not well-defined. the smallest (or largest) element from the unsorted portion of the list and moving it to the
 Binary search can be less efficient than other algorithms, such as hash tables, for sorted portion of the list. The algorithm repeatedly selects the smallest (or largest) element
searching very large datasets that do not fit in memory. from the unsorted portion of the list and swaps it with the first element of the unsorted
Applications of Binary search: portion. This process is repeated for the remaining unsorted portion of the list until the
 Searching in machine learning: Binary search can be used as a building block for more
entire list is sorted. One variation of selection sort is called “Bidirectional selection sort”
complex algorithms used in machine learning, such as algorithms for training neural that goes through the list of elements by alternating between the smallest and largest
networks or finding the optimal hyperparameters for a model. element, this way the algorithm can be faster in some cases.
 Commonly used in Competitive Programming.
The algorithm maintains two subarrays in a given array.
 Can be used for searching in computer graphics. Binary search can be used as a building  The subarray which already sorted.
block for more complex algorithms used in computer graphics, such as algorithms for  The remaining subarray was unsorted.
ray tracing or texture mapping. In every iteration of the selection sort, the minimum element (considering ascending order)
 Can be used for searching a database. Binary search can be used to efficiently search a from the unsorted subarray is picked and moved to the beginning of unsorted subarray.
database of records, such as a customer database or a product catalog.
When to use Binary Search: After every iteration sorted subarray size increase by one and unsorted subarray size
decrease by one.
 When searching a large dataset as it has a time complexity of O(log n), which means
that it is much faster than linear search. After N (size of array) iteration we will get sorted array.
 When the dataset is sorted.
 When data is stored in contiguous memory. How selection sort works?
 Data does not have a complex structure or relationships. Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
Important Differences
 For the first position in the sorted array, the whole array is traversed from index 0 to 4
sequentially. The first position where 64 is stored presently, after traversing whole array
Linear Search Binary Search it is clear that 11 is the lowest value.

64 25 12 22 11
In linear search input data need not to be in In binary search input data need to be in
sorted. sorted order.
 Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in
the array, tends to appear in the first position of the sorted list.
It is also called sequential search. It is also called half-interval search.
11 25 12 22 64

The time complexity of binary search O(log


The time complexity of linear search O(n). n). Second Pass:
 For the second position, where 25 is present, again traverse the rest of the array in a
sequential manner.
Multidimensional array can be used. Only single dimensional array is used.
11 25 12 22 64 {
int temp = *xp;
*xp = *yp;
 After traversing, we found that 12 is the second lowest value in the array and it should *yp = temp;
appear at the second place in the array, thus swap these values. }
11 12 25 22 64
void selectionSort(int arr[], int n)
{
Third Pass: int i, j, min_idx;
 Now, for third place, where 25 is present again traverse the rest of the array and find the
third least value present in the array.
// One by one move boundary of unsorted subarray
11 12 25 22 64 for (i = 0; i < n-1; i++)
{
 While traversing, 22 came out to be the third least value and it should appear at the third // Find the minimum element in unsorted array
place in the array, thus swap 22 with element present at third position. min_idx = i;
for (j = i+1; j < n; j++)
11 12 22 25 64 if (arr[j] < arr[min_idx])
min_idx = j;
Fourth pass:
 Similarly, for fourth position traverse the rest of the array and find the fourth least // Swap the found minimum element with the first element
element in the array if(min_idx != i)
 As 25 is the 4th lowest value hence, it will place at the fourth position.
swap(&arr[min_idx], &arr[i]);
11 12 22 25 64 }
}
Fifth Pass:
 At last the largest value present in the array automatically get placed at the last position
/* Function to print an array */
in the array void printArray(int arr[], int size)
 The resulted array is the sorted array. {
int i;
11 12 22 25 64
for (i=0; i < size; i++)
printf("%d ", arr[i]);
Follow the below steps to solve the problem:
printf("\n");
 Initialize minimum value(min_idx) to location 0. }
 Traverse the array to find the minimum element in the array.
 While traversing if any element smaller than min_idx is found then swap both the // Driver program to test above functions
values.
int main()
 Then, increment min_idx to point to the next element.
 Repeat until the array is sorted. {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
Program: selectionSort(arr, n);
// C program for implementation of selection sort printf("Sorted array: \n");
#include <stdio.h> printArray(arr, n);
return 0;
void swap(int *xp, int *yp) }

information fetched from the program. One such way is to store the fetched information in
Complexity Analysis of Selection Sort: a file. Different operations that can be performed on a file are:
Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested 1. Creation of a new file (fopen() with attributes as “a” or “a+” or “w” or “w+”)
loops: 2. Opening an existing file (fopen())
 One loop to select an element of Array one by one = O(N) 3. Reading from file (fscanf() or fgets())
 Another loop to compare that element with every other Array element = O(N) 4. Writing to a file (fprintf() or fputs())
Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N2) 5. Moving to a specific location in a file (fseek(), rewind())
Auxiliary Space: O(1) as the only extra memory used is for temporary variables while 6. Closing a file (fclose())
swapping two values in Array. The selection sort never makes more than O(N) swaps and The text in the brackets denotes the functions used for performing those operations.
can be useful when memory write is a costly operation.
Is Selection Sort Algorithm stable? Why do we need File Handling in C?
Stability: The default implementation is not stable. However, it can be made stable. Please The output of a C program is generally deleted when the program is closed. Sometimes, we
see stable selection sort for details. need to store that output for purposes like data analysis, result presentation, comparison of
Is Selection Sort Algorithm in place? output for different conditions, etc. The use of file handling is exactly what the situation
Yes, it does not require extra space. calls for.
In order to understand why file handling makes programming easier, let us look at a few
Advantages of Selection Sort Algorithm: reasons:
 Simple and easy to understand.  Reusability: The file-handling process keeps track of the information created after the
 Preserves the relative order of items with equal keys which means it is stable. program has been run.
 Works well with small datasets.  Portability: Without losing any data files can be transferred to another in the computer
 It is adaptable to various types of data types. system. The risk of flawed coding is minimized with this feature.
 Selection sort is an in-place sorting algorithm, which means it does not require any  Efficient: A large amount of input may be required for some programs. File handling
additional memory to sort the list. allows you to easily access a part of a code using individual commands which saves a
Disadvantages of Selection Sort Algorithm: lot of time and reduces the chance of errors.
 Selection sort has a time complexity of O(n^2) in the worst and average case.  Storage Capacity: Files allow you to store data without having to worry about storing
 Does not works well on large datasets. everything simultaneously in a program.
 Selection sort algorithm needs to iterate over the list multiple times, thus it can lead to Types of Files in C
an unbalanced branch. Generally, a text file contains alphabets, digits, and special characters or symbols, while a
 Selection sort has poor cache performance and hence it is not cache friendly. binary file contains bytes or a compiled version of the text. It is important to recognize two
 Not adaptive, meaning it doesn’t take advantage of the fact that the list may already be types of files when dealing with files:
sorted or partially sorted
 Not a good choice for large data sets with slow random access memory (RAM)  Text Files
 It’s not a comparison sort and doesn’t have any performance guarantees like merge sort  Binary Files
or quick sort. Text Files: Text files contain data in the form of ASCII characters and are generally used
 It has poor cache performance to store a stream of characters. Each line in a text file ends with a new line character (‘/n’).
 It can cause poor branch prediction due to its high branch misprediction rate Text files are used to store the source code.
 It has a high number of write operations, leading to poor performance on systems with Binary Files: Binary files contain data that is stored in a similar manner to how it is stored
slow storage. in the main memory. Instead of ASCII characters, it is stored in binary format. The binary
 It is not a parallelizable algorithm, meaning that it cannot be easily split up to be run on files can be created only from within a program and their contents can only be read by a
multiple processors or cores. program.
 It does not handle data with many duplicates well, as it makes many unnecessary swaps.
 It can be outperformed by other algorithms such as quicksort and heapsort in most Functions in File Operations:
cases.

FILE HANDLING

So far the operations using the C program are done on a prompt/terminal which is not
stored anywhere. But in the software industry, most programs are written to store the
Searches file. If the file exists, its contents are overwritten. If the file doesn’t
w exist, a new file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are overwritten.
wb If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory
and sets up a pointer that points to the last character in it. If the file doesn’t
a exist, a new file is created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file
ab does not exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets
up a pointer that points to the first character in it. Returns NULL, if unable to
r+ open the file.

Open for both reading and writing in binary mode. If the file does not exist,
rb+ fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t
Opening or Creating a File w+ exist a new file is created. Returns NULL, if unable to open the file.
For opening a file, fopen() function is used with the required access modes. Some of the
commonly used file access modes are mentioned below.
File opening modes in C: Open for both reading and writing in binary mode. If the file exists, its contents
wb+ are overwritten. If the file does not exist, it will be created.
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t
and sets up a pointer that points to the first character in it. If the file cannot be a+ exist, a new file is created. Returns NULL, if unable to open the file.
r opened fopen( ) returns NULL.

ab+ Open for both reading and appending in binary mode. If the file does not exist,
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns it will be created.
NULL.

As given above, if you want to perform operations on a binary file, then you have to append ---------- Some file Operations -------
‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have
to use “a+b”. For performing the operations on the file, a special pointer called File pointer
is used which is declared as: fclose(filePointer)
FILE *filePointer; Example 1: Program to Open a File, Write in it, And Close the File

So, the file can be opened as // C program to Open a File,

// Write in it, And Close the File


filePointer = fopen(“fileName.txt”, “w”)
The second parameter can be changed to contain all the attributes listed in the above table. # include <stdio.h>
Reading From a File
The file read operations can be performed using functions fscanf or fgets. Both the # include <string.h>
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. So, it depends on you if you want to read the file line by line or
character by character.
And the code snippet for reading a file is as:
int main( )
FILE * filePointer;
{

filePointer = fopen(“fileName.txt”, “r”);

fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year); // Declare the file pointer
Writing to a File
The file write operations can be performed by the functions fprintf and fputs with FILE *filePointer ;
similarities to read operations. The snippet for writing to a file is as:
FILE *filePointer ;

// Get the data to be written in file


filePointer = fopen(“fileName.txt”, “w”);

char dataToBeWritten[50]
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
Closing a File = "GeeksforGeeks-A Computer Science Portal for Geeks";
After every successful file operation, you must always close a file. For closing a file, you
have to use fclose() function. The snippet for closing a file is given as:
FILE *filePointer ;
// Open the existing file GfgTest.c using fopen()
filePointer= fopen(“fileName.txt”, “w”);
// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w") ; }

// Check if this filePointer is null // Closing the file using fclose()

// which maybe if the file does not exist fclose(filePointer) ;

if ( filePointer == NULL )

{ printf("Data successfully written in file GfgTest.c\n");

printf( "GfgTest.c file failed to open." ) ; printf("The file is now closed.") ;

} }

else return 0;

{ }

Output:
The file is now opened.
printf("The file is now opened.\n") ;
Data successfully written in file GfgTest.c
The file is now closed.
This program will create a file named GfgTest.c in the same directory as the source file
// Write the dataToBeWritten into the file which will contain the following text: “GeeksforGeeks-A Computer Science Portal for
Geeks”.
if ( strlen ( dataToBeWritten ) > 0 ) Example 2: Program to Open a File, Read from it, And Close the File

{
// C program to Open a File,

// Read from it, And Close the File

// writing in the file using fputs()

fputs(dataToBeWritten, filePointer) ;
# include <stdio.h>

fputs("\n", filePointer) ;
# include <string.h>

int main( )

{ // Read the dataToBeRead from the file

// Declare the file pointer // using fgets() method

FILE *filePointer ; while( fgets ( dataToBeRead, 50, filePointer ) != NULL )

// Declare the variable for the data to be read from file

char dataToBeRead[50]; // Print the dataToBeRead

// Open the existing file GfgTest.c using fopen() printf( "%s" , dataToBeRead ) ;

// in read mode using "r" attribute }

filePointer = fopen("GfgTest.c", "r") ;

// Check if this filePointer is null // Closing the file using fclose()

// which maybe if the file does not exist fclose(filePointer) ;

if ( filePointer == NULL )

{ printf("Data successfully read from file GfgTest.c\n");

printf( "GfgTest.c file failed to open." ) ; printf("The file is now closed.") ;

} }

else return 0;

{ }

Output:
The file is now opened.
printf("The file is now opened.\n") ;
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c // Program will exit.
The file is now closed.
exit(1);
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.
}
Write to a Binary File
// else it will return a pointer to the file.
Example 3: Program to write to a Binary file using fwrite()
for (n = 1; n < 5; ++n) {

// C program to write to a Binary file using fwrite() num.n1 = n;

#include <stdio.h> num.n2 = 5 * n;

#include <stdlib.h> num.n3 = 5 * n + 1;

struct threeNum { fwrite(&num, sizeof(struct threeNum), 1, fptr);

int n1, n2, n3; }

}; fclose(fptr);

int main() return 0;

{ }

int n;

Reading from Binary File


// Structure variable declared here.
Example 4: Program to Read from a binary file using fread()
struct threeNum num;

FILE* fptr; // C Program to Read from a binary file using fread()

if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) { #include <stdio.h>

printf("Error! opening file"); #include <stdlib.h>

// If file pointer will return NULL struct threeNum {

int n1, n2, n3;

}; return 0;

int main() }

{
Output:
n1: 1 n2: 5 n3: 6
int n;
n1: 2 n2: 10 n3: 11
struct threeNum num; n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21
FILE* fptr; Accessing Data using fseek()
If we have multiple records inside a file and need to access a particular record that is at a
if ((fptr = fopen("C:\\program.bin", "rb")) == NULL) { specific position, so we need to loop through all the records before it to get the record.
Doing this will waste a lot of memory and operational time. To reduce memory
consumption and operational time we can use fseek() which provides an easier way to get
printf("Error! opening file"); to the required data. fseek() function in C seeks the cursor to the given record in the file.
Syntax for fseek():
// If file pointer will return NULL
int fseek(FILE *ptr, long int offset, int pos);

// Program will exit.


// C Program to demonstrate the use of fseek() in C
exit(1);
#include <stdio.h>
}

// else it will return a pointer to the file.


int main()
for (n = 1; n < 5; ++n) {
{
fread(&num, sizeof(struct threeNum), 1, fptr);
FILE* fp;
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,
fp = fopen("test.txt", "r");
num.n3);

}
// Moving pointer to end
fclose(fptr);
fseek(fp, 0, SEEK_END);
ftell() to return the current position of a file pointer.

// Printing position of pointer


rewind() to set the file pointer to the beginning of a file.
printf("%ld", ftell(fp));

putw() to write an integer to a file.

return 0; getw() to read an integer from a file.

Practice here: https://www.geeksforgeeks.org/c-file-handling-question-1/


Output:
81
More Functions for File Handling in C STRUCTURE
Functions Description What is Structure data type?
A structure is a keyword that creates user-defined data types in C/C++. A structure
fopen() to create a file or to open a file.
creates a data type that can be used to group items of possibly different types into a
single type.

fclose() to close a file.

fgets() to read a file.

fprintf() to write blocks of data into a file.

fscanf() to read blocks of data from a file.

getc() to read a single character to a file.

putc() to write a single character to a file.

fseek() to set the position of a file pointer to a mentioned location.

int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}

How to initialize structure members?


Structure members cannot be initialized with declaration. For example, the
following C program fails in the compilation.

struct Point
{
Where to use the Structure data type? int x = 0; // COMPILER ERROR: cannot initialize members here
We can use this data type to store dates of different attributes of different data types. int y = 0; // COMPILER ERROR: cannot initialize members here
For example, If we want to store data on multiple patients such as patient name, age, };
and blood group.
How to create a structure? The reason for above error is simple, when a datatype is declared, no memory is
‘struct’ keyword is used to create a structure. Following is an example. allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, the
struct address
following is a valid initialization.
{
char name[50]; How to access structure elements?
char street[100];
Structure members are accessed using dot (.) operator.
char city[50];
char state[20]; #include <stdio.h>
int pin;
}; struct Point {
int x, y;
How to declare structure variables?
};
A structure variable can either be declared with structure declaration or as a separate
declaration like basic types.
int main()
// A variable declaration with structure declaration. {
struct Point p1 = { 0, 1 };
struct Point
{ // Accessing members of point p1
p1.x = 20;
printf("x = %d, y = %d", p1.x, p1.y); // Access array members
arr[0].x = 10;
return 0; arr[0].y = 20;
}
What is designated Initialization? printf("%d %d", arr[0].x, arr[0].y);
Designated Initialization allows structure members to be initialized in any order. return 0;
This feature has been added in C99 standard. }
#include <stdio.h> Output

struct Point { 10 20
int x, y, z; What is a structure pointer?
}; Like primitive types, we can have a pointer to a structure. If we have a pointer to
structure, members are accessed using arrow ( -> ) operator.
int main()
#include <stdio.h>
{
// Examples of initialization using designated
struct Point {
// initialization
int x, y;
struct Point p1 = { .y = 0, .z = 1, .x = 2 };
};
struct Point p2 = { .x = 20 };

int main()
printf("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);
{
printf("x = %d", p2.x);
struct Point p1 = { 1, 2 };
return 0;
}
// p2 is a pointer to structure p1
Output
struct Point* p2 = &p1;
x = 2, y = 0, z = 1
// Accessing structure members using structure pointer
x = 20
printf("%d %d", p2->x, p2->y);
This feature is not available in C++ and works only in C. return 0;
What is an array of structures? }
Like other primitive data types, we can create an array of structures. Output
12
#include <stdio.h>
Limitations of C Structures
struct Point { In C language, Structures provide a method for packing together data of different
types. A Structure is a helpful tool to handle a group of logically related data items.
int x, y;
However, C structures have some limitations.
};
 The C structure does not allow the struct data type to be treated like built-in data
int main() types:
{  We cannot use operators like +,- etc. on Structure variables. For example,
// Create an array of structures consider the following code:
struct Point arr[10]; struct number {
float x;

};  Construction creation in Structure: Structures in C cannot have a constructor


int main() inside Structures.
{
struct number n1, n2, n3; A nested structure in C is a structure within structure. One structure can be
n1.x = 4; declared inside another structure in the same way structure members are declared
n2.x = 3; inside a structure.
n3 = n1 + n2; Syntax:
return 0; struct name_1
} {
member1;
member2;
/*Output:
.
.
prog.c: In function 'main': membern;
prog.c:10:7: error:
invalid operands to binary + (have 'struct number' and struct name_2
'struct number') n3=n1+n2; {
member_1;
*/ member_2;
.
But we can use arithmetic operation on structure variables like this. .
// Use of arithmetic operator in structure member_n;
}, var1
#include <stdio.h>
} var2;
struct number {
float x; The member of a nested structure can be accessed using the following syntax:
}; Variable name of Outer_Structure.Variable name of Nested_Structure.data member
int main() to access
{
struct number n1, n2, n3;
Example:
 Consider there are two structures Employee (depended structure) and another
n1.x = 4;
structure called Organisation(Outer structure).
n2.x = 3;
 The structure Organisation has the data members like
n3.x = (n1.x) + (n2.x);
organisation_name,organisation_number.
printf("\n%f", n3.x);  The Employee structure is nested inside the structure Organisation and it has the
return 0; data members like employee_id, name, salary.
} For accessing the members of Organisation and Employee following syntax will be
 No Data Hiding: C Structures do not permit data hiding. Structure members can used:
be accessed by any function, anywhere in the scope of the Structure
Functions inside Structure: C structures do not permit functions inside org.emp.employee_id;

Structure org.emp.name;
Static Members: C Structures cannot have static members inside their body org.emp.salary;

 Access Modifiers: C Programming language does not support access modifiers. org.organisation_name;
So they cannot be used in C Structures. org.organisation_number;
Here, org is the structure variable of the outer structure Organisation and emp is struct Organisation org;
the structure variable of the inner structure Employee.
// Print the size of organisation
Different ways of nesting structure
// structure
The structure can be nested in the following different ways:
printf("The size of structure organisation : %ld\n",
1. By separate nested structure sizeof(org));
2. By embedded nested structure.
1. By separate nested structure: In this method, the two structures are created, but org.emp.employee_id = 101;
the dependent structure(Employee) should be used inside the main strcpy(org.emp.name, "Robert");
structure(Organisation) as a member. Below is the C program to implement the org.emp.salary = 400000;
approach: strcpy(org.organisation_name,
"GeeksforGeeks");
// C program to implement
strcpy(org.org_number, "GFG123768");
// the above approach
#include <stdio.h>
#include <string.h>
// Printing the details
printf("Organisation Name : %s\n",
// Declaration of the
org.organisation_name);
// dependent structure
printf("Organisation Number : %s\n",
struct Employee
org.org_number);
{
printf("Employee id : %d\n",
int employee_id;
org.emp.employee_id);
char name[20];
printf("Employee name : %s\n",
int salary;
org.emp.name);
};
printf("Employee Salary : %d\n",
org.emp.salary);
// Declaration of the
}
// Outer structure
Output:
struct Organisation
The size of structure organisation : 68
{
Organisation Name : GeeksforGeeks
char organisation_name[20]; Organisation Number : GFG123768
char org_number[20]; Employee id : 101
Employee name : Robert
// Dependent structure is used Employee Salary : 400000
// as a member inside the main
// structure for implementing 2. By Embedded nested structure: Using this method, allows to declare structure
// nested structure inside a structure and it requires fewer lines of code.
struct Employee emp; Case 1: Error will occur if the structure is present but the structure variable is
missing.
};
// C program to implement
// the above approach
// Driver code
#include <stdio.h>
int main()
{
// Declaration of the outer
// Structure variable
// structure

struct Organisation
{ // Declaration of the dependent
char organisation_name[20]; // structure
char org_number[20]; struct Employee
{
// Declaration of the employee int employee_id;
// structure char name[20];
struct Employee int salary;
{
int employee_id; // variable is created which acts
char name[20]; // as member to Organisation structure.
int salary; } emp;
};
// This line will cause error because
// datatype struct Employee is present , // Driver code
// but Structure variable is missing. int main()
}; {
}; struct Organisation org;

// Driver code // Print the size of organisation


int main() // structure
{ printf("The size of structure organisation : %ld\n",
// Structure variable of organisation sizeof(org));
struct Organisation org;
printf("%ld", sizeof(org)); org.emp.employee_id = 101;
} strcpy(org.emp.name, "Robert");
Note: org.emp.salary = 400000;
Whenever an embedded nested structure is created, the variable declaration is strcpy(org.organisation_name,
compulsory at the end of the inner structure, which acts as a member of the outer "GeeksforGeeks");
structure. It is compulsory that the structure variable is created at the end of the strcpy(org.org_number, "GFG123768");
inner structure.
Case 2: When the structure variable of the inner structure is declared at the end of
the inner structure. Below is the C program to implement this approach: // Printing the details
// C program to implement
printf("Organisation Name : %s\n",
// the above approach
org.organisation_name);
#include <stdio.h>
printf("Organisation Number : %s\n",
#include <string.h>
org.org_number);
printf("Employee id : %d\n",
// Declaration of the main
org.emp.employee_id);
// structure
printf("Employee name : %s\n",
struct Organisation
org.emp.name);
{
printf("Employee Salary : %d\n",
char organisation_name[20];
org.emp.salary);
char org_number[20];
}
Output: printf("College name : %s\n",
c1.college_name);
The size of structure organisation : 68 printf("Ranking : %d\n",
Organisation Name : GeeksforGeeks c1.ranking);
Organisation Number : GFG123768 printf("Student id : %d\n",
c1.student1.student_id);
Employee id : 101 printf("Student name : %s\n",
Employee name : Robert c1.student1.name);
Employee Salary : 400000 printf("Roll no : %d\n",
c1.student1.roll_no);
Drawback of Nested Structure return 0;
The drawback in nested structures are: }

 Independent existence not possible: It is important to note that structure Output:


Employee doesn’t exist on its own. One can’t declare structure variable of type College name : GeeksforGeeks
struct Employee anywhere else in the program. Ranking : 7
 Cannot be used in multiple data structures: The nested structure cannot be Student id : 111
used in multiple structures due to the limitation of declaring structure variables Student name : Paul
within the main structure. So, the most recommended way is to use a separate Roll no : 278
structure and it can be used in multiple data structures
Note:
Nesting of structure within itself is not allowed.
C Nested Structure Example
Below is another example of a C nested structure. Example:
struct student
// C program to implement {
// the nested structure
#include <stdio.h> char name[50];
#include <string.h>
char address[100];
// Declaration of Outer structure
int roll_no;
struct College
{ struct student geek; // Invalid
char college_name[20];
int ranking; }

// Declaration of Inner structure Accessing Nested Structure


struct Student Nested Structure can be accessed in two ways:
{
int student_id;
1. Using Normal variable.
char name[20];
2. Using Pointer variable.
int roll_no;
Let’s discuss each of these methods in detail.
1. Using Normal variable: Outer and inner structure variables are declared as
// Inner structure variable
} student1;
normal variables and the data members of the outer structure are accessed using a
}; single dot(.) and the data members of the inner structure are accessed using the two
dots. Below is the C program to implement this concept:

// Driver code // C program to implement


// the above approach
int main() #include <stdio.h>
{ #include <string.h>
struct College c1 = {"GeeksforGeeks", 7,
{111, "Paul", 278}};

// Declaration of inner structure {


struct college_details int college_id;
{ char college_name[50];
int college_id;
char college_name[50]; };

}; // Declaration of Outer structure


struct student_detail
// Declaration of Outer structure {
struct student_detail int student_id;
{ char student_name[20];
int student_id; float cgpa;
char student_name[20];
float cgpa; // Inner structure variable
struct college_details clg;
// Inner structure variable } stu, *stu_ptr;
struct college_details clg;
} stu; // Driver code
int main()
// Driver code {
int main() struct student_detail stu = {12, "Kathy", 7.8,
{ {14567, "GeeksforGeeks"}};
struct student_detail stu = {12, "Kathy", 7.8,
{14567, "GeeksforGeeks"}}; stu_ptr = &stu;

// Printing the details // Printing the details


printf("College ID : %d \n", stu.clg.college_id); printf("College ID : %d \n", stu_ptr->clg.college_id);
printf("College Name : %s \n", stu.clg.college_name); printf("College Name : %s \n", stu_ptr->clg.college_name);
printf("Student ID : %d \n", stu.student_id); printf("Student ID : %d \n", stu_ptr->student_id);
printf("Student Name : %s \n", stu.student_name); printf("Student Name : %s \n", stu_ptr->student_name);
printf("Student CGPA : %f \n", stu.cgpa); printf("Student CGPA : %f \n", stu_ptr->cgpa);
return 0; return 0;
} }

Output: Output:
College ID : 14567 College ID : 14567
College Name : GeeksforGeeks College Name : GeeksforGeeks
Student ID : 12 Student ID : 12
Student Name : Kathy Student Name : Kathy
Student CGPA : 7.800000
Student CGPA : 7.800000
A nested structure will allow the creation of complex data types according to the
2. Using Pointer variable: One normal variable and one pointer variable of the requirements of the program.
structure are declared to explain the difference between the two. In the case of the
pointer variable, a combination of dot(.) and arrow(->) will be used to access the
data members. Below is the C program to implement the above approach: An array of structure in C programming is a collection of different datatype variables,
grouped together under a single name.
// C program to implement
// the above approach General form of structure declaration
#include <stdio.h>
#include <string.h> The structural declaration is as follows −

// Declaration of inner structure


struct tagname{
struct college_details datatype member1;
datatype member2; // 2nd student's record
datatype member n; record[1].id=2;
}; strcpy(record[1].name, "Priya");
Here, struct is the keyword record[1].percentage = 90.5;
tagname specifies name of structure // 3rd student's record
member1, member2 specifies the data items that make up structure. record[2].id=3;

Example strcpy(record[2].name, "Hari");


The following example shows the usage of array of structures in C programming − record[2].percentage = 81.5;
struct book{ for(i=0; i<3; i++){
int pages; printf(" Records of STUDENT : %d
", i+1);
char author [30];
printf(" Id is: %d
float price; ", record[i].id);
}; printf(" Name is: %s
Array of structures ", record[i].name);
 The most common use of structure in C programming is an array of structures. printf(" Percentage is: %f
 To declare an array of structure, first the structure must be defined and then an array
variable of that type should be defined. ",record[i].percentage);
 For Example − struct book b[10]; //10 elements in an array of structures of type ‘book’ }
Example: return 0;
The following program shows the usage of array of structures. }

Output
#include <stdio.h> When the above program is executed, it produces the following result −
#include <string.h> Records of STUDENT : 1
struct student{ Id is: 1
int id; Name is: Bhanu
char name[30]; Percentage is: 86.500000
float percentage; Records of STUDENT : 2
}; Id is: 2
int main(){ Name is: Priya
int i; Percentage is: 90.500000
struct student record[2]; Records of STUDENT : 3
// 1st student's record Id is: 3
record[0].id=1; Name is: Hari
strcpy(record[0].name, "Bhanu"); Percentage is: 81.500000
record[0].percentage = 86.5; Self-Referential structures: are those structures that have one or more pointers which
point to the same type of structure, as their member.

#include <stdio.h>

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

In other words, structures pointing to the same type of structures are self-referential int main()
in nature {
struct node ob1; // Node1
struct node {
int data1; // Initialization
char data2; ob1.link = NULL;
struct node* link; ob1.data1 = 10;
}; ob1.data2 = 20;

int main() struct node ob2; // Node2


{
struct node ob; // Initialization
return 0; ob2.link = NULL;
} ob2.data1 = 30;
ob2.data2 = 40;
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. // Linking ob1 and ob2
An important point to consider is that the pointer should be initialized properly ob1.link = &ob2;
before accessing, as by default it contains garbage value.
Types of Self Referential Structures // Accessing data members of ob2 using ob1
1. Self-Referential Structure with Single Link printf("%d", ob1.link->data1);
2. Self-Referential Structure with Multiple Links printf("\n%d", ob1.link->data2);
Self Referential Structure with Single Link: These structures can have only one return 0;
self-pointer as their member. The following example will show us how to connect }
the objects of a self-referential structure with the single link and access the
corresponding data members. The connection formed is shown in the following
Output
figure. 30
40
Applications: Self-referential structures are very useful in creation of other complex memory at execution time so that it has initialized each block with the default garbage
data structures like: value initially.
 Linked Lists
 Stacks Syntax:
 Queues ptr = (cast-type*) malloc(byte-size)
 Trees For Example:
 Graphs etc. ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the
DYNAMIC MEMORY ALLOCATION IN C USING MALLOC(), pointer ptr holds the address of the first byte in the allocated memory.
CALLOC(), FREE() AND REALLOC()
Since C is a structured language, it has some fixed rules for programming. One of them
includes changing the size of an array. An array is a collection of items stored at contiguous
memory locations.

If space is insufficient, allocation fails and returns a NULL pointer.


Example:

As it can be seen that the length (size) of the array above made is 9. But what if there is a #include <stdio.h>
requirement to change this length (size). For Example, #include <stdlib.h>

 If there is a situation where only 5 elements are needed to be entered in this array. In int main()
this case, the remaining 4 indices are just wasting memory in this array. So there is a {
requirement to lessen the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled. // This pointer will hold the
But there is a need to enter 3 more elements in this array. In this case, 3 indices more // base address of the block created
are required. So the length (size) of the array needs to be changed from 9 to 12. int* ptr;
This procedure is referred to as Dynamic Memory Allocation in C. int n, i;
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime. // Get the number of elements for the array
C provides some functions to achieve these tasks. There are 4 library functions provided by printf("Enter number of elements:");
C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C scanf("%d",&n);
programming. They are: printf("Entered number of elements: %d\n", n);
1. malloc()
2. calloc() // Dynamically allocate memory using malloc()
3. free() ptr = (int*)malloc(n * sizeof(int));
4. realloc()
Let’s look at each of them in greater detail. // Check if the memory has been successfully
// allocated by malloc or not
C malloc() method: The “malloc” or “memory allocation” method in C is used to if (ptr == NULL) {
dynamically allocate a single large block of memory with the specified size. It returns a printf("Memory not allocated.\n");
pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize exit(0);
}

else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


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

ptr[i] = i + 1;

}
// Print the elements of the array If space is insufficient, allocation fails and returns a NULL pointer.
printf("The elements of the array are: "); Example:
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]); #include <stdio.h>
} #include <stdlib.h>
}
return 0; int main()
} {

Output: // This pointer will hold the


Enter number of elements: 5 // base address of the block created
Memory successfully allocated using malloc. int* ptr;
int n, i;
The elements of the array are: 1, 2, 3, 4, 5,
// Get the number of elements for the array
C calloc() method:
n = 5;
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the printf("Enter number of elements: %d\n", n);
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are: // Dynamically allocate memory using calloc()
2. It initializes each block with a default value ‘0’. ptr = (int*)calloc(n, sizeof(int));
3. It has two parameters or arguments as compare to malloc().
Syntax: // Check if the memory has been successfully
ptr = (cast-type*)calloc(n, element-size); // allocated by calloc or not
if (ptr == NULL) {
here, n is the no. of elements and element-size is the size of each element.
printf("Memory not allocated.\n");
For Example: exit(0);
ptr = (float*) calloc(25, sizeof(float)); }
This statement allocates contiguous space in memory for 25 elements each with the size of else {
the float.
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) { int main()
printf("%d, ", ptr[i]); {
}
// This pointer will hold the
} // base address of the block created
int *ptr, *ptr1;
int n, i;
return 0;
// Get the number of elements for the array
} n = 5;
printf("Enter number of elements: %d\n", n);

Output: // Dynamically allocate memory using malloc()


Enter number of elements: 5 ptr = (int*)malloc(n * sizeof(int));

Memory successfully allocated using calloc. // Dynamically allocate memory using calloc()
The elements of the array are: 1, 2, 3, 4, 5, ptr1 = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
C free() method: “free” method in C is used to dynamically de-allocate the memory. The if (ptr == NULL || ptr1 == NULL) {
memory allocated using functions malloc() and calloc() is not de-allocated on their own. printf("Memory not allocated.\n");
Hence the free() method is used, whenever the dynamic memory allocation takes place. It exit(0);
helps to reduce wastage of memory by freeing it. }
else {
Syntax:
// Memory has been successfully allocated
free(ptr);
printf("Memory successfully allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated


printf("\nMemory successfully allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;

Example:
Output:
#include <stdio.h> Enter number of elements: 5
#include <stdlib.h>

Memory successfully allocated using malloc. n = 5;


printf("Enter number of elements: %d\n", n);
Malloc Memory successfully freed.
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
Memory successfully allocated using calloc.
Calloc Memory successfully freed. // Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
C realloc() method: “realloc” or “re-allocation” method in C is used to dynamically exit(0);
change the memory allocation of a previously allocated memory. In other words, if the }
memory previously allocated with the help of malloc or calloc is insufficient, realloc can be else {
used to dynamically re-allocate memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the default garbage value. // Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
Syntax:
ptr = realloc(ptr, newSize); // Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
where ptr is reallocated with new size 'newSize'. }

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

// Get the new size for the array


n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);

// Dynamically re-allocate memory using realloc()


ptr = realloc(ptr, n * sizeof(int));

If space is insufficient, allocation fails and returns a NULL pointer. // Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
Example:
// Get the new elements of the array
#include <stdio.h>
for (i = 5; i < n; ++i) {
#include <stdlib.h>
ptr[i] = i + 1;
}
int main()
{
// Print the elements of the array
printf("The elements of the array are: ");
// This pointer will hold the
for (i = 0; i < n; ++i) {
// base address of the block created
printf("%d, ", ptr[i]);
int* ptr;
}
int n, i;
free(ptr);
// Get the number of elements for the array
} marks = (int*)realloc(
marks,
return 0; (index + 1)
} * sizeof(
int)); // Dynamically reallocate
Output: // memory by using realloc
Enter number of elements: 5 // check if the memory is successfully
Memory successfully allocated using calloc. // allocated by realloc or not?
if (marks == NULL) {
The elements of the array are: 1, 2, 3, 4, 5, printf("memory cannot be allocated");
}
else {
Enter the new size of the array: 10 printf("Memory has been successfully "
"reallocated using realloc:\n");
Memory successfully re-allocated using realloc.
printf(
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "\n base address of marks are:%pc",
marks); ////print the base or
///beginning address of
One another example for realloc() method is: ///allocated memory
}
}
#include <stdio.h>
} while (ans == 1);
#include <stdlib.h>
// print the marks of the students
int main()
for (i = 0; i <= index; i++) {
{
printf("marks of students %d are: %d\n ", i,
int index = 0, i = 0, n,
marks[i]);
*marks; // this marks pointer hold the base address
}
// of the block created
free(marks);
int ans;
}
marks = (int*)malloc(sizeof(
return 0;
int)); // dynamically allocate memory using malloc
}
// check if the memory is successfully allocated by
// malloc or not? Output:
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
// memory has successfully allocated
printf("Memory has been successfully allocated by "
"using malloc\n");
printf("\n marks = %pc\n",
marks); // print the base or beginning
// address of allocated memory
do {
printf("\n Enter Marks\n");
scanf("%d", &marks[index]); // Get the marks
printf("would you like to add more(1/0): ");
scanf("%d", &ans);

if (ans == 1) {
index++;

Function declaration for the sum of two numbers is shown below


int sum(int var1, int var2);
The parameter name is not mandatory while declaring functions. We can also declare the
above function without using the name of the data variables.
int sum(int, int);

FUNCTION
Functions are sets of statements that take inputs, perform some operations, and produce
results. The operation of a function occurs only when it is called. Rather than writing the
same code for different inputs repeatedly, we can call the function instead of writing the
same code over and over again. Functions accept parameters, which are data. A function Function Definition
performs a certain action, and it is important for reusing code. Within a function, there are a A function definition consists function header and a function body.
number of programming statements enclosed by {}.
return_type function_name (parameters)
Example:
{
int sum(int a, int b);
//body of the function
}
 Return_type: The function always starts with a return type of the function. But if there
is no return value then the void keyword is used as the return type of the function.
 Function_Name: Name of the function which should be unique.
 Parameters: Values that are passed during the function call.
Function Call
To Call a function parameters are passed along the function name. In the below example,
the first sum function is called and 10,30 are passed to the sum function. After the function
call sum of a and b is returned and control is also returned back to the main function of the
program.

Function Declarations
Function declarations tell the compiler how many parameters a function takes, what kinds
of parameters it returns, and what types of data it takes. Function declarations do not need
to include parameter names, but definitions must.
Syntax:
return_type name_of_the_function (parameters);
Sum is: 40
Types of Functions

1. User Defined Function

Functions that are created by the programmer are known as User-Defined functions
or “tailor-made functions”. User-defined functions can be improved and modified
according to the need of the programmer. Whenever we write a function that is case-
specific and is not defined in any header file, we need to declare and define our own
functions according to the syntax.
Advantages of User-Defined functions
 Changeable functions can be modified as per need.
 The Code of these functions is reusable in other programs.
 These functions are easy to understand, debug and maintain.
Example:

// C program to show
// user-defined functions
Working of Function
#include <stdio.h>

int sum(int a, int b)


// C program to show function
{
// call and definition
return a + b;
#include <stdio.h>
}
// Function that takes two parameters
// Driver code
// a and b as inputs and returns
int main()
// their sum
{
int sum(int a, int b)
int a = 30, b = 40;
{
return a + b;
// function call
}
int res = sum(a, b);
// Driver code
printf("Sum is: %d", res);
int main()
return 0;
{
}
// Calling sum function and
// storing its value in add variable Output
int add = sum(10, 30);
Sum is: 70
printf("Sum is: %d", add);
return 0; 2. Library Function
}
A library function is also referred to as a “built-in function”. There is a compiler package
Output that already exists that contains these functions, each of which has a specific meaning and
is included in the package. Built-in functions have the advantage of being directly usable

without being defined, whereas user-defined functions must be declared and defined before
being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
 C Library functions are easy to use and optimized for better performance.
 C library functions save a lot of time i.e, function development time.
 C library functions are convenient as they always work.
Example:

// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

1. Pass by Value: Parameter passing in this method copies values from actual parameters
// Computing the square root with
// the help of predefined C into function formal parameters. As a result, any changes made inside the functions do not
// library function
double squareRoot = sqrt(Number); reflect in the caller’s parameters.

printf("The Square root of %.2lf = %.2lf", Below is the C program to show pass-by-value:
Number, squareRoot); // C program to show use
return 0; // of call by value
} #include <stdio.h>
Output
void swap(int var1, int var2)
The Square root of 49.00 = 7.00 {
Passing Parameters to Functions int temp = var1;
The value of the function which is passed when the function is being invoked is known as var1 = var2;
the Actual parameters. In the below program 10 and 30 are known as actual parameters. var2 = temp;
Formal Parameters are the variable and the data type as mentioned in the function }
declaration. In the below program, a and b are known as formal parameters.
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(var1, var2); In C programming language, functions can be called either with or without arguments and
printf("After swap Value of var1 and var2 is: %d, %d", might return values. They may or might not return values to the calling functions. To know
var1, var2); more about function Arguments and Return values refer to the article – Function
Arguments & Return Values in C.
return 0;
 Function with no arguments and no return value
}  Function with no arguments and with return value
 Function with argument and with no return value
Output
 Function with arguments and with return value
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2 C Math

2. Pass by Reference: The caller’s actual parameters and the function’s actual parameters C Programming allows us to perform mathematical operations through the functions defined
refer to the same locations, so any changes made inside the function are reflected in the in <math.h> header file. The <math.h> header file contains various methods for performing
caller’s actual parameters. mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
Below is the C program to show pass-by-reference:
C Math Functions
// C program to show use of
// call by Reference There are various methods in math.h header file. The commonly used functions of math.h
#include <stdio.h> header file are given below.

void swap(int *var1, int *var2) No. Function Description


{
int temp = *var1;
*var1 = *var2; 1) ceil(number) rounds up the given number. It returns the integer value which is greater
*var2 = temp; than or equal to given number.
}
2) floor(number) rounds down the given number. It returns the integer value which is less
// Driver code than or equal to given number.
int main()
{
3) sqrt(number) returns the square root of given number.
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2); 4) pow(base, returns the power of given number.
swap(&var1, &var2); exponent)
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
5) abs(number) returns the absolute value of given number.
return 0;
}

Output C Math Example

Before swap Value of var1 and var2 is: 3, 2 Let's see a simple example of math functions found in math.h header file.
After swap Value of var1 and var2 is: 2, 3
#include<stdio.h>
Function Arguments and Return values #include <math.h>

int main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}

Output:

4.000000
4.000000
3.000000 Declaration of Strings
3.000000 Declaring a string is as simple as declaring a one-dimensional array. Below is the basic
4.000000 syntax for declaring a string.
2.645751
16.000000 char str_name[size];
27.000000 In the above syntax str_name is any name given to the string variable and size is used to
12 define the length of the string, i.e the number of characters strings will store.
Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays.
STRING When a Sequence of characters enclosed in the double quotation marks is encountered by
String in C programming is a sequence of characters terminated with a null character ‘\0’. the compiler, a null character ‘\0’ is appended at the end of the string by default.
Strings are defined as an array of characters. The difference between a character array and a Initializing a String
string is the string is terminated with a unique character ‘\0’. A string can be initialized in different ways. We will explain this with the help of an
example. Below are the examples to declare a string with the name str and initialize it with
Example of C String: “GeeksforGeeks”.
4 Ways to Initialize a String in C
1. Assigning a string literal without size: String literals can be assigned without size.
Here, the name of the string str acts as a pointer because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a string literal with a predefined size: String literals can be assigned with a
predefined size. But we should always account for one extra space which will be assigned
to the null character. If we want to store a string of size n then we should always declare a
string with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning character by character with size: We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size: We can assign character by character We can see in the above program that strings can be printed using normal printf statements
without size with the NULL character at the end. The size of the string is determined by the just like we print any other variable. Unlike arrays, we do not need to print a string,
compiler automatically. character by character.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'}; Note: The C language does not provide an inbuilt data type for strings but it has an access
specifier “%s” which can be used to print and read strings directly.
Below is the memory representation of the string “Geeks”.
How to Read a String From User?
// C program to read string from user
#include<stdio.h>

int main()
{
// declaring string
char str[50];

// reading string
scanf("%s",str);
Let us now look at a sample program to get a clear understanding of declaring, initializing a
string in C, and also how to print a string with its size.
// print string
// C program to illustrate strings printf("%s",str);

#include <stdio.h> return 0;


}
#include <string.h>
Input:
int main() GeeksforGeeks
{
// declare and initialize string Output:
char str[] = "Geeks"; GeeksforGeeks
You can see in the above program that the string can also be read using a single scanf
// print string statement. Also, you might be thinking that why we have not used the ‘&’ sign with the
string name ‘str’ in scanf statement! To understand this you will have to recall your
printf("%s\n", str);
knowledge of scanf.
We know that the ‘&’ sign is used to provide the address of the variable to the scanf()
int length = 0; function to store the value read in memory. As str[] is a character array so using str without
length = strlen(str); braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’
in this case as we are already providing the base address of the string to scanf.
// displaying the length of string
printf("Length of string str is %d", length); How to Read a Line of Text in C?

return 0; We can use the fgets() function to read a line of string and gets() to read characters from the
} standard input (stdin) and store them as a C string until a newline character or the End-of-
file (EOF) is reached.
For Example:
Output:
Geeks // C program to illustrate
Length of string str is 5 // fgets()
#include <stdio.h>
#define MAX 50

int main() String is : GeeksforGeeks


{
Note: We can’t read a string value with spaces, we can use
char str[MAX]; either gets() or fgets() in the C programming language.
Strings and Pointers
// MAX Size if 50 defined
In Arrays, the variable name points to the address of the first element.
fgets(str, MAX, stdin); Similar to Arrays in C we can create a character pointer to a string that points
to the starting address of the string which is the first character of the string.
printf("String is: \n"); The string can be accessed with the help of pointers as shown in the below
example.
// Displaying Strings using Puts
// C program to print string using Pointers
puts(str);
#include <stdio.h>
return 0;
int main()
}
{
Input:
GeeksforGeeks char str[20] = "GeeksforGeeks";

Output: // Pointer variable which stores


String is: // the starting address of
GeeksforGeeks // the character array str
char* ptr = str;
Passing Strings to Function: As strings are character arrays, so we can
pass strings to function in the same way we pass an array to a function. // While loop will run till
Below is a sample program to do this: // the character value is not
// equal to null character
// C program to illustrate how to while (*ptr != '\0') {
// pass string to functions printf("%c", *ptr);
#include <stdio.h>
// moving pointer to the next character.
void printStr(char str[]) { printf("String is : %s", str); } ptr++;
}
int main()
{ return 0;
// declare and initialize string }
char str[] = "GeeksforGeeks";
Output
// print string by passing string GeeksforGeeks
// to a different function
printStr(str); Most Used Functions in C Strings:

return 0;
} Function Name Description
Output:
strlen(string_name) Returns the length of string name. Two – dimensional array is the simplest form of a multidimensional array. We can see a
two – dimensional array as an array of one-dimensional array for easier understanding.
The basic form of declaring a two-dimensional array of size x, y:
strcpy(s1, s2) Copies the contents of string s2 to string s1. Syntax:
data_type array_name[x][y];
Compares the first string with the second string. If strings are the Here, data_type is the type of data to be stored.
We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:
strcmp(str1, str2) same it returns 0.
int x[10][20];
Concat s1 string with s2 string and the result is stored in the first Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row
strcat(s1, s2) string. number and ‘j’ is the column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the
strlwr() Converts string to lowercase. row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1). A two –
dimensional array ‘x’ with 3 rows and 3 columns is shown below:
strupr() Converts string to uppercase.

strstr(s1, s2) Find the first occurrence of s2 in s1.

Must Read:
 puts() vs printf() to print a string
 Swap strings in C
 Storage for strings in C
 gets() is risky to use!

MULTIDIMENSIONAL ARRAYS IN C / C++ Initializing Two – Dimensional Arrays: There are various ways in which a Two-
A multi-dimensional array can be termed as an array of arrays that stores homogeneous Dimensional array can be initialized.
data in tabular form. Data in multidimensional arrays are stored in row-major order. First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
The general form of declaring N-dimensional arrays is:
data_type array_name[size1][size2]....[sizeN]; The above array has 3 rows and 4 columns. The elements in the braces from left to right are
stored in the table also from left to right. The elements will be filled in the array in order,
 data_type: Type of data to be stored in the array.
the first 4 elements from the left in the first row, the next 4 elements in the second row, and
 array_name: Name of the array
so on.
 size1, size2,… ,sizeN: Sizes of the dimension
Examples: Second Method:
Two dimensional array: int two_d[10][20]; int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

Three dimensional array: int three_d[10][20][30]; Third Method:


Size of Multidimensional Arrays: int x[3][4];
The total number of elements that can be stored in a multidimensional array can be for(int i = 0; i < 3; i++){
calculated by multiplying the size of all the dimensions.
For example: for(int j = 0; j < 4; j++){
 The array int x[10][20] can store total (10*20) = 200 elements. printf(“%d”,x[i][j]);
 Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
}
Two-Dimensional Array }
Fourth Method(Dynamic Allocation):

int** x = new int*[3]; Output:


Element at x[0][0]: 0
for(int i = 0; i < 3; i++){
Element at x[0][1]: 1
x[i] = new int[4];
Element at x[1][0]: 2
for(int j = 0; j < 4; j++){
Element at x[1][1]: 3
printf(“%d”,x[i][j]);
Element at x[2][0]: 4
}
Element at x[2][1]: 5
}
This type of initialization makes use of nested braces. Each set of inner braces represents Three-Dimensional Array
one row. In the above example, there is a total of three rows so there are three sets of inner
braces.
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays
are accessed using the row indexes and column indexes.
Example:
int x[2][1];
The above example represents the element present in the third row and second column.
Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for
row index 2 row number is 2+1 = 3. To output all the elements of a Two-Dimensional array
we can use nested for loops. We will require two ‘for‘ loops. One to traverse the rows and
another to traverse columns.

Example:

// C Program to print the elements of a


// Two-Dimensional array

#include<stdio.h> Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the


same as that of Two-dimensional arrays. The difference is as the number of dimensions
int main(void) increases so the number of nested braces will also increase.
{ Method 1:
// an array with 3 rows and 2 columns. int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
int x[3][2] = {{0,1}, {2,3}, {4,5}}; 11, 12, 13, 14, 15, 16, 17, 18, 19,
// output each array element's value 20, 21, 22, 23};
for (int i = 0; i < 3; i++) Method 2(Better):
{ int x[2][3][4] =
for (int j = 0; j < 2; j++)
{ {
printf("Element at x[%i][%i]: ",i, j);
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
printf("%d\n",x[i][j]);
} { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
}
};
return (0); Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-
} Dimensional Arrays is also similar to that of Two-Dimensional Arrays. The difference is
we have to use three loops instead of two loops for one additional dimension in Three-
dimensional Arrays.

// C program to print elements of Three-Dimensional Array

#include <stdio.h>

int main(void)
{
// initializing the 3-dimensional array
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };

// output each element's value


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at x[%i][%i][%i] = %d\n", i, j, k, x[i][j][k]);
}
}
}
return (0);
}

// This code is contributed by sarajadhav12052009

Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
In similar ways, we can create arrays with any number of dimensions. However, the
complexity also increases as the number of dimensions increases. The most used
multidimensional array is the Two-Dimensional Array.

You might also like