Unit 1
Unit 1
Input (Data):
Input is the raw information entered into a computer from the input devices. It is the collection of
letters, numbers, images etc.
Process:
Process is the operation of data as per given instruction. It is totally internal process of the
computer system.
Output:
Output is the processed data given by computer after data processing. Output is also called as
Result. We can save these results in the storage devices for the future use.
Computer Classification: By Size and Power
Computers differ based on their data processing abilities. They are classified according to
purpose, data handling and functionality.
According to functionality, computers are classified as:
• Analog Computer: A computer that represents numbers by some continuously variable physical
quantity, whose variations mimic some system’s properties being modeled.
• Personal computer: A personal computer is a computer small and low cost. The term”personal
computer” is used to describe desktop computers.
• Workstation: A terminal or desktop computer in a network. In this context, the workstation is
just a generic term for a user’s machine (client machine) in contrast to a “server” or
“mainframe.”
• Minicomputer: A minicomputer isn’t very mini. At least, not in the way most of us think of
mini. You know how big your personal computer is and its related family.
• Mainframe: It refers to the kind of large computer that runs an entire corporation.
• Supercomputer: It is the most giant, fastest, and most expensive computers on earth.
• Microcomputer: Your personal computer is a microcomputer.
In 1640s, Computer term was first used as “one who calculates.” From 1897, term changed
and got a new computer meaning “Calculating machine“. From 1945 the term indicates as
“programmable digital electronic computer“.
Computer Definition
The word compute is derived from the Latin word ‘computare’, was meaning “arithmetic,
accounting”.
The Computer meaning is the digital device that stores information in memory using input
devices and manipulate information to produce output according to given instructions.
The actual machinery, the physical parts of a computer system refer to as Computer hardware;
the instruction (a program) that tells the computer what to do or how to do, that is
called Computer software (often called just software).
Computer Meaning in general term
Two Different form of computer are exited: analog and digital computer
• Memory: It is a physical device (integrated circuits or chip) that enables a computer to store
data and programs tSsemporarily or permanently. It is also term as “primary storage”.
• Mass storage device (MSD): It is used to store large amounts of data for example hard disks,
USB drive, CD-ROM etc.
• Input device: It is any hardware device like keyboard and mouse that sends data to a computer.
• Output device: It is a device that sends data from a computer to another device.
• CPU (Central Processing Unit): It is also referred to as a processor or brains of a computer
that carries out the instructions of a computer system.
History of Computer
Uses of Computer
In digital world, from a small wrist watch to space satellite all are controlled by computer. A
small or large machine was handled by humans in past, but in digitalized world these are handled
by programmed humans i.e. ‘Robots’.
According to required services speed or efficiency different types of computers are available in
market.
• Super Computer: Large in size and more powerful. Used for large and complex calculation.
• Mainframe Computer: Mainframe computers are smaller than supercomputer. It has large
storage capacity and capable to perform large calculation. Used in bank, educational institution.
• Minicomputer: Minicomputers are multi user which are mainly used by small organization
• Microcomputer: Microcomputer is defined as small size, inexpensive, easy to carry computer
e.g. Laptop, tablets.
A computer can process data, pictures, sound and graphics. They can solve highly complicated
problems quickly and accurately. A computer as shown in Fig. performs basically five major
computer operations or functions irrespective of their size and make. These are
3. Processing: The task of performing operations like arithmetic and logical operations is called
processing. The Central Processing Unit (CPU) takes data and instructions from the storage unit
and makes all sorts of calculations based on the instructions given and the type of data provided.
It is then sent back to the storage unit.
4. Output: This is the process of producing results from the data for getting useful information.
Similarly the output produced by the computer after processing must also be kept somewhere
inside the computer before being given to you in human readable form. Again the output is also
stored inside the computer for further processing.
5. Control: The manner how instructions are executed and the above operations are performed.
Controlling of all operations like input, processing and output are performed by control unit. It
takes care of step by step processing of all operations inside the computer.
Functional Units
In order to carry out the operations mentioned in the previous section the computer allocates the
task between its various functional units. The computer system is divided into three separate
units for its operation. They are
Arithmetic Logical Unit (ALU)
Logical Unit :After you enter data through the input device it is stored in the primary storage
unit. The actual processing of the data and instruction are performed by Arithmetic Logical Unit.
The major operations performed by the ALU are addition, subtraction, multiplication, division,
logic and comparison. Data is transferred to ALU from storage unit when required. After
processing the output is returned back to storage unit for further processing or getting stored.
It requires more space and more It requires less space and less
power on the computer due to its power due to its smaller size as
5. Space
bigger size as compared to utility compared to application
software. software.
Base 16(Hexadecimal) — Represent any number using 10 digits and 6 characters [0–
9, A, B, C, D, E, F]
In any of the number systems mentioned above, zero is very important as a place-holding value.
Take the number 1005. How do we write that number so that we know that there are no tens and
hundreds in the number? We can’t write it as 15 because that’s a different number and how do we
write a million (1,000,000) or a billion (1,000,000,000) without zeros? Do you realize it’s
significance?
First, we will see how the decimal number system is been built, and then we will use the same
We all know how to write numbers up to 9, don’t we? What then? Well, it’s simple really. When
you add another digit to the left and make the right digit 0.
Then again go up to until you finish up all your symbols on the right side and when
you hit the last symbol increase the digit on the left by 1.
When you used up all the symbols on both the right and left digit, then make both of
them 0 and add another 1 to the left and it goes on and on like that.
Once you reach 9, make rightmost digit 0 and add 1 to the left which means 10.
Then on right digit, we go up until 9 and when we reach 19 we use 0 on the right digit
Likewise, when we reach 99, we use 0s in both of these digits’ places and add 1 to the
So you see when we have ten different symbols, when we add digits to the left side of a number,
each position is going to worth 10 times more than it’s previous one.
Let’s take the same decimal number system. There are only two rules actually.
You have a symbol to represent a quantity [0–9]
Then the meaning of a digit based on its position — let’s get this clarified a bit.
Let’s take one digit number ‘8’. This simply means 8, in other words, it is exactly what it says it
represents. What about 24? In case of two digits, right digit says what it means, but left digit
means ten times what it says. That is, 4 is 4, 2 is 20. Altogether forms 24.
If we take a three digit number, rightmost digit means what it says, the middle one is ten times
what it says, leftmost digit 100 times what it says. Simply if we take number 546, it means 6 + (10
* 4) + (5 * 100) = 546.
Binary
With binary, we have only two digits to represent a number, 0 and 1 and we are already out of
symbols. So what do we do? Let’s apply the same rules that we used on the decimal system.
We make the right digit 0 and add 1 to left, that is, our next number is ‘10’. Then we go up until
we used up all our symbols on the right side.So the next number in line is 11.
After ‘11’, we put 0s in both these places and add 1 to the left and we get 100.
This binary number system is based on two digits and each position is worth two times more than
Reading a binary number is almost same as reading a decimal. Right digit says what it means,
next one means two times the previous one, after that 4 times etc…
These same rules apply to octal and hexadecimal number systems as well. With octal, we have
only 8 digits to represent numbers so once we get to 7 the next number is 10 and in hexadecimal,
we have 10 digits and 6 letters to represent numbers. In that case, when we reach 9 next number is
represented in the letter ‘A’. Next one ‘B’. Likewise, we go up to letter ‘F’ and after ‘F’ comes
‘10’.
I’ll just list down few numbers in these 4 different number systems and see whether you can apply
Introduction to flowchart:
What is a Flowchart?
Flowchart is a graphical representation of an algorithm. Programmers often use it as a
program-planning tool to solve a problem. It makes use of symbols which are connected
among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic
flow. A pause/halt is generally used in a program logic under some error conditions.
Terminal is the first and last symbols in the flowchart.
Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship among
different symbols of flowchart.
Disadvantages of Flowchart:
It is difficult to draw flowcharts for large and complex programs.
There is no standard to determine the amount of detail.
Difficult to reproduce the flowcharts.
It is very difficult to modify the Flowchart.
Making a flowchart is costly.
Some developer thinks that it is waste of time.
It makes software processes low.
If changes are done in software, then the flowchart must be redrawn
Example : Draw a flowchart to input two numbers from the user and display the largest
of two numbers
// C program to find largest of two numbers
#include <stdio.h>
int main()
{
int num1, num2, largest;
/*Input two numbers*/
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
/*check if a is greater than b*/
if (num1 > num2)
largest = num1;
else
largest = num2;
/*Print the largest number*/
printf("%d", largest);
return 0;
}
Output
Enter two numbers:
10 30
30
Introduction to Algorithms:
Definition of Algorithm
The word Algorithm means ” A set of finite rules or instructions to be followed in
calculations or other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that frequently
involves recursive operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.
As one would not follow any written instructions to cook the recipe, but only the standard one.
Similarly, not all written instructions for programming are an algorithm. For some instructions
to be an algorithm, it must have the following characteristics:
Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs. It may or may not take input.
Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well. It should produce at least 1 output.
Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
Every instruction which contains a fundamental operator must be terminated within
a finite amount of time. Infinite loops or recursive functions without base conditions
do not possess finiteness.
Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
Language Independent: The Algorithm designed must be language-independent,
i.e. it must be just plain instructions that can be implemented in any language, and
yet the output will be the same, as expected.
Input: An algorithm has zero or more inputs. Each that contains a fundamental
operator must accept zero or more inputs.
Output: An algorithm produces at least one output. Every instruction that contains
a fundamental operator must accept zero or more inputs.
Definiteness: All instructions in an algorithm must be unambiguous, precise, and
easy to interpret. By referring to any of the instructions in an algorithm one can
clearly understand what is to be done. Every fundamental operator in instruction
must be defined without any ambiguity.
Effectiveness: An algorithm must be developed by using very basic, simple, and
feasible operations so that one can trace it out by using just paper and pencil.
Properties of Algorithm:
It should terminate after a finite time.
It should produce at least one output.
It should take zero or more input.
It should be deterministic means giving the same output for the same input case.
Every step in the algorithm must be effective i.e. every step should do some work.
Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:
1. Brute Force Algorithm:
It is the simplest approach to a problem. A brute force algorithm is the first approach that
comes to finding when we see a problem.
2. Recursive Algorithm:
A recursive algorithm is based on recursion. In this case, a problem is broken into several sub-
parts and called the same function again and again.
Here's a C example that calculates the factorial of a non-negative integer using recursion:
#include <stdio.h>
int factorial(int n)
if (n == 0 || n == 1)
return 1;
else
int main() {
int num;
scanf("%d", &num);
if (num < 0)
else
return 0;
}
3. Backtracking Algorithm:
The backtracking algorithm builds the solution by searching among all possible solutions.
Using this algorithm, we keep on building the solution following criteria. Whenever a solution
fails we trace back to the failure point build on the next solution and continue this process till
we find the solution or all possible solutions are looked after.
4. Searching Algorithm:
Searching algorithms are the ones that are used for searching elements or groups of elements
from a particular data structure. They can be of different types based on their approach or the
data structure in which the element should be found.
5. Sorting Algorithm:
Sorting is arranging a group of data in a particular manner according to the requirement. The
algorithms which help in performing this function are called sorting algorithms. Generally
sorting algorithms are used to sort groups of data in an increasing or decreasing manner.
6. Hashing Algorithm:
Hashing algorithms work similarly to the searching algorithm. But they contain an index with a
key ID. In hashing, a key is assigned to specific data.
7. Divide and Conquer Algorithm :
This algorithm breaks a problem into sub-problems, solves a single sub-problem, and merges
the solutions to get the final solution. It consists of the following three steps:
Divide
Solve
Combine
8. Greedy Algorithm:
In this type of algorithm, the solution is built part by part. The solution for the next part is built
based on the immediate benefit of the next part. The one solution that gives the most benefit
will be chosen as the solution for the next part.
9. Dynamic Programming Algorithm :
This algorithm uses the concept of using the already found solution to avoid repetitive
calculation of the same part of the problem. It divides the problem into smaller overlapping
subproblems and solves them.
10. Randomized Algorithm:
In the randomized algorithm, we use a random number so it gives immediate benefit. The
random number helps in deciding the expected outcome.
Advantages of Algorithms:
It is easy to understand.
An algorithm is a step-wise representation of a solution to a given problem.
In an Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms :
Writing an algorithm takes a long time so it is time-consuming.
Understanding complex logic through algorithms can be very difficult.
Branching and Looping statements are difficult to show in Algorithms(imp).
Example: Consider the example to add three numbers and print the sum.
Step 1: Fulfilling the pre-requisites
As discussed above, to write an algorithm, its prerequisites must be fulfilled.
1. The problem that is to be solved by this algorithm: Add 3 numbers and print their
sum.
2. The constraints of the problem that must be considered while solving the
problem: The numbers must contain only digits and no other characters.
3. The input to be taken to solve the problem: The three numbers to be added.
4. The output to be expected when the problem is solved: The sum of the three
numbers taken as the input i.e. a single integer value.
5. The solution to this problem, in the given constraints: The solution consists of
adding the 3 numbers. It can be done with the help of the ‘+’ operator, or bit-wise,
or any other method.
Step 2: Designing the algorithm
Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3
respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END
Step 3: Testing the algorithm by implementing it.
To test the algorithm, let’s implement it in C language.
Program:
// C program to add three numbers
// with the help of above designed algorithm
#include <stdio.h>
int main()
{
// Variables to take the input of the 3 numbers
int num1, num2, num3;
// Variable to store the resultant sum
int sum;
// Take the 3 numbers as input
printf("Enter the 1st number: ");
scanf("%d", &num1);
printf("%d\n", num1);
printf("Enter the 2nd number: ");
scanf("%d", &num2);
printf("%d\n", num2);
printf("Enter the 3rd number: ");
scanf("%d", &num3);
printf("%d\n", num3);
// Calculate the sum using + operator
// and store it in variable sum
sum = num1 + num2 + num3;
// Print the sum
printf("\nSum of the 3 numbers is: %d", sum);
return 0;
}
Output
Enter the 1st number: 0
Enter the 2nd number: 0
Enter the 3rd number: -1577141152
One problem, many solutions: The solution to an algorithm can be or cannot be more than
one. It means that while implementing the algorithm, there can be more than one method to
implement it. For example, in the above problem of adding 3 numbers, the sum can be
calculated in many ways:
+ operator
Bit-wise operators
. . etc
Fixed Part: This refers to the space that is required by the algorithm. For example,
input variables, output variables, program size, etc.
Variable Part: This refers to the space that can be different based on the
implementation of the algorithm. For example, temporary variables, dynamic
memory allocation, recursion stack space, etc.
Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C
is the fixed part and S(I) is the variable part of the algorithm, which depends on
instance characteristic I.
2. Time Complexity: The time complexity of an algorithm refers to the amount of time
required by the algorithm to execute and get the result. This can be for normal operations,
conditional if-else statements, loop statements, etc.
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 5: return 0 ends the main() function.
Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
C Variables:
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords),
for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
Syntax
type variableName = value;
Where type is one of C types (such as int), and variableName is the name of the variable (such as
x or myName). The equal sign is used to assign a value to the variable.
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
You can also declare a variable without assigning the value, and assign the value later:
Example
// Declare a variable
int myNum;
// Assign a value to the variable
myNum = 15;
Output Variables
You learned from the output chapter that you can output values/print text with the printf()
function:
Example
printf("Hello World!");
In many other programming languages (like Python, Java, and C++), you would normally use a
print function to display the value of a variable. However, this is not possible in C:
Example
int myNum = 15;
printf(myNum); // Nothing happens
To output variables in C, you must get familiar with something called "format specifiers".
Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of
data the variable is storing. It is basically a placeholder for the variable value.
A format specifier starts with a percentage sign %, followed by a character.
For example, to output the value of an int variable, you must use the format specifier %d or %i
surrounded by double quotes, inside the printf() function:
Example
int myNum = 15;
printf("%d", myNum); // Outputs 15
To combine both text and a variable, separate them with a comma inside the printf() function:
Example
int myNum = 15;
printf("My favorite number is: %d", myNum);
To print different types in a single printf() function, you can use the following:
Example
int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);
Example
// Create a variable and assign the value 15 to it
int myNum = 15;
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
Declare Multiple Variables
To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
C Variable Names
All C variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Example
// Good
int minutesPerHour = 60;
However, if you want a real-life example on how variables can be used, take a look at the
following, where we have made a program that stores different data of a college student:
Example
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
Data Types
As explained in the Variables chapter, a variable in C must be a specified data type, and you must
use a format specifier inside the printf() function to display it:
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
%d or %i Int
%f Float
%lf Double
%c Char
%s Used for strings (text), which you will learn more about in a later
chapter
Set Decimal Precision
You have probably already noticed that if you print a floating point number, the output will show
many digits after the decimal point:
Example
float myFloatNum = 3.5;
double myDoubleNum = 19.99;
If you want to remove the extra zeros (set decimal precision), you can use a dot ( .) followed by a
number that specifies how many digits that should be shown after the decimal point:
Example
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
1. **int**:
- Typically 32 bits on most systems.
- Range: -2,147,483,648 to 2,147,483,647 (for a signed int).
- Range: 0 to 4,294,967,295 (for an unsigned int).
2. **long**:
- Often 32 bits on 32-bit systems.
- Often 64 bits on 64-bit systems.
- Range: -2,147,483,648 to 2,147,483,647 (for a signed long on a 32-bit system).
- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (for a signed long on a 64-
bit system).
- Range: 0 to 4,294,967,295 (for an unsigned long on a 32-bit system).
- Range: 0 to 18,446,744,073,709,551,615 (for an unsigned long on a 64-bit system).
3. **long long**:
- Typically 64 bits on most systems.
- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (for a signed long long).
- Range: 0 to 18,446,744,073,709,551,615 (for an unsigned long long).
Keep in mind that these ranges are common but not guaranteed. To determine the exact range for
these data types on your specific system, you can use the `limits.h` header and its constants like
`INT_MIN`, `INT_MAX`, `LONG_MIN`, `LONG_MAX`, `LLONG_MIN`, and
`LLONG_MAX`. These constants are defined in the C standard library and provide information
about the minimum and maximum representable values for each data type.
For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But
since we are working with integers (and not floating-point values), the following example will just
output 2:
Example
int x = 5;
int y = 2;
int sum = 5 / 2;
To get the right result, you need to know how type conversion works.
Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.
Example
// Automatic conversion: int to float
float myFloat = 9;
As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the float
value 9.99 to an int value of 9:
Example
// Automatic conversion: float to int
int myInt = 9.99;
printf("%d", myInt); // 9
What happened to .99? We might want that data in our program! So be careful. It is important that
you know how the compiler work in these situations, to avoid unexpected results.
As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And as you
know from the beginning of this page, if you store the sum as an integer, the result will only display
the number 2. Therefore, it would be better to store the sum as a float or a double, right?
Example
float sum = 5 / 2;
Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the division. In
this case, you need to manually convert the integer values to floating-point values. (see below).
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Considering our problem from the example above, we can now get the right result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;
And since you learned about "decimal precision" in the previous chapter, you could make the output
even cleaner by removing the extra zeros (if you like):
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
Constants
If you don't want others (or yourself) to change existing variable values, you can use
the const keyword.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
Good Practice
Another thing about constant variables, is that it is considered good practice to declare them with
uppercase. It is not required, but useful for code readability and common for C programmers:
Example
const int BIRTHYEAR = 1980;
Storage classes: Automatic, Register, Static and
extern:
C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a
particular variable during the runtime of a program.
C language uses 4 storage classes, namely:
1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope). Of course, these can be accessed within nested blocks within the
parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers given
here by pointing to the very exact memory location where the variables reside. They are
assigned a garbage value by default whenever they are declared.
2. extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this
can be overwritten/changed in a different block as well. So an extern variable is nothing but a
global variable initialized with a legal value where it is declared in order to be used elsewhere.
It can be accessed within any function/block.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword
before its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead, we are using/accessing the global variable only. The
main purpose of using extern variables is that they can be accessed between two different files
which are part of a large program.
3. static
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after
they are out of their scope! Hence, static variables preserve the value of their last use in their
scope. So we can say that they are initialized only once and exist till the termination of the
program. Thus, no new memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
4. register
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of
the microprocessor if a free register is available. This makes the use of register variables to be
much faster than that of the variables stored in the memory during the runtime of the program.
If a free registration is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program are declared with the register
keyword which improves the running time of the program. An important and interesting point
to be noted here is that we cannot obtain the address of a register variable using pointers.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;
Example
Functions follow the same syntax as given above for variables. Have a look at the following C
example for further clarification:
// A C program to demonstrate different storage
// classes
#include <stdio.h>
printf("--------------------------------");
}
void registerStorageClass()
{
void externStorageClass()
{
printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nLoop started:\n");