Unit 1
Unit 1
Unit 1
A computer is an electronic machine that takes input from the user, processes the given input
and generates output in the form of useful information. A computer accepts input in different
forms such as data, programs and user reply.
HISTORY OF COMPUTERS
Advantages:-
Fastest computing devices of their time.
Able to execute complex mathematical problems in an efficient manner.
Disadvantages
These computers were not very easy to program being machined dependent.
They were not very flexible in running different types of applications as designed for
special purposes.
The use of vacuum tube technology made these computers very large and bulky and also
required to be placed in cool places.
They could execute only one program at a time and hence, were not very productive.
They generated huge amount of heat and hence were prone to hardware faults.
Disadvantage
They are not provided with an intelligent program that could guide them in performing different
operations.
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.
Control unit
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.
C-PROGRAMMING UNIT-1[R-23] Page 4
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.
Storage 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. It is also referred to as hard
drive, disk drive, or hard disk drive. The hard disk provides a large amount of storage space for
the programs and data.
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other. For
example, if we want to teach someone, we need a language that is understandable by both the
communicators.
Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.
i. Machine Language
The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.
Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-understandable
form. It uses an assembler to convert the assembly language to machine language. The advantage
of assembly language is that it requires less memory and less execution time to execute a
program.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective
C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language. A high-level
language is further divided into three parts
Procedural Oriented Programming (POP) language is derived from structured programming and
based upon the procedure call concept. It divides a program into small procedures
called routines or functions.
The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.
Example: C, FORTRAN, Basic, Pascal, etc
Object-Oriented Programming (OOP) language is based upon the objects. In this programming
language, programs are divided into small parts called objects. It is used to implement real-world
entities like inheritance, polymorphism, abstraction; etc in the program to makes the program
reusable, efficient, and easy-to-use. The main advantage of object-oriented programming is that
OOP is faster and easier to execute, maintain, modify, as well as debug.
Natural language is a part of human languages such as English, Russian, German, and Japanese.
It is used by machines to understand, manipulate, and interpret human's language. It is used by
developers to perform tasks such as translation, automatic summarization, Named Entity
Recognition (NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any subject and
directly respond within seconds.
Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming language
and pseudo-language.
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
ii) Flowchart
A 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 that 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‖.
iii) Pseudocode
Pseudo code is a simplified representation of an algorithm that uses the English language to
describe coding logic. It allows programmers to plan any algorithm's structure using simple
commands.
Advantages of pseudo code
There are several benefits of using pseudo code on a programming project, including:
Evaluation: Writing pseudo code can help you evaluate the logic of an algorithm and solve
problems before spending time and resources writing the technical code.
Translation: Once you complete your pseudocode, you can use it as a clear outline for
translating each line into a programming language.
Documentation: Saving your pseudocode documents can help you record project goals, best
practices and ideal outcomes for a project.
BEGIN
NUMBER len, area,perimeter
INPUT len
area = len*len
perimeter = len*4
OUTPUT area
OUTPUT perimeter
END
COMPILATION PROCESS IN C
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.
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.
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
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.
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,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code of
our program. Sometimes the situation arises when our program refers to the functions defined in
hello.c
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello ");
5. return 0;
6. }
Documentation Section
Link section
Documentation section:
The documentation section consists of a set of comment lines giving the name of the program,
the author and other details and so on. In C comments are of two types
Single line comments and double line comments
Single line comments are represented by // and it will affected to a single line
Ex:- // This is a single line comment
The Multi-line comment in C starts with a forward slash and asterisk ( /* ) and ends with an
asterisk and forward slash ( */ ). Any text between /* and */ is treated as a comment and is
ignored by the compiler.
/*Comment starts
continues
continues
.
.
Comment ends*/
Definition section
The definition section defines all symbolic constants.
Example #define pi 3.14
TOKENS
Tokens in C are the element to be used in creating a program in C. We define the token as the
smallest individual element in C.
Tokens in C language can be divided into the following categories:
o Keywords in C
o Identifiers in C
o Constant in C
Keywords in C can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-defined
words used by the compiler, so they cannot be used as the variable names.
do if static while
IDENTIFIERS
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore.
o The first character of an identifier should be either an alphabet or an underscore, and then
it can be followed by any of the character, digit, or underscore.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
C-PROGRAMMING UNIT-1[R-23] Page 14
o Commas or blank spaces cannot be specified within an identifier.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
i) Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional – or + sign.
Valid
examples of decimal integer constants are:
123 – 321 0 654321 +78
An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0.
Some examples of octal integer are: 037 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also
i. Arithmetic operators:-
C provides all the basic arithmetic operators. The operators +, –, *, and / all work the same way
as they do in other languages. These can operate on any built-in data type allowed in C.
Operator Meaning
OPERATOR Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulor division
Examples:-
a – b = 10
a + b = 18
a * b = 56
a / b = 3 (decimal part truncated)
a % b = 2 (remainder of division)
Example
10 < 20
x>y
y==z
Example:
a > b && x == 10
An expression of this kind, which combines two or more relational expressions, is termed as a
logical expression or a compound relational expression.
C has a distinction of supporting special operators known as bitwise operators for manipulation
of data at bit level. These operators are used for testing the bits, or shifting them right or left.
Bitwise operators may not be applied to float or double. Table 5.5 lists the bitwise operators and
their meanings.
Data Types
Data type:
Data type determines the type and size of data associated with variables. C language is rich in its
data types. The variety of data types available allows the programmer to select the type
appropriate to the needs of the application as well as the machine. ANSI C supports three classes
of data types
Integer Types
Integers are whole numbers with a range of values supported by a particular machine. Generally,
integers occupy one word of storage, and since the word sizes of machines vary (typically, 16 or
32 bits) the size of an integer that can be stored depends on the computer. If we use a 16 bit word
Character Types
A single character can be defi ned as a character(char) type data. Characters are usually stored in
8 bits (one byte) of internal storage. The qualifi er signed or unsigned may be explicitly applied
to char. While unsigned chars have values between 0 and 255, signed chars have values from –
128 to 127.
VARIABLES
A variable is a named memory location a type, such as integer, character. That is, the name has
nothing to do with its type. After designing suitable variable names, we must declare them to the
compiler. Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
A variable can be used to store a value of any data type. That is, the name has nothing to do with
its type.
The syntax for declaring a variable is as follows:
data-type v1,v2,....vn ;
v1, v2, ....vn are the names of variables. Variables are separated by commas. A declaration
statement must end with a semicolon. For example, valid declarations are:
int count;
float average;
double ratio;
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
Reading a character:
The simplest of all input/output operations is reading a character from the ‗standard input‘ unit
(usually the keyboard) and writing it to the ‗standard output‘ unit (usually the screen). Reading a
single character can be done by using the function getchar. The getchar takes the following form:
variable_name = getchar( );
variable_name is a valid C name that has been declared as char type.
Example
char name;
name = getchar();
Writing a character:
Like getchar, there is an analogous function putchar for writing characters one at a time to the
terminal. It takes the form as shown below:
putchar (variable_name);
where variable_name is a type char variable containing a character. This statement displays the
character contained in the variable_name at the terminal.
Example
answer = ‗Y‘;
putchar (answer);
Example Program:
#include <stdio.h>
int main() {
char ch;
ch=getchar();
putchar(ch);
return 0;
}
Read the string using gets() functions is a very popular way to read the array of characters i.e.
string.
Syntax:
gets(variable);
Example Program:
#include<stdio.h>
int main()
{
char name[20];
printf("Enter a string: ");
gets(name);
printf("The Entered string : %s\n",name);
return (0);
}
The puts() function in C is used to write a line or string to the output(stdout) stream. It prints the
passed string with a newline and returns an integer value. The return value depends on the
success of the writing procedure.
Syntax:
int puts(str);
Exammple:
#include<stdio.h>
int main()
{
//string initialisation
char Mystr[20] ;
gets(Mystr);
puts(Mystr); //writing the string to stdout
return 0;
}
Formatted input refers to an input data that has been arranged in a particular format. This is
possible in C using the scanf function. (scanf means scan formatted.)
Syntax:
scanf (―control string‖, &arg1,&arg2, ...... ,&argn);
The control string specifies the field format in which the data is to be entered and the arguments
&arg1,&arg2, ...., &argn specify the address of locations where the data is stored. Control string
and arguments are separated by commas.
Inputting Integer Numbers
The field specification for reading an integer number is: %d
Example:
scanf (―%2d %5d‖, &num1, &num2);
Inputting Real Numbers
The field specification for reading an real(float) number is: %f
Example:
scanf(―%f %f %f‖, &x, &y, &z);
Inputting Character Strings
The field specification for reading an character is: %c
Example:
scanf (―%c‖,&code);
Reading Mixed Data Types
It is possible to use one scanf statement to input a data line containing mixed mode data.
Example:
scanf (―%d %c %f %s‖, &count, &code, &ratio, name);
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type
conversion is performed by a compiler. In type conversion, the destination data type can‘t be
smaller than the source data type. Type conversion is done at compile time and it is also
called widening conversion because the destination data type can‘t be smaller than the source
data type.
Example:-
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
(type) expression
Type indicated the data type to which the final result is converted.
Eample:
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
OUTPUT:
sum = 2
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
There are two main approaches to design an algorithm—top-down approach and bottom-up
approach
Top-down approach:- A top-down design approach starts by dividing the complex algorithm
into one or more modules. These modules can further be decomposed into one or more sub-
modules, and this process of decomposition is iterated until the desired level of module
complexity is achieved. Top-down design method is a form of stepwise refinement where we
begin with the topmost module and incrementally add modules that it calls.
Therefore, in a top-down approach, we start from an abstract design and then at each step, this
design is refined into more concrete levels until a level is reached that requires no further
refinement.
CHARACTERISTICS OF ALGORITHMS:
1. Well-described steps: Algorithms are composed of a specific and unambiguous set of
instructions or steps that can be observed to perform a selected task or solve a problem.
Each step ought to be well-defined, leaving no room for ambiguity or confusion.
2. Input and output: Algorithms take inputs, which might be the preliminary records or
facts furnished to the algorithm, and produce outputs, which are the results or solutions
generated by using the set of rules after processing the inputs. The relation among the
inputs and outputs is decided by means of the algorithm's good judgment.
3. Finiteness: Algorithms must have a well-defined termination condition. This method
means that they finally attain an endpoint or change after a finite quantity of steps. If a set
of rules runs indefinitely without termination, it's far taken into consideration wrong or
incomplete.
4. Determinism: Algorithms are deterministic, that means that given the same inputs and
achieved below the same conditions, they may continually produce the identical outputs.
The conduct of a set of rules ought to be predictable and regular.
5. Efficiency: Algorithms attempt to be efficient in phrases of time and sources. They goal
to clear up issues or perform obligations in an inexpensive quantity of time and with
ultimate use of computational sources like memory, processing power, or garage.
6. Generality: A set of rules must be designed to resolve a particular problem or carry out a
selected assignment, but it must also be relevant to a broader elegance of times or
scenarios. It ought to have a certain level of flexibleness and flexibility.
7. Correctness: Algorithms must be designed to produce correct results for all legitimate
inputs inside their domain. They must accurately solve the problem they may be designed
for, and their outputs must match the anticipated consequences.
8. Modularity and reusability: Algorithms may be modular, meaning they may be divided
into smaller sub problems or features that may be reused in unique parts of the algorithm
or in other algorithms. This promotes code agency, maintainability, and code reuse.
9. Understandability: Algorithms need to be designed with clarity and ease in mind,
making them easy to apprehend and implement. Well-documented and readable code can
enhance the understandability of an algorithm.
Analyzing an algorithm means determining the amount of resources (such as time and memory)
needed to execute it. Algorithms are generally designed to work with an arbitrary number of
inputs, so the efficiency or complexity of an algorithm is stated in terms of time and space
complexity.
The time complexity of an algorithm is basically the running time of a program as a function of
the input size.
The space complexity of an algorithm is the amount of computer memory that is required during
the program execution as a function of the input size. In other words, the number of machine
instructions which a program executes is called its time complexity. This number is primarily
dependent on the size of the program‗s input and the algorithm used.