Programming Through C
Vijaya Kumar G
Assistant Professor
Department of ECE
VNRVJIET
January 23, 2022 Department of ECE, VNRVJIET, Hyderabad 1
Syllabus
UNIT-I:
Introduction to Programming: Introduction to
components of a computer system (disks, memory,
processor, where a program is stored and executed,
operating system, compilers etc.). Idea of Algorithm:
steps to solve logical and numerical problems.
Representation of Algorithm: Flow chart / Pseudo
code with examples. From algorithms to programs;
source code, variables (with data types) variables
and memory locations, syntax and logical errors in
compilation, object and executable code .Arithmetic
expressions and precedence.
January 23, 2022 Department of ECE, VNRVJIET, Hyderabad 2
Agenda
▪ Introduction to components of a computer
A computer is an electronic device that takes data and instructions as an
input from the user , process data and provides useful information known
as output.
Data Process Information
Instructions
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 3
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 4
➢ Application areas:
▪ Data Processing (commercial use)
▪ Numerical computing (scientific use)
▪ Text processing (office and educational use)
▪ Message communication (e-mail)
▪ Image processing(animation and industrial use)
▪ Voice recognition (multimedia)
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 5
Components of a Computer?
➢ There are three components
1. Central Processing Unit(CPU)
2. Input devices
3. Output devices
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 6
Control Unit
Input ALU Output
Memory Unit
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 7
Central Processing Unit(CPU)
Control Unit
CPU
( Central Processing Unit )
CU (Control Unit)
ALU
ALU (Arithmetic Logic Unit)
MU (Memory Unit)
Memory Unit
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 8
Control Unit
▪ CU decodes and executes instructions from memory
▪ It controls and coordinates the functioning of all parts of the computer.
▪ Maintain and regulate the flow of information across the processor.
▪ It does not take part in processing and storing data.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 9
ALU: (Arithmetic Logic Unit)
Performs arithmetic and logical functions
1. Arithmetic functions include
▪ addition,
▪ subtraction,
▪ multiplication
▪ division etc
2. Logical functions include
▪ Selecting
▪ Comparing
▪ Merging the data
➢ A CPU may contain more than one ALU
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 10
Memory Unit
This unit stores
▪ Instructions
▪ Data
▪ Intermediate results
➢ It is called Random access memory (RAM) / Main memory
➢ It temporarily stores data, programs, and intermediate and final results of
processing
➢ it acts as a temporary storage area
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 11
Input and Output devices
Input device:
▪ H/w device which is used to give Input to the computer
Output device:
▪ H/w device which is used to give Output from the computer
Input devices: Output devices:
Keyboard Monitor
Mouse Printer
CD/DVD writer Speaker
Microphone Projector
Camera
Joystick
Scanner
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 12
Hardware Software
Hardware is a physical parts of computer that cause Software is a set of instructions that tells a
processing of data. computer exactly what to do.
It is manufactured. It is developed and engineered.
Hardware can not perform any task without
software can be executed with/without hardware.
software.
As Hardware are physical electronic devices, we can We can see and also use the software but can’t
see and touch hardware. actually touch them.
It has four main categories: input device, output It is mainly divided into System software,
devices, storage, and internal components. Programming software and Application software.
Hardware is not affected by computer viruses. Software is affected by computer viruses.
It can not be transferred from one place to another
But, it can be transferred.
electrically through network.
If software is damaged, its backup copy can be
If hardware is damaged, it is replaced with new one.
reinstalled.
Ex: Keyboard, Mouse, Monitor, Printer, CPU, Hard Ex: Ms Word, Excel, Power Point, Photoshop,
disk, RAM, ROM etc. Department of ECE, VNRVJIET, Hyderabad
MySQL etc. January 23, 2022 13
Agenda
▪ Introduction to software
▪ Operating System
▪ Computer memory
▪ Memory Management
▪ Random Access Memory
▪ Read Only Memory
▪ Secondary Memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 14
Software
There are two categories of software
1. System Software
Example: Operating system
2. Application Software
Example: MS word, calculator etc
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 15
Operating System(OS)
▪ Software required to run the hardware parts of the computer / To give
instructions to the computer
System software
Acts as interface between hardware and user applications.
Operating System(OS)
System software that is responsible for functioning of all hardware parts and their
functions
➢ Booting is the process of loading system software
▪ OS is the first software to be loaded into computer memory
▪ OS manages functions like
▪ Storing/ retrieving data in memory
▪ Retrieving files from storage devices
▪ Scheduling tasks based on priority
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 16
User Interaction
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 17
Computer Memory
▪ Every piece of information stored in a computer memory is encoded as 0’s
and 1’s, called as bits(binary digits).
▪ Each bit is represented by an electronic device i.e., either “off”(zero) or
“on”(one).
▪ The size of memory is usually expressed as multiples of
2^10=1024 bytes=1KB.
▪ Group of 8 bits is a byte.
▪ 1MB=10^6=1024 KB=2^10 KB=2^10*2^10 B
▪ 1GB=10^9=1024 MB=2^10*2^10*2^10 B.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 18
Name Equal To Size(In Bytes)
Bit 1 Bit 1/8
Nibble 4 Bits 1/2 (rare)
Byte 8 Bits 1
Kilobyte 1024 Bytes 1024
Megabyte 1, 024 Kilobytes 1, 048, 576
Gigabyte 1, 024 Megabytes 1, 073, 741, 824
Terrabyte 1, 024 Gigabytes 1, 099, 511, 627, 776
Petabyte 1, 024 Terabytes 1, 125, 899, 906, 842, 624
Exabyte 1, 024 Petabytes 1, 152, 921, 504, 606, 846, 976
Zettabyte 1, 024 Exabytes 1, 180, 591, 620, 717, 411, 303, 424
1, 208, 925, 819, 614, 629, 174, 706,
Yottabyte 1, 024 Zettabytes
176
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 19
Memory Management
Memory can be classified in to two types:
1. Primary memory
2. Secondary memory
➢ Primary memory is fast but expensive
➢ Secondary memory is slow but inexpensive
Primary memory / Main memory
1. Primary storage is directly accessible by the CPU.
2. It further classified in to RAM and ROM
▪ RAM ---Random Access Memory
▪ ROM ---Read Only Memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 20
Computer Memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 21
Random Access Memory
▪ RAM memory is very fast
▪ data stored in RAM can be accessed in any random order
▪ It is volatile memory i.e. all data stored in RAM is lost when power lost
Types of RAM
1. DRAM (Dynamic RAM)
▪ computers use faster dual data rate (DDR) DRAM
▪ Uses capacitors and very few transistors---offchip memory
2. SRAM(Static RAM)
▪ Is faster than DRAM, but more expensive
▪ Uses transistors and latches---onchip memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 22
Read Only Memory
▪ ROM is a type of non-volatile memory
▪ Data stored in ROM persists even in power lost
CPU can read ROM without the need for drivers , load parts of the operating
system into primary memory so that it can start up and become ready to use
Types of ROM
1. PROM--- Programmable Read-Only Memory
2. EPROM--- Erasable Programmable Read-Only Memory
3. EEPROM---Electrically Erasable Programmable Read-Only Memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 23
RAM- ROM
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 24
Secondary Memory
Secondary memory comprises many different storage media
▪ Secondary or external storage is not directly accessible by the CPU
▪ The data needs to be brought into the primary memory before the CPU
can use it
▪ Secondary storage contains a large amount of data permanently
Examples:
Hard Disk, Floppy Disk, Memory Card,pen drive, CD etc
➢ Hard disks are the most famously used secondary storage devices
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 25
Secondary Memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 26
Compiler
▪ It is a kind of system software that translates programs written in high level
language to machine level language.
▪ The original high level program is source program
▪ The resulting machine level program is object program
▪ Ex: C-compiler, Java compiler, Pascal compiler…
Interpreter:
▪ It is similar to compiler
▪ It converts high level language program one line at a time to machine
language and then executes that converted line.
▪ Then the next line is converted and executed and so on.
▪ Interpreter is a smaller and simpler software than compiler but take more
time for execution.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 27
Agenda
▪ Address Space Or Memory Layout Of C Program
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 28
Memory Layout Of C Program
When we run any C-program
▪ Executable image loaded into RAM in an organized manner
▪ Which is called as Address Space/ Memory layout
executable image
Run C Progrm
loaded into RAM
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 29
Contents of Memory Layout
Memory layout contain 4 segments
1. Text/Code segment
2. Data segment
3. Heap segment
4. Stack segment
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 30
Memory Layout structure
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 31
Text/Code Segment
▪ Contains executable instructions of C program
▪ Includes all functions of the program i.e. both user-defined
and system
▪ Text Segment is read-only, to prevent modifications
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 32
Data segment
There are two subsections of this segment
1. Initialized data
▪ It contains both static and global data that initialized with non-zero
values
2. Uninitialized data
▪ contains all global and static variables that initialized to zero or do
not have explicit initialization in source code
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 33
Heap & Stack segment
Heap segment
▪ Contains dynamically allocated memory using malloc(), calloc(), realloc()
etc
▪ We can free dynamically allocated memory space (by
using free() or delete()
▪ malloc/free eventually, cause heap fragmentation
Stack segment
▪ In this segment local variables stored
▪ When we call any function, the stack frame created and when a function
returns, the stack frame destroyed/rewind including all local variables of
that particular function
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 34
Agenda
▪ Idea of Algorithm
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 35
Algorithm
An algorithm is a well-defined sequence of steps to solve a problem.
Properties of Algorithm:
▪ Correctness
▪ Finiteness
▪ Independent
▪ Input/output
▪ Efficiency
▪ Unambiguous
▪ Feasibility
▪ Flexibility
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 36
Algorithm Properties
Correctness: It should produce the output according to the requirements
Finiteness: Algorithm must complete after a finite number of steps
Independent: Algorithm should derive the output independent of language
used
Input/output: inputs and results must be defined
Efficient : Efficiency is measured in terms of time and space required to
implement the algorithm
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 37
Algorithm Properties
Un Ambiguity: Each step must be defined, having only one interpretation
Feasibility: It must be possible to execute each instruction
Flexibility: It should be easy to make modifications in the algorithm
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 38
Complexity of Algorithm
Complexity of algorithm is a measure of amount of time and/or space
required by an algorithm for an input of a given size(n).
Time Complexity: Running time of a program as a function w.r.t size of the input
▪ If algorithm takes more time, then its time complexity is High
Space Complexity: Analysis of how much space an algorithm needs to
complete its task
▪ If algorithm require more space, then its Space complexity is High
Algorithm Complexity is analyzed in Three ways
▪ Best Case Complexity
▪ Average Case Complexity
▪ Worst Case Complexity
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 39
Program Development Steps
1. Analyze the problem to identify inputs, outputs and processing requirements.
2. Identify various processing steps needed to solve the problem and represent
them in a particular way(algorithm, pseudo code, flow chart, etc.)
3. Refine step 2 in a way that all the processing steps are details enough such that
every processing step is equivalent to one instruction of programming
language.
4. Add the syntax of the programming language, it becomes the program.
5. Type the program and compile it after removing all syntax related errors.
6. Run the program and check it with different types of input to verify its
correctness.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 40
Problem
Problem
Algorithm 1 Algorithm 2 Algorithm n
Program 1 Program 2 Program n
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 41
Algorithm-Problem1
Write a program to find addition of two numbers
1. Read first and second number
2. Add both numbers to get the result
3. Print the result
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 42
Algorithm-Problem 2
Write a program to find the bigger number out of two distinct numbers
1. Read first and second number
2. Compare first number with second number
3. If first number is bigger than second then print the first number
4. Otherwise print the second number
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 43
Algorithm-Problem 3
Write a program to find the largest number out of three distinct numbers
1. Read first, second and third number
2. Print first number If it is bigger than second and third.
3. Otherwise print the second number If it is bigger than first and third.
4. Otherwise print third number.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 44
Algorithm-Problem 3.a
Write a program to find the largest number out of three distinct numbers
1. Read first, second and third number
2. If first number is bigger than second and first number is bigger than third.
3. Print first number as largest.
4. Otherwise (means that first is not largest)
5. If second number is bigger than first and second number is bigger than
third
6. print the second number as largest
7. Otherwise (means that second is not largest and first is also not largest)
8. print third number as maximum.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 45
Algorithm-Problem 3.b
Write a program to find the largest number out of three distinct numbers
1. Read first, second and third number
2. If first number is bigger than second number
3. If first number is bigger than third.
4. Print first number as largest.
5. Otherwise (means that third is bigger than first and first was already
bigger than second )
6. print third number as largest.
7. Otherwise (means that second is bigger than first and thus second is
compared with third)
8. If second number is bigger than third number
9. print the second number as largest
10. Otherwise (means that third is bigger than second and second was
already bigger than first)
11. print third number as maximum.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 46
Algorithm-Problem 4
Write a program to find the average of n numbers
1. Read the value of ‘n’ 1. Read the value of n
2. Read ‘n’ numbers 2. Assign 0 to sum
3. Add these ‘n’ numbers 3. Repeat n times
4. Divide the addition 4. Read number
result by ‘n’ to get the 5. Add number to sum
average 6. End repeat
5. Print the average 7. Divide the sum by n to
get the average
8. Print average
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 47
Agenda
▪ Representation of Algorithm
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 48
Algorithm Representation
An algorithm can be represented in two ways
1. Pseudo code: is an informal description of an Algorithm which does not
follow any programming syntax
1. Flow Chart:
A flowchart can be defined as a pictorial representation of an algorithm
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 49
Pseudo Code
▪ In pseudo code representation, each of the steps will be written via operators
and statements equivalent to some programming language instructions.
▪ Exact syntax of the programming language not followed.
▪ All pseudo codes starts with keyword ‘START’ and complete with ‘STOP’ or
‘END’.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 50
Pseudo code examples
Problem-1 Problem-2
1.START 1.START
2.Read number1, number2 2.Read number1, number2
3.Sumnumber1+number2 3.If number1 > number2 then
4.Print sum 4. Print number1
5.STOP 5. Else
6. Print number2
7. STOP
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 51
Pseudo code examples
Problem-3.a Problem-3.b
1.START 1.START
2.Read number1, number2,number3 2.Read number1, number2,number3
3.If number1 > number2 AND 3.If number1 > number2 then
number1 > number 3 then 4. If number1 > number 3 then
4. Print number1 5. Print number1
5. Else 6. Else
6. If number2 > number1 AND 7. Print number3
number2 > number 3 then 8. Else
7. Print number2 9. If number2 > number3 then
8. Else 10. Print number2
9. Print number3 11. Else
10. STOP 12. Print number3
13. STOP
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 52
Pseudo code examples
Problem-4
1. START
2. Read n
3. Sum 0
4. For i 1 to n do
5. read numberi
6. sum sum + numberi
7. End for
8. average sum/n
9. Print average
10. STOP
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 53
Flow Chart Symbols
Symbol Symbol Use
Name
Start/Stop Indicates beginning and end of the algorithm
Indicates processes like mathematical operations.
Process
Used for denoting program inputs and outputs-Read and
Input/ Print.
Output
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 54
Flow Chart Symbols
Symbol Symbol name Use
Stands for decision statements in a program, where
Decision answer is usually Yes or No- Condition check.
Shows relationships between different shapes-
Arrow Direction of flow.
Connectors Connects two or more parts of a flowchart, which are
(for longer flow on the same page.
charts)
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 55
Example : Sequence
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 56
Example : Decision
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 57
Login Example
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 58
Problem-1
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 59
Problem-2
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 60
Problem-3.a
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 61
Problem-3.b.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 62
Problem-4
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 63
Agenda
▪ Algorithms to Programs
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 64
APPLICATIONS DESIGNED USING COMPUTER LANGUAGE
•STANDALONE APPLICATION : application always dependent to OS.
•WEB APPLICATION :
A web application is a computer program that utilizes web browsers
and web technology to perform tasks over the Internet.
STANDALONE APPLICATION
▪ Must be downloaded
▪ Single user access at a time
▪ Compatible for Single OS
▪ VLC,MS-Office, Adobe Photoshop
WEB APPLICATION
▪ No need of Installation
▪ Independent to OS
▪ Face book , Gmail, IRCTC
Steps to learn C
C Tokens
In C programs, each word and punctuation is referred to as a token. C Tokens are the smallest
building block or smallest unit of a C program.
The compiler breaks a program into the smallest possible units and proceeds to the various
stages of the compilation, which is called token.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 86
▪ A list of 32 reserved keywords in c language. you can not use them as a
variable name.
▪ EX:
#include<stdio.h>
int main()
{
float a, b;
printf("Showing how keywords are used.");
return 0;
}
▪ In the above program, float and return are keywords. The float is used to
declare variables, and return is used to return an integer type value in this
program.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 88
Data Types
▪ It is just a representation of data. That means how much memory is
required to be allocated and what type of data is allowed to store.
These two are represented by the data type in any programming
language.
▪ C Data Types are used to:
• Identify the type of a variable when it declared.
• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.
• Syntax: DataType Identifier;
• Example: int a;
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 90
Data types in C Language are classified into three types as follows.
1. Primitive Data Types: Integer, character, float, void. All these are
called primitive data types.
2. Derived Data Types: Array, String, Pointer, etc. come under derived
data types.
3. User-Defined Data Types: Structure, union, typedef, enum, etc. are
comes under user-defined data types.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 91
Modifiers
▪ The amount of memory space to be allocated for a variable is derived
by modifiers. Modifiers are prefixed with basic data types to modify
(either increase or decrease) the amount of storage space allocated to
a variable.
▪ There are 5 modifiers available in the C Programming language. They
are,
1. Short
2. Long
3. Signed
4. Unsigned
5. long
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 92
▪ Classification of Primitive Data Types in C Language:
Primitive Data Types are classified into four types are as follows.
1. Integer
2. Character
3. Float
4. Void
Integer Data Type in C Language:
▪ Integer is divided into three types are as follows.
1. Short---either it is signed or unsigned, it occupies two bytes of memory
2. Int---either signed or unsigned, it will occupy two or four bytes of
memory depending upon the compiler
3. Long---either signed or unsigned it occupies 4 bytes of memory
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 93
▪ Again, the short data type is divided into two types i.e. signed short and
unsigned short. Same for int and long i.e. signed int, unsigned int, signed
long, and unsigned long. So, one integer data type is again subdivided
into 6 types.
▪ The size of the data type ‘int’ is 2 bytes or 16 bits. The minimum value for
the signed ‘int’ data type is -32768. The maximum value for the signed
‘int’ data type is 32767
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 94
Character Data Type in C Language:
▪ Char is an integer data type , it is used to store the encoding of
characters. Ex: ’a’ in ASCII—97--01100001
▪ The Character Data Type in C language is divided into two types. One
is a signed character and the second one is an unsigned character.
Both are of size 1 byte.
▪ The size of the data type char is 1 byte or 8 bits. The minimum and
maximum values for the ‘char’ data type are -128 to 127.
▪ char Name;
Name=’x’;
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 95
Float Data Type in C Language
▪ The Float Data Type in C language is divided into three types one is
float type, the second one is double and the last one is long double.
Float is of size 4 bytes; double is of size 8 bytes and long double is of
size 10 byte
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 96
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 97
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 98
Type Size (bytes) Format Specifier
int at least 2, usually 4 %d
char 1 %c
float 4 %f
double 8 %lf
short int 2 usually %hd
unsigned int at least 2, usually 4 %u
long int at least 4, usually 8 %ld
long long int at least 8 %lld
unsigned long int at least 4 %lu
unsigned long long int at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %Lf
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 99
Range
#include <stdio.h>
int main()
{
printf("%d",sizeof(long int));
return 0;
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 100
▪ Some programs related to float…
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 101
VOID
▪ Void is an empty data type that has no value. We use void data type in
functions when we don’t want to return any value to the calling
function.
▪ void sum (int a, int b); – This function won’t return any value to the
calling function.
int sum (int a, int b); – This function will return value to the calling
function.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 102
Derived Data Types in C Language
▪ Derived data types in C Programming Language are those that are
derived from the fundamental data types using some declaration
operators. The basic derived types that are available in C are:
1. Array
2. Functions
3. Pointers
4. Structures
5. Classes
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 103
Array Derived Data Type in C
▪ The arrays can be defined as a set of finite and homogeneous data
elements.
▪ Each element of an array is referenced using an index.
▪
Example: If the name of an array is A which has 4 elements then the
array will be represented as A[0], A[1], A[2], A[3].
▪ Here, these subscripts which are containing the digit are known as an
index.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 104
▪ Function Derived Data Type in C
▪ The function can be defined as a part of the program which is declared
by the programmer in any part of the program and a function can be of
any name depending upon the choice of the programmer. The function
declared can be invoked from other parts of the program.
▪ Pointer Derived Data Type in C
▪ A pointer is a variable that holds the address of the memory space. If
one variable can hold the address of another variable then it is said
that the first variable is pointing to the second.
▪ Structure Derived Data Type in C
▪ The structure can be defined as a collection or a group of variables
that are referenced under one name. It is used to keep related
information together. We use a ‘struct’ keyword to construct a structure.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 105
Variables
➢ A variable is a name of the memory location
➢ It is used to store data
➢ Its value can be changed or reused many times
Syntax
datatype variable_name;
Example
int a,b; int a=10,b=20;
float c; float f=6.9;
char d; char c='A'
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 106
Rules
Rules for defining variables
▪ A variable name can have alphabets, digits, and underscore.
▪ It can't start with a digit.
▪ No whitespace is allowed.
▪ No keyword can be used as variable name
Invalid variable names
int 2; int a=2;
int a b; int a,b;
int long; int pi1
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 107
Types of Variables
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 108
Local, Global Variable
Local Variable
A variable that is declared and used inside the function or block is called local
variable. It’s scope is limited to function or block. It cannot be used outside the
block. Local variables need to be initialized before use.
Global Variable
A variable that is declared outside the function or block. It is declared at the
starting of program. It is available to all the functions.
▪ Any function can change the value of the global variable
▪ It is available to all the functions
Example
int value=30;//global variable
void function1()
{
int x=10;//local variable
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 109
Ex. Program for global variable
▪ #include <stdio.h>
▪ int x = 20;//global variable
▪ void function1()
▪ {
▪ printf("%d\n" , x);
▪ }
▪ void function2()
▪ {
▪ printf("%d\n" , x);
▪ }
▪ int main() {
▪ function1();
▪ function2();
▪ return 0;
▪ }
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 110
Static Variable
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
void function1()
{
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If we call this function many times static variable will print the incremented
value but local variable will print the same value at each iteration
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 111
Automatic Variable
Automatic Variable
All variables declared inside the block are automatic variables by default.
▪ We can use auto keyword to declare an automatic variable
▪ Automatically destroys its value after execution
▪ If we won’t initialize auto variable, by default it is initialized with
garbage(random) value.
Example
void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 112
External Variable
External Variable
We can share a variable in multiple C source files by using an external
variable
▪ To declare an external variable, you need to use ”extern” keyword
myfile1.h
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 113
▪ Definition means allocation of memory.
▪ Multiple declarations are allowed and multiple definitions are not allowed.
▪ Valid example:
▪ extern int a; extern int a; extern int a;
▪ Invalid example:
▪ Int a; Int a; Int a; -----redefinition error
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 114
Example and Syntax
There are two ways to define constant in C programming
1. const data_type variable_name;
Ex:- const float PI=3.14;
▪ If we change the value of PI, it will give compile time error.
2. #define preprocessor
Syntax: #define token value
Ex:- #define PI 3.14
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 116
Constant definition in C
▪ const keyword defines a constant in C.
▪ Putting const keyword either before or after the datatype is possible.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 117
CONSTANTS
▪ Constants refer to the fixed values that do not change during the execution of
a program.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 118
Integer Constants
▪ An integer constant is a sequence of digits without any fractional part.
There are three types of integer constants in C language.
They are:
1. Decimal integer constants: It consists of set of digits 0 to 9, preceded by an
optional sign + or -.
▪ Eg., +125, 0, -525, 68 etc.
2. Octal integer constants(base-8): It consists of a set of digits 0 to 7,
preceded by 0.
▪ Eg., 031 , 0642, 0426 etc.
3. Hexadecimal constants(base-16): It consists of a sequence of digits 0 to 9,
A to F preceded by 0X. The letters A to F represents the numbers 10 to 15.
▪ Eg., 0X5, 0XF, OXABC etc.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 119
Real Constants
▪ Integer constants are not suitable to represent continuously varying
quantities such as distances, heights, temperatures etc.
▪ These quantities can be represented by numbers containing fractional part.
Such constants are known as real(or floating point) constants.
Eg., .7, -0.63, 7.5, 8.40, -0.0089 etc.
▪ A real number may also be expressed in exponential notation.
Syntax:-
mantissa e exponent
Eg., 0.56e3, 10e-3, 3.5E3, -2.5E-2 etc.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 120
Character Constants & String Constants
Single Character Constants:
▪ A single character constant contains a single character enclosed within a pair of
single quotation marks.
Example: ‘5’, ‘x’, ‘;’, ‘ ‘ etc.
▪ Every character value has an equivalent integer value known as ASCII value. ASCII
stands for American Standard Code for Information Interchange.
String Constants:
▪ A string constant is a sequence of characters enclosed within a pair of double
quotation marks.
Example: “abcd”, “2006”, “A+B”, “5+8” etc.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 121
Symbolic Constants
▪ A symbolic Constant is a name that substitutes for a sequence of characters.
▪ The characters may represent a numeric constant, a character constant or a string
constant.
# define NAME text
▪ Where name represents a symbolic name, typically written in uppercase letters,
and text represents the sequence of characters associated with the symbolic
name. Note that text does not end with a semicolon.
# define TAXRATE 0.25
# define PI 3.1415
# define TRUE 1
# define FALSE 0
# define FRIEND “rama”
▪ Notice that the symbolic names are written in uppercase, to distinguish them
from ordinary C identifiers.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 122
▪ Ex: char c[]= “c string”;
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 124
• Brackets[] − Opening and closing of brackets are used for array element reference, which
indicate single and multidimensional subscripts.
• Parentheses() − These special symbols are used for function calls and function
parameters.
• Braces{} − Opening and closing of curly braces indicates the start and end of a block of
code which contains more than one executable statement.
• Comma (, ) − It is used to separate more than one statements like separating parameters
in function calls.
• Colon(:) − It is an operator which essentially invokes something called as an initialization
list.
• Semicolon(;) − It is called as a statement terminator that indicates the end of one logical
entity. That is the reason each individual statement must be ended with a semicolon.
• Asterisk (*) − It is used to create a pointer variable.
• Assignment operator(=) − It is used for assigning values.
• Pre-processor (#) − The pre-processor called as a macro processor is used by the
compiler to transform your program before the actual compilation starts.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 126
Type Conversions in Expressions
When an operator has operands of different types, they are converted to a common
type according to a some rules.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 127
Type Conversions in Expressions
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 128
Type Conversions
1. Implicit Type Conversion
int a = 15; // integer x
char b = ‘A'; // character c // b implicitly converted to into ASCII
// value of ‘A' is 65
a = a + b;
2. Explicit Type Conversion
Syntax:- (type) expression
float a = 2.34;
// Explicit conversion from float to int
int b = (int)a + 2;
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 129
Type Conversions in Expressions
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 130
Agenda
➢ Errors in C language is defined as an illegal operation performed by
the user which will result in the abnormal or abrupt working of the
program logic. Programming errors are unidentified until the program
is compiled or executed. Some of the errors in C are hidden or prevent
the program from compiled or executed. So while we are executing
our application successfully, we must remove the errors from the
program.
➢ Syntax Errors
➢ Logical Errors
➢ Semantic Errors
➢ Run-time Errors
➢ Linker Errors
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 131
1. Syntax Errors
Syntax
It is the Structure of statements in a computer language.
Syntax Error
It is an error in source code of a program
▪ Errors occur when the violation of rules of writing C syntax is said to be
“Syntax errors”. This compiler error indicates that this must be fixed before
the code will be compiled. These errors are identified by the compiler so
these errors are called “compile-time errors”.
1. Common Syntax errors
2. Spelling mistakes
3. Missing quotes””, ‘’
4. Missing colon:
5. Missing semicolon;
6. Missing brackets (),[]
7. Using Upper case characters.. Etc.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 132
2. Logical Errors
Logic:
Mistake in programs source code that results in incorrect or unexpected
output
If our expectation is one thing and result output is other thing then that
kind of error we said it as “Logical errors”.
Example:// we don’t get error on compilation of following code
int main() {
int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{ printf("loop ");
continue;
}
getchar();
return 0; }
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 133
3. Semantic Errors
Semantic errors :
This error occurs when the statements written in the program are not
meaningful/understandable to the compiler.
Example:
void main()
{
int a, b, c;
a + b = c; //semantic error
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 134
4. Run-time Errors
Run-time Errors :
Errors which are occurred after a successful compilation of program is said to
be “run-time errors”. Number divisible by zero, array index out of bounds,
string index out of bounds, etc. are most frequent run-time errors.
Example: Division by zero
//compiler doesn’t point to error
#include <stdio.h>
void main()
{
int n = 5, div;
// this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 135
5. Linker Errors
▪ These errors are generated after compilation we link the different object files
with the main’s object using the Ctrl+F9 short cut key.
▪ These errors occurred when the executable program cannot be generated. This
may be due occurred because of wrong function declaration, importing incorrect
header files, etc. Most frequent linker error is writing Main() instead of a main()
method.
▪ Example:
▪ void Main() // Here Main() method used instead of main() method
{
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 136
Agenda
➢ Operators in C
➢ Arithmetic expressions
➢ Associativity
➢ Precedence
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 137
Operators in C
Operator:
▪ An operator is simply a symbol that is used to perform operations
Types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Shift Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary or Conditional Operators
7. Assignment Operator
8. Misc Operator
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 138
Arithmetic Operators
A=10, B=20
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the A − B = -10
first.
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of B%A=0
after an integer division.
++ Increment operator increases the A++ = 11
integer value by one.
-- Decrement operator decreases the A-- = 9
integer value by one.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 139
Relational Operators
Operator Description Example
== Checks if two operands are equal or A=50, B=100
not. (A == B) is not true
!= Checks if the values are not equal, then A=50, B=100
the condition becomes true (A != B) is true.
> Checks if greater than (A > B) is not true.
< Checks if less than (A < B) is true.
>= Checks if greater than or equal to (A >= B) is not true.
<= Checks if less than or equal to (A <= B) is true.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 140
Logical Operators
Operator Description Example
&& Logical AND operator, A = 0, B = 1
If both are non-zero, then the condition
is true (A && B) is false.
|| Logical OR Operator, A = 0, B = 1
If any one is non-zero, then condition is
true. (A || B) is true.
! Called Logical NOT Operator. It is used A = 0, B = 1
to reverse the logical state of its
operand. If a condition is true, then !(A && B) is true.
Logical NOT operator will make it false.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 141
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation
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
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 142
Bitwise Operators
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
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 143
Bitwise Operators
A =60= 0011 1100 B = 13=0000 1101
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) = 12, i.e., 0000 1100
exists in both operands.
| Binary OR Operator (A | B) = 61, i.e., 0011 1101
^ Binary XOR Operator ,only one is true and other is (A ^ B) = 49, i.e., 0011 0001
false
~ Binary One's Complement Operator is unary and (~A ) = ~(60), i.e,. 1100 0011
has the effect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands value
is moved left by the number of bits specified by the A << 2 = 240 i.e., 1111 0000
right operand.
>> Binary Right Shift Operator.
A >> 2 = 15 i.e., 0000 1111
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 144
Logical vs Bitwise
A Bitwise And operator is represented as ‘&’ and a logical AND operator is
represented as ‘&&’. The following are some basic differences between the two
operators.
▪ The logical AND operator ‘&&’ expects its operands to be boolean
expressions (either 1 or 0) and returns a boolean value.
The bitwise AND operator ‘&’ work on Integral (short, int, unsigned, char,
bool, unsigned char, long) values and return Integral value.
▪ If an integer value is used as an operand for ‘&&’ which is supposed to work
on boolean values, the following rule is used in C.
…..Zero is considered as false and non-zero is considered as true.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 145
Assignment Operators
Operator Description Example
= Assigns values from right to left operand C=A+B
will assign the value of A + B to C
+= Add AND assignment operator, It adds the right
C += A is equivalent to C = C + A
to left and assign
-= Subtract AND assignment
C -= A is equivalent to C = C - A
*= Multiply AND assignment operator
C *= A is equivalent to C = C * A
/= Divide AND assignment operator C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes
modulus using two operands and assigns the C %= A is equivalent to C = C % A
result to the left operand.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 146
Conditional Operators
▪ Syntax:
The conditional operator is of the form
variable = Expression1 ? Expression2 : Expression3
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 147
▪ Ex:
▪ // C program to find largest among two
▪ // numbers using ternary operator
#include <stdio.h>
int main()
{
int m = 5, n = 4;
(m > n) ? printf("m is greater than n that is %d > %d",
m, n)
: printf("n is greater than m that is %d > %d",
n, m);
return 0;
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 148
Miscellaneous Operators
Operator Description Example
sizeof() sizeof(a), where a is integer, will
Returns the size of a variable.
return 4.
& &a; returns the actual address of
Returns the address of a variable.
the variable.
* Pointer to a variable. *a;
?: If Condition is true ? then value X
Conditional Expression.
: otherwise, value Y
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 149
Arithmetic Expressions
▪ Arithmetic expressions contain set of operators and operands
Example:
A+B-C*D/E
▪ Operators (+,-, *, /, %...etc)
▪ Operands ( Numbers, variables ..etc)
▪ Fully parenthesized expressions will evaluate fine but it is difficult to
evaluate Arithmetic expression in absence of brackets
➢ We need Operator Precedence and Associativity to evaluate in
absence of brackets
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 150
Operator Precedence
Example
5 + 10 * 20
// 5+10=15*20 = 300 or 10*20 = 200+5 = 205
To avoid the confusion we consider operator precedence
5 + (10 * 20)
* → Higher precedence
+ → Lower precedence
Then
10*20 = 200 + 5 = 205 is evaluated based on the precedence
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 151
Operators Associativity
Example
10 / 5 * 2
// both the operators( / ), ( * )have equal precedence but Left to Right
Associativity
Then Equal Precedence
10 / 5 * 2
Left to Right
Associativity
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 152
Operator Precedence
The Table is Organized as High(Top) to Low(Bottom)
Operator Operator Associativity
Type / Category
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
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 153
Operator Precedence
Category Operator Associativity
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
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 154
Agenda
➢ formatted and unformatted IO
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 155
Formatted IO
▪ printf(),scanf() are formatted input and output functions,
➢ used with all data types
➢ Formatted input and output functions contain format specifier in their syntax
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“Enter value of a:”);
scanf(“%d”, &a);
printf(“ a = %d”, a);
getch();
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 156
Example:
#include <stdio.h>
int main()
{
char c[20];
printf("Enter your name: ");
scanf("%s", c);
printf("Your name is %s.", c);
return 0;
}
**We can use the fgets() function to read a line of string. And, we
can use puts() to display the string.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 157
Example:fgets
Example:
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Note: The gets() function can also be to take input from the user.
However, it is removed from the C standard.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 158
Un Formatted IO
➢ getch()
➢ getche()
➢ getchar()
➢ gets()
➢ puts()
➢ putchar()
etc. are examples of unformatted input output functions
➢ Unformatted input and output functions do not contain format specifier
in their syntax.
➢ used mainly for character and string data types.
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 159
Example : getche
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch ;
clrscr();
printf(“enter any character:”);
ch = getche();
printf(“\nYou pressed :”)
putchar(ch);
getch();
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 160
Example:getchar
Example:
#include <stdio.h>
void main ()
{
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
}
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 161
Example : gets
Example:
#include <stdio.h>
void main ()
{
char a[50];
printf("Enter a string : \n");
gets(a);
// printf("You entered: %s", a);
puts(a);
Department of ECE, VNRVJIET, Hyderabad January 23, 2022 162