0% found this document useful (0 votes)
1K views

PPS Unit-1 Notes

The document discusses the basic components and concepts of computer systems including hardware, software, and users. It defines hardware as the physical components of a computer like input/output devices, storage, and other parts. Software is programs that allow the hardware to function and is divided into system software that controls the computer, and application software for specific tasks. Key hardware components covered include the central processing unit, memory, storage devices like hard disks, and input/output components. The document also discusses operating systems, compilers vs interpreters, and basic concepts in computer programming.

Uploaded by

Laxmi Venki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

PPS Unit-1 Notes

The document discusses the basic components and concepts of computer systems including hardware, software, and users. It defines hardware as the physical components of a computer like input/output devices, storage, and other parts. Software is programs that allow the hardware to function and is divided into system software that controls the computer, and application software for specific tasks. Key hardware components covered include the central processing unit, memory, storage devices like hard disks, and input/output components. The document also discusses operating systems, compilers vs interpreters, and basic concepts in computer programming.

Uploaded by

Laxmi Venki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

UNIT-I

Introduction to Programming
1. Introduction to components of a computer system:

Computer is an electronic device which operates under the control of instructions stored
in its own memory. A computer can take data from the user through input devices (Input),
process the user given data (Processing), produces the result to the user through output
devices (Output)and stores data (Information) for future use. Computer can be defined as
follows...

Components of a Computer System:


Every computer mainly consists of three things and those are...
 Hardware
 Software
 User

Here the user interacts with the software, and the software makes the computer hardware
parts to work for the user.

Computer Hardware:
All physical components of the computer are called as computer hardware. A user can see,
touch and feel every hardware of the computer. All hardware components perform any task
based on the instructions given by the computer software.
The computer hardware is the physical part of a computer.
The computer hardware components are as follows...
 Input Devices - These are the parts through which a user can give the data to the
computer.
 Output Devices - These are the physical components of a computer through which the
computer gives the result to the user.
 Storage Devices- These are the physical components of a computer in which the data
can be stored.
 Devices Drives- Using drives, user can read and write data on to the strorage devices
like CD, floppy, etc.,
 Cables- Various cables (Wires) are used to make connections in a computer
 Other Devices- Other than the above hardware components, a computer also contains
components like Mother board, CPU (Processor), SMPS, Fans, etc.,
Input Devices
Computer input devices are the physical components of the computer which are used to give
the data given by the user to the computer. Using input devices the user can give the data to
the computer.
Example
Output Devices
Computer output devices are the physical components of the computer which are used to give
the computer result to the User. Using output devices, the user can see the computer
generated result.
Example

Storage Devices
Computer storage devices are the physical components of the computer which are used to
store data internally or externally.
Example

Disk:
Generally, a disk is a a round plate on which data can be encoded. There are two basic types
of disks: magnetic disks and optical disks.

Magnetic Disks
On magnetic disks, data is encoded as microscopic magnetized needles on the disk's surface.
You can record and erase data on a magnetic disk any number of times, just as you can with a
cassette tape. Magnetic disks come in a number of different forms:
Floppy disk
A typical 5¼-inch floppy disk can hold 360K or 1.2MB (megabytes). 3½-inch floppies
normally store720K, 1.2MB or 1.44MB of data. Floppy disks or obsolete today, and are
found on older computer systems.

Hard disk
Hard disks can store anywhere from 20MB to more than 1-TB (terabyte). Hard disks are also
from 10 to 100 times faster than floppy disks.

Optical Disks
Optical disks record data by burning microscopic holes in the surface of the disk with a laser.
To read the disk, another laser beam shines on the disk and detects the holes by changes in
the reflection pattern.
Optical disks come in three basic forms:

CD-ROM
Most optical disks are read-only. When you purchase them, they are already filled with data.
You can read the data from a CD-ROM, but you cannot modify, delete, or write new data.

WORM
Worm stands for write-once, read-many. WORM disks can be written on once and then read
any number of times; however, you need a special WORM disk drive to write data onto a
WORM disk.

Erasable optical (EO):


EO disks can be read to, written to, and erased just like magnetic disks. The machine that
spins a disk is called a disk drive. In each disk drive one or more heads (often called
read/write heads) that actually read and write data. Accessing data from a disk is not as fast
as accessing data from main memory, but disks are much cheaper. And unlike RAM, disks
hold on to data even when the computer is turned off. Consequently, disks are the storage
medium of choice for most types of data. Another storage medium is magnetic tape. But
tapes are used only for backup and archiving because they are sequential-access devices (to
access data in the middle of a tape, the tape drive must pass through all the preceding data).

Primary memory is where programs and data are kept when the processor is actively using
them. When programs and data become active, they are copied from secondary memory into
main memory where the processor can interact with them. A copy remains in secondary
memory.
Main memory is intimately connected to the processor, so moving instructions and data into
and out of the processor is very fast. Main memory is sometimes called RAM. RAM stands
for Random Access Memory. "Random" means that the memory cells can be accessed in any
order.
When people say that a computer has "512 megabytes of RAM" they are talking about how
big its main memory is. One megabyte of memory is enough to hold approximately one
million (106 ) characters of a word processing document. (There will be more about bytes
and megabytes later on in these notes.)
Nothing permanent is kept in main memory. Sometimes data are placed in main memory for
just a few seconds, only as long as they are needed.
Secondary Memory Secondary memory is where programs and data are kept on a long-term
basis. Common secondary storage devices are the hard disk and optical disks.
 The hard disk has enormous storage capacity compared to main memory.
 The hard disk is usually contained inside the case of a computer.
 The hard disk is used for long-term storage of programs and data.
 Data and programs on the hard disk are organized into files.
 A file is a section of the disk that has a name.
A hard disk might have a storage capacity of 500 gigabytes (room for about 500 x 109
characters).
Primary memory Secondary memory
Fast Slow
Expensive cheap
Low capacity Large Capacity
Works directly with the processor Not connected directly to the
processor
Processor:
A processor, or "microprocessor," is a small chip that resides in computers and other
electronic devices. Its basic job is to receive input and provide the appropriate output. While
this may seem like a simple task, modern processors can handle trillions of calculations per
second.

Operating System:

An operating system (OS) is the program that, after being initially loaded into the computer
by a boot program, manages all of the other application programs in a computer. The
application programs make use of the operating system by making requests for services
through a defined application program interface (API).

Compiler and Interpreter:

Compiler Interpreter

It considers the completion of your program It considers 1 statement in your program at a


as input for converting to machine code. time as input for converting to machine code.

It usually generates intermediate code in the It doesn't create an intermediate object (.obj)
form of the object file (.obj). code.

Faster execution of control statements as Slower execution of control statements as


compared to the interpreter. compared to the compiler.

Detected errors in the program get displayed Detected errors in the program get displayed
after the entire program is read by compiler. after each instruction read by the interpreter.

Example: C++, Java. Example. BASIC, Python, PHP.

Software:
The software is the collection of programs (Instructions) that allow the hardware to do its job.
Computer Software divided into two categories.
1) System Software
2) Application Software

The programs directly related to the computer hardware and perform tasks associated with
controlling and utilizing computer hardware

System software:
The programs directly related to the computer hardware and perform tasks associated with
controlling and utilizing computer hardware
System Software mainly divided into three classes.
1) Operating System : An operating system (OS) is the program that, after being
initially loaded into the computer by a boot program, manages all the other programs
in a computer. The other programs are called applications or application programs.
Ex: Windows versions, Linux versions
2) System support: System support software is software that supports, or facilitates the
smooth and efficient execution of various programs and operations of a computer.
There are four major categories of systems support software: utility programs,
language translators, database management systems, and performance statistics
software.

System Development: System support software is software that supports in development of


some software products. Ex: Device drivers

Application Software:
An application is a job or task a user wants to accomplish through a computer.
Application Software is broken into two classes.
General Purpose Software: General Purpose software is programs that help a user perform
general tasks. Ex: word processing, spreadsheets.
Applications Specific Software: Application Specific software are programs that help a user
perform a specific job. Ex: c, c++, java
2. Creating and Running Programs:
We explain the procedure for turning a program written in C into machine language. The
process is presented in a straightforward, linear fashion, but you should recognize that these
steps are repeated many times during development to correct errors and make improvements
to the code.

The job of the programmer to write and test the program. There are four steps in this process.
1. Writing and Editing Programs
2. Compiling Programs
3. Linking Programs
4. Executing Programs
Important Points
1. C program file (Source file) must save with .c extension.
2. Compiler converts complete program at a time from high level language to low level
language.
3. Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
4. Compiler converts the file only if there are no errors in the source code.
5. CPU places the result in User Screen window.

3. Number Systems:

Number systems are the technique to represent numbers in the computer system


architecture, every value that you are saving or getting into/from computer memory has a
defined number system.
Computer architecture supports following number systems.
 Binary number system
 Octal number system
 Decimal number system
 Hexadecimal (hex) number system
Binary Number System
A Binary number system has only two digits that are 0 and 1. Every number (value)
represents with 0 and 1 in this number system. The base of binary number system is 2,
because it has only two digits.
Octal number system
Octal number system has only eight (8) digits from 0 to 7. Every number (value)
represents with 0,1,2,3,4,5,6 and 7 in this number system. The base of octal number
system is 8, because it has only 8 digits.
Decimal number system
Decimal number system has only ten (10) digits from 0 to 9. Every number (value)
represents with 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base of decimal
number system is 10, because it has only 10 digits.
Hexadecimal number system
A Hexadecimal number system has sixteen (16) alphanumeric values from 0 to 9 and A to
F. Every number (value) represents with 0,1,2,3,4,5,6, 7,8,9,A,B,C,D,E and F in this
number system. The base of hexadecimal number system is 16, because it has 16
alphanumeric values. Here A is 10, B is 11, C is 12, D is 13, E is 14 and F is 15.
Table of the Numbers Systems with Base, Used Digits, Representation, C language
representation:
Number Bas Used digits Example C Language
system e assignment
Binary 2 0,1 (11110000) int
2 val=0b1111000
0;
Octal 8 0,1,2,3,4,5,6,7 (360)8 int val=0360;
Decimal 10 0,1,2,3,4,5,6,7,8, (240)10 int val=240;
9
Hexadecima 16 0,1,2,3,4,5,6,7,8, (F0)16 int val=0xF0;
l 9,
A,B,C,D,E,F

Number System Conversions:


There are two types of conversion:
 Decimal Number System to Other Base
[for example: Decimal Number System to Binary Number System]
 Other Base to Decimal Number System
[for example: Binary Number System to Decimal Number System]

Decimal Number System to Other Base


To convert Number system from Decimal Number System to Any Other Base is quite easy;
you have to follow just two steps:

 Divide the Number (Decimal Number) by the base of target base system (in which
you want to convert the number: Binary (2), octal (8) and Hexadecimal (16)).
 Write the remainder from step 1 as a Least Signification Bit (LSB) to Step last as a
Most Significant Bit (MSB).

Result
Decimal to Binary Conversion
Decimal Number is : (12345)10

Decimal to Octal Conversion Result


Decimal Number is : (12345)10 Octal Number is
(30071)8
Decimal to Hexadecimal Conversion Result
Example 1 Hexadecimal
Decimal Number is : (12345)10 Number is
(3039)16

Example 2 Hexadecimal
Decimal Number is : (725)10 Number is
(2D5)16
Convert
10, 11, 12, 13, 14,
15
to its equivalent...
A, B, C, D, E, F

Other Base System to Decimal Number Base


1. To convert Number System from Any Other Base System to Decimal Number System,
you have to follow just three steps:
2.
Determine the base value of source Number System (that you want to convert), and also
determine the position of digits from LSB (first digit’s position – 0, second digit’s
position – 1 and so on).
3.
Multiply each digit with its corresponding multiplication of position value and Base of
Source Number System’s Base.
4. Add the resulted value in step-2.
Explanation regarding examples:
 Below given exams contains the following rows:
 Row 1 contains the DIGITs of number (that is going to be converted).
 Row 2 contains the POSITION of each digit in the number system.
 Row 3 contains the multiplication: DIGIT* BASE^POSITION.
 Row 4 contains the calculated result of step C.
 And then add each value of step D, resulted value is the Decimal Number.

Binary to Decimal Conversion:


Binary Number is : (11000000111001)2
Octal to Decimal Conversion Result
Octal Number is : (30071)8 =12288+0+0+56+1
=12345
Decimal Number
is: 
(12345)10

Hexadecimal to Decimal Result


Conversion
Hexadecimal Number is : (2D5)16 =512+208+5
=725
Decimal Number is: (725)10

4. Introduction to algorithms:

To write a logical step-by-step method to solve the problem is called algorithm, in other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or
computer problem, this is the first step of the procedure. An algorithm includes calculations,
reasoning and data processing.

Algorithms must satisfy the following criteria -


Input: There are more quantities that are extremely supplied.
Output: At least one quantity is produced.
Definiteness: Each instruction of the algorithm should be clear and unambiguous.
Finiteness: The process should be terminated after a finite number of steps.
Effectiveness: Every instruction must be basic enough to be carried out theoretically or by
using paper and pencil.

Algorithms can be presented by natural languages, pseudo code and flowcharts, etc.

Pseudo code is an artificial and informal language that helps programmers develops
algorithms. Pseudo code is very similar to everyday English.

Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.

Pseudo code:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”

Detailed Algorithm
Step 1: Read M1,M2,M3,M4
Step 2: GRADE = (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
end if

Flowchart:

A flowchart is the graphical or pictorial representation of an algorithm with the help of


different symbols, shapes and arrows in order to demonstrate a process or a program.

Predefined Process or Function

Function definition

Loop or repetition

Flow lines (represents direction)

Connector

Data Base
The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colours. In a flowchart, we can
easily highlight a certain element and the relationships between each part.

Example 1: Print 1 to 20:

Algorithm:

Step 1: Initialize X as 0,

Step 2: Increment X by 1,

Step 3: Print X,

Step 4: If X is less than 20 then go back to step 2.

Flowchart:

5. Program design and structured programming

We’ve now seen the steps that are necessary to build a program. In this section, we discuss
how we go about developing a program. This critical process determines the overall quality
and success of our program. If we carefully design each program using good structured
development techniques, our programs will be efficient, error-free, and easy to maintain.

System Development Life Cycle


Program Development:
1. Writing and Editing Programs
2. Compiling Programs
3. Linking Programs
4. Executing Programs
Generally, the programs created using programming languages like C, C++, Java etc., are
written using high level language like English. But, computer cannot understand the high
level language. It can understand only low level language. So, the program written in high
level language needs to be converted into low level language to make it understandable for
the computer. This conversion is performed using either Interpreter or Compiler.

Popular programming languages like C, C++, Java etc., use compiler to convert high level
language instructions into low level language instructions. Compiler is a program that
converts high level language instructions into low level language instructions. Generally,
compiler performs two things, first it verifies the program errors, if errors are found, it returns
list of errors otherwise it converts the complete code into low level language.

To create and execute C programs in Windows Operating System, we need to install Turbo C
software. We use the following steps to create and execute C programs in Windows OS…

6. Introduction to C programming language:

History of C
C is a structured programming language. It is also known as function orientated programming
language. C programming language was developed in the year of 1972 by Dennis Ritchie at
Bell Laboratories in USA (AT & T).
In the year of 1968, research was started by Dennis Ritchie on programming languages like
BCPL, CPL. The main aim of his research was to develop a new language to create an OS
called UNIX. After four years of research, a new programming language was created with
solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new
language was introduced with the name “Traditional C”.

The name 'c' was selected from the sequence of previous language ‘B’ (BCPL), because most
of the features of 'c' was derived from BCPL (B language).
The first outcome of the c language was UNIX operating system. The initial UNIX OS was
completely developed using 'c' programming language.
The founder of the ‘C’ language,Dennis Ritchie is known as “Father of C”and also “Father of
UNIX”.
C programming language is a very popular programming language, because it is reliable,
simple and easy to use and it is the base for almost all the other programming languages.

The following are the language before ‘c’ & various versions of ‘c’.

1. CPL (Common Programming Language)


The CPL was invented by Martin Richards at the University of Cambridge in the early of
1960's.

2. BCPL (Basic Combined Programming Language)


The BCPL was invented by Martin Richards at the University of Cambridge in the year of
1966. It was a popular programming language at that time. BCPL allows the user, direct
access to the computer memory. BCPL is the extension of CPL.

3. B Language
B language is derived from BCPL. It was introduced in the year of 1969 by Ken Thompson
and Dennis Ritchie at Bell Laboratory, USA. The B language is similar to the BCPL.

4. C Language
C language is derived from B language. It was introduced in the year of 1972 by Dennis
Ritchie at Bell Laboratory, USA. The C language was mainly developed to create a operating
system called UNIX. The name C is given based on the previous language B and BCPL.

5. ANSI C (C89)
In the year of 1983, the ANSI (American National Standards Institute) formed a committee to
frame standard specifications for the C language. In the year of 1989, this committee
introduced a standard version of C with the name "ANSI C" with standard library files. The
ANSI C is also called as C89 in short form.

6. C90
In the year of 1990, the ANSI C was got ISO (Intenational Organization for Standardization)
standardization with the inclusion of few new features like new library files, new processor
commands.
7. C99
In the year of 1995, many new features were added to the C90 to create a new version of it.
Basic structure of C programs:

C is a structured programming language. Every c program and its statements must be in a


particular structure. Every c program has the following general structure...

Line 1: Comments - They are ignored by the compiler


This section is used to provide small description of the program. The comment lines are
simply ignored by the compiler, which means they are not executed. In C, there are two types
of comments.
1.Single Line Comments: Single line comment begins with // symbol. We can write
any number of single line comments.
2.Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends
with */. We can write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write the
comments. All the comment lines in a C program just provide the guidelines to understand
the program and its code.

Line 2: Pre-processing Commands


Pre-processing commands are used to include header files and to define constants. We use
#include statement to include header file into our program. We use #define statement to
define a constant. The pre-processing statements are used according to the requirement. If we
don't need any header file, then no need to write #include statement. If we don't need any
constant, then no need to write #define statement.

Line 3: Global Declaration


Global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions. This
global declaration is used based on the requirement.

Line 4: int main()


Every C program must write this statement. This statement (main) specifies the starting point
of the C program execution. Here, main is a user defined method which tells the compiler that
this is the starting point of the program execution. Here, int is a data type of a value that is
going to return to the Operating System after completing the main method execution. If we
don't want to return any value, we can use it as void.

Line 5: Open Brace ({ )


The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with '{' symbol.

Line 6: Local Declaration


In this section, we declare the variables and functions that are local to the function or block in
which they are declared. The variables which are declared in this section are valid only within
the function or block in which they are declared.

Line 7: Executable statements


In this section, we write the statements which perform tasks like reading data, displaying
result, calculations etc., all the statements in this section are written according to the
requirement.

Line 9: Closing Brace ( } )


The close brace indicates the end of the block which belongs to the main method. In C
program every block ends with '}' symbol.

Line 10, 11, 12, ...: User defined function()


This is the place where we implement the user defined functions. The user defined function
implementation can also be performed before the main method. In this case, the user defined
function need not to be declared. Directly it can be implemented, but it must be before the
main method. In a program, we can define as many user defined functions as we want. Every
user defined function needs a function call to execute its statements.es for any C program
1.Every executable statement must end with semicolon symbol (;).
2.Every C program must contain exactly one main method (Starting point of the
program execution).
3.All the system defined words (keywords) must be used in lowercase letters.
4.Keywords cannot be used as user defined names(identifiers).
5.For every open brace ({), there must be respective closing brace (}).
6.Every variable must be declared before it is used.

C tokens:

Every C program is a collection of instructions and every instruction is a collection of some


individual units. Every smallest individual unit of a c program is called token.

In a c program tokens may contain the following


1.Keywords
2.Identifiers
3.Operators
4.Special Symbols
5.Constants
6.Strings
7.Data values
In a C program, collection of all the keywords, identifiers, operators, special symbols,
constants, strings and data values are called as tokens.
Consider the following C program...
#include>stdio.h>
int main()
{
int i;
printf(“ASCII characters”);
for(i=-128;i<=127;i++)
printf(“%d->%c”,i,i);
}
In the above program there are 22 tokens.

Keywords:
In C programming language, keywords are special words with predefined meaning.
Keywords are also known as reserved words in C programming language.
In C programming language, there are 32 keywords. All the 32 keywords have their own
meaning which is already known to the compiler.

Keywords are the reserved words with predefined meaning which already known to the
compiler
Whenever C compiler comes across a keyword, automatically it understands its meaning.

Properties of Keywords
1.All the keywords in C programming language are defined as lowercase letters so
they must be use only in lowercase letters
2.Every keyword has a specific meaning; users can not change that meaning.
3.Keywords cannot be used as user defined names like variable, functions, arrays,
pointers etc...
4.Every keyword in C programming language represents something or specifies some
kind of action to be performed by the compiler.
The following table specifies all the 32 keywords with their meaning...
Identifiers:

Identifier is a user defined name of an entity to identify it uniquely during the program
execution

Example
int marks;
char studentName[30];
Here, marks and studentName are identifiers.

Rules for Creating Identifiers


1.An identifier can contain letters (UPPERCASE and lowercase),  numeric  & 
underscore  symbol only.
2.An identifier should not start with numerical value. It can start with a letter or an
underscore.
3.We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
4.Keywords should not be used as identifiers.
5.There is no limit for length of an identifier. However, compiler considers first 31
characters only.
6.An identifier must be unique in its scope.
Constants:
A constant can be defined as follows...
A constant is a named memory location which holds only one value throughout the program
execution.
In C programming language, constant can be of any data type like integer, floating point,
character, string and double etc.

Integer constants
An integer constant can be a decimal integer or octal integer or hexa decimal integer. A
decimal integer value is specified as direct integer value whereas octal integer value is
prefixed with 'o' and hexa decimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer
constant. Unsigned integer constant value is suffixed with 'u' and long integer constant value
is suffixed with 'l' whereas unsigned long integer constant value is suffixed with 'ul'.

Examples
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant

Floating Point constants


A floating point constant must contain both integer and decimal parts. Some times it may also
contain exponent part. When a floating point constant is represented in exponent form, the
value must be suffixed with 'e' or 'E'.

Example
The floating point value 3.14 is represented as 3E-14 in exponent form.

Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.

Example
'A'
'2'
'+'
In C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape
sequence is prefixed with '\' symbol. These escape sequences are used in output function
called 'printf()'.

Strings:

String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences
that are enclosed in double quotations.
Ex: "This""is""btechsmartclass"
Special Symbols:

The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose.

[] () {} , ; : * … = #

Braces {}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.

Parentheses (): These special symbols are used to indicate function calls and function
parameters.

Brackets []: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.

Variables :

Variable is a name given to a memory location where we can store defferent values of same
datatype during the program execution.
Every variable in c programming language must be declared in the declaration section before
it is used. Every variable must have a data type that determines the range and type of values
to be stored and size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the
rules to specify a variable name...
1.Variable name should not start with digit.
2.Keywords should not be used as variable names.
3.Variable name should not contain any special symbols except underscore(_).
4.Variable name can be of any length but compiler considers only the first 31
characters of the variable name.

Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with
specified variable name and allows only specified datatype values into that memory location.

Declaration Syntax:

datatype variableName;

Example: int number;


The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.

Data Types:

Data used in c program is classified into different types based on its properties. In c
programming language, data type can be defined as a set of values with similar
characteristics. All the values in a data type have the same properties.
Data types in c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of value of a variable are determined by varible
datatype. In a c program, each variable or constant or array must have a datatype and this
datatype specifies how much memory is to be allocated and what type of values are to be
stored in that variable or constant or array. The formal definition of datatype is as follows...

Datatype is a set of value with predefined characteristics. Datatypes are used to


declare variable, constants, arrays, pointers and functions.

In c programming language, datatypes are classified as follows...


1.Primary Datatypes (Basic Datatypes OR Predefined Datatypes)
2.Derived Datatypes (Secondary Datatypes OR Userdefined Datatypes)
3.Enumeration Datatypes
4.Void Datatype

Primary Datatypes
The primary datatypes in C programming language are the basic datatypes. All the primary
datatypes are already defined in the system. Primary datatypes are also called as Built-In
datatypes. The following are the primary datatypes in c programming lanuage...
1.Integer Datatype
2.Floating Point Datatype
3.Double Datatype
4.Character Datatype

Integer Datatype
Integer datatype is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer datatype in c. We use the keyword int to
declare the variables and to specify return type of a function. The integer datatype is used
with different type modifiers like short, long, signed and unsigned. The following table
provides complete details about integer datatype.
Floating Point Datatypes
Floating point datatypes are set of numbers with decimal value. Every floating point value
must contain the decimal value. The floating point datatype has two variants...
float
double
We use the keyword "float" to represent floating point datatype and "double" to represent
double datatype in c. Both float and double are similar but they differ in number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19
decimal places. The following table provides complete details about floating point datatypes.

Character Data type


Character datatype is a set of characters enclosed in single quotations. The following table
provides complete details about character datatype.
The following table provides complete information about all the datatypes in c programming
language...

void Datatype
The void datatype means nothing or no value. Generally, void is used to specify a function
which does not return any value. We also use the void datatype to specify empty parameters
of a function.

Enumerated Datatype
An enumerated datatype is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define enumerated datatype.

Derived Datatypes
Derived datatypes are user-defined data types. The derived datatypes are also called as user
defined datatypes or secondary datatypes. In c programming language, the derived datatypes
are created using the following concepts...
Arrays
Structures
Unions
Enumeration
7. Syntax and Logical Errors in compilation:

Error is an illegal operation performed by the user which results in abnormal working of the
program.
Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors should
be removed before compiling and executing.

The most common errors can be broadly classified as follows.

1. Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax
are known as syntax errors. This compiler error indicates something that must be
fixed before the code can be compiled. All these errors are detected by compiler and
thus are known as compile-time errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it
 Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
    int x = 10;
    int y = 15; 
    
    printf("%d", (x, y)) // semicolon missed
}
Error:
error: expected ';' before '}' token
 Syntax of a basic construct is written wrong. For example : while loop
2. Run-time Errors : Errors which occur during program execution(run-time) after
successful compilation are called run-time errors. One of the most common run-time
error is division by zero also known as Division error. These types of error are hard to
find as the compiler doesn’t point to the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate
// run-time error
#include<stdio.h>
void main()
{
    int n = 9, div = 0;
    
    // wrong logic
    // number is divided by 0,
    // so this program abnormally terminates
    div = n/0;
    printf("resut = %d", div);
}
Error:
warning: division by zero [-Wdiv-by-zero]
div = n/0;
3. Linker Errors: These error occurs when after compilation we link the different
object files with main’s object using Ctrl+F9 key(RUN). These are errors generated
when the executable of the program cannot be generated. This may be due to wrong
function prototyping, incorrect header files. One of the most common linker error is
writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>
  
void Main() // Here Main() should be main()
{
    int a = 10;
    printf("%d", a); 
}
Error:
(.text+0x20): undefined reference to `main'
4. Logical Errors : On compilation and execution of a program, desired output is not
obtained when certain input values are given. These types of errors which provide
incorrect output but appears to be error free are called logical errors. These are one of
the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to
detect if we follow the line of execution and determine why the program takes that
path of execution.
// C program to illustrate
// logical error
int main()
{
    int i = 0;
  
    // logical error : a semicolon after loop
    for(i = 0; i < 3; i++);
    {
        printf("loop ");
        continue;
    } 
    getchar();
    return 0;
}
No output
5. Semantic errors : This error occurs when the statements written in the program are
not meaningful to the compiler.
// C program to illustrate
// semantic error
void main()
{
  int a, b, c;
  a + b = c; //semantic error
}
Error
error: lvalue required as left operand of assignment
a + b = c; //semantic error

8. Object and executable code:

 Object code is the output of a compiler after it processes the source code.


 The object code is usually a machine code, also called a machine language, which
can be understood directly by a specific type of CPU (central processing unit), such
as x86 (i.e., Intel-compatible) or PowerPC.
 However, some compilers are designed to convert source code into an assembly
language or some other another programming language.
 An assembly language is a human-readable notation using
the mnemonics (mnemonic is a symbolic name for a single executable machine
language instruction called an opcode) in the ISA ( Instruction Set Architecture) of
that particular CPU .

 Executable (also called the Binary) is the output of a linker after it processes


the object code.
 A machine code file can be immediately executable (i.e., runnable as a program), or it
might require linking with other object code files (e.g. libraries) to produce a
complete executable program.

9. Operators:
• An operator is a symbol which helps the user to give instruction to the computer to
do a certain mathematical or logical manipulations.
• Operators are used in C language program to operate on data and variables.
• C has a rich set of operators which can be classified as follows:
1. Arithmetic operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increments and Decrement Operators.
6. Conditional Operators.
7. Bitwise Operators.
8. Special Operators.
1.Arithmetic Operators
 All the basic arithmetic operations can be carried out in C.
 All the operators have almost the same meaning as in other languages.
 Both unary and binary operations are available in C language.
 Unary operations operate on a single operand,
 Therefore the number 5 when operated by unary – will have the value –5.
Operator Meaning

+ Addition or Unary Plus


- Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
Examples of arithmetic operators are: x + y , x - y , x * y , x / y , x % y
The modulus operator is a special operator in C language which evaluates the remainder of
the operands after division.
Integer Arithmetic
When an arithmetic operation is performed on two integers than such an operation is called as
integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 x + y = 32 , x
– y = 22 , x * y = 115 , x % y = 2 , x / y = 5
Floating point arithmetic
When an arithmetic operation is performed on two real numbers such an operation is called
floating point arithmetic. Let x = 14.0 and y = 4.0 then x + y = 18.0 , x – y = 10.0 , x * y =
56.0 , x / y = 3.50
Mixed mode arithmetic
When one of the operand is real and other is an integer and if the arithmetic operation is
carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand
is of real type then the result will always be real 15/10.0 = 1.5

2.Relational Operators

Often it is required to compare the relationship between operands and bring out a decision
and program accordingly. This is when the relational operator come into picture. C supports
the following relational operators.
Ex: It is required to compare the marks of 2 students, salary of 2 persons, we can compare
them using relational operators.
(6.5 <= 25) , (-65 > 0) , (10 < 7 + 5)
which result in either TRUE OR FALSE
Relational expressions are used in decision making statements of C language such as if, while
and for statements to decide the course of action of a running program

Operato Meaning
r
< 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

3.Logical Operators

C has the following logical operators; they compare or evaluate logical and relational
expressions.
Operato Meaning
r Op1 Op2 Op1 & Op1||
op2 op2
&& Logical AND
Nonzer Nonzer 1 1
o o
|| Logical OR
Nonzer 0 0 1
o
! Logical NOT
0 Nonzer 0 1
o

0 0 0 0

Logical AND (&&)


If both the expressions are true then the whole compound expression is true. Example: a
> b && x = = 10
Logical OR (||)
If any one of the 2 expressions is true.
Example: a < m || a < n
Logical NOT (!)
The logical not operator evaluates to true if the expression is false and evaluates to false if the
expression is true.
For example: ! (x >= y)

4.Assignment Operators

 The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression.
Example: x = a + b
In addition, C has a set of shorthand assignment operators of the form.
var oper = exp;
Example: x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows
Shorthand assignment operators

Statement with Statement with


simple shorthand operator
assignment 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

5.Increment and Decrement Operators

1. The increment and decrement operators are one of the unary operators which are very
useful in C language.
2. They are extensively used in for and while loops. The syntax of the operators is given
below
1. ++ variable name 2. variable name++
3. – –variable name 4. variable name– –
The increment operator ++ adds the value 1 to the current value of operand.
The decrement operator – – subtracts the value 1 from the current value of operand.

1. ++variable name and variable name++ mean the same thing when they form
statements independently.
2. They behave differently when they are used in expression on the right hand side of an
assignment statement.
Consider the following
m = 5;
y = ++m; (prefix) In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix) Then the value of y will be 5 and that of m will be 6.

6.Conditional or Ternary Operator

The conditional operator consists of 2 symbols the question mark (?) and the colon (:). The
syntax for a ternary operator is as follows:
exp1 ? exp2 : exp3
The ternary operator works as exp1 is evaluated first. If the expression is true then exp2 is
evaluated & its value 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 expression is
evaluated.
For example:
a = 10; b = 15; x = (a > b) ? a : b
Here x will be assigned to the value of b.
The condition follows that the expression is false therefore b is assigned to x.
Output
Input 2 integers : 45 34
The largest of two numbers is 45

7.Bitwise Operators
 The C language is well suited to system programming because it contains operators that
can manipulate data at the bit level.
 Those operators are used for testing, complementing or shifting bits to the right on
left.
 C has two categories of bitwise operators that operate on data at the bit level:
1. Logical bitwise operators and
2. Shift bitwise operators.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift right

Bitwise Operators Truth table


~a a^b a|b a&b B a
1 0 0 0 0 0
1 1 1 0 1 0
0 1 1 0 0 1
0 0 1 1 1 1

Bitwise Shift Operators


The shift operators moves bits to the right or left.
Bitwise shift-right operator:
 The bitwise shift right (>>) is a binary operator that requires two integral operands .
 The first operand is the value to be shifted.
 The second operand specifies the number of bits to be shifted.
Ex: a >>= 5; /* shift right 5 bits */
 When we shift a binary numbers, the right-shift operator divides by a power of 2.
 If we shift a binary number two places to the right, we are dividing by 4.
 If we shift it three places , we are dividing by 8.

2 shift Divide by Shift Operator


value
1 2 >>1
2 4 >>2
3 8 >>3
4 16 >>4
….. ……. ……
n 2n >>n

Bitwise Left-Shift Operators


 The bitwise shift right (<<) is a binary operator that requires two integral operands .
 The first operand is the value to be shifted.
 The second operand specifies the number of bits to be shifted.
Ex: a <<=3; /* shift right 5 bits */
 When we shift a binary numbers, the Left-shift operator multiplies by a power of 2.
 If we shift a binary number two places to the left, we are multiplying by 4.
 If we shift it three places , we are multiplying by 8.
2 shift Multiplies by Shift Operator
value
1 2 <<1
2 4 <<2
3 8 <<3
4 16 <<4
…. …….. ……
n 2n <<n

8.Special Operators
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and ->). The size of and the
comma operators are discussed here.

The Comma Operator


The comma operator can be used to link related expressions together. A comma linked list of
expressions are evaluated left to right and 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 10 to x and 5 to y and finally assigns 15 to value. Since comma has
the lowest precedence in operators the parenthesis is necessary. Some examples of comma
operator are In for loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops While (c=getchar(), c != ‘10’)
Exchanging values t = x, x = y, y = t; .
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in
the memory. The operand may be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of 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 the execution of the program

10. Operator precedence and associativity:

Precedence
1. Precedence is used to determine the order in which different operators in a complex
expression are evaluated .
2. C extents the concept to 15 levels.
Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Associativity
1. Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression.
2. Precedence is applied before associativity to determine the order in which expressions
are evaluated.
3. Associativity can be left-to-right or right-to-left.

Left to Right Associativity

All the operators have the same precedence. Their associativity is from left to right. so they
are grouped as follows
Ex: 3* 8 / 4 % 4 * 5

Right to Left Associativity


All the operators have the same precedence. Their associativity is from right to left. so they
are grouped as follows
Ex: a += b *= c -= 5 which is (a=a+(b=b*(c=c-5)))
Operato Description Precedenc Associativity
r e
() Parentheses (function call) 1 left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement
++ -- Prefix increment/decrement 2 right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of
* type)
& Dereference
sizeof Address (of operand)
Determine size in bytes on this
implementation
*  /  % Multiplication/division/modulus 3 left-to-right
+  - Addition/subtraction 4 left-to-right
<<  >> Bitwise shift left, Bitwise shift right 5 left-to-right
Operato Description Precedenc Associativity
r e
<  <= Relational less than/less than or equal to 6 left-to-right
>  >= Relational greater than/greater than or equal
to
==  != Relational is equal to/is not equal to 7 left-to-right
& Bitwise AND 8 left-to-right
^ Bitwise exclusive OR 9 left-to-right
| Bitwise inclusive OR 10 left-to-right
&& Logical AND 11 left-to-right
|| Logical OR 12 left-to-right

?: Ternary conditional 13 right-to-left


= Assignment 14 right-to-left
+=  -= Addition/subtraction assignment
*=  /= Multiplication/division assignment
%=  &= Modulus/bitwise AND assignment
^=  |= Bitwise exclusive/inclusive OR assignment
<<=  >>= Bitwise shift left/right assignment
, Comma (separate expressions) 15 left-to-right

11. Evaluation of expressions:

 An expression is a sequence of operands and operators that reduce to a single value.


 Expressions can be simple or complex.
 An operator is a syntactical token that requires an action be taken.
 An operand is an object on which an operation is performed; it receives an operator’s
action .
 A simple expression contains only one operator. Ex: 2+5
 A complex expression contains more than one operator. Ex: 2+5*7
 An expression always reduces to a single value.
 We can divide simple expressions into six categories based on number of operands,
relative position of the operand and operator and the precedence of operator.

Now we evaluate expressions as we know precedence, associativity of operators


Ex: a*4+b/2-c*b consider a=3 b=4 c=5
Replace variables by their values
3*4+4/2–5*4
Apply precedence rules
(3 * 4) + (4 / 2) – (5 * 4)
Apply Associativity rules as they are left to right associative
(((3 * 4) + (4 / 2)) – (5 * 4))
In evaluation of these expressions there are no side effects
Expressions with side effects
Now look for example with side effects and parenthesized expressions.
Ex: --a * ( 3 + b ) / 2 – c++ * b
Assume a=3 b=4 c=5
Calculate the value of parenthesized expressions
--a * 7 / 2 – c++ * b
Evaluate postfix expression
--a * 7 / 2 – 5 * b
1. Evaluate prefix expression 2*7/2–5*b
1. Now apply multiply and division 14 / 2 – 5*4
1. Last step is to evaluate subtraction 7-20=-13
After the side effects the variables have the values shown below a=2 b=4 c=6

12. Storage Classes:


Object Storage Attributes
• Each and every variable is stored in computer memory.
• Every variable and function in C has two attributes:
1. datatype (Eg: int, float, char, etc..)
2. Storage Class
• Storage Class specifies the scope, extent and linkage.

• Scope determines the region of the program in which a defined object is visible.
• Scope pertains to any object that can be declared, such as a variable or a function
declaration.
• An object can have three levels of scope
1. Block scope
2. Function scope
3. File scope
Block Scope
• Variables defined within a block have a local scope. They are visible in that block
only. Outside the block they are not visible. Eg:
• { //outer block starts
{//inner block starts

}//inner block ends


• } //outer block ends
• Variables are in scope from their point of declaration until the end of the block. Block
scope is also referred as local scope.
• Variables that are declared in a block are known as local variables.
Function Scope
• Variables defined within a function (including main) are local to this function and no
other function has direct access to them.
• Eg: int add(int a, int b) //add() is a function
{ //function scope starts
}//function scope ends
File Scope
• File scope includes the entire source file for a program, including any files that are
part of it.
• An object with file scope has visibility through the whole source file in which it is
declared.
• Objects within block scope are excluded from file scope unless specifically declared
to have file scope; in other words, by default, block scope hides objects from file
scope.
• An object with file scope sometimes referred to as a global object and the variables
declared inside this scope are referred to as Global Variables.
Extent
• Defines the duration for which the computer allocates memory for the variable.
• It is also known as storage duration.
• Extents are of two types:
1. Automatic Extent: object is created each time when it is declared and it is
destroyed each time when the block is exited.
2. Static Extent: object is created when the program is loaded for execution and it is
destroyed when the execution stops.
Linkage
 A large application program may be broken into several modules, with each module
potentially written by a different programmer. Each module is a separate source file
with its own objects.
 We can define two types of linkages:
-internal
-external
 Internal Linkage: An object with an internal linkage is declared and visible in one
module. Other modules cannot refer to this object.
 External Linkage: An object with an external linkage is declared in one module but is
visible in all other modules with a special keyword, extern.
 There are four storage classes
 Automatic (auto variable)
 The default and the most commonly used storage class is automatic.
 Memory for automatic variables is allocated when a block or function is created.
They are defined and are “local” to the block.
 When the block is exited, the system releases the memory that was allocated to the
automatic variables, and their values are lost.
 These variables are also referred as local variables.
• Characteristics:
• Scope: block
• Extent: automatic
• Linkage: internal
• Declaration:
auto type variable_name;
• Initialization:
An auto variable can be initialized where it is defined or left uninitialized. When auto
variables are not initialized, its value is a garbage value.
int main()
{//main block starts
auto int i=1;//auto is a keyword
{//inner block starts
auto int i=2;
{//inner-inner block starts
auto int i=3;
printf("OUTPUT\n");
printf("i=%d\t",i);//Print 3
}//inner-inner block ends
printf("i=%d\t",i);//Print 2
}//inner block ends
printf("i=%d\t",i);Print 1
return 0;
}//main block ends
Register (register variable)
 Register variables specify to the compiler that the variables should be stored in high-
speed memory registers if possible. This is done for efficiency.
 If no register space is free, variables become auto instead.
 Keep register variables in small local blocks which are reallocated quickly.
 The address of a register variable is unavailable to the user. The user program can’t
use both the address operator and the indirection operator (pointer) with a register.
• Characteristics:
• Scope: block
• Extent: automatic/register
• Linkage: internal
• Declaration:
register type variable name;
• Initialization:
A register variable can be initialized where it is defined or left uninitialized.
int main()

{//main block starts

register int i=1;//register is a keyword

{//inner block starts


register int i=2;

{//inner-inner block starts


register int i=3;
printf("OUTPUT\n");
printf("i=%d\t",i);//Print 3
}//inner-inner block ends

printf("i=%d\t",i);//Print 2
}//inner block ends
Static (static variable):
• The value of static variables persists until the end of the program.
• It is declared using the keyword static :
static int x;
static float y;
• By default, Static variables are initialized with zero.
• The static specifier has two different usages depending on its scope.
1. static variable with block scope
2. static variable with file scope.
Static variable with block scope
• When a static variable is declared in a block scope, static defines the extent of the
variable
• Static variables with Block Scope are also known as Static Local Variables
Scope: Block
Extent: Static
Linkage: Internal
• Declaration:
static type variable_name
• Initialization:
• A static variable name can be initialized where it is defined, or it can be left
uninitialized. If it is initialized, it is initialized only once. If not initialized, its value
will be initialized to zero
Static variable with file scope
• When the static specifier is used with a variable that has a file scope (global scope)
and its linkage is internal.
Scope: File
Extent: Static
Linkage: Internal
Declaration:
Static type variable name;
#include <stdio.h>
#include<conio.h>
void fun1();//function definition
int main()
{//main block starts
int i=1;
printf("OUTPUT\n");
for(i=1;i<=5;i++)
fun1(); //call fun1() 5 times
return 0;
}//main block ends

//function definition
void fun1()
{//function scope starts
static int x=0;//declaring x as static variable
//int x=0;
printf("%d\n",x++);
}//function scope ends
#include<stdio.h>
#include<conio.h>

void fun1();//function declaration

static int x;//static variable x

int main()
{//main block starts

int i=0;
for(i=1;i<=5;i++)
{
printf("In Main\n");
printf("x=%d",x++);
fun1();
}//for loop ends

printf("x=%d\n",x);
return 0;
}//main block ends
void fun1()
{//function scope ends

printf("In function\n");
printf("x=%d\n",x++);
}//function scope ends
External (extern variable)
 Extern is used for global variables that are shared across code in several files.
 External variables are used with separate compilations.
 Large projects are decomposed in to many source files.
 Decomposed source files are compiled separately and linked together to form a unit.
 Storage is permanently assigned to Global variables (defined outside functions) and
all functions of the storage class extern.
• Characteristics:
• Scope: file
• Extent: static
• Linkage: external
• Declaration:
extern type variable_name;
#include <stdio.h>
#include<conio.h>

extern int i=10;


int main()
{//main block starts

{//inner block starts

{//inner-inner block starts

printf("OUTPUT\n");
printf("i=%d\t",i);//Print 10
}//inner-inner block ends

printf("i=%d\t",i);//Print 10
}//inner block ends

printf("i=%d\t",i);//Print 10
return 0;
}//main block ends
Class Scop Extent Linkag Keyword
e e

auto block automatic internal auto or none


register block automatic internal register
static(extent) block static internal static
static(linkage file static internal static
)
extern file static internal extern or none

13. Type Conversion:

we have assumed that all of our expressions involved data of the same type. But, what
happens when we write an expression that involves two different data types, such as
multiplying an integer and a floating-point number? To perform these evaluations, one of
the types must be converted.
Type conversion is of two types:
1. Implicit Type Conversion
2. Explicit Type Conversion (Cast)
Implicit Type Conversion
When the types of the two operands in a binary expression are different, C automatically
converts one type to another. This is known as implicit type conversion.
Conversion rank:
1. We assign a rank to the integral and floating point arithmetic types.
2. These ranks are known as conversion ranks.
3. Conversion ranks are shown below

Conversions in Assignment Expressions


A simple assignment involves an assignment operator and two operands. Depending on
the difference in the rank, C tries to either promote or demote the right expression to
make it the same rank as the left variable.
1. Promotion occurs if the expression has lower rank.
2. Demotion occurs if the right expression has higher rank.
Promotion
1. There is normally no problem with promotion.
2. The rank of right expression is elevated to the rank of the left variable.
3. The value of the expression is the value of the right expression after the promotion.
Ex: bool b= true
char c= ‘A’
int i=1234
long double d=3458.0004
c=b //value of c is SOH (ASCII 1)
i= c //value of i is 65
d=b //value of d is is 1.0
d=i // value of d is 1234.0
Demotion
1. Demotion may or may not create problems.
2. If the size of the variable at the left side can accommodate the value of the expression,
then there is no problem.
3. If the size of the variable at the left side can not accommodate the value of the
expression, then demotion occurs.
Ex:
bool b = false
char c = ‘A’
short int s = 78
int j = 32200
int k = 65
b=c // value of b is 1 (true)
s=j // value of s is unpredictable
c=k+1 // demotion value of c is ‘B’
Conversion in other binary expressions:

Conversion has a different set of rules for other binary expressions.


1. The operand with higher rank is determined using the ranking table.
2. The lower ranked operand is promoted to the rank defined in step 1. After the
promotion both expressions have the same rank.
3. The operation is performed with the expression value having the type of the promoted
rank.
Ex: bool b = true;
char c = ‘A’
int i = 3650
short int s= 78
long double d = 3458.0004\
b+c // b promoted: result is ‘B’
I*s // result is an integer
d*c // result is long double

Explicit type conversion (cast)


1. In explicit type conversion we convert the data from one type to another type using
explicit type conversion.
2. Explicit type conversion uses the unary type cast operator
3. To cast the data from one type to another, we specify the new type in parentheses
before the value we want to convert.
Ex: (float) a
One use of the cast is to ensure that the result of a divide is a real number.
Ex: avg=(float) totalscores/ numscore
here totalscores is integer
numscore is int
but result is float due type cast operator before totalscores

14. The main method and command line arguments:

The most important function of C is main() function. It is mostly defined with a return
type of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are
given after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
 argc (ARGument Count) is int and stores number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a
program, value of argc would be 2 (one for argument and one for program name)
 The value of argc should be non negative.
 argv(ARGument Vector) is array of character pointers listing all the arguments.
 If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
 Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
Properties of Command Line Arguments:
1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values
inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.

15. Conditional Branching:

Selection / Conditional/ Decision Making and Branching Statement


1. We have seen that a C program is a set of statements that are normally executed
sequentially in the order in which they appear.
2. However, in practice, we have a number of situations where we may have to change
the order of execution of statements based on certain conditions, or repeat a group of
statements until certain specific conditions are met.
3. This involves a kind of decision making to see whether a particular condition has
occurred or not and then direct the computer to execute certain statements
accordingly.
4. C language possesses such decision making capabilities by supporting the following
statements:
l if statement
l switch statement
l goto statement
These statements are popularly known as decision making statements.
These statements control the flow of execution they are also known as control statements
If Statement
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements.
It is basically a two-way decision statement and is used in conjunction with an expression
takes the following form
The if statement may be implemented in different forms depending on the complexity
of conditions to be tested.
1. The different forms are
simple if statement
if …. else statement
nested if… else statement
else if ladder.
Simple if statement
The general form of simple if statement is
if (test expression)
{
statement-block;
}
statement-X
If test expression is true , then statement block will be executed; otherwise the statement
block will be skipped and the execution will jump to the statement-X

if…else statement
The if…else statement is an extension of the simple if statement. It takes the following
general form:
if ( test expression)
{
true-block statement(s)
}
else
{
false-block statement(s)
}
statement-x
If the test expression is true, then the true block statements are executed.
If the test expression is false, then the false block statements are executed.
It never executes both blocks at a time.
In both cases the control is transferred
to the statement-X

Nesting of if…else statement


When a series of decisions are involved, we may have to use more than one if… else
statement in nested form.
if (test condition-1)
{
if (test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-X
1. Once we start nesting if….else statements, we encounter a classical problem known as
the dangling else.
2. This problem is created when there is no matching else for every if.
3. else is always paired with the most recent unpaired if.

The else if Ladder

1. There is another of putting ifs together when multipath decisions are involved .
2. A multipath decision is a chain of ifs in which the statement associated with each else
is an if.
3. It takes general form, as shown below.
if(condition-1)
statement-1;
else if (condition-2)
statement-2;
else if(condition-3)
statement-3
else if(condition n)
statement-n;
else
default statements;
statement-X

Multi way selection statement

1. In addition to two-way selection, most programming languages provide another


selection concept known as multi way selection.
2. Multi way selection chooses among several alternatives.
3. C has two different ways to implement multi way selection:
4. The switch statement and
5. else-if construct.(difficult if no of alternatives are more).
6. The switch statement can be used only when the selection condition reduces to an
integral expression.
7. Many times, when the selection is based on a range of values , the condition is not an
integral. In these cases we use else-if which we already discussed.
switch(expression)
{
case constant-expression:
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */
….....
default : /* Optional */
statement(s);
}

Loops:
There are three loop statements:
1. the while
2. the for and
3. the do…while.
The first two are pretest loops and the third is a post-test loop.
Every loop consists of the following properities.

Loop Initialization
1. Loop initialization must be done before the first execution of the loop body.
2. Initialization may be explicit or implicit.
3. When the initialization is explicit, we include code to set the beginning values of key
loop variables.
4. Implicit initialization provided no direct initialization code; rather, it relies on a
preexisting situation to control the loop

Loop Update
How can the condition that controls the loop be true for a while and then change to false.
The answer is that something must happen inside the body of the loop to change the
condition.
1. The actions that cause these changes are known as loop update.
2. Update is done in each iteration, usually as the last action.
3. If the body of the loop is repeated m times, then updating is also done m times.

Loop Control Expression:


1. The concept of loop, contains the action will be repeated forever.
2. We definitely do not want this to happen.
3. We want our loop to end when the work is done.
4. To make sure that it ends, we must have a condition that controls the loop.
5. We must design the loop so that before or after each iteration, it checks to see if the
task is done.
6. If not done, the loop repeats one more time;
7. If the task is done, the loop terminates.
8. This test is known as a loop control expression.

The while loop


1. The while loop is a pretest loop.
2. The while loop uses an expression to control the loop.
3. Because it is a pretest loop, it tests the expression before every iteration of the loop.
4. No semicolon is needed at the end of the while statement.
5. Statements within the while loop ends with semicolon.
The for loop
1. The for statement is a pretest loop that uses three expressions.
 The first expression contains ant initialization statements
 The second contains the limit-test expression.
 The third contains the updating expression.
2. A for loop is used when a loop is to be executed a known number of times.
3. We can do the same thing with a while loop, but the for loop is easier to read and
more natural for counting loops.
4. The for loop uses three expression in a single line, each expression is separated by a
semi-colon.

The do…while loop


1. The do…while statement is a post test loop.
2. Like the while and for loops, it also uses an expression to control the loop.
3. The do…while loop tests the expression after the execution of the body.
4. The do…while loop is concluded with a semicolon.
5. The body of the do…while loop is executed atleast once.
Three other C statements are related to loops:
1. break
2. continue
3. goto.
Break
1. In a loop, the break statement causes a loop to terminate.
2. If we are in a series of nested loops, break terminates only inner loop—the one we are
currently in.
3. Break statements needs a semicolon.
4. The break statements can be used in any of the loops—while, do…while, for and in
the selection switch statement.
5. Good structured programming limits its usage.
The continue
1. The continue statement does not terminate the loop but simply transfers the control to
the test expression in while and do…while statements and transfers to the updating
expression in a for statement.
2. Although the transfer is to different positions in pretest and post test loops, both can
logically thought of as a jump to the end the loops body.
3. The use of continue is also considered as unstructured programming.

The goto
1. C supports the goto statement to branch unconditionally one point to another point in
the program.
2. Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify.
3. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax:
The syntax for a goto statement in C is as follows:
goto label;
..
.
Label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement.

10. Formatted I/O Statements


C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from keyboard. C programming language
provides the following built-in input functions...
1. scanf()
2. printf()

scanf() function
The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
When we want to use scanf() function in our program, we need to include the respective
header file (stdio.h) using #include statement. The scanf() function has the following syntax...

Syntax:

scanf("format strings",&variableNames);

Example Program

#include <stdio.h>

void main(){

int i;

printf("\nEnter any integer value: ");

scanf("%d",&i);

printf("\nYou have entered %d number",i);

}
Output:
Enter any integer value: 55
You have entered 55 number
In the above example program, we used the scanf() function to read an integer value from the
keyboard and store it into variable 'i'.
The scanf function also used to read multiple data values of different or same data types.
Consider the following example program...
#include <stdio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
Enter one integer followed by one float value: 20 30.5
integer = 20, float = 30.5
In the above example program, we used the scanf() function to read one integer value and one
float value from the keyboard. Here 'i' is an integer variable so we have used format string
%d, and 'x' is a float variable so we have used format string %f.

The scanf() function returns an integer value equal to the total number of input values read
using scanf function.

Example Program

#include <stdio.h>

void main(){

int i,a,b;

float x;

printf("\nEnter two integers and one float : ");

i = scanf("%d%d%f",&a, &b, &x);

printf("\nTotal inputs read : %d",i);

}
Output:
Enter two integers and one float : 10 20 55.5
Total inputs read : 3
Formatted output Functions in C:
C programming language provides built-in functions to perform output operation. The output
opearations are used to display data on user screen (output screen) or printer or any file. C
programming language provides the following built-in output functions...
1. printf()

printf() function
The printf() function is used to print string or data values or combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in
a header file called "stdio.h". When we want to use printf() function in our program we need
to include the respective header file (stdio.h) using #include statement. The printf() function
has the following syntax...

Syntax:

printf("message to be display!!!");

Example Program
#include <stdio.h>
void main(){
printf("Hello! Welcome to btechsmartclass!!!");
}
Output:
Hello! Welcome to btechsmartclass!!!
In the above example program, we used the printf() function to print a string on to the output
screen.

The printf() function is also used to display data values. When we want to display data values
we use format string of the data value to be display.

Syntax:

printf("format string",variableName);

Example Program
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output:
10 5.5
In the above example program, we used the printf() function to print data values of variables i
and x on to the output screen. Here i is a integer variable so we have used format string %d
and x is a float variable so we have used format string %f.
The printf() function can also used to display string along with data values.

Syntax:

printf("String format string",variableName);

Example Program
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}
Output:
Integer value = 10, float value = 5.5
In the above program we are displaying string along with data values.

Every function in C programming language must have a return value. The printf() function
also have integer as return value. The printf() function returns an integer value equalent to the
total number of characters it has printed.

Example Program
#include <stdio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);
}
Output:
btechsmartclass is 15 number of characters.
In the above program, first printf() function printing "btechsmartclass" which is of 15
characters. So it returns integer value 15 to variable "i". The value of "i" is printed in the
second printf() function.

Formatted printf() function


Generally, when we write multiple printf() statements the result is displayed in single line
because the printf() function displays the output in a single line. Consider the following
example program...
#include <stdio.h>
void main(){
printf("Welcome to ");
printf("btechsmartclass ");
printf("the perfect website for learning");
}
Output:
Welcome to btechsmartclass the perfect website for learning
In the above program, there are 3 printf() statements written in different lines but the output is
displayed in single line only.

To display the output in different lines or as we wish, we use some special characters
called escape sequences. Escape sequences are special characters with special functionality
used in printf() function to format the output according to the user requirment. In C
programming language, we have the following escape sequences...
Escape sequence Meaning
\n New line
\t Horizontal Tab
\v Vertical Tab
\a Beep sound
\b Backspace
\\ Backward slash
\? Question mark
\' Single quotation mark
\" Double quotation mark
Consider the following example program...
#include <stdio.h>
void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");
}
Output:
Welcome to
btechsmartclass
the perfect website for learning

You might also like