Unit 1 CP (R23)
Unit 1 CP (R23)
The history of computer is considered with the generations of a computer from first
generation to fifth generation. In 19th century English mathematics professor name Charles Babbage
referred as a “Father of Computer”.
Generally, computers can be classified into five generations. The generations of computer are
as follows:
In 1937 the first electronic digital computer was built by Dr. John V. Atanasoff and Clifford
Berry. It was called the Atanasoff-Berry Computer (ABC). In 1943 an electronic computer name the
Colossus was built for the military. Other developments continued until in 1946 the first general–
purpose digital computer, the Electronic Numerical Integrator and Calculator (ENIAC) was built. It is
said that this computer weighed 30 tons, and had 18,000 vacuum tubes which was used for
processing. When this computer was turned on for the first time lights dim in sections of
Philadelphia. Computers of this generation could only perform single task, and they had no operating
system.
Characteristics:
Second generation of computers used transistors instead of vacuum tubes which were more
reliable. In 1951 the first computer for commercial use was introduced to the public; the Universal
Automatic Computer (UNIVAC 1). In 1953 the International Business Machine (IBM) 650 and 700
series computers made their mark in the computer world. During this generation of computers over
100 computer programming languages were developed, computers had memory and operating
systems. Storage media such as tape and disk were in use also were printers for output.
Characteristics:
i. The computers were still large, but smaller than the first generation of computers.
ii. They use transistor in place of Vacuum Tubes to perform calculation.
iii. They were produced at a reduced cost compared to the first generation of computers.
iv. Possession of magnetic tapes as for data storage.
v. They were using punch cards as input and output of data and information. The use of
keyboard as an input device was also introduced.
vi. These computers were still generating a lot of heat in which an air conditioner is
needed to maintain a cold temperature.
vii. They have about one thousand circuits per cubic foot.
The invention of integrated circuit brought us the third generation of computers. With this
invention computers became smaller, more powerful more reliable and they are able to run many
different programs at the same time.
Characteristics:
i. They used large-scale integrated circuits, which were used for both data processing
and storage.
ii. Computers were miniaturized, that is, they were reduced in size compared to
previous generation.
iii. Keyboard and mouse were used for input while the monitor was used as output
device.
iv. Use of programming language like COBOL and FORTRAN were developed.
v. They have hundred thousand circuits per cubic foot.
Characteristics:
Fifth generations computing devices, based on artificial intelligence (AI) are still in
development, although there are some application such as voice recognition, facial face detector and
thumb print that are used today.
Characteristics:
Input Unit
Data and instructions are entered into the computer through the input unit to get processed
into information. Input devices like the keyboard, the mouse, or the microphone are used to
enter the data. The data is entered in various forms depending on the type of input devices. For
instance, a keyboard can be used to input characters, numbers, and certain symbols; a mouse is a
device that has an on-screen pointer that enables the users to select items and choose options; a
microphone can be used if the user wishes to enter instructions by making a voice entry.
Regardless of the ways in which the input devices receive the inputs, the input interfaces convert
them into binary codes, i.e., 0s and 1s, as the primary memory of the computer is designed to
accept data only in this format.
The actual processing of the data is carried out in the Central Processing Unit (CPU), which is
the brain of computer. The CPU stores the data and instructions in the primary memory of the
computer, called the Random Access Memory (RAM) and processes them from this location. The
Arithmetic Logic Unit (ALU) and the Control Unit (CU) are the two subcomponents of the CPU.
The ALU carries out the arithmetic and logical operations while the CU retrieves the information
from the storage unit and interprets this information. The CPU also consists of circuitry devices
called cache and registers.
The data and instructions stored in the RAM are transferred to the ALU for processing. The
ALU performs the logical and the arithmetic operations on the data and the results are
temporarily stored in the RAM. After the processing, the final results are stored in the secondary
memory, i.e., the storage unit, and are released through an output device.
The CU obtains the program instructions stored in the primary memory of the computer,
interprets them, and issues signals that result in their execution. It helps in maintaining order and
directs the operations of the entire system. It selects, interprets, and ensures the proper
execution of the program instructions.
Output Unit
The output unit passes on the final results of computation to the users through the output
devices like the monitor, printer, etc. A monitor displays the final results of the processed data on
the screen while a printer can be used for obtaining the output in a printed format. These output
devices link the computer with the users. The output interfaces convert the binary code produced
by the computer into the human-readable form.
Storage Unit
Before the actual processing takes place, the data and instructions that enter the computer
system have to be stored internally. Also, the final results generated by the computer after
processing has to be stored before being sent to the output unit. The storage unit of a computer
system is designed to store the data generated at various stages of processing. Storage media like
hard disks, floppy disks, etc., aid in storing the data in various forms. The hard disk is an integral
part of the computer system.
Program Counter
A program counter is a register in a computer processor that contains the address (location)
of the instruction being executed at the current time. As each instruction gets fetched, the
program counter increases its stored value by 1. After each instruction is fetched, the program
counter points to the next instruction in the sequence. When the computer restarts or is reset, the
program counter normally reverts to 0.
ALGORITHM
5) Effectiveness : Every instruction must be basic enough to be carried out theoretically or by using
paper and pencil.
FLOWCHART
PSEUDOCODE
Compilation Process
The compilation and execution process of C can be divided into multiple steps:
Preprocessing: Using a Preprocessor program to convert C source code in expanded source
code. "#include" and "#define" statements will be processed and replaced actually source
codes in this step.
Compilation: Using a Compiler program to convert C expanded source to assembly source
code.
Assembly: Using a Assembler program to convert assembly source code to object code.
Linking: Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.
Loading: Using a Loader program to load the executable code into CPU for execution.
Linking
After all of the files are compiled, they must be "merged together" to produce a single
executable file that the user use to run the program.
In C, most compiled programs produce results only with the help of some standard programs,
known as library files that reside in the computer. This process is called linking.
The result obtained after linking is called the executable file.
The linker′s primary function is to bind symbolic names to memory addresses.
To do this, it first scans the files and concatenates the related file sections to form one large
file. Then, it makes a second pass on the resulting file to bind symbol names to real memory
addresses.
Loading is loading the executable into memory prior to execution.
There are two types of linking: Static linking. Dynamic linking.
Static linking occurs at compilation time; hence it occurs prior to loading a program. With
static linking the external symbols that are used by the program (e.g. function names) are
resolved at compile time.
Dynamic linking occurs at run time, so it occurs after or at the time of the loading of a
program. With dynamic linking the symbols are resolved either at loading time, or at run time
A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.
The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
float 4 byte
double 8 byte
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them. It is frequently applied to variables that include values, such as counts, indices, or
other numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2
billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one byte of memory. Characters
such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4 x
1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed, such as
in scientific calculations or financial applications, it provides greater accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields
larger values. C treats floating point numbers as doubles by default if no explicit type is supplied.
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables for
the number pi.
Variables
The variable is used to store the value. As the name indicates its value can be changed or also it can
be reused many times. We have to define its Data Types in C as shown below.
Syntax :
Datatype variable_name;
e.g. int a;
Where ‘a’ is the variable.
Types of Variables in C:
There are many types of variables in c:
local variable
global variable
static variable
external variable
Automatic variable
1. Local variable – A variable which is declared inside the function is known as local variable. It is
used only inside the function in which it is declared.
2. Global variable – A variable which is declared outside the function is known as global variable. It
can be used throughout the program.
3. Static variable – It is used to retain its value between multiple function calls. It is declared using
static keyword.
4. External variable – You can share a variable in multiple C source files by using external variable. It
is declared using extern keyword.
5. Automatic variable – Variable which is declared inside the block is known as automatic variable by
default.
Constants:
Its value is fixed throughout the program that means constants are those variables which value is not
changed throughout the program.
C constants can be divided into two major categories:
Primary Constants
Secondary Constants
1. Using #define
#include <stdio.h>
#define value 10
void main() {
int data;
data = value*value;
printf("value of data : %d",data);
}
Output
value of data : 100
Output
value of data : 100
Input means to provide the program with some data to be used in it.
Output means to display data on the screen or write the data to a printer or a file.
There are two types of input output functions:
i. Unformatted Input/Output functions
ii. Formatted Input/Output functions
1. getchar()
2. putchar()
3. gets()
4. puts()
5. getch()
1. getchar(): The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads one
character at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
// Driver code
int main()
{
// Declaring a char type variable
char ch;
2. putchar(): The putchar() function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)
Syntax: putchar(variable_name);
Ex: // C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
3. gets(): gets() function reads a group of characters or strings from the keyboard by the user and
these characters get stored in a character array. This function allows us to write space-separated
texts or strings. This function is declared in stdio.h(header file).
Syntax: gets(variable_name)
Ex: char str[length of string in number]; //Declare a char type variable of any length
gets(str);
Ex: //C program to implement
// the gets() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type array of length 50 characters
char name[50];
printf("Please enter some texts: ");
4. puts(): In C programming puts() function is used to display a group of characters or strings which
is already stored in a character array. This function is declared in stdio.h(header file).
Syntax: puts(identifier_name );
// Displays string
puts(name);
return 0;
}
Output:
Enter your text: Welcome to BVCITS
Your text is: Welcome to BVCITS
5. getch(): getch() function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately returned without pressing enter
key. This function is declared in conio.h(header file). getch() is also used for hold the screen.
Syntax: getch();
or variable-name = getch();
Ex: // C program to implement getch() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
printf("Enter any character: ");
return 0;
}
Output:
Enter any character:
ii. Formatted Input/Output functions:
Formatted I/O functions are used to take various inputs from the user and display multiple
outputs to the user. These types of I/O functions can help to display the output to the user in
different formats using the format specifiers. These I/O supports all data types like int, float, char,
and many more. These functions are called formatted I/O functions because we can use format
specifiers in these functions.
Format Specifier
S NO. Type Description
int/signed
1 %d used for I/O signed integer value
int
2 %c char Used for I/O character value
3 %f float Used for I/O decimal floating-point value
Used for I/O string/group of characters
4 %s string
5 %ld long int Used for I/O long signed integer value
6 %u unsigned int Used for I/O unsigned integer value
1. printf()
2. scanf()
1. printf(): printf() function is used in a C program to display any value like float, integer, character,
string, etc on the console screen. It is a pre-defined function that is already declared in the
stdio.h(header file).
Syntax 1:
return 0;
}
Output
20
Syntax 2:
#include <stdio.h>
// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string
2. scanf(): scanf() function is used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float, character, string,
and many more. This function is declared in stdio.h(header file), that’s why it is also a pre-defined
function. In scanf() function we use &(address-of operator) which is used to store the variable
value on the memory location of that variable.
// Driver code
int main()
{
int num1;
// Printing a message on
// the output screen
printf("Enter a integer number: ");
return 0;
}
Output:
Enter a integer number: 56
You have entered 56
Output
The above example has a double variable with a value 4150.12. Notice that we have assigned the
double value to an integer variable.
Here, the C compiler automatically converts the double value 4150.12 to integer value 4150. Since
the conversion is happening automatically, this type of conversion is called implicit type conversion.
#include<stdio.h>
#include<conio.h>
int main() {
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
// assign character value to integer variable
int number=alphabet;
printf("Integer Value: %d", number);
return 0;
}
Output
Character Value: a
Integer Value: 97
The code above has created a character variable alphabet with the value 'a'. Notice that we are
assigning alphabet to an integer variable.
Here, the C compiler automatically converts the character 'a' to integer 97. This is because, in C
programming, characters are internally stored as integer values known as ASCII Values.
ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has
integer value 97, that's why the character 'a' is automatically converted to integer 97.
If you want to learn more about finding ASCII values, visit find ASCII value of characters in C.
Output
Integer Value: 35
Double Value: 35.00
We have created an integer variable named number with the value 35 in the above program. Notice
the code,
Here,
(double) - represents the data type to which number is to be converted.
number - value that is to be converted to double type.
#include<stdio.h>
#include<conio.h>
int main() {
// create an integer variable
int number = 97;
printf("Integer Value: %d\n", number);
// (char) converts number to character
char alphabet = (char) number;
printf("Character Value: %c", alphabet);
return 0;
}
Output
Integer Value: 97
Character Value: a
We have created a variable number with the value 97 in the code above. Notice that we are
converting this integer to character.
Here,
In our earlier examples, when we converted a double type value to an integer type, the data after
decimal was lost.
#include<stdio.h>
int main() {
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number=value;
printf("Integer Value: %d", number);
return 0;
}
Output
Here, the data 4150.12 is converted to 4150. In this conversion, data after the decimal, .12 is lost.
This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data
from larger type to smaller, there will be data loss..
Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data
type is converted to lower type, data is lost, and if lower data type is converted to higher type, no
data is lost.
Here,
data loss - if long double type is converted to double type
no data loss - if char is converted to int
Top-Down Approach:
In the top-down approach, a complex algorithm is broken down into smaller fragments, better
known as ‘modules.’ These modules are then further broken down into smaller fragments until they
can no longer be fragmented. This process is called ‘modularization.’
By breaking a bigger problem into smaller fragments, the top-down approach minimizes the
complications usually incurred while designing algorithms. In this approach, each function in a code is
unique and works independently of other functions. The top-down approach is mainly used by
Structured programming languages like C, Fortran, etc.
Advantages
Disadvantages
Specification tends to change over time and in a top-down approach, all decisions made from
the beginning of the project depend directly or indirectly on the high-level specification.
In Dynamic Programming, the top-down approach is slow as compared to the bottom-up
approach, as it involves recursion.
There is a chance of stack overflow here.
It takes more memory space as it involves recursion
Bottom-Up Approach
designed individually and are then integrated together to form a complete algorithmic design.
Moreover, the bottom-up approach is more suitable when a system needs to be created from some
existing components.
So, in this method, each and every module is built and tested at an individual level (unit testing) prior
to integrating them to build a concrete solution. The unit testing is performed by leveraging specific
low-level functions. The bottom-up approach is used by Object-Oriented programming languages like
C++, C#, Java, etc.
Test:
The system/solution needs to be tested to meet the requirements. This can be done by
running a series of tests on the system/solution.
Advantages
Disadvantages
In the Bottom-Up approach, we solve all sub-problems (even though some of the solutions of
the subproblems aren’t needed to solve), which requires additional calculations.
In the Bottom-Up approach, sometimes it is difficult to identify the overall functionality of the
system in the initial stages.
As this is an iterative approach, more code needs to be written.
It is more difficult to implement.
2. Space Complexity
1. Time Complexity:
The time complexity of an algorithm is the amount of computing time required by an
algorithm to run its completion.
There are 2 types of computing time 1. Compile time 2. Run time
The time complexity generally computed at run time (or) execution time.
The time complexity can be calculated in terms of frequency count.
Frequency count is a count denoting the number of times the statement should be executed.
The time complexity can be calculated as Comments – 0
Assignment / return statement – 1
Conditional (or) Selection Constructs – 1
Example 1: Sum of the elements in an Array
2. Space Complexity:
Space Complexity can be defined as amount of memory (or) space required by an
Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 26
INTRODUCTION TO PROGRAMMING UNIT-1
Algorithm to run.
To compute the space complexity we use 2 factors i. Constant ii. Instance characteristics.
The space requirement S(p) can be given as S(p) = C+Sp
Where C- Constant, it denotes the space taken for input and
output. Sp – Amount of space taken by an instruction,
variable and identifiers.
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10
and variable B holds 20 then –
(A == B)
Checks if the values of two operands are equal or not. If yes, then the
== is not
condition becomes true.
true.
Checks if the values of two operands are equal or not. If the values are not (A != B)
!=
equal, then the condition becomes true. is true.
Checks if the value of left operand is greater than the value of right (A > B) is
>
operand. If yes, then the condition becomes true. not true.
Checks if the value of left operand is less than the value of right operand. If (A < B) is
<
yes, then the condition becomes true. true.
(A >= B)
Checks if the value of left operand is greater than or equal to the value of
>= is not
right operand. If yes, then the condition becomes true.
true.
Checks if the value of left operand is less than or equal to the value of right (A <= B)
<=
operand. If yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then −
Show Examples
Called Logical AND operator. If both the operands are non-zero, then the (A && B)
&&
condition becomes true. is false.
Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B)
!
operand. If a condition is true, then Logical NOT operator will make it false. is true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows –
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −
Show Examples
(A & B) =
& Binary AND Operator copies a bit to the result if it exists in both operands. 12, i.e.,
0000 1100
(A | B) =
| Binary OR Operator copies a bit if it exists in either operand. 61, i.e.,
0011 1101
(A ^ B) =
^ Binary XOR Operator copies the bit if it is set in one operand but not both. 49, i.e.,
0011 0001
Binary One's Complement Operator is unary and has the effect of 'flipping' (~A ) =
~
bits. ~(60), i.e,.
-0111101
A << 2 =
Binary Left Shift Operator. The left operands value is moved left by the
<< 240 i.e.,
number of bits specified by the right operand.
1111 0000
A >> 2 =
Binary Right Shift Operator. The left operands value is moved right by the
>> 15 i.e.,
number of bits specified by the right operand.
0000 1111
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
C = A + B will
Simple assignment operator. Assigns values from right side operands to left assign the
=
side operand value of A +
B to C
C += A is
Add AND assignment operator. It adds the right operand to the left operand
+= equivalent
and assign the result to the left operand.
to C = C + A
C -= A is
Subtract AND assignment operator. It subtracts the right operand from the
-= equivalent
left operand and assigns the result to the left operand.
to C = C - A
C *= A is
Multiply AND assignment operator. It multiplies the right operand with the
*= equivalent
left operand and assigns the result to the left operand.
to C = C * A
C /= A is
Divide AND assignment operator. It divides the left operand with the right
/= equivalent
operand and assigns the result to the left operand.
to C = C / A
C %= A is
Modulus AND assignment operator. It takes modulus using two operands
%= equivalent
and assigns the result to the left operand.
to C = C % A