Notes
Notes
task.
Input Unit:
Computers need to receive data and instruction in order to solve any problem.
Therefore, we
need to input the data and instructions into the computers. The input unit
consists of one or
more input devices. Keyboard is the one of the most commonly used input
device. Other
commonly used input devices are the Mouse, Scanner, Microphone etc. All
the input devices
Storage Unit:
The storage unit of the computer holds data and instructions that are entered
through the input
unit, before they are processed. It preserves the intermediate and final results
before these are
sent to the output devices. It also saves the data for the later use. The various
storage devices
a) Primary Storage: Stores and provides very fast. This memory is generally
used to hold
the program being currently executed in the computer, the data being received
from the
input unit, the intermediate and final results of the program. The primary
memory is
temporary in nature. The data is lost, when the computer is switched off. In
order to store
the data permanently, the data has to be transferred to the secondary memory.
The cost of
documents, data bases etc. The programs that you run on the computer are
first transferred
to the primary memory before it is actually run. Whenever the results are
saved, again they
get stored in the secondary memory. The secondary memory is slower and
cheaper than the
primary memory. Some of the commonly used secondary memory devices are
Hard disk,
CD, etc.,
Memory Size:
All digital computers use the binary system, i.e. 0’s and 1’s. Each character or
a number is
equal to 1024 bytes and one MB is equal to 1000KB. The size of the primary
storage in a
typical PC usually starts at 16MB. PCs having 32 MB, 48MB, 128 MB,
256MB memory are
quite common.
Output Unit:
world. Printers, Visual Display Unit (VDU) are the commonly used output
devices. Other
All calculations are performed in the Arithmetic Logic Unit (ALU) of the
computer. It also
does comparison and takes decision. The ALU can perform basic operations
such as addition,
subtraction, multiplication, division, etc and does logic operations viz, >, <, =,
‘etc. Whenever
calculations are required, the control unit transfers the data from storage unit
to ALU once the
computations are done, the results are transferred to the storage unit by the
control unit and
Control Unit:
It controls all other units in the computer. The control unit instructs the input
unit, where to
store the data after receiving it from the user. It controls the flow of data and
instructions from
the storage unit to ALU. It also controls the flow of results from the ALU to
the storage unit.
The control unit is generally referred as the central nervous system of the
computer that control
The Control Unit (CU) and Arithmetic Logic Unit (ALU) of the computer are
together known
as the Central Processing Unit (CPU). The CPU is like brain performs the
following functions:
Types of Computer
powerful microprocessor
4 Main Frame
PC (Personal Computer)
entire CPU on one chip. Businesses use personal computers for word
processing, accounting,
home, the most popular use for personal computers is playing games and
surfing Internet.
Macintosh and PC offer the same computing power and graphics capability as
low-end
Workstation
mass storage device such as a disk drive, but a special type of workstation,
called a diskless
Common operating systems for workstations are UNIX and Windows NT.
Like PC,
Workstations are also single-user computers like PC but are typically linked
together to form
Minicomputer
Mainframe
Supercomputer
expensive and are employed for specialized applications that require immense
amount of
● Input Devices: Input Devices are those devices through which a user
enters data and information into the Computer or simply, User interacts
with the Computer. Examples of Input Devices are Keyboard, Mouse,
Scanner, etc.
● Output Devices: Output Devices are devices that are used to show the
result of the task performed by the user. Examples of Output Devices
are Monitors, Printers, Speakers, etc.
● Storage Devices: Storage Devices are devices that are used for storing
data and they are also known as Secondary Storage Data. Examples of
Storage Devices are CDs, DVDs, Hard Disks, etc.
● Internal Component: Internal Components consist of important
hardware devices present in the System. Examples of Internal
Components are the CPU, Motherboard, etc.
Properties of an Algorithm
● Input
● Output
● Finiteness
● Definiteness
● Effectiveness
The Algorithm for finding the average of three numbers is as follows: It reads
three numbers, calculates their average and sum, and then prints the
average value. It involves basic arithmetic operations and simple
input/output steps.
● STEP 1 : Start
● STEP 2 : Read 3 numbers a,b,c
● STEP 3 : Compute sum = a+b+c
● STEP 4 : Compute average = sum/3
● STEP 5 : Print average value
● STEP 6 : Stop
Diagrammatic Representation
Flow Chart
There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the
program, and the creation date and time of the program. It is specified at
the start of the program in the form of comments. Documentation can be
represented as:
The basic structure of a C program is divided into 6 parts which makes it easy
to read, modify, document, and understand in a particular format. C
program must follow the below-mentioned outline in order to successfully
compile and execute. Debugging is easier in a well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the
program, and the creation date and time of the program. It is specified at
the start of the program in the form of comments. Documentation can be
represented as:
or
/*
*/
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section
of the program. Header files help us to access others improved code into
our code. A copy of these multiple files is inserted into our program before
the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the
process of compilation. There are multiple steps which are involved in the
writing and execution of the program. Preprocessor directives start with the
‘#’ symbol. The #define preprocessor is used to create a constant
throughout the program. Whenever this name is encountered by the
compiler, it is replaced by the actual piece of defined code.
Example:
4. Global Declaration
Example:
5. Main() Function
Every C program must have a main function. The main() function of the
program is written in this section. Operations like declaration and
execution are performed inside the curly braces of the main program. The
return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int
main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of
the program is shifted to the called function whenever they are called from
the main or outside the main() function. These are specified as per the
requirements of the programmer.
Example:
return x+y;
}
Structure of C Program with example
/**
* file: sum.c
* author: you
*/ // Documentation
printf("%d",y);
return 0;
The below table illustrates the primary differences between the keywords
and identifiers:
Keywords are
predefined word
Identifiers are the values used to
that gets reserved
define different programming
for working
items such as variables,
Definition program that have
integers, structures, unions and
special meaning
others and mostly have an
and cannot get
alphabetic character.
used anywhere
else.
Keywords
dou ext
el en
b e floa got
s u for if
l r t o
e m
e n
reg
i ret sta
lo size
s u shor signe t
int n o
t r t d i
g f
e n c
r
s
typ unsi vola w
w
stru e uni g t h
i
c d o n void i i
t
t e n e l l
c
f d e e
h
Identifiers
#include <stdio.h>
// although it is predefined
}
Difference Between Constants and Variables in C
The constants and variables in C are both used to store data. So it is essential
to know the difference between the variables and constants in C so that we
can decide which one to use based on the situation.
In this article, we will discuss the basic difference between a constant and a
variable in C language.
Variables in C
A variable in simple terms is a storage place that has some memory allocated
to it. It is used to store some form of data and retrieve it when required.
Different types of variables require different amounts of memory and have
some specific set of operations that can be applied to them.
C Variable Declaration
type variable_name;
A variable name can consist of alphabets (both upper and lower case),
numbers, and the underscore ‘_’ character. However, the name must not
start with a number.
Example of C Variable
#include <stdio.h>
int main()
float b;
return 0;
OUTPUT : a
Constants in C
The constants are those variables or values in the C which cannot be modified
once they are defined in the program.
Example of C Constant
#include <stdio.h>
Output
Integer Constant: 10
Character Constant: a
The following table lists the differences between the constant and variables in
C:
Constant Variables
A constant is used to hold the fixed values A variable is used to hold some
which we can retrieve later but cannot value that can be changed
change. according to the requirement.
The variables are stored inside a
The constants are generally stored in the text data segment, heap, or stack
segment as they are read-only depending on the environment
it is declared in.
We can only assign a value to the constant We can assign value to the
while defining it. variable anytime.
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc. Each
data type requires different amounts of memory and has some specific
operations which can be performed over it.
The data types in C can be classified as follows:
Data
Types Description Typ
es
int,
Primiti Primitive data types are the most char,
ve basic data types that are used float,
Data for representing simple values doub
Typ such as integers, float, le,
es characters, etc. void
array,
Derive The data types that are derived point
d from the primitive or built-in ers,
Typ datatypes are referred to as funct
es Derived Data Types. ion
User structur
Defi e,
ned The user-defined data types are unio
Data defined by the user himself. n,
Typ enu
es m
Understanding C’s data types is critical for writing efficient programs.
The integer datatype in C is used to store the integer numbers (any number
including positive, negative and zero without decimal part). Octal values,
hexadecimal values, and decimal values can be stored in int data type in C.
Syntax of Integer
int var_name;
values from zero to positive numbers but it can’t store negative values
like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store
than int.
4. unsigned short int: Similar in relationship with short int as unsigned
Example of int
#include <stdio.h>
int main()
int a = 9;
// integer value with negative data.
int b = -9;
int c = 89U;
c);
return 0;
}
Output
Syntax of char
char var_name;
Example of char
#include <stdio.h>
int main()
char a = 'a';
char c;
a++;
// character 'c'
c = 99;
return 0;
}
Output
Value of a: a
Value of c: c
Float Data Type
Syntax of float
float var_name;
Example of Float
// of Floating types
#include <stdio.h>
int main()
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
Output
9.000000
2.500000
0.000200
Syntax of Double
The variable can be declared as double precision floating point using the
double keyword:
double var_name;
Example of Double
// C Program to demonstrate
#include <stdio.h>
int main()
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output
123123123.000000
12.293123
2312312312.123123
Void Data Type
The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller. It has no values and no operations. It is
used to represent nothing. Void is used in multiple ways as function return
type, function arguments as void, and pointers to void.
Syntax:
int print(void);
Example of Void
// C program to demonstrate
#include <stdio.h>
int main()
printf("%d", *(int*)ptr);
return 0;
}
Output
30
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so
we cannot define the universal size of the data types. For that, the C
language provides the sizeof() operator to check the size of the data types.
Example
#include <stdio.h>
int main()
size_of_char);
size_of_float);
size_of_double);
return 0;
Output
Size
Form
(
at
b
S
y
Data Type Range pe
t
ci
e
fi
s
er
)
unsigned
2 0 to 65,535 %hu
short int
unsigned
4 0 to 4,294,967,295 %lu
long int
long long
8 -(2^63) to (2^63)-1 %lld
int
unsigned
long 8 0 to 18,446,744,073,709,551,615 %llu
long int
unsigned
1 0 to 255 %c
char
Different data types also have different ranges up to which they can store
numbers. These ranges may vary from compiler to compiler. Below is a list
of ranges along with the memory requirement and format specifiers on the
32-bit GCC [Link]: The long, short, signed and unsigned are
datatype modifiers that can be used with some primitive data types to
change the size or length of the datatype.
Enumeration (or enum) in C
The keyword ‘enum’ is used to declare new enumeration types in C and
C++. Enums in C allow you to assign names to integral constants, making
code more readable.
Variables of type enum can also be defined. They can be defined in two
ways:
// Or
// of enum in C
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
day = Wed;
printf("%d",day);
return 0;
Output:
In the above example, we declared “day” as the variable and the value of
“Wed” is allocated to day, which is 2. So as a result, 2 is printed.
Another example of enumeration is:
#include<stdio.h>
int main()
int i;
return 0;
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the
value of i is Jan which is 0 and the value of Dec is 11.
Interesting facts about initialization of enum.
1. Two enum names can have same value. For example, in the following C
program both ‘Failed’ and ‘Freezed’ have same value 0.
#include <stdio.h>
int main()
return 0;
Output:
1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by
default assigns values starting from 0. For example, in the following C
program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>
int main()
return 0;
Output:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the
operands ‘a’ and ‘b’. To dive deeper into how operators are used with data
structures, the C Programming Course Online with Data Structures
covers this topic thoroughly.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6
types based on their functionality:
1. Arithmetic Operations in C
Symb Operat
S. No. Description Syntax
ol or
Multipl
3 * Multiply two numeric values. a*b
y
4 / Divide Divide two numeric values. a/b
Unary
6 + Used to specify the positive values. +a
Plus
Unary
7 – Min Flips the sign of the value. -a
us
Increm
8 ++ Increases the value of the operand by 1. a++
ent
#include <stdio.h>
int main()
int a = 25, b = 5;
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26
2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands.
All these operators are binary operators that return true or false values as
the result of comparison.
Less
Returns true if the left operand is less than
1 < tha a<b
the right operand. Else false
n
Greate
r Returns true if the left operand is greater
2 > a>b
tha than the right operand. Else false
n
Less
tha
n
Returns true if the left operand is less than
3 <= or a <= b
or equal to the right operand. Else false
equ
al
to
Greate
r
tha Returns true if the left operand is greater
4 >= a >= b
n than or equal to right operand. Else false
or
equ
al
to
Equal
5 == Returns true if both the operands are equal. a == b
to
Not
equ Returns true if both the operands are NOT
6 != a != b
al equal.
to
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
S
Sym
b Operator Description Syntax
ol
Logical
1 && Returns true if both the operands are true. a && b
AND
Logical
3 ! Returns true if the operand is false. !a
NOT
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
}
Output
a && b : 1
a || b : 1
!a: 0
4. Bitwise Operators in C
Sy
S.
m
N Operat
b Description Syntax
o or
o
.
l
Bitwis
e Performs bit-by-bit AND operation and
1 & a&b
AN returns the result.
D
Bitwis
Performs bit-by-bit OR operation and
2 | e a|b
returns the result.
OR
Bitwis
e Performs bit-by-bit XOR operation and
3 ^ a^b
XO returns the result.
R
Bitwis
e
Firs
t Flips all the set and unset bits on the
4 ~ ~a
Co number.
mpl
em
ent
Bitwis
e Shifts the number in binary form by one
<
5 Lef place in the operation and returns the a << b
<
tshi result.
ft
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side operand
of the assignment operator is a value. The value on the right side must be
of the same data type as the variable on the left side otherwise the compiler
will raise an error.
The assignment operators can be combined with some other operators in C to
provide multiple operations using a single operator. These operators are
called compound operators.
Performs bitwise OR
OR and and assigns this
8 |= a |= b
assign value to the left
operand.
Performs bitwise XOR
XOR and and assigns this
9 ^= a ^= b
assign value to the left
operand.
Performs bitwise
Rightshift
Rightshift and assign
10 >>= and a >>= b
this value to the left
assign
operand.
Performs bitwise
Left shift and Leftshift and assign
11 <<= a <<= b
assign this value to the left
operand.
#include <stdio.h>
int main()
int a = 25, b = 5;
// using operators and printing results
return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a >>= b: 0
a <<= b: 0
6. Other Operators
Apart from the above operators, there are some other operators available in C
used to perform some specific tasks. Some of them are discussed here:
sizeof Operator
Syntax
sizeof (operand)
Comma Operator ( , )
Syntax
operand1 , operand2
To know more about the topic refer to this article.
Conditional Operator ( ? : )
Syntax
Syntax
structure_variable . member;
and
To know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.
Cast Operator
Syntax
(new_type) operand;
● Pointer operator & returns the address of a variable. For example &a;
will give the actual address of the variable.
● The pointer operator * is a pointer to a variable. For example *var; will
pointer to a variable var.
To know more about the topic refer to this article.
#include <stdio.h>
int main()
// integer variable
Output
sizeof(num) = 4 bytes
&num = 0x7ffe2b7bdf8c
*add_of_num = 10
(10 < 5) ? 10 : 20 = 20
(float)num = 10.000000
Unary, Binary and Ternary Operators in C
Operators can also be classified into three types on the basis of the number of
operands they work on:
The below table describes the precedence order and associativity of operators
in C. The precedence of the operator decreases from top to bottom.
Parentheses (function
() left-to-right
call)
Brackets (array
[] left-to-right
1 subscript)
Postfix
a++ , a– increment/decrement left-to-right
(a is a variable)
Prefix
++a , –a increment/decrement right-to-left
(a is a variable)
Logical negation/bitwise
2 !,~ right-to-left
complement
* Dereference right-to-left
& Address (of operand) right-to-left
Multiplication/division/m
3 *,/,% left-to-right
odulus
6
Relational greater
> , >= than/greater than or left-to-right
equal to
Relational is equal to/is
7 == , != left-to-right
not equal to
10 | Bitwise OR left-to-right
12 || Logical OR left-to-right
= Assignment right-to-left
14
Addition/subtraction
+= , -= right-to-left
assignment
Multiplication/division
*= , /= right-to-left
assignment
Modulus/bitwise AND
%= , &= right-to-left
assignment
Bitwise
^= , |= exclusive/inclusive right-to-left
OR assignment
Error Handling in C
Although C does not provide direct support to error handling (or
exception handling), there are ways through which error handling
can be done in C. A programmer has to prevent errors in the first
place and test return values from the functions.
What is errno?
errno Error
va
lu
e
1 Operation not
permitted
2 No such file or
directory
3 No such process
4 Interrupted system
call
5 I/O error
6 No such device or
address
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
Example of errno
C
#include <errno.h>
#include <stdio.h>
int main()
FILE* fp;
return 0;
Output
Value of errno: 2
Note: Here the errno is set to 2 which means “No such file or
directory”. It may give Errno 13 in online IDE, which says
permission denied.
1. perror()
2. strerr()
3. ferror()
4. feof()
5. clearerr()
6. Exit Status
7. Divide by Zero Error
1. perror()
Syntax
Example
C
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
FILE* fp;
// not exist.
return 0;
}
Output
Value of errno: 2
2. strerror()
The strerror() function is also used to show the error description. This
function returns a pointer to the textual representation of the current
errno value.
Syntax
Parameters
Example
C
// C implementation to see how strerror() function is used
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;
// not exist.
return 0;
Output
Value of errno: 2
The error message is : No such file or directory
3. ferror()
Syntax
Parameters
Return Value
Example
C
// C program to demonstrate the ferror() function
#include <stdio.h>
int main()
// indicate an error
return 1;
}
int c;
}
if (ferror(file)) {
printf(
else {
fclose(file);
// execution
return 0;
}
Output
4. feof()
Syntax
Parameters
Return Value
Example
C
#include <stdio.h>
int main()
if (fptr == NULL) {
// Print error message if file opening fails
return 1;
if (ferror(fptr)) {
// Print error message if file operation fails
fclose(fptr);
return 0;
Output
Error opening the file: No such file or directory
5. clearerr()
Syntax
Parameters
Example
C
#include <stdio.h>
int main()
if (file == NULL) {
// Print an error message
// indicate an error
return 1;
}
// Perform file operations
// opened file
if (ferror(file)) {
// if an error occurred
"operations.\n");
// file stream
clearerr(file);
// Continue with file operations
fclose(file);
return 0;
}
6. Exit Status
Exit status is the value returned by the program after its execution is
completed which tells the status of the execution of the program.
Example
C
// C implementation which shows the
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
FILE* fp;
fp = fopen("[Link]", "rb");
if (fp == NULL) {
exit(EXIT_FAILURE);
else {
fclose(fp);
exit(EXIT_SUCCESS);
return 0;
Output
Value of errno: 2
Example
C
// C program to check and rectify
#include <stdio.h>
#include <stdlib.h>
void function(int);
int main()
int x = 0;
function(x);
return 0;
void function(int x)
{
float fx;
if (x == 0) {
exit(EXIT_FAILURE);
}
else {
fx = 10 / x;
Output