0% found this document useful (0 votes)
18 views41 pages

PPC Unit 1 Ref Material 2022-23

The document outlines a course titled 'Principles of Programming using C' with a focus on computer architecture, C programming constructs, and user-defined data structures. It includes course objectives, detailed unit topics, programming assignments, and reference books. The course aims to equip students with the skills to design and develop solutions to real-world problems using C language.

Uploaded by

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

PPC Unit 1 Ref Material 2022-23

The document outlines a course titled 'Principles of Programming using C' with a focus on computer architecture, C programming constructs, and user-defined data structures. It includes course objectives, detailed unit topics, programming assignments, and reference books. The course aims to equip students with the skills to design and develop solutions to real-world problems using C language.

Uploaded by

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

Course Title Principles of Programming using C

Course Code: 22UCS119C CIE Marks 50


Course Type SEE Marks 50
(Theory/Practical
/Integrated )
Total Marks 100
Teaching Hours/Week 2:0:2:0 Exam Hours 03
(L:T:P: S)
Total Hours of Pedagogy 40 hours (28 T+24 P) Credits 03

Course Learning Objectives:


CLO 1 Explain the basic architecture and functionalities of a Computer
CLO 2 Apply programming constructs of C language to solve the real-world problems
CLO 3 Explore user-defined data structures like arrays, structures and pointers in implementing solutions
to problems
CLO 4 Design and Develop Solutions to problems using structured programming constructs such as
functions and procedures

UNIT-I 08 Hours
Basic Organization of a Computer, Steps in problem solving, Algorithms and Flowcharts with examples.
Overview of C: Features of C, Structure of C program., process of compiling and executing the C program.
Constants, Variables and Data types: Introduction ,Character set, C tokens, Keywords and Identifiers,
Constants, Variables, Data types, Declaration of variables, Example programs.
Operators and Expressions: Arithmetic operators, Relational operators, Logical operators, Assignment
operators, Increment and Decrement operators, Conditional operator, Bitwise operators, Special operators,
Arithmetic expressions, Evaluation of expressions, Precedence of arithmetic operators, Type conversion in
expressions, Operator precedence and Associativity, Example programs.

UNIT-II 06 Hours
Managing Input and Output Operations: Formatted and Unformatted input and output statements,
Example programs.
Decision making and Branching: Decision making with if, if-else, Nesting of if-else statements, else-if
ladders, switch statement, ?: Operator, goto statement, Example programs.
Decision making and Looping: while statement, do-while statement, for statement, jumps in loops, Example
programs.

UNIT-III 06 Hours
Arrays: Introduction, One dimensional arrays, declaration and initialization of one-dimensional arrays, Two
dimensional arrays, declaration and initialization of two-dimensional arrays. Operations on arrays and
Example programs.
Strings: Introduction, Declaring and initializing string variables, String-handling functions, Array of String,
Example programs.
UNIT-IV 08 Hours
User defined functions: Introduction, Need for user-defined functions, a multi-function program, Elements
of user defined function, Definition of functions, Return values and their types, Function calls, Function
declaration. Category of functions: Based on call by value, call by reference, argument and return type and
recursion, Example programs.
Structures and Unions: Defining a structure, Declaring structure variables, Accessing structure members,
Initialization, Arrays of structure, Structures and Functions, Unions, Example programs.
Pointers: Introduction, Accessing the address of a variable, Declaring and initialization of pointer variables,
Pointers as function arguments , Example programs.

REFERENCE BOOKS:
1. E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw Hill Publications, 2017.
2. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second edition,
2017.
3. Kernighan and Ritchie, C Programming Language, 2nd Edition, 1988, 49th Reprint, 2017
4. Wesley J. Chun, A Structured Programming approach using C, Pearson Education India, 3rd Edition, 2015.
5. Stephen Kochan, Programming in C, 4th Edition, 2014
6. B. S. Anami, S. A. Angadi & S. S. Manvi, Computer Concepts and C programming-A Holistic approach to
learning C, 2nd Edition, PHI, 2010

Course Outcomes

At the end of the course the student will be able to:

CO1. Explain the basic architecture and functionalities of a computer and also recognize the hardware
parts.

CO 2. Apply programming constructs of C language to solve the real world problem

CO 3. Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting

CO 4. Explore user-defined data structures like structures, unions and pointers in implementing solutions

CO5. Design and Develop Solutions to problems using modular programming constructs using functions

E-Resource
https://nptel.ac.in/courses/106104128 - Students can adopt the course for more clarity in understanding
the topics and varieties of problem solving methods using C language.
Programming Assignments

Part A

1. Write a C program that aid in evaluating return on investment of Principal amount for 3 years at 9%
rate of interest using simple interest and compound interest. SI=PTR/100 and CI=P[1+R/100]t.

2 Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.

3 An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise per
unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a
minimum of Rs. 100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge of
15% of total amount is charged. Write a program to read the name of the user, number of units consumed and
print out the charges.

4. A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input
through the keyboard. Help the cashier to find the total number of currency notes of each denomination to be
given to the customer.

5. Write a C program to determine whether a seller has made the profit or incurred the loss and display the
amount and percentage of profit or loss.

6. Write a C program to identify whether the entered character belongs to an alphabet, digit or special
character.

7. Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and
Computer. Calculate percentage and display the grade according to following:

Percentage Grade
More than or equal to 90% S
Between 80% - 89.99% A
Between 70%-79.99% B
Between 60%-69.99% C
Between 40%-59.99% D
Between 35%-40% E
Below 35% F

8. Write a C program, to check whether a person is eligible for the marriage or not.

9. Write a C program to identify the quadrant of a point, when coordinates (x,y) are given.

10. Write a C program to compute area of the following of geometric objects based on user’s
preference using switch case:
i. Circle
ii. Triangle
iii. Parallelogram
iv. Square
Part B

1. Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321
---------------------------
nth row

2. Write a C program to generate the prime numbers between 1 to n.

3. Write a C program to Implement Binary Search on Integers.

4. Implement Matrix multiplication and validate the rules of multiplication.

5. Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the built-in library
function. Print both the results with appropriate inferences.

6. Sort the given set of N numbers using Bubble sort.

7. Write functions to implement string operations such as compare, concatenate, and find string length.
Use the parameter passing techniques.

8. Write a C program to find the factorial of a number using recursive function.

9. Implement structures to read, write and compute average- marks of the students, list the students
scoring above and below the average marks for a class of N students.

10. Write a C program to read two numbers and swap them with help of function through call by reference
method.
UNIT-I 08 Hours
Basic Organization of a Computer, Steps in problem solving, Algorithms and Flowcharts with examples.

Overview of C: Features of C, Structure of C program., process of compiling and executing the C program.

Constants, Variables and Data types: Introduction ,Character set, C tokens, Keywords and Identifiers,
Constants, Variables, Data types, Declaration of variables, Example programs.

Operators and Expressions: Arithmetic operators, Relational operators, Logical operators, Assignment
operators, Increment and Decrement operators, Conditional operator, Bitwise operators, Special operators,
Arithmetic expressions, Evaluation of expressions, Precedence of arithmetic operators, Type conversion in
expressions, Operator precedence and Associativity, Example programs.

Introduction to computer science:

Overview of computer science: Computer science (also called computing science) is the study of the
theoretical foundations of information and computation plus their implementation and application in
computer systems.
A degree in Computer Science can lead to a career in software development and software engineering where
graduates design, implement, test and maintain large software systems, or a career in such specialized fields
as computer graphics, games, security, robotics, artificial intelligence and expert systems, machine learning,
distributed systems, embedded applications, databases, web applications, network applications and
networking and many more.
What is Computer?
 Computer is an electronic device that is used for information processing. It is a calculation machine.
 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.
Parts of a Computer System:

 Hardware: Refers to the physical components of a computer ex: Monitor, printer etc..
 Software: Is a collection of instructions, procedures, documentation that performs different tasks on a
computer system .It tells the hardware, what to do and how to do it, including
Computer programs and applications. Example: MS word, PowerPoint.
 Data: Piece of information.
 User: People operating the computer.
Block Diagram of a Digital Computer

Functional units of a computer:


A computer in its simplest form comprises five functional units namely input unit, output unit ,memory unit,
arithmetic & logic unit and control unit.

1. Input Unit: Computer accepts encoded information through input unit. The standard input device is a
keyboard. Whenever a key is pressed, keyboard controller sends the code to CPU/Memory.

Examples include Mouse, Joystick, Scanner etc.

2. Memory Unit: Memory unit stores the program instructions (Code), data and

results of computations etc. Memory unit is classified as:

• Primary /Main Memory

• Secondary /Auxiliary Memory

Primary memory is a semiconductor memory that provides access at high speed. Run time program
instructions and operands are stored in the main memory. Main memory is classified again as ROM and
RAM. ROM holds system programs and firmware routines such as I/O Drivers that are essential to manage
the hardware of a computer. RAM is termed as Read/Write memory or user memory that holds run time
program instruction and data. While primary storage is essential, it is volatile in nature and expensive.
Additional requirement of memory could be supplied as auxiliary memory at cheaper cost.

Secondary memories are non volatile in nature. These are used when large amount of data and programs
have to be stored.
3. Arithmetic and logic unit: ALU consist of necessary logic circuits like adder, comparator etc., to perform
operations of addition, multiplication, comparison of two numbers etc.

4. Output Unit: Computer after computation returns the computed results, error messages, etc. via output
unit. The standard output device is a monitor, LCD/TFT monitor. Other output devices are printers, projectors
etc.

5. Control Unit: Control unit co-ordinates activities of all units by issuing control signals. Control signals
issued by control unit govern the data transfers and then appropriate operations take place. Control unit
interprets or decides the operation/action to be performed.

Hardware and Software:

Computer Hardware:

Hardware refers to the physical components of a computer. Computer Hardware is any part of the computer
that we can touch these parts. These are the primary electronic devices used to build up the computer.
Examples of hardware in a computer are the Processor, Memory Devices, Monitor, Printer, Keyboard,
Mouse, and the Central Processing Unit.

Categories of computer hardware:

1. Input devices: These components are mostly to be used for recognized the input data that are given
by users for solving their problems. Input instructions can be different types such as text, images,
audio, and video.

Ex: keyboard, mouse ,scanner, touch screen, microphone etc..

2. Processing devices: The main function of processing devices are have to responsible for getting
meaningful information from converted data with the help of various processing devices. Ex: CPU,
Motherboard etc..

3. Output devices: Received the processed information from processing components, and finally
produce them into various form such text, audio, and video. Ex: Monitor, projector, printer etc..
4. Storage devices: The core task of the memory is storage and retrieval, this depend on the
Read/Write operation of all types of memory.

There are two types of storage devices such as:

1. Primary Storage device: are designed for temporarily storage, but fastest to storage devices and
small size as well. Ex. RAM: is volatile storage memory (temporary memory) because during
power failure the information stored in RAM will be erased.

2. Secondary Storage Device: used for the permanently storage of data, because if further time
require any data then can be retrieved easily. The sizes of these components have large compare
to primary storage devices, and storage capacity much high also. Ex: Hard disk, CD, DVD etc..

Computer Software:

Software is a collection of instructions, procedures, documentation that performs different tasks on a


computer system. we can say also Computer Software is a programming code executed on a computer
processor. The code can be machine-level code or the code written for an operating system. Examples of
software are Ms Word, Excel, Power Point, Google Chrome, Photoshop, MySQL etc.

Types of Software:

System Software: Basically, it is a software to manage computer hardware behaviour so as to provide basic
functionalities that are required by the user. In simple words, we can say that system software is an
intermediator or a middle layer between the user and the hardware.
Some common system software examples are:
Operating System: It is the most prominent example of System Software. It is a collection of software that
handles resources and provides general services for the other applications that run over them. It acts as an
interface between user and computer system. Examples are Windows, Linux, Unix, Android, etc..
Language Processors: These are mediator programs on which software programs rely to translate high-level
language code to machine-level code.
Assembler –
The Assembler is used to translate the program written in Assembly language into machine code. The source
program is a input of assembler that contains assembly language instructions. The output generated by
assembler is the object code or machine code understandable by the computer. Example: GNU Assembler,
Microsoft Macro Assembler, Netwide Assembler

Interpreter –
The translation of single statement of source program into machine code is done by language processor and
executes it immediately before moving on to the next line is called an interpreter. If there is an error in the
statement, the interpreter terminates its translating process at that statement and displays an error message.
The interpreter moves on to the next line for execution only after removal of the error. Example: Perl,
Python and MatLab.

Compiler –
The language processor that reads the complete source program written in high level language as a whole in
one go and translates it into an equivalent program in machine language is called as a Compiler. The
compiler specifies the errors at the end of compilation with line numbers when there are any errors in the
source code. The errors must be removed before the compiler can successfully recompile the source code
again. Example: C, C++, C#, Java

Device drivers: Device driver or hardware driver is a group of files that enable one or
more hardware devices to communicate with the computer's operating system. Without drivers, the computer
would not be able to send and receive data correctly to hardware devices, such as a printer.

Utility software helps to manage, maintain and control computer resources. Operating systems typically
contain the necessary tools for this, but separate utility programs can provide improved functionality.
Examples of utility programs are antivirus software, backup software etc..

Application software is commonly defined as any program or number of programs designed for end-users.
General purpose application software is a type of application that can be used for a variety of tasks. It is
not limited to one particular function. ... Examples of General purpose application software include: Word
processors, Spreadsheet and Presentation software.

Specialist application software performs a single very specific type of task. Examples include programs to
work out payroll, calculate accounts, deal with stock control and handle appointments.
Customised software development is the process of designing, creating, deploying and
maintaining software for a specific set of users, functions or organizations. Example includes salary
component of an organization.
Execution
The program may ask user for input/s and generates output after processing the input/s.

Debugging and Testing


Debugging is the discovery and correction of programming errors. When error appears debugging is
necessary.
Testing ensures that program performs correctly the required task.
Algorithm and flowchart

The algorithm and flowchart are two types of tools to explain the process of a program. An algorithm is a
step-by-step analysis of the process, while a flowchart explains the steps of a program in a graphical way.

Definition of algorithm
To write a logical step-by-step method to solve the problem is called the 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 in the process. An algorithm includes calculations, reasoning, and data processing. Algorithms
can be presented by natural languages, pseudocode etc.
Algorithm has the following characteristics

Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs.


Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-
defined as well.
Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps should be clear in
all aspects and must lead to only one meaning.
Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops .
Feasible: The algorithm must be simple, generic and practical, such that it can be executed upon the
available resources. It must not contain some future technology, or anything.
Language Independent: The algorithm designed must be language-independent, i.e. it must be just plain
instructions that can be implemented in any language, and yet the output will be same, as expected.
Advantages of Algorithms:
 It is easy to understand.
 Algorithm is a step-wise representation of a solution to a given problem.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the
programmer to convert it into an actual program.

Disadvantages of Algorithms:
 Writing an algorithm takes a long time so it is time-consuming.
 Branching and Looping statements are difficult to show in Algorithms.

Algorithm to find area of square


Step 1. Start
Step 2. Print ‘Enter the value for side’
Step 3. Read side
Step 4. area=side*side
Step 5. Print ‘The area of square is=’, area
Step 6. Stop

Algorithm to find area of circle


Step 1. Start
Step 2. Print ‘Enter the value of radius’
Step 3. Read radius
Step 4. area=3.14*radius*radius
Step 5. Print ‘Area of circle is=’, area
Step 6. Stop

Algorithm to find Sum of two numbers


Step 1 : start
Step 2 : Read a,b
Step 3 : c=a+b
Step 4 : Print ‘Sum of’,a,’and’,b,’is=’, c
Step 5 : Stop

Algorithm to perform basic arithmetic operations


Step 1 : Start
Step 2 : Read a, b
Step 3 : calculate add=a+b, sub=a-b, multi=a*b, div=a/b.
Step 4 : Print add, sub, multi, div.
Step 5 : Stop

Algorithm to check whether a person can vote or not

Step 1. Start.
Step 2. Print ‘Enter age of person’
Step 3. Read age
Step 4. If(age>=18) goto step 5 else goto step 6 endif
Step 5. Print “you can vote” goto step6
Step 6. Print “you cannot vote”
Step 7. Stop

Algorithm to find largest of two numbers


Step 1: Start.
Step 2 Print ‘Enter any 2 numbers’
Step 3: Read a, b
Step 4: If a>b Print “a is the largest number” goto step 5
Esle Print “b is the largest number”. End if
Step 5: Stop

Algorithm to find the given number is positive or negative.


Step 1: Start.
Step 2 Print ‘Enter any number’
Step 3: Read number
Step 4: If number>0 Display “number is positive” goto step 5
Else Display “number is negative”. End if
Step 5: Stop
Definition of flowchart
A flowchart is the graphical or pictorial representation of an algorithm. In flowchart, we use different
symbols, shapes, and arrows to demonstrate a process or a program. With algorithms, we can easily
understand a program. Following are symbols used in building flowchart:

Advantages Of Using FLOWCHARTS:

• Communication: Flowcharts are better way of communicating the logic of a system to all concerned or
involved.

• Effective analysis: With the help of flowchart, problem can be analysed in more effective way therefore
reducing cost and wastage of time.

• Proper documentation: Program flowcharts serve as a good program documentation, which is needed for
various purposes, making things more efficient.
• Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program
development phase.

• Proper Debugging: The flowchart helps in debugging process.

• Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on that part

Disadvantages Of Using FLOWCHARTS:


• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy. This will become a pain for the user, resulting in a waste of time and money trying to
correct the problem
• Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Examples:
1.Sum of two numbers
Algorithm:
step 1 : start
step 2 : Input a,b
step 3 : c=a+b
step 4 : Display c
step 5 : end

Flowchart:
2. Convert Temperature from Fahrenheit (F) to Celsius (C)

Algorithm:
Step 1: Start

step 2: Read temperature in Fahrenheit

Step 3: Calculate temperature with formula C=5/9*(F-32)


Step 4: Print C
step 5: Stop

Flowchart:
3. largest of two numbers

Algorithm:
Step 1: Start
Step 2: Input a, b .
Step 3: If a>b then
Display “a is the largest number”.
Otherwise
Display “b is the largest number”.
Step 4: Stop.

Flowchart:
4. To check the given number is even or odd.
Algorithm:
Step 1: Start
Step 2: Input Number .
Step 3: If Number%2==0 then
Display “Even number”. goto Step4
Otherwise
Display “odd number”.
Step 4: End.

Flowchart
5. To check the given number is zero, positive or negative.

Algorithm

Step 1: Start
Step 2: Get n
Step 3: If n==0 then print “zero” goto step5
Step 4: if n>0 then print “positive” goto step5
Otherwise print “negative”
Step5: stop

Flowchart
6. To find largest of three numbers

Algorithm
step 1 : start
step 2 : Read A,B,C
step 3 : if(A>B)then goto next step
otherwise goto step5
step 4 : if(A>C) then goto step6 otherwise step8
step 5 : if(B>C) goto step7 otherwise step8
step6:print “A is largest” then goto step9
step7:print “B is largest” then goto step9
step8:print “C is largest”
Step9:stop

Flowchart
Overview of C Language: Why C? Scope of Computer Science, Applications, Features, Structure of C
program., process of compiling and running the program.

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop
the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer
in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C,
now known as the K&R standard.

The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C. C has now become a widely used professional language for various reasons −

Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms

Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around the early 1970s.
The language was formalized in 1988 by the American National Standard Institute (ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.

Why use C?
C was initially used for system development work, particularly the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast as
the code written in assembly language. Some examples of the use of C might be −
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities

Features of C language

Structured Programming

Portable
Expandable

Structure of C program
Process of compiling and running the program

Constants, Variables and Data types: Introduction ,Character set, C tokens, Keywords and Identifiers,
Constants, Variables, Data types, Declaration of variables, Example programs.
Tokens in C
A C program consists of various tokens and a token is either, a keyword, an identifier, a constant, a string
literal, or a symbol. For example, the following C statement consists of five tokens −

Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.

auto int Struct


double

break else long Switch

case enum register Typedef

char extern return Union

const float short Unsigned

continue for signed Void

default goto sizeof Volatile

do if static While

Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and
digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here
are some examples of acceptable identifiers −
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.

Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start with /*
and terminate with the characters */. You cannot have comments within comments and they do not occur
within a string or character literals.

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age for the compiler to be
able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and apples, although you are free
to include some if you wish to increase readability.
Data Type
Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
The types in C can be classified as follows –

Sl. No. Types & Description

1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b) floating-point
types.

2 Enumerated types
They are again arithmetic types and they are used to define variables that can only assign certain
discrete integer values throughout the program.

3 The type void


The type specifier void indicates that no value is available.

4 Derived types
They include (a) Pointer types, (b) Array types,

5 User Defined types


(a) Structure types (b) Union types and (c) Function types.

The array types and structure types are referred collectively as the aggregate types. The type of a function
specifies the type of the function's return value. We will see the basic types in the following section, where
as other types will be covered in the unit 3 and 4.

Integer Types
The following table provides the details of standard integer types with their storage sizes and value ranges –

Type Storage size Value range

Char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647


unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

Short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

Long 8 bytes or (4bytes for -9223372036854775808 to 9223372036854775807


32 bit OS)

unsigned long 8 bytes 0 to 18446744073709551615

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes.

Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and value ranges
and their precision −

Type Storage size Value range Precision

Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

Double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places


The void Type
The void type specifies that no value is available. It is used in three kinds of situations –

Sr.No. Types & Description

1
Function returns as void
There are various functions in C which do not return any value or you can say they return void. A
function with no return value has the return type as void. For example, void exit (int status);

2
Function arguments as void
There are various functions in C which do not accept any parameter. A function with no
parameter can accept a void. For example, int rand(void);

3
Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example, a
memory allocation function void *malloc( size_t size ); returns a pointer to void which can be
casted to any data type.

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in
C has a specific type, which determines the size and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based
on the basic types explained above, there will be the following basic variable types –

Sr.No. Type & Description

1
char
Typically a single octet(one byte). It is an integer type.

2
int
The most natural size of integer for the machine.
3
float
A single-precision floating point value.

4
double
A double-precision floating point value.

5
Void
Represents the absence of type.

C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study
only basic variable types.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid
declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage class are implicitly initialized with NULL
(all bytes have the value 0); the initial value of all other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and
name so that the compiler can proceed for further compilation without requiring the complete detail about
the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual
variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the
files which will be available at the time of linking of the program. You will use the keyword extern to
declare a variable at any place. Though you can declare a variable multiple times in your C program, it can
be defined only once in a file, a function, or a block of code.

Operators and Expressions: Arithmetic operators, Relational operators, Logical operators, Assignment
operators, Increment and Decrement operators, Conditional operator, Bitwise operators, Special operators,
Arithmetic expressions, Evaluation of expressions, Precedence of arithmetic operators, Type conversion in
expressions, Operator precedence and Associativity, Example programs.

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then –

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B /A= 2


% Modulus Operator and remainder of after an integer division. B %A= 0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then –

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B) is
condition becomes true. not true.

!= Checks if the values of two operands are equal or not. If the values are not (A != B) is
equal, then the condition becomes true. true.

> Checks if the value of left operand is greater than the value of right operand. (A > B) is
If yes, then the condition becomes true. not true.

< Checks if the value of left operand is less than the value of right operand. If (A < B) is
yes, then the condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is
right operand. If yes, then the condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B) is
operand. If yes, then the condition becomes true. true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then –

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A && B) is
condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the (A || B) is
condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B) is
operand. If a condition is true, then Logical NOT operator will make it false. true.

Assignment Operators
The following table lists the assignment operators supported by the C language –

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to left C = A + B will
side operand assign the
value of A + B
to C

+= Add AND assignment operator. It adds the right operand to the left operand C += A is
and assign the result to the left operand. equivalent to
C= C+A

-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalent to
C=C–A

*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent to
C=C*A

/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent to
C=C/A

%= Modulus AND assignment operator. It takes modulus using two operands C %= A is


and assigns the result to the left operand. equivalent to
C=C%A

<<= Left shift AND assignment operator. C <<= 2 is


same as C = C
<< 2

>>= Right shift AND assignment operator. C >>= 2 is


same as C = C
>> 2
&= Bitwise AND assignment operator. C &= 2 is
same as C = C
&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is


same as C = C
^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same


as C = C | 2

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows

P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

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 ) =
Binary One's Complement Operator is unary and has the effect of 'flipping'
~(60), i.e,. -
bits.
0111101

<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 =
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

Misc Operators: sizeof & ternary


Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& Returns the address of a variable. &a; returns the actual address of the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X : otherwise


Conditional Expression.
value Y
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right


Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right

You might also like