C prog notes-1
C prog notes-1
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.
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.
1. It is most importantly used when programmers make projects. As a flowchart is a basic step to make
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
Comment or Annotation
On-page connector/reference
Off-page connector/reference
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).
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.
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:
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
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
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
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:
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.
} 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.
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”
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
enum suit {
Why enums are used?
An enum variable can take only one value. Here is an example to demonstrate it,
club = 0,
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
Output Output
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.
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
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.
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 }
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
And, finally the result variable is printed as an output giving out the summation of 8 and 7.
i.e 15.
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
% 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
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
>= 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;
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
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true). printf(“%d ”,i);
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;
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:
int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
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) {
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
3 3
// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>
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()
{
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:
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
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
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.
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
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
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 ;
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") ; }
if ( filePointer == NULL )
} }
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,
fputs(dataToBeWritten, filePointer) ;
# include <stdio.h>
fputs("\n", filePointer) ;
# include <string.h>
int main( )
// Open the existing file GfgTest.c using fopen() printf( "%s" , dataToBeRead ) ;
if ( filePointer == NULL )
} }
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) {
}; fclose(fptr);
{ }
int n;
}; 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);
}
// Moving pointer to end
fclose(fptr);
fseek(fp, 0, SEEK_END);
ftell() to return the current position of a file pointer.
int x, y;
} p1; // The variable p1 is declared with 'Point'
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
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;
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;
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 −
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;
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 {
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()
} {
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));
return 0;
Example:
Output:
#include <stdio.h> Enter number of elements: 5
#include <stdlib.h>
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
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
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>
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.
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);
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
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.
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}};
Example:
#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:
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.