Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

COMPUTER

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

The history of computer development is often discussed in terms of different generation of


computers, as listed below.
 First generation computers
 Second generation computers
 Third generation computers
 Fourth generation computers
 Fifth generation computers

i) First Generation Computers (1940-1956)


These computers used the vacuum tubes technology for calculation as well as for storage and
control purposes. Therefore, these computers were also known as vacuum tubes or thermionic
valves based machines.

Some examples of first generation computers are

ENIAC, EDVAC, EDSAC and UNIVAC.

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.

ii) Second Generation Computers (1956-1963)


These computers use transistors in place of vacuum tubes in building the basic logic circuits. A
transistor is a semiconductor device that is used to increase the power of the incoming signals by
preserving the shape of the original signal.
Some examples of second generation computers are PDP-8, IBM1401 and IBM 7090.

C-PROGRAMMING UNIT-1[R-23] Page 1


Advantages
 Fastest computing devices of their time.
 Easy to program because of the use of assembly language.
 Small and light weight computing devices.
 Required very less power in carrying out operations.
Disadvantages
 Input and output media for these computers were not improved to a considerable extent.
 Required to be placed in air-conditioned places.
 Very expensive and beyond the reach of home users.
 Being special-purpose computers they could execute only specific applications.

iii) Third Generation Computers (1964-1971)


The major characteristic feature of third generation computer systems was the use of Integrated
Circuits (ICs). ICs are the circuits that combine various electronic components, such as
transistors, resistors, capacitors, etc. onto a single small silicon chip.
Some examples of third generation computers are NCR 395, B6500, IBM 370, PDP 11 and CDC
7600.
Advantages
 Computational time for these computers was usually in nanoseconds hence were the
fastest computing devices
 Easily transportable because of their small size.
 They used high-level languages which is machine independent hence very easy to use.
 Easily installed and required less space.
 Being able to execute any type of application (business and scientific) these were
considered as general-purpose computers.
Disadvantages
 Very less storage capacity.
 Degraded performance while executing complex computations because of the small
storage capacity.
 Very expensive.

iv) Fourth Generation Computers (1971-2010)


The progress in LSI and VLSI technologies led to the development of microprocessor, which
became the major characteristic feature of the fourth generation computers. The LSI and VLSI
technology allowed thousands of transistors to be fitted onto one small silicon chip. A
microprocessor incorporates various components of a computer—such as CPU, memory and
Input/Output (I/O) controls—onto a single chip. Some popular later microprocessors include
Intel 386, Intel 486 and Pentium.
Some of the examples of fourth generation computers are IBM PC, IBM PC/AT, Apple and
CRAY-1.

C-PROGRAMMING UNIT-1[R-23] Page 2


Advantages
 LSI and VLSI technologies made them small, cheap, compact and powerful.
 high storage capacity
 highly reliable and required very less maintenance.
 provided a user-friendly environment with the development of GUIs and interactive I/O
devices.
 programs written on these computers were highly portable because of the use of high-
level languages.
 very versatile and suitable for every type of applications.
 required very less power to operate.
Disadvantages
 the soldering of LSI and VLSI chips on the wiring board was complicated
 still dependent on the instructions given by the programmer.

v) Fifth Generation Computers (2010 and Beyond)


Fifth generation computers are based on the Ultra Large Scale Integration (ULSI) technology
that allows almost ten million electronic components to be fabricated on one small chip.
Advantages
 faster, cheaper and most effi cient computers till date.
 They are able to execute a large number of applications at the same time and that too at a
very high speed.
 The use of ULSI technology helps in decreasing the size of these computers to a large
extent.
 very comfortable to use because of the several additional multimedia features.
 versatile for communications and resource sharing.

Disadvantage
They are not provided with an intelligent program that could guide them in performing different
operations.

C-PROGRAMMING UNIT-1[R-23] Page 3


BASIC ORGANIZATION OF A COMPUTER
Any computer can perform the four basic operations of Input, Processing, Output, and Storage

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.

Central Processing Unit


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.

Arithmetic logic unit


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.

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.

INTRODUCTION TO PROGRAMMING LANGUAGES

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.

What is a Programming Language?

A programming language is a computer language that is used by programmers (developers) to


communicate with computers. It is a set of instructions written in any specific language ( C, C++,
Java, Python) to perform a specific task.

Types of programming language

1. Low-level programming language

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.

Low-level language is further divided into two parts -

i. Machine Language

Machine language is a type of low-level programming language. It is also called as machine


code or object code. Machine language is easier to read because it is normally displayed in

C-PROGRAMMING UNIT-1[R-23] Page 5


binary or hexadecimal form (base 16) form. It does not require a translator to convert the
programs because computers directly understand the machine language programs.

The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.

ii. Assembly 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.

2. High-level programming language

High-level programming language (HLL) is designed for developing user-friendly software


programs and websites. This programming language requires a compiler or interpreter to
translate the program into machine language (execute the program). The main advantage of a
high-level language is that it is easy to read, write, and maintain.

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

i. Procedural Oriented programming language

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

ii. Object-Oriented Programming language

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.

C-PROGRAMMING UNIT-1[R-23] Page 6


Example: C++, Java, Python, C#, etc

iii. Natural language

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.

3. Middle-level programming language

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.

Example: C, C++, language

BASICS OF A COMPUTER PROGRAM


i) Algorithm
An algorithm is a set of instructions designed to perform a specific task.
It can be implemented using a formal language, and such a language is known as a programming
language. In general terms, an algorithm provides a blueprint to write a program to solve a
particular problem. It is considered to be an effective procedure for solving a problem in finite
number of steps

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‖.

C-PROGRAMMING UNIT-1[R-23] Page 7


Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm to show


Start/Stop
start and end of the program.

Indicates processes like mathematical operations.


Process

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program, where


answer is usually Yes or No.
Decision

Shows relationships between different shapes.


Arrow

Connects two or more parts of a flowchart, which are


on the same page.
On-page Connector

Connects two parts of a flowchart which are spread


over different pages.
Off-page Connector

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.

C-PROGRAMMING UNIT-1[R-23] Page 8


Collaboration: The simple language in pseudocode makes it a valuable tool for explaining
complex technical details to team members who may have little programming knowledge.

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.

Example:-Find Area and Perimeter of a Square

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.

C-PROGRAMMING UNIT-1[R-23] Page 9


Preprocessor

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

C-PROGRAMMING UNIT-1[R-23] Page 10


other files; then linker plays a very important role in this. It links the object code of these files to
our program. Therefore, we conclude that the job of the linker is to link the object code of our
program with the object code of the library files and other files. The output of the linker is the
executable file. The name of the executable file is the same as the source file but differs only in
their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'.

Let's understand through an example.

hello.c

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello ");
5. return 0;
6. }

C-PROGRAMMING UNIT-1[R-23] Page 11


STRUCTURE OF C PROGRAM
A C-program may contain one or more sections as shown below

Documentation Section

Link section

Global declaration section

main() function section


{
Declaration part
Executable part
}

The subprogram section


Function-1
Function-2
-------------
------------
Function-n

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*/

C-PROGRAMMING UNIT-1[R-23] Page 12


Link section
The link section provides instructions to the compiler to link functions from the system library.
Example :- #include<stdio.h>, #include<string.h>, #include<math.h>

Definition section
The definition section defines all symbolic constants.
Example #define pi 3.14

Global declaration section


There are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section that is outside of all the
functions. This section also declares all the user-defined functions.

main() function section


Every C program must have one main() function section. This section contains two parts,
i)declaration part
The declaration part declares all the variables used in the executable part
ii) Executable part.
There is at least one statement in the executable part.
These two parts must appear between the opening and the closing braces. The program execution
begins at the opening brace and ends at the closing brace. All statements in the declaration and
executable parts end with a semicolon(;).

The subprogram section


The subprogram section contains all the user-defined functions that are called in the main
function. User-defined functions are generally placed immediately after the main function,
although they may appear in any order. All sections, except the main function section may be
absent when they are not required.

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

C-PROGRAMMING UNIT-1[R-23] Page 13


o Operators in C
o Strings in C
o Special Characters 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.

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

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.

Rules for constructing C identifiers

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 It should not begin with any numerical digit.

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 Keywords cannot be represented as an identifier.

o The length of the identifiers should not be more than 31 characters.

o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

total, sum, average, _m _, sum_1, etc.


CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants

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

C-PROGRAMMING UNIT-1[R-23] Page 15


include alphabets A through F or a through f. The letter A through F represent the numbers 10
through 15.
Following are the examples of valid hex integers:
0X2 0x9F 0Xbcd 0x
ii) Real Constants
Integer numbers are inadequate to represent quantities that vary continuously, such as distances,
heights, temperatures, prices, and so on. These quantities are represented by numbers containing
fractional parts like 17.548. Such numbers are called real (or fl oating point) constants.
Further examples of real constants are:
0.0083 –0.75 435.36 +247.0
These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part. It is possible to omit digits before the decimal point, or digits after
the decimal point.
That is, 215. .95 –.71 +.5 are all valid real numbers.
A real number may also be expressed in exponential (or scientifi c) notation. For example, the
value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The
general for is:
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is
an integer number with an optional plus or minus sign. The letter e separating the mantissa and
the exponent can be written in either lowercase or uppercase.

iii) Single-Character Constants


A single character constant (or simply character constant) contains a single character enclosed
within a pair of single quote marks. Example of character constants are:
‗5‘ ‗X‘ ‗;‘ ‗ ‘
Note that the character constant ‗5‘ is not the same as the number 5. The last constant is a blank
space.
iv) String Constants
A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters, numbers, special characters and blank space. Examples are:
―Hello!‖ ―1987‖ ―WELL DONE‖ ―?...!‖ ―5+3‖ ―X‖
Remember that a character constant (e.g., ‗X‘) is not equivalent to the single character string
constant (e.g., ―X‖).

v) Backslash Character Constants


C supports some special backslash character constants that are used in output functions. For
example, the symbol ‗\n‘ stands for newline character. A list of such backslash character
constants is given in Table

C-PROGRAMMING UNIT-1[R-23] Page 16


OPERATORS

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)

ii. Relational operators


We often compare two quantities and depending on their relation, take certain decisions. For
example, we may compare the age of two persons, or the price of two items, and so on. These
comparisons can be done with the help of relational operators.
C supports six relational operators in all.

C-PROGRAMMING UNIT-1[R-23] Page 17


Operator Meaning
OPERATOR MEANING
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Example
10 < 20
x>y
y==z

iii. Logical operators


The logical operators are used when we want to test more than one condition and make
decisions. In addition to the relational operators, C has the following three logical operators.
OPERATOR MEANING
&& logical AND
|| logical OR
! logical NOT

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.

iv. Assignment operators


Assignment operators are used to assign the result of an expression to a variable. The usual
assignment operator, ‗=‘. In addition, C has a set of ‗shorthand‘ assignment operators of the form
addition, C has a set of ‗shorthand ‘ assignment operators of the form
v op= exp;
Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator
op= is known as the shorthand assignment operator. The assignment statement v op= exp; is
equivalent to v = v op (exp). Some of the commonly used shorthand assignment operators are

C-PROGRAMMING UNIT-1[R-23] Page 18


Statement with simple Statement with
assignment operator shorthand operator
a=a+1 a += 1
a=a–1 a –= 1
a = a * (n+1) a *= n+1
a = a / (n+1) a /= n+1
a=a%b a %= b

v. Increment and decrement operators


C allows two very useful operators not generally found in other languages. These are the
increment and decrement operators: ++ and — –
The operator ++ adds 1 to the operand, while – – subtracts 1. Both are unary operators and takes
the following form:
++m; or m++;
– —m; or m– —;
++m; is equivalent to m = m+1; (or m += 1;)
– —m; is equivalent to m = m–1; (or m –= 1;)
Consider the following:
m = 5;
y = ++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m = 5;
y = m++;
then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand
and then the result is assigned to the variable on left. On the other hand, a postfix operator first
assigns the value to the variable on left and then increments the operand.

vi. Ternary operator


A ternary operator pair ―? :‖ is available in C to construct conditional expressions of the form
exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions.
The operator ? : works as follows: exp1 is evaluated first. If it is nonzero (true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions (either exp2 or exp3) is evaluated. For example, consider the following statements:
a = 10;
b = 15;
x = (a > b) ? a : b;
In this example, x will be assigned the value of b. This can be achieved using the if..else
statements as

C-PROGRAMMING UNIT-1[R-23] Page 19


follows:
if (a > b)
x = a;
else
x = b;

vii. Bitwise operators

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.

viii. Special operators


C supports some special operators of interest such as comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. and –> ).

The Comma Operator


The comma operator can be used to link the related expressions together. A comma-linked list of
expressions are evaluated left to right and the value of right-most expression is the value of the
combined expression. For example, the statement
value = (x = 10, y = 5, x+y);
first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 (i.e. 10 + 5) to value.
Since comma operator has the lowest precedence of all operators, the parentheses are necessary.

The sizeof Operator


The sizeof is a compile time operator and, when used with an operand, it returns the number of
bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.
Examples: m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);

C-PROGRAMMING UNIT-1[R-23] Page 20


The sizeof operator is normally used to determine the lengths of arrays and structures when their
sizes are not known to the programmer. It is also used to allocate memory space dynamically to
variables during execution of a program.
Program
main()
{
int a, b, c, d;
a = 15;
b = 10;
c = ++a - b;
printf(―a = %d b = %d c = %d\n‖,a, b, c);
d = b++ +a;
printf(―a = %d b = %d d = %d\n‖,a, b, d);
printf(―a/b = %d\n‖, a/b);
printf(―a%%b = %d\n‖, a%b);
printf(―a *= b = %d\n‖, a*=b);
printf(―%d\n‖, (c>d) ? 1 : 0);
printf(―%d\n‖, (c<d) ? 1 : 0);
}
Output
a = 16 b = 10 c = 6
a = 16 b = 11 d = 26
a/b = 1
a%b = 5
a *=b = 176
0
1

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

C-PROGRAMMING UNIT-1[R-23] Page 21


:
1. Primary (or fundamental) data types
Primitive data types are the most basic data types that are used for representing simple
values such as integers, float, characters, etc.

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

C-PROGRAMMING UNIT-1[R-23] Page 22


length, the size of the integer value is limited to the range –32768 to +32767 (that is, –215 to
+215–1). A signed integer uses one bit for sign and 15 bits for the magnitude of the number.
Similarly, a 32 bit word length can store an integer ranging from -2,147,483,648 to
2,147,483,647.
In order to provide some control over the range of numbers and storage space, C has three
classes of integer storage, namely short int, int, and long int, in both signed and unsigned forms.

Floating Point Types


Floating point (or real) numbers are stored in 32 bits (on all 16 bit and 32 bit machines), with 6
digits of precision. Floating point numbers are defined in C by the keyword fl oat. When the
accuracy provided by a float number is not sufficient, the type double can be used to define the
number. A double data type number uses 64 bits giving a precision of 14 digits. These are known
as double precision numbers. Remember.

C-PROGRAMMING UNIT-1[R-23] Page 23


Void Types
The void type has no values. This is usually used to specify the type of functions. The type of a
function is said to be void when it does not return any value to the calling function. It can also
play the role of a generic type, meaning that it can represent any of the other standard types.

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.

2. Derived data types


The data types that are derived from the primitive or built-in data types are referred to
as Derived Data Types.
3. User-defined data types
The user-defined data types are defined by the user himself.

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-PROGRAMMING UNIT-1[R-23] Page 24


BASIC INPUT AND OUTPUT OPERATIONS

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;
}

C-PROGRAMMING UNIT-1[R-23] Page 25


Read the string:

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);
}

Writing the string:

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;
}

C-PROGRAMMING UNIT-1[R-23] Page 26


Formatted input

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);

C-PROGRAMMING UNIT-1[R-23] Page 27


Formatted output(printf()):-
The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print-outs on the terminals. The general form of printf statement is:

printf(“control string”, arg1, arg2, ....., argn);

Control string consists of following three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t, and \b.
The control string indicates how many arguments follow and what their types are.
The arguments arg1,arg2, ....., argn are the variables whose values are formatted and printed
according to the specifications of the control string.
Example Program:
#include<stdio.h>
int main()
{
char name[20];
printf("Enter name: ");

// user input will be taken here


scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

TYPE CONVERSION, AND CASTING:

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.

There are two types of Conversion:


1. Implicit Type Conversion(automatic type conversion)
A. Done by the compiler on its own, without any external trigger from the user.
B. All the data types of the variables are upgraded to the data type of the variable with the
largest data type.

C-PROGRAMMING UNIT-1[R-23] Page 28


bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float ->
double -> long double
C. It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly converted
to float).

Example:-
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Output:
x = 107, z = 108.000000

C-PROGRAMMING UNIT-1[R-23] Page 29


Explicit Type Conversion
This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type. The syntax in C Programming:

(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

C-PROGRAMMING UNIT-1[R-23] Page 30


Operators Precedence

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.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C-PROGRAMMING UNIT-1[R-23] Page 31


ALGORITHM

An algorithm is a set of instructions designed to perform a specific task.


It can be implemented using a formal language, and such a language is known as a programming
language. In general terms, an algorithm provides a blueprint to write a program to solve a
particular problem. It is considered to be an effective procedure for solving a problem in finite
number of steps.

Different Approaches to Designing an Algorithm


Algorithms are used to manipulate the data contained in data structures. When working with data
structures, algorithms are used to perform operations on the stored data. A complex algorithm is
often divided into smaller units called modules. This process of dividing an algorithm into
modules is called modularization. The key advantages of modularization are as follows:
 It makes the complex algorithm simpler to design and implement.
 Each module can be designed independently. While designing one module, the details of
other modules can be ignored, thereby enhancing clarity in design which in turn Simplifies
implementation, debugging, testing, documenting, and maintenance of the overall algorithm.

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.

C-PROGRAMMING UNIT-1[R-23] Page 32


Bottom-up approach:- A bottom-up approach is just the reverse of top-down approach. In the
bottom-up design, we start with designing the most basic or concrete modules and then proceed
towards designing higher level modules. The higher level modules are implemented by using the
operations performed by lower level modules. Thus, in this approach sub-modules are grouped
together to form a higher level module. All the higher level modules are clubbed together to form
even higher level modules. This process is repeated until the design of the complete algorithm is
obtained.

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.

C-PROGRAMMING UNIT-1[R-23] Page 33


TIME AND SPACE COMPLEXITY

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.

Worst-case running time


This denotes the behaviour of an algorithm with respect to the worst possible case of the input
instance. The worst-case running time of an algorithm is an upper bound on the running time for
any input. Therefore, having the knowledge of worst-case running time gives us an assurance
that the algorithm will never go beyond this time limit.

Average-case running time


The average-case running time of an algorithm is an estimate of the running time for an
average‗input. It specifies the expected behavior of the algorithm when the input is randomly
drawn from a given distribution. Average-case running time assumes that
all inputs of a given size are equally likely.

Best-case running time


The term ‗best-case performance is used to analyse an algorithm under optimal conditions. For
example, the best case for a simple linear search on an array occurs when the desired element is
the first in the list. However, while developing and choosing an algorithm to solve a problem, we
hardly base our decision on the best-case performance. It is always recommended to improve the
average performance and the worst-case performance of an algorithm.

Amortized running time


Amortized running time refers to the time required to perform a sequence of (related) operations
averaged over all the operations performed. Amortized analysis guarantees the average
performance of each operation in the worst case.

C-PROGRAMMING UNIT-1[R-23] Page 34

You might also like