0% found this document useful (0 votes)
39 views54 pages

C Programming UNIT 1

The document provides an introduction to computer programming concepts including algorithms, flowcharts, program development steps, computer languages, and number systems. It discusses the structure of a C program including the character set, tokens, data types, operators, and gives examples of binary, octal, and hexadecimal number systems and conversions between them. It also provides details about computer memory including how data is stored as 1s and 0s, the logical view of main memory as addressable locations, and an example program for coming to college.

Uploaded by

Phani Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
39 views54 pages

C Programming UNIT 1

The document provides an introduction to computer programming concepts including algorithms, flowcharts, program development steps, computer languages, and number systems. It discusses the structure of a C program including the character set, tokens, data types, operators, and gives examples of binary, octal, and hexadecimal number systems and conversions between them. It also provides details about computer memory including how data is stored as 1s and 0s, the logical view of main memory as addressable locations, and an example program for coming to college.

Uploaded by

Phani Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

CHAPTER -I

CONTENTS:
Introduction to computer programming,
ALGORITHM
FLOW CHART,
PROGRAM DEVELOPMENT STEPS.

Computer languages:
o Machine level
o Assembly level
o High-level language.
Number Systems:
o DECIMAL NUMBER SYSTEM
o BINARY NUMBER SYSTEM
o OCTAL NUMBER SYSTEM
o HEXA DECIMAL NUMBER SYSTEM
o Conversions- decimal, binary, octal, hexadecimal.
‘C’ Fundamentals:

❖ STRUCTURE OF A C-PROGRAM
❖ C-CHARACTER SET
❖ C TOKENS-
➢ VARIABLES,
➢ CONSTANTS
➢ IDENTIFIERS
➢ DATA TYPES AND SIZES
➢ OPERATORS

1|Page
1. A Brief Introduction To Computers

Computer is made by Electronic devices. In olden days, computers are called as


Electronic Computing Machines (ECM). Electronic devices work with the principles of
Electrical Voltages (EV). There are two types of EV - one is high or required voltage by which
a Bulb or Fan or Electronic Device functions. The second one is low or no voltage by which a
Bulb or Fan or Electronic device stop functioning. These two EV can be denoted in the
following way. The high or required voltage can be denoted as “ON or ONE”. The low or no
voltage is denoted as “LOW or ZERO”.
Assume that there are, three switches S1, S2 and S3 with the status ON, ON, OFF. We can
also denote or the status of three switches as 1 1 0. This “high or 1” and “low or Zero” created
a Binary (means two values 0 or 1) number system and Binary Logic.
That is internally in Computer everything is represented or stored or Executed or
Evaluated with High (1) and Low (0) Voltages because Computer is made up of Electronic
devices which works with the principles of Electrical Voltages.
That means, whatever we type using Keyboard will be stored internally as group of 1’s
and 0’s because Computer (ECM) can only understand them. But whenever we ask to display
the stored contents, then the group of 1’s and 0’s are converted into alphanumeric system as
shown in Fig.1.
In Fig.1 the user or programmer typed HELLOW using keyboard. The word HELLOW is
stored in memory in terms of group of zero’s and one’s (High or low voltages). Memory is an
Electronic device that works with the principles of EV. Later to display the word on the screen
these group of zero’s and one’s, (stored in the computer memory) are converted into the word
HELLOW and displayed on the screen.

Fig.1: Conversion Mechanism.

2|Page
1.1 Binary System

1.1.1 Decimal System

To understand Computer System, we should understand Binary Number System. For this
we should understand Decimal System. In Decimal (base-10) system there are 10 different
digits. i.e., { 0,1,2,3,4,5,6,7,8,9}.
To prove a number as 7579 (Seven thousand Five hundred and Seventy Nine), we follow
weighted system. Each Decimal digit is having a weight... like unit (10 0), tens (101), hundred
(102), thousand (103),…,.and so on……

Now let us think about the range of a decimal system. Assume that you have three

decimal digit spaces as shown in Fig.2.

Fig.2: 3 decimal digit space.

A decimal digit is a space where you can place any digit from 0 to 9.

Now answer the following questions

3|Page
Q1. What range of numbers you can represent with the digits.

Or

Q2. With 3 digits you can address how many students (by giving Roll no’s or Hall ticket no’s)?

Or

Q3. How many houses we can address with the 3 digits?

In above all three questions represents the same.

MIN Number : 000

Three digits MAX Number : 999

That means, the Range of numbers or the No of students or Houses we can address are
from 000 to 999 which are 1000.
✓ The range is 0 to 103 -1. (Here 103 because there are 3 digits).
✓ Why we should use 10 – powers – because we are in Decimal System.
In the same with N digits we can address 0 to 10N -1 students or houses or Line No’s. The range
is 0 to 10N -1.
1.2 Binary Numbers – a Brief Introduction
How to understand a binary system? Let us consider a binary number: 11010 (S 1:ON
S2:ON S3:OFF S4:ON S5:OFF), what is this binary number represents? What is the value of
11010 in decimal? For this we follow the same notation of Decimal. Each and every bit of a
binary number is also represented with weights (in the same way as decimal system) as shown
below.
A binary system is also a weighted system (20, 21, 22, 23,…, 2N) like Decimal system.

4|Page
In computer terminology to represent Binary digit - we use Binary bit. A bit can be either

a Zero (0) or One (1). In a similar way a digit can be either a 0 or 1 or 2 or 3 … or 9.

The notations or units used in binary system.

• 8 bits are called as 1 Byte.

• 2 bytes (2*8=16 bits) are called as a Word.

• 210 =1024 is called as Kilo, represented as K.

• All students should know the values from 20 to 210.

For example, 64K means 64×1024=26×210=216.

Range in Binary

Assume that there is a Space for 3 binary bits as shown in Fig.3.

Fig.3: Space for 3 binary bits.

5|Page
Q1. Give me the range of binary numbers and their equivalent decimal numbers with 3 bits?

Or

Q2. With 3 bits how many students we can address by giving roll no’s or hall ticket no’s?

Or

Q3. How many Houses we can address with 3 binary digits?

MIN Binary Number: 0 0 0

MAX Binary Number: 1 1 1

(why all 111

why can’t 999 or 222 discuss)

• Range is 000 to 111 in Binary.

(111)2 : 1 1 1 = 1*22 + 1*21 + 1*20

22 21 20 =7

That means just like Decimal Number System the range with 3 binary bits is 000 to 2 3 -1

= 0 to 7.

Here 23 The number of bits used for range.

The base.

• Say what range of numbers you can represent with 8 bits.

8 bits
7 6 5 4 3 2 1 0 0 to 7

0 0 0 0 0 0 0 0 to 1 1 1 1 1 1 1 1
= 0 to 28-1
= 0 to 255

6|Page
The range of numbers we can represent with N bits is 0 to 2N-1.

• With 16 bits, 24, 32 and 64 bits?

Say what range of numbers we can represent with 2, 4, 6, 8, 10, 12, 14, 16, 32, 64 bits?

1. What is a Memory?

Anything which is capable of storing information is called Memory. (Eg. note books, text

books, name plates, benches, hands, walls, etc).

Whenever we type through keyboard, the alphanumeric characters are stored in the main

memory in binary form (i.e. Zero’s or one’s) that is in terms of electrical voltages.

• The Main memory is a Volatile memory that is if the power goes down all the contents

stored will be removed or deleted or vanished. This is the main disadvantage with the

main memory. For example black board is a volatile memory with respect to water.

Means by throwing or pouring water on black board the written contents will be

vanished, where as the case is not same for a name plate.

• Hence, we have to save our programs or documents i.e., saving means copying the

contents from main memory to secondary memory, which is on Hard Disk. In Hard disk,

the contents are not deleted even though the power goes down.

7|Page
2. Logical view of Main memory

The Main memory looks like a LKG square book as shown below. In each square, we can

write only a single symbol. In Main memory, the square is called a Cell. In each cell, we can

place a Zero or One (which means that each cell is a switch and if 1 is placed in it, it will be ON

and a zero means it will be OFF).

✓ The Line No’s are called as Location No’s in Computer terminology which specifies the

address of the data.

✓ In location 2, the data stored is 11000. Here location 2 is the Address and 11000 is the

Data. That means Line No’s or Location No’s represent the address of the Data.

✓ Place or write in Location No 7 11111 and in location No 5, 00111

Line 0 1 0 0 0 0 0 0 0
Line 1 1 1 1 1 1 0 1 1
Line 2 1 1 0 0 1 1 0 0
Line 3 1 1 0 0 1 1 0 1

8|Page
Line 4 1 1 0 1 1 1 0 0
Line 5
Line 6
Line 7

3. PROGRAMM – A BRIEF INTRODUCTION

WHAT IS A PROGRAM?

A program is nothing but a sequence of instructions. To execute a program, one should

execute instructions step by step in the given order. The order of execution is important. In our

day-to-day life, everything can be considered as a program. For example consider a situation -

coming to college.

Example-1: Program for Coming to college

Begin

Instruction 1: get up by 6 A.M


Instruction 2: refresh yourself by 6.30 A.M
Instruction 3: take bath
Instruction 4: wear uniform and shoes
Instruction 5: wear ID card
Instruction 6: check the bag
Instruction 7: have breakfast
Instruction 8: come to bus stop by 8 A.M and catch the bus
Instruction 9: come to college by 9 A.M
end

9|Page
CENTRAL PROCESSING UNIT (CPU)

CPU Central Processing System: The CPU is a place where our programs are decoded

and executed. CPU can be viewed as a Brain of a Human being. To execute a program CPU

does the following

It reads the program, instruction by instruction.

Decodes the instructions.

Executes by activating various circuits.

The brain or CPU is contains some internal memory – which is called as Registers in computer

terminology

Algorithm:
A step-by-step method of solving a problem or making decisions.
Properties of the algorithm

1. Finiteness. An algorithm must always terminate after a finite number of steps.


2. Definiteness. Each step of an algorithm must be precisely defined; the actions to be
carried out must be rigorously and unambiguously specified for each case.
3. Input. An algorithm has zero or more inputs, i.e, quantities which are given to it initially
before the algorithm begins.
4. Output. An algorithm has one or more outputs i.e, quantities which have a specified
relation to the inputs.
5. Effectiveness. An algorithm is also generally expected to be effective. This means that all
of the operations to be performed in the algorithm must be sufficiently basic that they can
in principle be done exactly and in a finite length of time

Example:

Write an algorithm to find the largest among three different numbers entered by user.

6. Step 1: Start
7. Step 2: Declare variables a,b and c.
8. Step 3: Read variables a,b and c.
10 | P a g e
9. Step 4: If a>b
10. If a>c
11. Display a is the largest number.
12. Else
13. Display c is the largest number.
14. Else
15. If b>c
16. Display b is the largest number.
17. Else
18. Display c is the greatest number.
19.Step 5: Stop

Example:

Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.

Step 1: Start

Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;

Step 3: Calculate discriminant

D←b2-4ac

Step 4: If D≥0

r1←(-b+√D)/2a

r2←(-b-√D)/2a

Display r1 and r2 as roots.

Else

Calculate real part and imaginary part

rp←b/2a
11 | P a g e
ip←√(-D)/2a

Display rp+j(ip) and rp-j(ip) as roots

Step 5: Stop

FLOW CHART
A flowchart is a type of diagram that represents an algorithm, workflow or process, showing
the steps as boxes of various kinds, and their order by connecting them with arrows. This
diagrammatic representation illustrates a solution model to a given problem. Flowcharts are
used in analyzing, designing, documenting or managing a process or program in various fields.

The following are some of the commonly used shapes used in flowcharts. Generally, flowcharts
flow from top to bottom and left to right.

Shape Name Description

An arrow coming from one symbol and ending at another


symbol represents that control passes to the symbol the arrow
Flow Line points to. The line for the arrow can be solid or dashed. The
meaning of the arrow with dashed line may differ from one
flowchart to another and can be defined in the legend.

Represented as circles, ovals, stadiums or rounded (fillet)


rectangles. They usually contain the word "Start" or "End", or
Terminal
another phrase signaling the start or end of a process, such as
"submit inquiry" or "receive product".

Represented as rectangles. This shape is used to show that


Process something is performed. Examples: "Add 1 to X", "replace
identified part", "save changes", etc....

12 | P a g e
Represented as a diamond (rhombus) showing where a decision
is necessary, commonly a Yes/No question or True/False test.
The conditional symbol is peculiar in that it has two arrows
coming out of it, usually from the bottom point and right point,
one corresponding to Yes or True, and one corresponding to No
Decision
or False. (The arrows should always be labeled.) More than two
arrows can be used, but this is normally a clear indicator that a
complex decision is being taken, in which case it may need to be
broken-down further or replaced with the "predefined process"
symbol. Decision can also help in the filtering of data.

Represented as a parallelogram. Involves receiving data and


Input/Output displaying processed data. Can only move from input to output
and not vice versa. Examples: Get X from the user; display X.

Represented as rectangles with double-struck vertical edges;


these are used to show complex processing steps which may be
Predefined detailed in a separate flowchart. Example: PROCESS-FILES. One
Process subroutine may have multiple distinct entry points or exit flows .
If so, these are shown as labeled 'wells' in the rectangle, and
control arrows connect to these 'wells'.

Represented as a hexagon. May also be called initialization.


Shows operations which have no effect other than preparing a
Preparation value for a subsequent conditional or decision step.
Alternatively, this shape is used to replace the Decision Shape in
the case of conditional looping.

Generally represented with a circle, showing where multiple


control flows converge in a single exit flow. It will have more
than one arrow coming into it, but only one going out. In simple
cases, one may simply have an arrow point to another arrow
On-Page instead. These are useful to represent an iterative process (what
Connector in Computer Science is called a loop). A loop may, for example,
consist of a connector where control first enters, processing
steps, a conditional with one arrow exiting the loop, and one
going back to the connector. For additional clarity, wherever two
lines accidentally cross in the drawing, one of them may be
13 | P a g e
drawn with a small semicircle over the other, showing that no
connection is intended.

Represented as a home plate-shaped pentagon. Similar to the on-


Off-Page
page connector except allows for placing a connector that
Connector
connects to another page.

EXAMPLE: FLOW CHART TO FIND THE LARGEST OF THREE NUMBERS

EXAMPLE: FLOW CHART TO FIND THE ROOTS OF A QUADRATIC EQUATION :

14 | P a g e
PROGRAM DEVELOPMENT STEPS:
The following steps are used in sequence for developing an efficient program:
• Specifying the problem statement
• Designing an algorithm
• Coding
• Debugging
• Testing and Validating
• Documentation and Maintenance.

Specifying the Problem:


The Problem which has to be implemented into a program must be thoroughly
understood before the program is written. Problem must be analyzed to determine the input and
output requirements of the program. A problem is created with these specifications.
Designing an Algorithm:
With the problem statement obtained in the previous step, various methods available for
obtaining the required solution are analyzed and the best suitable method is designed into
algorithm.
To improve clarity and understandability of the program flow charts are drawn using the
algorithms.
Coding:
The actual program is written in the required programming language with the help of
information depicted in flow charts and algorithms.
Debugging:
There is a possibility of occurrence of errors in programs. These errors must be removed
to ensure proper working of programs. Hence error check is made. This process is known as
“Debugging”.
Types of errors that may occur in the program are:
1. Syntactic Errors: These errors occur due to the usage of wrong syntax for the
statements.
Syntax means rules of writing the program.
Example: x=z*/b;
There is syntax error in this statement. The rules of binary operators state that there
cannot be more than one operator between two operands.
2. Runtime Errors: These Errors are determined at the execution time of the program.
Example: Divide by zero
Range out of bounds
Square root of a negative number
15 | P a g e
3. Logical Errors: These Errors occur due to incorrect usage of the instruction in the
program. These errors are neither displayed during compilation or execution nor cause
any obstruction to the program execution. They only cause incorrect outputs. Logical
Errors are determined by analyzing the outputs for different possible inputs that can be
applied to the program. By this way the program is validated.

Testing and Validating:


Testing and Validation is performed to check whether the program is producing correct
results or not for different values of input.

Documentation and Maintenance:


Documentation is the process of collecting, organizing and maintaining, in written the
complete information of the program for future references. Maintenance is the process of
upgrading the program according to the changing requirements.

COMPUTER LANGUAGES
1)Machine code or machine language is a set of instructions executed directly by
a computer's central processing unit (CPU). Each instruction performs a very specific task, such
as a load, a jump, or an ALU operation on a unit of data in a CPU register or memory. Every
program directly executed by a CPU is made up of a series of such instructions.

It is represented in 0’s and 1’s … computers can understand this language only.

2)An assembly (or assembler) language, often abbreviated asm, is a low-level


programming language for a computer, or other programmable device, in which there is a very
strong (generally one-to-one) correspondence between the language and
the architecture's machine code instructions. Each assembly language is specific to a particular
computer architecture. In contrast, most high-level programming languages are
generally portable across multiple architectures but require interpreting or compiling. Assembly
language may also be called symbolic machine code.[2]
Assembly language is converted into executable machine code by a utility program referred to
as an assembler. The conversion process is referred to as assembly, or assembling the source
code. Assembly time is the computational step where an assembler is run.
Assembly language uses a mnemonic to represent each low-level machine
instruction or opcode,
1. Assembly Language: They are written in mnemonics for representing the actions.

16 | P a g e
Example: ADD for addition
MOV for moving the data etc...
In computer science, a high-level programming language is a programming language with
strong abstraction from the details of the computer. In comparison to low-level programming
languages, it may use natural language elements, be easier to use, or may automate (or even
hide entirely) significant areas of computing systems (e.g. memory management), making the
process of developing a program simpler and more understandable relative to a lower-level
language. The amount of abstraction provided defines how "high-level" a programming
language is.
In the 1960s, high-level programming languages using a compiler were commonly
called autocodes.[2] Examples of autocodes are COBOL and Fortran.
1. Third Generation Languages: Earlier assembler programs produced only one machine
instruction for every one assembly language instruction. To speed up the process, these
languages are developed.
Example: BASIC, FORTRAN, COBOL, etc…
2. Fourth Generation Languages: To make the Programming easy, these languages are
developed. The instructions in these languages are more like English Words.

Number Systems
Human beings use decimal (base 10) number system for counting and measurements .
Computers use binary (base 2) number system, as they are made from binary digital
components (known as transistors) operating in two states – on (1’s) and off (0’s). In
computing, we also use hexadecimal (base 16) or octal (base 8) number systems, as
a compact form for represent binary numbers.

Each 1 and 0 is called a bit. 4 bits is called a nibble. 8 bits is called a byte. 16/32/64/128
bits is called a word.

Binary(2) 0 1
Octal (8) 0 1 2 3 4 5 6 7
Decimal (10) 0 1 2 3 4 5 6 7 8 9
Hexadecimal (16) 0 1 2 3 4 5 6 7 8 9 A B C D E F

Number Systems Conversion


1. Binary to Decimal Conversion
To convert a binary number to decimal, sum together the weights. Each weight is calculated by
multiplying the bit by 2i, where i is the index relative to the LSB.

17 | P a g e
2. Decimal to Binary Conversion
To convert a decimal number to its equivalent binary number representation, the easiest method
is to use repeated division by 2. Each time, save the remainder. The first remainder is the least
significant bit. The last remainder is the most significant bit.

3. Octal Numbers
Octal to Decimal Conversion Converting octal to decimal is just like converting binary to
decimal, except instead of powers of 2, we use powers of 8. That is, the LSB is 8 0, the next is
81, then 82, etc.

Decimal to Octal Conversion is just like converting decimal to binary, except instead of
dividing by 2, we divide by 8.

Octal to Binary conversion can be done by looking at 3 bit combinations, and then
concatenating them together.
Octal (8) 0 1 2 3 4 5 6 7 372 777
Binary 000 001 010 011 100 101 110 111 011111010 111111111
(2)

18 | P a g e
Binary 000 001 010 011 100 101 110 111 010111010 111111111
(2)
Octal (8) 0 1 2 3 4 5 6 7 372 777

4. Hexadecimal Numbering
The hexadecimal numbering system is the most common system seen today in representing raw
computer data. This is because it is very convenient to represent groups of 4 bits. Consequently,
one byte (8 bits) can be represented by two groups of four bits easily in hexadecimal.

Hex to Decimal Conversion is just like converting binary to decimal, except instead of powers
of 2, we use powers of 16. That is, the LSB is 160, the next is 161, then 162, etc.

Decimal to Hex Conversion is just like converting decimal to binary, except instead of dividing
by 2, we divide by 16.

Hex to Binary Conversion, Binary to Hex

19 | P a g e
Structure of C program
documentation section

link section

definition section

global declaration section

function prototype section

main() function section

declaration part

execution part

sub program section

function 1

function 2

function n

1. Documentation section: The documentation section consists of a set of comment lines


giving the name of the program. All the comments will be put inside /*...*/. Example:
/* My first program */
2. Link section: The link section provides instructions to the compiler to link functions from
the system library.

20 | P a g e
3. Definition section: The definition section defines all symbolic constants.
4. 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.
5. Function prototype section: In this section the prototype (i. e., the nature of the function)
of the user defined function is specified to the compiler.
6. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
7. Declaration part: The declaration part declares all the variables used in the executable
part.
8. Executable part: There is at least one statement in the executable part. These two parts
must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function is
the logical end of the program. All statements in the declaration and executable part end
with a semicolon.
9. 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 section, except the main () function section may be absent when they are not required.

C Character Set :
Whenever we write any C program then it consists of different statements. Each C Program is
set of statements and each statement is set of different c programming lexims. In C
Programming each and every character is considered as single lexim. i.e [ Basic Lexical
Element ]

Character Set Consists Of –

Types Character Set

Lowercase Letters a-z

Uppercase Letters A to Z

Digits 0-9
21 | P a g e
Types Character Set

Special Characters !@#$%^&*

White Spaces Tab Or New line Or Space

C Tokens
• In C Programming punctuation, individual words ,characters etc are called tokens.
• Tokens are basic building blocks of C Programming

Token Example :

No Token Type Example 1 Example 2

1 Keyword do while

2 Identifier number sum

3 Constants -76 89

4 String “HTF” “PRIT”

5 Special Symbol * @

6 Operators ++ /

22 | P a g e
Basic Building Blocks and Definition :

Token Meaning

A variable is a meaningful name of data storage location


Keyword in computer memory. When using a variable you refer to
memory address of computer

Constant Constants are expressions with a fixed value

Identifier The term identifier is usually used for variable names

String Sequence of characters

Special Symbols other than the Alphabets and Digits and white-
Symbol spaces

A symbol that represent a specific mathematical or non


Operators
mathematical action

Keywords in C Programming Language :

1. Keywords are those words whose meaning is already defined by Compiler


2. Cannot be used as Variable Name
3. There are 32 Keywords in C
4. C Keywords are also called as Reserved words .

23 | P a g e
32 Keywords in C Programming Language

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

What is Variable in C Programming?


Variable in C Programming is also called as container to store the data. Variable name may
have different data types to identify the type of value stored. Suppose we declare variable of
type integer then it can store only integer values. Variable is considered as one of the building
block of C Programming which is also called as identifier.

[box]A Variable is a name given to the memory location where the actual data is stored.[/box]

Consider real time example , suppose we need to store water then we can store water in glass if
quantity of water is small and Bucket is the quantity of water is large. And big can to store
water having quantity larger than bucket similarly Variable (i.e Value container) may have
different size for storing different verities of values.

1. Initially 5 is Stored in memory location and name x is given to it


2. After We are assigning the new value (3) to the same memory location

24 | P a g e
3. This would Overwrite the earlier value 5 since memory location can hold only one
value at a time
4. Since the location ‘x’can hold Different values at different time so it is refered as
‘Variable‘
5. In short Variable is name given to Specific memory location or Group.

Consider following Scenario –

Step 1 : Memory Before Variable Declaration

25 | P a g e
Initially before declaring variable ,We have Only memory.

Memory is block of bytes.

Each byte is filled with random or garbage data.

Step 2 : Declaring Variable in C Programming

1. Now we have declared a variable. (in this case we have declared character variable)
2. Compiler Checks data type . Depending on data type it will allocate appropriate bytes of
memory. (in this case Compile will allocate 1 byte because we have declared Character
data type)
3. It’s only declaration so , garbage value inside that address remains the same.

26 | P a g e
Step 3 : Initialize Variable in C Programming

1. We have Initialize character variable now.


2. After initializing value inside that memory block gets overwritten.

Conclusion :

1. Variable Name always holds a single Value.


2. Variable Name is user defined name given to Memory Address.
3. During Second Run , Address of Variable may change.
4. During second Run , Value set inside variable during current will be considered as
garbage..

Rules For Constructing Variable Name

1. Characters Allowed :
o Underscore(_)
o Capital Letters ( A – Z )
o Small Letters ( a – z )
o Digits ( 0 – 9 )

27 | P a g e
2. Blanks & Commas are not allowed
3. No Special Symbols other than underscore(_) are allowed
4. First Character should be alphabet or Underscore
5. Variable name Should not be Reserved Word

Explanation with Example

Tip 1 : Use allowed Characters

Valid Names

num
Num
Num1
_NUM
NUM_temp2

Tip 2 : blanks are not allowed

Invalid Names

number 1
num 1
addition of program

Tip 3 : No special symbols other that underscore

Valid Identifier

num_1
number_of_values
status_flag

28 | P a g e
Tip 4 : First Character must be underscore or Alphabet

Valid Identifier

_num1
Num
Num_
_
__

Invalid Identifier

1num
1_num
365_days

Tip 5 : Reserve words are not allowed

• C is case sensitive.
• Variable name should not be Reserve word.
• However if we capitalize any Letter from Reserve word then it will become legal variable
name.

Valid Identifier

iNt
Char
Continue
CONTINUE

Invalid Identifier

int
29 | P a g e
char
continue

Tip 6 : Name of Identifier cannot be global identifier

What is Constant ?
Constant in C means the content whose value does not change at the time of execution of a
program.
Definition :

[box]Constant means “Whose value cannot be changed“[/box]

Explanation :

• Initially 5 is Stored in memory location and name x is given to it


• After We are assigning the new value (3) to the same memory location
• This would Overwrite the earlier value 5 since memory location can hold only one
value at a time
• The value of ‘3’,’5′ do not change ,so they are constants
• In Short the ‘Values of Constant Does not Change‘.

Different Types of C Constants :

Constant Type of Value Stored

30 | P a g e
Constant Type of Value Stored

Integer Constant Constant which stores integer value

Floating Constant Constant which stores float value

Character Constant Constant which stores character value

String Constant Constant which stores string value

How to Declare Constant in C :

We can declare constant using const variable. Suppose we need to declare constant of type
integer then we can have following two ways to declare it –

const int a = 1;
int const a = 1;

above declaration is bit confusing but no need to worry, We can start reading these variables
from right to left. i.e

Declaration Explanation

const int a = 1; read as “a is an integer which is constant”

int const a = 1; read as “a is a constant integer”

31 | P a g e
Primary Constant :

• Integer
• Float
• Character

Secondary Constant :

• Array
• Pointer
• Structure
• Union
• Enum

Rules of Constructing Integer and Float Constant

Sr.No Rule Integer Float

1 Decimal Point Not Allowed Allowed

2 Sign Positive or Negative Positive or Negative

3 Default Sign Positive Positive

4 No of Digits At least 1 At least 1

5 Min Value -32768 -3.4e38

6 Max Value +32767 3.4e38

Format of Real Number Constant :


Syntax : mantissa e exponent

Part Type Sign

32 | P a g e
Mantissa Integer Part of Real Number Has Optional +/- Sign

Exponent Power of 10 Has Optional +/- Sign

Note :

1. Exponent Part Should be Always Integer.


2. Default Sign is Positive for both Mantissa as well as Exponent
3. Special Characters not allowed
4. Spaces are not allowed

Illustrative Examples :

Real Number Representation

4567.45 4.56745e3

0.00045 4.5e-4

Consider Example 2:

1. Mantissa Should be in between 1 to 9


2. Number : 0.00045 so shift decimal Point to Right by 4 Digit to obtain Mantissa as 4.5
3. Decimal Point is Shifted 4 times to Right
4. According to above Fig . Real Number : 4.5 e -4

33 | P a g e
C Identifiers:
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore (_) as a first character.
There are certain rules that should be followed while naming C identifiers:
1. They must begin with a letter or underscore (_).
2. They must consist of only letters, digits, or underscore. No other special character is
allowed.
3. It should not be a keyword.
4. It must not contain white space.
5. It should be up to 31 characters long as only first 31 characters are significant.
Examples
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword

What is Data Type in C Programming ?

1. A Data Type is a Type of Data.


2. Data Type is a Data Storage Format that can contain a Specific Type or Range of
Values.
3. When computer programs store data in variables, each variable must be assigned
a specific data type.

Some of the Data Types Supported by C :

Data Type keyword Description

Integer Data Type int Stores the Integer Value

Float Data Type float Stores the Floating Point Value

Character Data Type char Stores the Single Character Value

Long Data Type long Stores the Long range Integer Value

34 | P a g e
Data Type keyword Description

Double Data Type double Stores the long range Floating Value

Explanation :

1. Whenever we declare variable in Computer’s memory, Computer must know the type of
the data to be stored inside the memory.
2. If we need to store the single character then the size of memory occupied will be different
than storing the single integer number.
3. The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C.
4. A byte can store a relatively small amount of data one single character or a small integer
(generally an integer between 0 and 255).

Size Required to Store Variable of Different Data Types

Data Type Borland C/C++ Compiler

Integer 2 Bytes

Float 4 Bytes

Character 1 Byte

Long 4 Bytes

Integer Data Type : About Short Integer & Long Integer

1. Integers are whole numbers with a wide range of values that are machine dependent.
2. Integer occupies 2 bytes memory space and its value range limited to -32768 to +32767

How this range is Calculated ?


35 | P a g e
Size of Integer = 2 bytes
No of Bits = 16 bits
= MSB bit is considered as Sign Bit
(Skip that bit)
= 16 bits - 1 bit
= 15 bits

Maximum Range of Integer

Max Range = 2 Raise to 15


= 32768

Minimum Range of Integer

Min Range = 2 Raise to -15


= -32768

Types of Integer Data Types :

1. Integer
2. Short Integer
3. Long Integer

Some Important Points :

• Range of Integer is [2^-15 to 2^+15]


• Each type is again classified into signed and unsigned integer.
• Unsigned integer don’t have sign bit , so its range is 0 to 65535
• A short int requires half the amount of storage than normal integer.
• Unlike signed integer, unsigned integers are always positive and use all the bits for the
magnitude of the number. Therefore the range of an unsigned integer will be from 0 to
65535.
• The long integers are used to declare a longer range of values and it occupies 4 bytes of
storage space.

36 | P a g e
Syntax of Declaring Integer

int num1;
short int num2;
long int num3;

Example of Integer Data types

• 500
• 6764
• 32100

OPERATORS:
Arithmetic Operators
arithmetic operators are shown in the following table. Arithmetic operators are used to perform
arithmetic operations in c programming.

Operator Meaning Example

+ Addition Operator 10 + 20 = 30

- Subtraction Operator 20 – 10 = 10

* Multiplication Operator 20 * 10 = 200

/ Division Operator 20 / 10 = 2

% Modulo Operator 20 % 6 = 2

Example : C Program to Verify Arithmetic Operator and Operation

#include <stdio.h>
int main()
{
int num1,num2;
int sum,sub,mult,div,mod;
printf("\nEnter First Number :");
37 | P a g e
scanf("%d",&num1);
printf("\nEnter Second Number :");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nAddition is : %d",sum);
sub = num1 - num2;
printf("\nSubtraction is : %d",sub);
mult = num1 * num2;
printf("\nMultiplication is : %d",mult);
div = num1 / num2;
printf("\nDivision is : %d",div);
mod = num1 % num2;
printf("\nModulus is : %d",mod);
return(0);
}

Output :

Enter First Number : 10


Enter Second Number : 5
Addition is : 15
Subtraction is : 5
Multiplication is : 50
Division is : 2
Modulus is : 0

Assignment Operators
38 | P a g e
1. Assignment Operator is Used to assign value to an variable.
2. Assignment Operator is denoted by equal to sign
3. Assignment Operator is binary operator which operates on two operands.
4. Assignment Operator have lower precedence than all available operators but has higher
precedence than comma Operator.

Different Ways of Using Assignment Operator :


Way 1 : Assignment Operator used to Assign Value

int main() {
int value;
value = 55;
return (0);
}

In the above example, we have assigned 55 to a variable ‘value’.


Way 2 : Assignment Operator used To Type Cast.

int value;
value = 55.450;
printf("%d",value);

Assignment operator can type cast higher values to lower values. It can also cast lower values to
higher values. Shorthand assignment operator is used express the syntax that are already
available in shorter way

Operator Name of the Equivalent


Example
symbol operator construct

39 | P a g e
Operator Name of the Equivalent
Example
symbol operator construct

+= Addition assignment x += 4; x = x + 4;

Subtraction
-= x -= 4; x = x – 4;
assignment

Multiplication
*= x *= 4; x = x * 4;
assignment

/= Division assignment x /= 4; x = x / 4;

Remainder
%= x %= 4; x = x % 4;
assignment

Unary operators:
unary minus:
The minus operator changes the sign of its argument. A positive number becomes negative, and
a negative number becomes positive.
int a = 10;
int b = -a; // b = -10

unary minus is different from subtraction operator, as subtraction requires two operands.

Increment and Decrement Operator in C

Increment Operators are used to increased the value of the variable by one and Decrement
Operators are used to decrease the value of the variable by one in C programs.

Both increment and decrement operator are used on a single operand or variable, so it is
called as a unary operator. Unary operators are having higher priority than the other operators
it means unary operators are executed before other operators.

40 | P a g e
Syntax

++ // increment operator
-- // decrement operator

Note: Increment and decrement operators are can not apply on constant.
Example

x= 4++; // gives error, because 4 is constant

Type of Increment Operator

• pre-increment
• post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside the expression
(initialize into another variable).

Syntax

++ variable;

Example pre-increment

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=++i;
printf("x: %d",x);
printf("i: %d",i);
getch();
41 | P a g e
}

Output

x: 11
i: 11

In above program first increase the value of i and then used value of i into expression.
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another
variable) and then increment the value of variable.
Syntax
variable ++;
Example post-increment
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

42 | P a g e
Output
x: 10
i: 11
In above program first used the value of i into expression then increase value of i by 1.
Type of Decrement Operator
• pre-decrement
• post-decrement
Pre-decrement (-- variable)
In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).
Syntax
-- variable;
Example pre-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=--i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

43 | P a g e
Output
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.
post-decrement (variable --)
In Post-decrement first value of variable is used in the expression (initialize into another
variable) and then decrement the value of variable.
Syntax
variable --;
Example post-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
getch();
}
Output
x: 10
i: 9
In above program first used the value of x in expression then decrease value of i by 1.
44 | P a g e
Relational operators in C: Relational operators are used to find the relation between
two variables. i.e. to compare the values of two variables in a C program.

S.No Operators Example Description


1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y

• In this program, relational operator (==) is used to compare 2 values whether they are
equal are not.
• If both values are equal, output is displayed as “values are equal”. Else, output is
displayed as “values are not equal”.
• Note: double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).

Logical Operator in C Programming


Whenever we use if statement then we can use relational operator which tells us the result of the
comparison, so if we want to compare more than one conditions then we need to use logical
operators. Suppose we need to execute certain block of code if and only if two conditions are
satisfied then we can use Logical Operator in C Programming.

Operator Name of the Operator

&& And Operator

|| Or Operator

! Not Operator

Let us look at all logical operators with example –

#include<stdio.h>
int main()
{
int num1 = 30;
int num2 = 40;
45 | P a g e
if(num1>=40 || num2>=40)
printf("Or If Block Gets Executed");

if(num1>=20 && num2>=20)


printf("And If Block Gets Executed");

if( !(num1>=40))
printf("Not If Block Gets Executed");

return(0);
}

Output :
Or If Block Gets Executed
And If Block Gets Executed
Not If Block Gets Executed

Explanation of the Program :


Suppose OR Operator is used inside if statement then if part will be executed if any of the
condition evaluated to be true.

if(num1>=40 || num2>=40)

In the above if statement first condition is false and second condition is true , so if part will be
executed.

if(num1>=20 && num2>=20)

In the above if statement both the conditions are true so if statement will be executed, AND
Operator will look for truthness of first condition, If it founds the true condition then it will look
for 2nd condition. If 2nd Condition founds to be true then it will look for next condition.

Logical Operator :
46 | P a g e
Operator Applied Condition Condition Final
Between 1 2 Output

AND True True True

True False False

False True False

False False False

OR True True True

True False True

False True True

False False False

NOT True - False

False - True

Conditional Operators [ ?: ] : Ternary Operator Statement in C

1. They are also called as Ternary Operator .


2. They also called as ?: operator
3. Ternary Operators takes on 3 Arguments
Syntax :
expression 1 ? expression 2 : expression 3

where

• expression1 is Condition
• expression2 is Statement Followed if Condition is True
• expression2 is Statement Followed if Condition is False

47 | P a g e
Meaning of Syntax :

1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is Executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is Executed
5. Expression1 is said to be FALSE if its result is ZERO

Example : Check whether Number is Odd or Even

#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");


scanf("%d",&num);

flag = ((num%2==0)?1:0);

if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}

More Simply we can write this program as –


#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");


scanf("%d",&num);

(num%2==0)?printf("Even"):printf("Odd");

48 | P a g e
}

Note : Operator that works on 3 operands is called as tertiary operator

Comma Operator
#include<stdio.h>
void main() {
int num1 = 1, num2 = 2;
int res;
res = (num1, num2);
printf("%d", res);
}

Explanation :

1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated
at last.
2. Comma operator returns the value of the rightmost operand when multiple comma
operators are used inside an expression.
3. Comma Operator Can acts as –
o Operator : In the Expression
Separator : Declaring Variable , In Function Call Parameter List
o
Usage of Comma Operator

Consider above example –


Comma as Separator

int num1 = 1, num2 = 2;

It can acts as Seperator in –

1. Function calls
2. Function definitions
3. Variable declarations
4. Enum declarations
49 | P a g e
Comma as Operator
res = (num1, num2);

In this case value of rightmost operator will be assigned to the variable. In this case value of
num2 will be assigned to variable res.
Examples of comma operator :
Comma Operator have lowest priority in C Programming Operators.

sizeof operator

1. sizeof operator is used to calcualte the size of data type or variables.


2. sizeof operator can be nested.
3. sizeof operator will return the size in integer format.
4. sizeof operator syntax looks more like a function but it is considered as an operator in c
programming
Example of sizeof() operator
Size of Variables
#include<stdio.h>
int main() {

int ivar = 100;


char cvar = 'a';
float fvar = 10.10;

printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
Output :
214
In the above example we have passed a variable to sizeof operator. It will print the value of
variable using sizeof() operator.

50 | P a g e
(type) operator:
(type) operator is used for type conversion. i. e., one type of data type is converted into
another type of data type.
Example:
int a = 10;
float b;
b = (float) a;
in above, value in variable a is converted into float. i.e., 10.00000 is assigned to variable b.

Bitwise Operators in C

The following table lists the Bitwise operators supported by C. Assume


variable 'A' holds 60 and variable 'B' holds 13, then −
Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) =
12, i.e.,
0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) =


61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) =
49, i.e.,
0011 0001

~ (~A ) = -60,
i.e,. 1100
Binary Ones Complement Operator is unary and has the effect of 'flipping'
0100 in 2's
bits.
complement
form.

<<

Binary Left Shift Operator. The left operands value is moved left by the A << 2 =

51 | P a g e
number of bits specified by the right operand. 240 i.e.,
1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 = 15
number of bits specified by the right operand. i.e., 0000
1111

Example

Try the following example to understand all the bitwise operators available in C −

#include <stdio.h>

main() {

int a = 60; /* 60 = 0011 1100 */

int b = 13; /* 13 = 0000 1101 */

int c = 0;

c = a & b; /* 12 = 0000 1100 */

printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */

printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */

printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */

52 | P a g e
printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */

printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */

printf("Line 6 - Value of c is %d\n", c );

When you compile and execute the above program, it produces the following result −

Line 1 - Value of c is 12

Line 2 - Value of c is 61

Line 3 - Value of c is 49

Line 4 - Value of c is -61

Line 5 - Value of c is 240

Line 6 - Value of c is 15

Precedence and Associativity of operators:


If more than one operators are involved in an expression, C language has a predefined rule of
priority for the operators. This rule of priority of operators is called operator precedence.

In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational operators(==, !=,


>, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, || and
!).

If two operators of same precedence (priority) is present in an expression, Associativity of


operators indicate the order in which they execute.

53 | P a g e
54 | P a g e

You might also like