Ip Unit-1
Ip Unit-1
Ip Unit-1
Functionalities of a computer:
Takes data as input.
Stores the data/instructions in its memory and use them when required.
Processes the data and converts it into useful information.
Generates the output.
Characteristics of Computer
Speed: Computers can perform operations at a great speed.
Accuracy: Computers exhibit a very high degree of accuracy. There is a very less chance of
computing error. Errors that may occur are usually due to human errors.
Reliability: Computers can carry out same type of work repeatedly without throwing up
errors.
Versatility: Computers can carry out a wide range of work ranging from simple data storage to
complex continuous calculations.
A Brief History of Computer:
One of the earliest and most well-known devices was an abacus. Then in 1822, the father of
computers, Charles Babbage began developing what would be the first mechanical computer. And
then in 1833 he actually designed an Analytical Engine which was a general-purpose computer.
Classification of generations of computers
The evolution of computer technology is often divided into five generations.
Five Generations of Computers
Fifth generation 1980s - present and the future Artificial intelligence based
The first generation of computers (1940s-1950s)
Main electronic component – vacuum tube
Main memory – magnetic drums and magnetic tapes
Programming language – machine language
Power – consume a lot of electricity and generate a lot of heat.
Speed and size – very slow and very large in size (often taking up entire room).
Input/output devices – punched cards and paper tape.
Examples – ENIAC, UNIVAC1, IBM 650, IBM 701, etc.
The second generation of computers (1950s-1960s)
Main electronic component – transistor
Memory – magnetic core and magnetic tape / disk
Programming language – assembly language
Power and size – low power consumption, generated less heat, and smaller in size (in
comparison with the first generation computers).
Speed – improvement of speed and reliability (in comparison with the first generation
computers).
Input/output devices – punched cards and magnetic tape.
Examples – IBM 1401, IBM 7090 and 7094, UNIVAC 1107, etc.
1.Input unit:
The set of devices used to give input to the computer is called an input unit. This unit makes a
link between user and computer.
The computer accepts input data from the user via an input device like keyboard.
The input data can be characters, word, text, sound, images, document, etc. This is either stored
in the memory or immediately used by the processor to perform the desired operations.
Commonly used input devices are Keyboard, Mouse, Joystick, Track Ball, Scanner, Microphone,
web cam etc.
2. Output unit:
The set of devices that are used to take the output from the computer are called an output unit.
The output is the result generated after the processing of data.
If the output is shown on the monitor, it is a soft copy and if the output is printed on the paper, it
is a hard copy.
Commonly used output devices are monitors, printers, speakers, headphones, projectors, GPS
devices, optical mark readers, etc.
b) Cache Memory:
Frequently addressed Instructions and data are stored in an exclusive faster memory in
the CPU to avoid wasting effort and time to bring it from slow main memory. Such
storage is called Cache memory, and its size is in the range of 2KB to 64KB.
The size of this memory is much smaller than the main memory, and the cost is higher
than the main memory but lesser than the Resisters.
c) Register Memory:
As part of the CPU, Registers are used to hold the memory addresses of the data, next
instruction, and intermediate results during the program execution.
It also acts as transit storage between the main memory and the Processor. It is the
costliest of all the memory; size-wise, it is the smallest.
Secondary storage
Secondary memory is where programs and data are kept on a long-term basis.
If we need to store large amounts of data or programs permanently, we need a cheaper and
permanent memory.
A secondary storage device refers to any non-volatile storage device that is internal or external to
the computer.
There are some characteristics of secondary memory, which distinguish it from primary memory,
such as:
It is non-volatile, which means it retains data when power is switched off.
It allows for the storage of data ranging from a few megabytes to petabytes.
It is cheaper as compared to primary memory.
Secondary storage devices like CDs and flash drives can transfer the data from one device to
another.
Secondary storage devices can be classified into three broad categories.
1) Magnetic storage devices
2) Optical storage devices
3) Solid-state storage devices
Program Counter:
A program counter (PC) is a CPU register in the computer processor which has the address of the
next instruction to be executed from memory. It is a digital counter needed for faster execution
of tasks as well as for tracking the current execution point. A program counter is also known as
an instruction counter
Flowchart:
Flowchart Symbols
Pseudo code:
Pseudo code is a term which is often used in programming and algorithm based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm.
Algorithms are represented with the help of pseudo codes as they can be interpreted by programmers
no matter what their programming background or knowledge is.
The c compilation process converts the source code taken as input into the object code or
machine code.
The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
Preprocessor
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it.
For example, if <stdio.h>, the directive is available in the program, then the preprocessor
interprets the directive and replace this directive with the content of the 'stdio.h' file.
The input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the
source code into expanded source code. The extension of the expanded source code would
be hello.i.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
The expanded source code is passed to the compiler, and the compiler converts this expanded
source code into assembly code. For example, The extension of the assembly code would be
hello.s.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file.
The extension of the object file in DOS is '.obj,' If the name of the source file is 'hello.c', then
the name of the object file would be 'hello.obj'.
Linker
A linker is a special program that combines the object files, generated by the compiler/assembler
and other pieces of code to an executable file that has a .exe extension.
In the object file, the linker searches and appends all libraries needed for the execution of the
file.
The extension of the executable file is '.exe,' i.e., ‘hello.exe’.
Loader
Loader takes input of executable files from linker, loads it to main memory, and prepares this code
for execution by computer. Loader allocates memory space to program.
Data Types in C
Data types are fundamental in computer programming because they enable a programmer to
determine the type of data that is being utilized and saved precisely.
Data type specifies what type of data , how much space should be allocated to that data
Primitive data types are built in data types. They are directly supported by machine. They are
also known as fundamental data types.
This data type includes-
integer data type (int),
character data type, i.e., character (char),
floating-point data type, i.e., containing fractional part (float),
double data type (double), which is the same as float data type, but it occupies twice
the storage space.
Void data type(void)
Variables declared with primitive data type can store only one value at a time and cannot be
divided into smaller parts.
In the table below, we have specified the various primitive data types along with specifier, range,
and memory occupied.
Size
Data type Format Specifier Range
bytes bits
int %d, %i 2 16 -32,768 to 32,767
unsigned int %u 2 16 0 to 65,535
Same as
signed int %d, %i Same as int Same as int
int
short int %hd 2 16 -32,768 to 32,767
unsigned short int %hu 2 16 0 to 65,535
signed short int %hd 2 16 Same as short int
-2,147,483,648 to
long int %ld, %li 4 32
2,147,483,647
Variables in C:
It is a name given to a memory location where we can store a value (or) Data name that is
used to store value of data
We can change the value of a variable in C or any other language, and we can also reuse it
multiple times.
How to declare a variable:
A variable can be declared by specifying its data type followed by the variable name. First choose a
data type like int, float, char, double.
Declare the variable
Syntax: data type variable1, variable2, variable3…….. ;
Example Declaration:
int age; - declares an integer variable named age
float salary; - declares a float variable named salary
char initial; - declares a char variable named initial
Declaring and initializing:
int age=25; - declares and initializes age to 25
float salary=500.25; - declares and initializes salary to 500.23
char initial=’A’; - declares and initializes initial to ‘A’
Multiple Declarations :
int a ,b ,c ; // declares three integer variables a,b,c
float x=12.05, y=3.8; // declares and initializes float variables x, y
Rules for constructing name of a Variable in C:
A variable name can consist of digits, alphabets, and special symbol underscore _
The name of the variable must not begin with a digit but begin with alphabet or underscore.
Keywords cannot be used as variable ( there are 32 keywords in c which have predefined
meaning. Keywords like include, if, while, for, switch, break etc.)
There must be no spaces or blanks in the variable name.
The maximum length of a variable must be less than or equal to 31
Examples:
Correct Wrong
int var1; int 1var;
int my_var; iny my$var;
int abc; char else;
int average; int my var:
int sum12; int sum,12;
int _sum; int roll number;
int roll_number;
Constants:
If you don't want others (or yourself) to change existing variable values, you can use
the constants
This will declare the variable as "constant", which means unchangeable and read-only:
Constants are fixed values not going to be changed throughout the program
Constants in C are declared in mainly two ways. The two ways are:
Using const Keyword
Using #define Preprocessor Directive
Declaring Constants in C using const Keyword
Constants in C can be defined by using the const Keyword.
The values of the variables which are defined using the const keyword cannot be changed
during the execution of the program.
Here is how we create constants in C using the const keyword.
Syntax: const data_type var_name = value;
const int MAX_VALUE = 100;
Declaring Constants in C using #define
We can also use #define to create constants in C. #define is a Preprocessor Directive. Here’s an
Example:
#define MAX_VALUE 100
we have to initialize the constant variables at declaration.
Otherwise, the variable will store some garbage value and we won’t be able to change it
Example program-1:
include <stdio.h>
int main( )
{
const float PI = 3.14;
float radius = 5.0;
// Using the constant PI
float area = PI * radius * radius;
printf("The area of circle is %f", area);
return 0;
}
Output: The area of circle is 78.500000
Example program-2:
#include <stdio.h>
#define PI 3.14
int main( )
{
float radius = 5.0;
// Using the constant PI
float area = PI * radius * radius;
printf("The area of circle is %f", area);
return 0;
}
Output: The area of circle is 78.500000
Tokens in C:
A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
The keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names.
C language supports 32 keywords which are given below:
do if static while
2. Identifiers
Identifiers in C are used for naming variables, functions, arrays, structures, etc. these are the user-
defined words.
It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting
letter should be either an underscore or an alphabet.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
3. Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values cannot be modified in the program once they are defined. Constants
may belong to any of the data types.
Examples of Constants in C
const int a = 20;
4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null character
indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character
is enclosed in single quotes in C.
Examples of String
Now, we describe the strings in different ways:
char a[12] = "cprogramming"; // The compiler allocates the 12 bytes to the 'a' array.
char a[] = " cprogramming "; // The compiler allocates the memory at the run time.
char a[12] = { ‘c’,’p’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,'\0'}; // String is represented in the
form of characters.
5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references. These indicate
single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
Period (.): Used to access members of a structure or union.
Tilde(~): Bitwise One’s Complement Operator.
6. Operators
In C language, operators are symbols that represent operations to be performed on one or
more operands. They are the basic components of the C programming.
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables.
The values and variables used with operators are called operands. So we can say that the
operators are the symbols that perform operations on operands.
For example: 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’.
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 Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement operators
7. Comma operator
8. Ternary or Conditional operator
9. Sizeof operator
1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
Subtracts right
2 – Minus operand from left a–b
operand.
Multiply two
3 * Multiply a*b
numeric values.
Divide two
4 / Divide a/b
numeric values.
Returns the
5 % Modulus a%b
remainder
Example of C Arithmetic Operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a + b = %d\n", a + b); 30
printf("a - b = %d\n", a - b); 20
printf("a * b = %d\n", a * b); 125
printf("a / b = %d\n", a / b); 5(QUOTIENT)
printf("a % b = %d\n", a % b); 0(REM)
return 0;
}
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.
These are a total of 6 relational operators in C:
S.
Symbol Operator Description Syntax
No.
Less than or Returns true if the left operand is less than or equal
3 <= a <= b
equal to to the right operand. Else false
6 != Not equal to Returns true if both the operands are NOT equal. a != b
C program to illustrate the relational operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}
Here, 0 means false and 1 means true.
3. Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.
1 && Logical AND Returns true if both the operands are true. a && b
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is performed on the
operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed
at the bit level for faster processing.
S.
Symbol Operator Description Syntax
No.
Bitwise First
4 ~ Flips all the set and unset bits on the number. ~a
Complement
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 single operator. These operators are called compound operators.
Minus and Subtract the right operand and left operand and
3 -= a -= b
assign assign this value to the left operand.
Multiply and Multiply the right operand and left operand and
4 *= a *= b
assign assign this value to the left operand.
Divide and Divide the left operand with the right operand and
5 /= a /= b
assign assign this value to the left operand.
Right shift and Performs bitwise Right shift and assign this value a >>=
10 >>=
assign to the left operand. b
Left shift and Performs bitwise Left shift and assign this value to a <<=
11 <<=
assign the left operand. b
2. Post-Increment
In post-increment, first use value of a variable and then increment operation is performed It is
also known as postfix increment.
Example
result = var1++;
The above expression is equivalent
result = var;
var = var + 1;
Example of Increment Operator
#include <stdio.h>
int main()
{
int a = 5,b=5,x,y;
x= ++a; // PREFIX
printf("Prefix Increment: %d\n", x);
x = b++; // POSTFIX
printf("Postfix Increment: %d", x);
return 0;
}
Output
Prefix Increment: 6
Postfix Increment: 5
As we can see in postfix, the value is incremented after the assignment operator is done.
Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an expression. The
decrement operator can also be used in two ways:
--a // AS PREFIX
a-- // AS POSTFIX
where a is variable.
1. Pre-Decrement Operator
In the Pre-Decrement, the value is first decremented and then used inside the expression.
Example
result = --var;
which can be expanded to
var = var - 1;
result = var;
2. Post-Decrement Operator
In the Post-Decrement, the value is first used inside the expression and then decremented.
Example
result = var--;
The above expression can be expanded as
result = var;
var = var-1;
Example of Decrement Operator
#include <stdio.h>
int main( )
{
int a = 5,b=5,x,y;
x = --a; // PREFIX
printf("Prefix = %d\n", x);
x = b--; // POSTFIX
printf("Postfix = %d", x);
return 0;
}
Output:
Prefix = 4
Postfix = 5
7. Comma Operator ( , )
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator.
Syntax: operand1, operand2
8. Conditional Operator ( ? : )
The conditional operator is the only ternary operator in C.
Syntax: variable = Expression1 ? Expression2 : Expression3;
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we
will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
Example program for conditional or ternary operator
#include <stdio.h>
int main()
{
int a = 5, b = 4;
(a > b) ? printf("a is greater than b that is %d > %d",a, b): printf("b is greater than a that is
%d > %d",b, a);
return 0;
}
Output
a is greater than b that is 5 > 4
9. Sizeof operator:
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
* Dereference right-to-left
10 | Bitwise OR left-to-right
12 || Logical OR left-to-right
= Assignment right-to-left
Example problem-1:
Example problem-2:
Example problem-3:
Example problem-4:
Typecasting
Typecasting is also called an explicit type conversion.
Compiler converts data from one data type to another data type implicitly. When compiler
converts implicitly, there may be a data loss.
In such a case, we convert the data from one data type to another data type using explicit type
conversion. To perform this we use the unary cast operator.
To convert data from one type to another type we specify the target data type in parenthesis as a
prefix to the data value that has to be converted.
The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Example
int total = 450, marks = 600 ;
float avg ;
avg = (float) total / marks * 100 ;
In the above example code, both total and marks are integer data values. When we perform
total/ marks the result is a float value, but the destination (avg) datatype is a float. So we use
type casting to convert total and marks into float data type.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf(“%d%d%d”,&a,&b,&c);
avg = (a + b + c) / 3 ;
printf(“Avg before casting: %f”, avg);
avg=(float)(a+b+c)/3;
printf(“Avg after casting: %f”, avg);
return 0;
}
Output:
Enter any three integer values : 2 4 5
Avg before casting: 3.000000
Avg after casting: 3.666666.
Hierarchy of datatypes
The conversion will occur in the hierarchy as follows.