0% found this document useful (0 votes)
83 views111 pages

PPS Unit 1 1

The document outlines the course objectives and outcomes for a Programming for Problem Solving course using C at Matrusri Engineering College. It covers fundamental concepts of computer systems, programming languages, control structures, data types, and file handling, along with practical applications in problem-solving. The syllabus includes topics such as algorithms, flowcharts, arrays, functions, pointers, and searching and sorting techniques.

Uploaded by

hoor syed
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)
83 views111 pages

PPS Unit 1 1

The document outlines the course objectives and outcomes for a Programming for Problem Solving course using C at Matrusri Engineering College. It covers fundamental concepts of computer systems, programming languages, control structures, data types, and file handling, along with practical applications in problem-solving. The syllabus includes topics such as algorithms, flowcharts, arrays, functions, pointers, and searching and sorting techniques.

Uploaded by

hoor syed
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/ 111

MATRUSRI

ENGINEERING COLLEGE

MATRUSRI ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
( UGC-Autonomous Institution )

Unit-I
PROGRAMMING FOR PROBLEM SOLVING
USING C
Mr. Bikshapathy Peruka
Assistant Professor

March 29, 2025 Programming for Problem Solving 1


MATRUSRI
COURSE OBJECTIVES AND COURSE OUTCOMES ENGINEERING COLLEGE

The objectives of this course are:


1. To relate basics of programming language constructs and problem-solving techniques
2. To classify and implement control structures and derived data types
3. To develop and analyse effective modular programming methods
4. To solve mathematical problems and use them in real time applications using
C Language
On successful completion of this course, the students will be able to:
1. Illustrate the use of algorithm, flowchart and pseudocodes in problem
solving, Write and execute programs on C tokens.
2. Implement programs using conditional and iterative statements in a given
problem
3. Develop solutions using modular programming and recursion techniques in
searching and sorting applications.
4. Demonstrate the use of pointers, structures and unions in problem solving.
5. Understand and perform file handling in C. 2
MATRUSRI
SYLLABUS ENGINEERING COLLEGE

UNIT-I: Fundamentals of computers: Components of a computer system, Operating


system, Computer Languages, Number systems: decimal, binary, octal, hexa
decimal systems. algorithm, Flowchart, Pseudo codes with examples
• Introduction to C Programming: C Language evolution, Structure and execution of
a C program, execution phases, Compiler. Interpreter, Linker, Loaders, Tokens,
Expressions and evaluation
• Statements: Declaration, Assignment statements, Standard I/O statements, Type
conversions
UNIT-II: Control Statements: Selection - simple if, if-else, else-if ladder, nested if-else
and switch-case statements. Iteration with - while, do-while, for statements.
Unconditional statements: break, continue, goto and return statements
UNIT-III: Arrays: 1-D arrays, 2-D arrays, Dynamic arrays, Character arrays and strings,
String handling functions
March 29, 2025 Programming for Problem Solving 3
SYLLABUS CNTD.. MATRUSRI
ENGINEERING COLLEGE

• Functions: Concept of top-down approach, Functions- declaration, definition,


calling, Types – built-in and user-defined functions, Parameter passing
techniques – call by value, call by reference, Recursive functions, Passing arrays
to functions, Storage classes.
UNIT-IV: Pointers: Pointer declaration, compatibility, Operations on pointers,
Pointers and arrays, Pointers and functions.
• Structures: Structure definition, Array of structures, Nested structures, Passing
structure to functions, Pointers and structures, Self-referential structures,
Unions, enumerated data types.
UNIT-V: File Handling: I/O streams, File operations, file modes, Sequential,
Random accessing of files, Command line arguments
• Searching and Sorting Techniques: Searching - Linear search and Binary search,
Sorting - Bubble sort and Selection sort 4
UNIT – I: CONTENTS MATRUSRI
ENGINEERING COLLEGE

Fundamentals of computers: Components of a computer system, Operating


system, Computer Languages, Number systems: decimal, binary, octal, hexa
decimal systems. algorithm, Flowchart, Pseudo codes with examples
• Introduction to C Programming: C Language evolution, Structure and
execution of a C program, execution phases, Compiler. Interpreter, Linker,
Loaders, Tokens, Expressions and evaluation
• Statements: Declaration, Assignment statements, Standard I/O statements,
Type conversions

COURSE OUTCOME1: Illustrate the use of algorithm, flowchart and


pseudocodes in problem solving, Write and execute programs on C tokens.

March 29, 2025 Programming for Problem Solving 5


MATRUSRI
Introduction to Computer System ENGINEERING COLLEGE

 What is a Computer?
 Computer is an electronic device which operates under the control of

instructions stored in its memory and it takes the data from the user,
processes that data and gives the output(result), and
 The results might be stored in its memory for future use.

 A Computer when requested,


 Reads(Take) data from the user through input devices (INPUT),

 Processes the user given data (PROCESSING),

 Produces the result to the user through output devices (OUTPUT) and

 Stores data (Information) for future use.

March 29, 2025 Programming for Problem Solving 6


MATRUSRI
Block Diagram of Computer ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 7


MATRUSRI
ENGINEERING COLLEGE

Computer System Mainly consists of three


things

March 29, 2025 Programming for Problem Solving 8


MATRUSRI
Computer Hardware ENGINEERING COLLEGE

• Computer hardware is the physical components that make up a computer.


• All hardware components perform their task based on the instructions given by
the computer software.
• Based on the functionality, computer hardware is classified into the following.
1. Input Unit
2. Central Processing Unit (CPU)
1. Control Unit (CU)
2. Arithmetic and Logic Unit (ALU)
3. Output Unit
4. Storage Device (Memory Device)

March 29, 2025 Programming for Problem Solving 9


MATRUSRI
Input Devices(I/P) ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 10


MATRUSRI
Output Devices(O/P) ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 11


MATRUSRI
Central Processing Unit(CPU) ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 12


MATRUSRI
Computer System ENGINEERING COLLEGE

A Computer System

Computer Science: A Structured Programming Approach Using C 13


MATRUSRI
ENGINEERING COLLEGE

Basic Hardware Components

Computer Science: A Structured Programming Approach Using C 14


MATRUSRI
Computer Software ENGINEERING COLLEGE

 Software is a set of programs(instructions) which enable the computer to


perform a specific task.
 There are two broad categories of softwares:
 System software

 Application software

 System software is a set of programs that manage the


resources/Components of a computer system.
 Example: All Operating Systems (MS-DOS, WINDOWS-XP, LINUX and so
on.) ,Compilers, Device Drivers etc
 Application Software is a set of Programs that complete a specific task.
Particular task may be set of tasks or a single task.
 Example: Computer games, Air / Bus Reservation systems, Microsoft
office, Database Management Systems, Paint application and so on.

March 29, 2025 Programming for Problem Solving 15


MATRUSRI
Types of Software in Computer System
ENGINEERING COLLEGE

Types of Software
Computer Science: A
Structured Programming
Approach Using C 16
MATRUSRI
Relationship Between System and Application Software ENGINEERING COLLEGE

Relationship between system and application software

Computer Science: A Structured Programming Approach Using C 17


MATRUSRI
Comparison between System & Application ENGINEERING COLLEGE

Softwares
• Application software works on any Defined System Software.
• Application Software is a part of System Software.
• System software provides the platform and application software performs
the particular task on any platform.
• System software helps in working of Application Software.
• System software is software that deals directly with the architecture of the
computer hardware.
• Application software provides an interface for user to complete a specific
task through a computer hardware by making use of system software.

March 29, 2025 Programming for Problem Solving 18


MATRUSRI
Working Process of a Computer ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 19


MATRUSRI
Computer Languages ENGINEERING COLLEGE

• User interacts with the computer using programs and that programs are
created using computer programming languages like C, C++, Java etc.,
• “Computer languages are the languages through which user can
communicate with the computer by writing program instructions.”

March 29, 2025 Programming for Problem Solving 20


MATRUSRI
Computer Language Evolution ENGINEERING COLLEGE

Computer Language Evolution


Computer Science: A Structured Programming Approach Using C 21
MATRUSRI
Machine Language ENGINEERING COLLEGE

• Low Level language is the only language which can be understood by the
computer.
• Binary Language is an example of low-level language.
• All the instructions of binary language are written in the form of binary
numbers 1's & 0's.
• A computer can directly understand the binary language.
• Disadvantages
• Very difficult to understand and use.
• Machine dependent, that means a program written for a particular
machine does not executes on another machine.
• More chance for errors and it is very difficult to find errors, debug and
modify.
March 29, 2025 Programming for Problem Solving 22
MATRUSRI
Assembly Language ENGINEERING COLLEGE

• Assembly language is an example of middle level language.


• In assembly language, we use predefined words called mnemonics.
• But computer cannot understand mnemonics, so we use a translator called
Assembler to translate mnemonics into binary language.
• Assembler is a translator which takes assembly code as input and produces
its equivalent machine code as output.
• Disadvantages
• Middle level language is machine dependent.
• Needs to be translated into low level language.So, it requires a language
translator.
• Executes slower compared to low level language.
March 29, 2025 Programming for Problem Solving 23
MATRUSRI
High Level Language ENGINEERING COLLEGE

• Every high-level language has a set of predefined words known as Keywords


and a set of rules known as Syntax to create instructions.
• High level language is easier to understand for the users, but the computer
cannot understand it. High level language needs to be converted into low
level language to make it understandable by the computer.
• We use Compiler or Interpreter to convert high level language to low level
language.
• Disadvantages
• Needs to be translated to low level language.
• Executes slower compared to middle and low-level languages.

March 29, 2025 Programming for Problem Solving 24


MATRUSRI
Computer Languages ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 25


Machine Language – Assembly Language – High-
MATRUSRI
ENGINEERING COLLEGE

Level Language
1 entry main,^m<r2>
1 00000000 00000100 0000000000000000
2 sub12 #12,sp
2 01011110 00001100 11000010 0000000000000010
3 jsb C$MAIN_ARGS
3 11101111 00010110 0000000000000101
4 moveb $CHAR_STRING_CON
4 11101111 10111110 0000000000001011
5
5 11111000 10101101 11011111 0000000000010010
6 pusha1 -8(fp)
6 01100010 11011111 0000000000010101
7 pusha1 (r2)
7 11101111 00000010 11111011 0000000000010111
8 calls #2,SCANF
8 11110100 10101101 11011111 0000000000011110
9 pusha1 -12(fp)
9 00000011 10100010 11011111 0000000000100001
10 pusha1 3(r2)
10 11101111 00000010 11011111 0000000000100100
11 calls #2,SCANF
11 01111110 11110100 10101101
12 mull3 -8(fp),-12(fp),-
12 11111000 10101110 11000101 0000000000101011
13 pusha 6(fp)
13 00000110 10100010 11111011 0000000000110001
14 calls #2,PRINTF
14 11101111 00000010 11111011 0000000000110100
15 clrl r0
15 01010000 11010100 0000000000111011
16 ret
16 00000100 0000000000111101

1 #include<stdio.h>
2 int main(void)
3 {
4 int n1, n2,product;
5 printf(“Enter two numbers : “);
6 scanf(“%d %d”,&n1,&n2);
7 product = n1 * n2;
8 printf(“%d”,product);
9 return 0;
1 }
0
MATRUSRI
Memory Types ENGINEERING COLLEGE

• Based on the speed and space(capacity of storage) classify the


Memory component into the following 6 types.
• Register Memory: Used the Register for storage
• Cache Memory: To maintain the Speed gap between Main and
Secondary
• Main memory (Primary ex: RAM,ROM): Fast but less Space
• Secondary Memory: Slow but large Space (Hard disk Memory)
• External Memory: External Device Memory like Pen drive, External
HDD etc.
• Network Memory: Used the Each System memory on Network
architecture.
• Space Speed
March 29, 2025 Programming for Problem Solving 27
MATRUSRI
Memory Types & Memory Units ENGINEERING COLLEGE

UNITS FULL NAME

1 bit Binary Digit

1Nibble=4 bits Nibble

1 Byte=8 bits Byte

1KB =1024 Bytes Kilo Byte

1MB =1024 KB Mega Byte

1GB =1024 MB Giga Byte

1TB =1024 GB Tera Byte

1PB =1024 TB Peta Byte

1HB =1024 PB Hexa Byte

1ZB =1024 HB Zetta Byte

March 29, 2025 Programming for Problem Solving 28


MATRUSRI
Number Systems ENGINEERING COLLEGE

 A number in a number system with base b is written as following

 Where, N = a number
 b = radix or base to number system
 n = number of digits in integer portion

 m = number of digits in the fractional portion

 dn-1 = Most Significant Digit (MSD)

 d-m = Least Significant Digit (LSD)

 Four Number Systems: In positional number systems, based on the no of symbols in


its alphabet and the radix used, numbers systems can be classified into
 Binary Number System, Octal Number System, Decimal Number System

 Hexa Decimal Number System


29
MATRUSRI
Number Systems ENGINEERING COLLEGE

Following table denotes the four number systems, the radix, and different
digit(symbol)s used in alphabet, along with the examples.

• The [place] value of any digit in a number can be determined by:


• The digit
• Its position in the number
• The base of the number system
March 29, 2025 Programming for Problem Solving 30
Decimal to Binary Conversion MATRUSRI
ENGINEERING COLLEGE

• Example: Convert (10.25) to Its • Example: Convert (1010.01)2 to Its


equivalent Binary number equivalent Decimal number
• Sol: Given (1010.01)2
• = 1×2^3 + 0x2^2 + 1×2^1+ 0x2^0
+ 0x2^ -1 + 1×2^ -2
• = 8+0+2+0+0+0.25
• = 10.25
• So, (1010.01)2 = (10.25)10

31
Decimal to Octal Conversion MATRUSRI
ENGINEERING COLLEGE

• Example: Convert (10.25)10 to Its • Example: Convert (12.2)8 to Its


equivalent Octal number equivalent Decimal number
• Sol: Given (12.2)8 = (?)10
• = 1×8^1+ 2x8^0 + 2x8^ -1
• = 8+2+0.25
• = 10.25
• So, (12.2)8 = (10.25)10

32
MATRUSRI
Hexadecimal and Binary Conversion ENGINEERING COLLEGE

• To convert from Binary to Hexadecimal, group the bits in groups of 4 and


write the hexadecimal digit for each of the 4-bit binary. Add 0's to the left to
adjust the group size.
• 1111011011 = (0011 1101 1011)2
• = (3DB)16
March 29, 2025 Programming for Problem Solving 33
MATRUSRI
Compute the Following.. ENGINEERING COLLEGE

March 29, 2025 Programming for Problem Solving 34


MATRUSRI
Steps in Problem Solving ENGINEERING COLLEGE

• 1) Understand the problem statement thoroughly and find a solution in


the form of an algorithm.
• 2) First produce a general algorithm that represents a solution for the
problem.
• Pseudocode is an artificial and informal language that helps
programmers develop algorithms. Pseudocode is very similar to
everyday English but has strict sequence flow.
• 3) Convert the algorithm into a computer program in some computer
language(C here)
• 4) Test the outputs by applying the Compilation-Debug-Execution
process on the computer program.

March 29, 2025 Programming for Problem Solving 35


MATRUSRI
Algorithms ENGINEERING COLLEGE

• An algorithm is a sequence of well-defined steps(operations) to solve a


problem.
• Properties of a good algorithm
• An algorithm should have:
• one or more inputs and zero or one Outputs.
• 1) Each step should be Clear and Unambiguous.
• 2) Algorithms should be precise, most effective among many different
ways to solve a problem.
• 3) An algorithm shouldn't include computer code.
• 4) Instead, the algorithm should be written in such a way that it can be
used in different programming languages.
March 29, 2025 Programming for Problem Solving 36
Algorithm Cntd.. MATRUSRI
ENGINEERING COLLEGE

• Example1: Write an algorithm to determine a student’s final grade and


indicate whether it is pass or fail. The final grade is calculated as the
average of four marks.

• Algorithm: For Printing the grade of a student


• Input: 4 Subjects’ marks Output: Prints PASS or FAIL
• Body(Steps):
• 1) Input a set of 4 marks
• 2) Calculate their sum
• 3) Calculate the average as (sum/4)
• 4) if average is below 50
• Print “FAIL”
• 5) else
• Print “PASS”

Programming for Problem Solving 37


Pseudocode MATRUSRI
ENGINEERING COLLEGE

• Pseudocode: It is a simpler version of a programming language code in plain


English and uses short and predefined phrases to implement algorithm steps,
indentation to specify flow structures and scope.
• It is one of the methods which can be used to represent(develop) an algorithm. It does
not have a specific syntax like any of the programming languages and can’t be executed
on a computer.
• Following is the pseudocode for displaying the grade of a student
• Function Grade(M1,M2,M3,M4): // Name of the code fragment
• Total= M1+M2+M3+M4
• Avg = Total/4
• IF (Avg < 50) THEN
• PRINT( “FAIL”)
• ELSE
• PRINT(“PASS”)
• ENDIF
• Note: pseudocode is not actual programming language code
March 29, 2025 Programming for Problem Solving 38
MATRUSRI
The Flowchart ENGINEERING COLLEGE

A Flowchart- Is a graphical representation of an algorithm(or pseudocode) that


specifies the given sequence of operations symbolically.
• A flowchart shows how data flows from the source of data, through the computer
to giving final results to users.
• Often shows the sequence of instructions(pictorially) in a single program or
subroutine.
• Symbols used to draw a flowchart are called the vocabulary of the graphical
language
• Advantage:
•Clear and understandable, and easy to write
• Limitations:
•Not suitable for complex and bigger tasks.
• In the next slide, gives the list of symbols(name, symbol, purpose) used in
flowcharting a solution
March 29, 2025 Programming for Problem Solving 39
MATRUSRI
Flowchart Symbols ENGINEERING COLLEGE

Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program

March 29, 2025 Programming for Problem Solving 40


MATRUSRI
Example1: Flowchart for computing the ENGINEERING COLLEGE

result (grade)

START
// Pseudocode of grade printing problem
Input
M1,M2,M3,M4 Function Grade(M1,M2,M3,M4):
Total= M1+M2+M3+M4
AVG(M1+M2+M3+M4)/4 Avg  Total/4
IF (Avg < 50) THEN
N
PRINT( “FAIL”)
IS Y
AVG<50
ELSE
PRINT(“PASS”)
PRINT PRINT ENDIF
“PASS” “FAIL”

STOP

March 29, 2025 Programming for Problem Solving 41


MATRUSRI
Example 2-Algorithm, Flowchart ENGINEERING COLLEGE

• Write an algorithm and draw a flowchart to convert the length in feet to


centimeters.
• Algorithm :
Input: length(ft) Output: length(cm)
Step1) Input the length in feet (Lft)
Step2) Calculate the length in cm (Lcm) by multiplying LFT with 30
Step3) Print length in cm (LCM)

• Pseudocode:
Function LengthCovert(length) :
Input Lft
Lcm  Lft x 30
Print (Lcm)
March 29, 2025 Programming for Problem Solving 42
MATRUSRI
Example 2 ENGINEERING COLLEGE

• Pseudocode:
Flowchart:
Function LengthCovert(length) : START

Input Lft
Lcm  Lft x 30 Input
Lft
Print (Lcm)

Lcm  Lft x 30

Print
Lcm

STOP

March 29, 2025 Programming for Problem Solving 43


MATRUSRI
Example 3-Algorithm & Flowchart ENGINEERING COLLEGE

Example3: Write an algorithm, Pseudocode and draw a flowchart that will read
the two sides of a rectangle and calculate its area.
• Algorithm:
• Input: width(w), length(L) Output : Area(A)
Step1) Input the width (W) and Length (L) of a rectangle
Step2) Calculate the area (A) by multiplying L with W
Step3) Print A
• Pseudocode:
• Function Area( length,width ):
Input W,L
AL x W
Print (A)

March 29, 2025 Programming for Problem Solving 44


MATRUSRI
Example 3-Flowchart ENGINEERING COLLEGE

START
Pseudocode:
• Function Area( length,width ): Input
Input W,L W, L
AL x W
Print (A)
ALxW

Print
A

STOP

March 29, 2025 Programming for Problem Solving 45


Example 4 MATRUSRI

ENGINEERING COLLEGE

Example4: Write an algorithm and draw a flowchart that will calculate the
roots of a quadratic equation ax2+bx+c=0 Hint: d = sqrt (b2-4*a*c ), and the
roots are: roo1 = (–b + d)/2a and root2 = (–b – d)/2a
• Algorithm: Roots of Quadratic Equation
• Input: a,b,c Output: root1, root2
• Steps: 1) Input the coefficients (a, b, c) of the quadratic equation
2) Calculate d= sqrt (b2-4*a*c)
3) If (d>0) then
3.1) Calculate root1 = (–b + d)/2a
3.2) Calculate root2 = (–b – d)/2a
4) If (d=0) then
4.1) Calculate root1 = (–b + d)/2a
4.2) Calculate root2 = (–b – d)/2a
5) Else Print” Roots are Imaginary”
6) Print root1 and root2
March 29, 2025 Programming for Problem Solving 46
Example 4- Flowchart MATRUSRI
ENGINEERING COLLEGE

START
• Algorithm steps: A simple algorithm and
its flowchart. Input
• Step 1: Input a, b, c a, b, c

• Step 2: d  sqrt (b  b  4  a  c)
• Step 3: root1  (–b + d) / (2 x a) d  sqrt(b x b – 4 x a x c)

• Step 4: root2  (–b – d) / (2 x a) root1 (–b + d) / (2 x a)


• Step 5: Print root1, root2
root2  (–b – d) / (2 x a)

Print
root1 , root2

STOP

March 29, 2025 Programming for Problem Solving 47


Decision Structures (Conditionals) MATRUSRI
ENGINEERING COLLEGE

• Decision structures are the statements that involve decisions(conditions) like


(A>B?) ,(A<B?) and (A=B?) and allow us to make decisions in programming.
• In such statements, the expression A>B is a logical(relational) expression and it
tests a condition we want to check.
• For example, C language provides following decision making statements such
as “ simple if statement, if-else, Nested if-else statements.
• if A>B is true (if A is greater than B) we take the action on left
• Print the value of A
• if A>B is false (if A is not greater than B) we take the action on right
• Print the value of B.
Y is N
A>B

Print A Print B

March 29, 2025 Programming for Problem Solving 48


MATRUSRI
Example 5-Decision Structures ENGINEERING COLLEGE

Example5: Write an algorithm that reads two values, determines the largest value and
prints the largest value with an identifying message.
START
ALGORITHM: Largest of any TWO values
Input: Value1,Value2 Output: Max(Value1,Value2) Input
• Step 1: Input VALUE1, VALUE2 VALUE1,VALUE2
• Step 2: if (VALUE1 > VALUE2) then
• MAX  VALUE1 Y Is N
• else VALUE1>VALUE2

• MAX  VALUE2
• endif MAX  VALUE1 MAX  VALUE2
• Step 3: Print “The largest value is”, MAX
Print
“The largest value is”, MAX

STOP
March 29, 2025 Programming for Problem Solving 49
MATRUSRI
IF–THEN–ELSE STRUCTURE ENGINEERING COLLEGE

 The if-then-else structure is as following


If condition then
Y N
true alternative Conditi
on
else True False
false alternative statement statement
endif
IF–THEN–ELSE STRUCTURE
• It is a decision making statement that contains an other decision making
statements in it.
• One of the alternatives within an IF–THEN–ELSE statement
• may involve further IF–THEN–ELSE statement
March 29, 2025 Programming for Problem Solving 50
Example 6 MATRUSRI
ENGINEERING COLLEGE
 Write an algorithm that reads three numbers and prints the value of the largest
number.
Algorithm: Prints the Largest of THREE numbers
Input: N1,N2,N3 Output: Largest(N1,N2,N3)
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX  N1 [N1>N2, N1>N3]
else
MAX  N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX  N2 [N2>N1, N2>N3]
else
MAX  N3 [N3>N2>N1]
endif
endif
Step 3: Print “The largest number is”, MAX
March 29, 2025 Programming for Problem Solving 51
MATRUSRI
Relational Operators ENGINEERING COLLEGE

Relational Operators
Operator Description Result
> Greater than x=10,y=12, Is(x>y)?TRUE( or 1)
< Less than Is(x>y)? FALSE( or 0)
= Equal to Is(x=y)? FALSE( or 0)
 Greater than or equal Is(xy)? FALSE( or 0)
to
 Less than or equal to Is(xy)? FALSE( or 0)
 Not equal to Is(xy)? TRUE( or 1)

March 29, 2025 Programming for Problem Solving 52


C Programming Language MATRUSRI
ENGINEERING COLLEGE

• C is a structured programming language developed by


Dennis Ritchie in 1970 @ AT&T Bell Labs.
• It’s considered a HLL because it allows the programmer to concentrate on the problem at
hand and not worry about the machine that the program will be using.
History: Language Year Developed By
• BCPL • 1967 • Martin Richard
• B • 1970 • Ken Thompson
• Traditional • 1972 • Dennis Ritchie
C
• K&RC • 1978 • Kernighan & Dennis Ritchie

• ANSI C • 1989 • ANSI Committee


• ANSI/ISO C • 1990 • ISO Committee
• C99 • 1999 • Standardization Committee
• While many languages claim to be machine independent, C is one of the closest to achieve
that goal.
C Language : Program Structure MATRUSRI
ENGINEERING COLLEGE

• That is another reason why it is used by software developers whose applications


have to run on many different hardware platforms.
• C Program: Is a sequence of statements when executed performs a particular
task for which it is written for. C Program has the following essential parts.

March 29, 2025 Programming for Problem Solving 54


Figure: The Greetings Program MATRUSRI
ENGINEERING COLLEGE

• Comments : Are used to document the whole or a part of a program. However,


don’t contribute to the logic. A comment can be inserted anywhere in a program.
C Supports TWO Ways :
• Single Line Comments: a= 5; // This is single line comment
• Multi-line (Block) Comments: b = 5; /* This is a multi-line comment ends with */
Compilation & Execution of a C Program in MATRUSRI
ENGINEERING COLLEGE

Linux Environment
• 1. Go to the Root($ prompt) by typing Cntl+Alt+T and + Enter
• 2. Create your own Directory in the format “ CSE-001” using the command “$
Type “$ mkdir CSEB001” + Enter
• 3. Go to your Directory using $cd CSEB001 + Enter
• 4. Create a C file using an Editor(like gedit, ed, or vi) typing $ gedit prog1.c
(+Enter)
• 5. Compile the Program $ gcc prog.c +Enter
• 6. Execute the program $ .\a.out +Enter

March 29, 2025 Programming for Problem Solving 56


Compilation and Execution Process of a C Program

3/29/2025 57
MATRUSRI
ENGINEERING COLLEGE

Computer Science: A Structured Programming Approach Using C Figure: Building a C Program 58


MATRUSRI
C Character Set and Tokens ENGINEERING COLLEGE

Character Set : Is the set of symbols(alphabet) of the C Programming language.


ASCII character set is the alphabet of C
• Lowercase and Uppercase letters of ISO Basic Latin Alphabet: a–z A–Z
• Decimal digits : 0–9
• 29 Special characters! ” # % & ‘ ( ) * + , – . / :
; < = > ? [ \ ] ^ _ { | } ~
• Escaping Sequences: These sequences are useful for representing, formatting
text, and controlling hardware devices.\b, \t , \v, \f, \n , \r, \\, etc
• These characters along with other tokens of the language are used to write
higher level constructs of a C program.
Computer Science: A Structured Programming Approach Using C
59
MATRUSRI
C Tokens ENGINEERING COLLEGE

• C Tokens: Are the fundamental units(valid words or strings) of a


C program and are used in writing correct statements and
programs.
• All the C Tokens are actually classified into,
• Keywords,
• Identifiers,
• Constants,
• Operators,
• Special Characters,
• Strings
March 29, 2025 Programming for Problem Solving 60
MATRUSRI
Keywords ( Reserved Words) ENGINEERING COLLEGE

Keywords: These are the predefined set of words that are assigned a role
(meaning). There are 32 keywords in C(given in the table below).
• Since the purpose is predefined and fixed, C does not allow change of
its purpose. Therefore, they are called reserved words.
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
Computer Science: A Structured Programming Approach Using C
61
Identifiers in C MATRUSRI
ENGINEERING COLLEGE

• Identifier: Is a well defined sequence of characters used to name(identify) data


item, array, function and files in a program
• This is a feature available in all programming languages.
• Each identified object in the computer is stored at a unique address, has a
unique name and value.
• If we didn’t have identifiers that we could use to symbolically represent data
locations, we would have to know and use object’s addresses.
• Instead, we simply give data identifiers and let the compiler keep track of where
they are physically located.
Computer Science: A Structured Programming Approach Using C 62
MATRUSRI
Identifiers in C ENGINEERING COLLEGE

Identifiers:
• Is a sequence of characters used to identify or name a data item, an array or a
function, program.
• C provides the following rules to write correct identifiers
Rules for Identifiers:

Note: An identifier must start with a letter or underscore: it may not have a
space or a hyphen.
Computer Science: A Structured Programming Approach Using C 63
MATRUSRI
Example Valid and Invalid Identifiers: ENGINEERING COLLEGE

Table 2-2 Examples of Valid and Invalid Names

Note: C is a case sensitive language means it treats ‘A’ as a different character to ‘a’. We
should be careful in naming the data item and its usage.

Computer Science: A Structured Programming Approach Using C 64


MATRUSRI
Data Types ENGINEERING COLLEGE

• Data type or just a type defines a set of values and a set of operations that can
be applied on those values.
• For example, a light switch can be compared to a computer type.
• It has a set of two values, on and off. Only two operations can be applied to a
light switch: turn-on and turn-off.
Different Data types in C :
• Following is the list of different classes of data types in C language. These are
classified basically into three types void, integral, and floating point types.
• Void Type
• Intégral Type
• Floating-Point Types
• We will discuss these data types first and will know about the derived and user
defined types later
Computer Science: A Structured Programming Approach Using C 65
MATRUSRI
ENGINEERING COLLEGE
Classification of C Data Types

Data Types

Computer Science: A Structured Programming Approach Using C 66


MATRUSRI
Character Types ENGINEERING COLLEGE

• Character Types: Are used to declare, define and use character data items in
programs. Following are the two different character types available in C.
• For example, char ch1; // declares ch1 as a character and can store a character in it.

Character Types

Computer Science: A Structured Programming Approach Using C 67


MATRUSRI
Integer Types ENGINEERING COLLEGE

• Integer Types: Are used to declare, define and use integer data in programs.
Following are the four different integer types available in C.
• For example, int n1; // declares n1 as an integer and can store an integer value in it.

Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)

Integer Types

Computer Science: A Structured Programming Approach Using C 68


MATRUSRI
ENGINEERING COLLEGE

Typical Integer Sizes and Values for Signed Integers

Computer Science: A Structured Programming Approach Using C 69


MATRUSRI
Floating Point Types ENGINEERING COLLEGE

• Floating Point Types: Are used to declare, define and use real data in
programs. Following are the three different floating point types available in C.
• For example, float n1; /* declares n1 as a real number and can store
• floating point value in it */

sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)


Floating-point Types

Computer Science: A Structured Programming Approach Using C 70


MATRUSRI
ENGINEERING COLLEGE

Data Types Summary

Computer Science: A Structured Programming Approach Using C 71


MATRUSRI
Variables ENGINEERING COLLEGE

• Variables are named memory locations that have a type, such as integer or
character, which is inherited from their data type.
• The data type of a variable denotes the type of data that a variable can
store and the operations that may be performed on it.
• A variable must be declared (and defined) before its use in a statement
• Variable Declaration: Allows us to define a data item of required type.
Following is the syntax of a declaration statement.
• Syntax: <datatype> <variable[s]>; For example, following declaration,
int x, y, sum; /* It’s a declaration statement that declares
variables x,y and sum to be of integer types and assigns 2B of memory to each data items*/
• Variable Initialization: Is a method of assigning initial(first) values in to the
memory locations allocated for a declared variable.
• If not initialized, a variable contains a garbage value. For example,
int rollno = 65; // declares rollno as an integer and initializes it with a value 65.
Computer Science: A Structured Programming Approach Using C 72
More on Variable Declarations MATRUSRI
ENGINEERING COLLEGE

Examples of Variable Declarations


73 and Definitions
Variables & Initializations MATRUSRI
ENGINEERING COLLEGE

Note:
When
Whenaavariable
variableisisdefined,
defined,but
butnotnotinitialized. Contains a garbage value in it.
initialized,Contains
Therefore,
Therefore,We
Weshould
shouldinitialize
initializeititwith
withprescribed
prescribeddata.
data.

Variable Initialization

Computer Science: A Structured Programming Approach Using C 74


Example: Program To Print the Sum of Three Numbers MATRUSRI
ENGINEERING COLLEGE

Computer Science: A Structured Programming Approach Using C 75


MATRUSRI
ENGINEERING COLLEGE
PROGRAM Print Sum of Three Numbers (continued)

Computer Science: A Structured Programming Approach Using C 76


MATRUSRI
ENGINEERING COLLEGE
PROGRAM Print Sum of Three Numbers (continued)

Computer Science: A Structured Programming Approach Using C 77


MATRUSRI
Constants ENGINEERING COLLEGE

• Constants are data values that cannot be changed during the execution of a
program.
• Like variables, constants have a type. In this section, we discuss Boolean,
character, integer, real, complex, and string constants.
• For example, ‘a’ is a character constant, 125 is an integer constant, and
245.20 is a floating point constant

• A character constant is enclosed in single quotes.


• Following lines give more useful character constants in C known
as control characters.

Computer Science: A Structured Programming Approach Using C 78


MATRUSRI
More useful Character Constants ENGINEERING COLLEGE

Symbolic Names for Control Characters


Computer Science: A Structured Programming Approach Using C 79
MATRUSRI
More Examples For Integer & Real Constants ENGINEERING COLLEGE

Computer Science: A Structured Programming Approach Using C 80


MATRUSRI
Examples of Complex Constants ENGINEERING COLLEGE

Note

• The two components of a complex constant must be of the same


precision, that is, if the real part is type double,
then the imaginary part must also be type double.

Computer Science: A Structured Programming Approach Using C 81


MATRUSRI
Some String Constants: ENGINEERING COLLEGE

• A String constant is a sequence of zero more characters written in between


double quotes(“ ”) as following.

• Special cases of Character and String Constants: are the Null character and Null
Strings which are given below. These are very useful in string processing
applications.

Some Strings

Computer Science: A Structured Programming Approach Using C 82


MATRUSRI
ENGINEERING COLLEGE

PROGRAM Memory Constants

Computer Science: A Structured Programming Approach Using C 83


MATRUSRI
ENGINEERING COLLEGE

PROGRAM Memory Constants (continued)

Computer Science: A Structured Programming Approach Using C 84


MATRUSRI
Expressions & Evaluation In C ENGINEERING COLLEGE

• An expression is any valid sequence of literals, variables, operators and


operands that can be evaluated to a single value. This value can be a number, a
string or any logical value.
• For instance a = b + c; denotes an expression in which there are 3 operands a, b,
c and two operators ’+’ and ‘=‘.
• A statement is the smallest independent computational unit, that specifies an
action to be performed. In most cases, statements are executed in sequence.
• The number of operands of an operator is called its arity. Based on the arity,
operators are classified as
• nullary (no operands), unary (1 operand), binary (2 operands), and
• ternary (3 operands).

March 29, 2025 Programming for Problem Solving 85


MATRUSRI
Operators and Expressions ENGINEERING COLLEGE

 Operators are symbols which take one or more operands( or expressions) and
perform its assigned computational task.
 Operands are variables or expressions which are used in conjunction with
operators in the evaluation of an expression. A valid combination of operands
and operators form an expression.
 Expressions are sequences of operators, operands, and punctuators that specify
a computation.
 Evaluation of expressions is based on the operators that the expressions contain
and the context in which they are used.
 Expression can result in a value and can produce side effects.
 A side effect is a change in the state of the execution environment.

March 29, 2025 Programming for Problem Solving 86


MATRUSRI
Different Types Of Operators In C ENGINEERING COLLEGE

Definition: An operator is a symbol that tells the compiler to perform a specific


mathematical or logical functions.
C language is rich in built-in operators and provides the following
types(categories) of operators:
 Arithmetic Operators +, - , * , / , %
 Assignment Operators =, += ,- =,*=,/= etc
 Relational Operators < , >, <= , >= ,== , !=
 Logical Operators ! , && ,||
 Conditional Operators ?:
 Increment & Decrement Operators ++ , - -

 Bitwise Operators ! , & ,| ,~, ^, <<, >>


 Special Operators sizeof , (comma),(),[].., -> etc
March 29, 2025 Programming for Problem Solving 87
MATRUSRI
Arithmetic Operators In C ENGINEERING COLLEGE

• The operators +(Addition),-(Subtraction),*(Multiplication),/(Division),%(Remainder) are called


arithmetic operators and are used in numerical data processing. Lets assume variable A holds
10 and variable B holds 20. Following table gives operator and its functionality.
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 which gives the remainder of 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


Programming for Problem Solving 88
Relational Operators In C MATRUSRI
ENGINEERING COLLEGE

• The operators ==(Equal to),!=(Not Equal to),>(Greater than),<(Less than),>=(Greater than or


equal to),<=(Less than or equal to) are called relational operators and are used check the
relationship between two data items. The value of a relational expression is always
Boolean( 0 or 1)
• Assume variable A holds 10 and B holds 10.0. Following table gives the operators and their
functionality.
Operator Description Example
• Checks if the values of two operands are equal or
== not. If yes, then the condition becomes true.
(A == B) is not true.

• Checks if the values of two operands are equal or


!= not. If the values are not equal, then the condition (A != B) is true.
becomes true.
• Checks if the value of left operand is greater than
> the value of right operand. If yes, then the (A > B) is not true.
condition becomes true.
March 29, 2025 Programming for Problem Solving 89
MATRUSRI
Relational Operators Cntd.. ENGINEERING COLLEGE

• Lets assume variable A holds 10 and variable B holds 20. Following table gives the operators
and their functionality.
Operator Description Example

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

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

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

March 29, 2025 Programming for Problem Solving 90


MATRUSRI
Logical Operators In C ENGINEERING COLLEGE

• The operators, &&(Logical AND), ||(Logical OR), !(Logical NOT) are logical operators and are
also called as compound relational operators. These are used to compare the relationship
between two or more data items( OR expressions). The value of a logical expression is always
Boolean( 0 or 1). Lets assume variable A holds ZERO(0) and variable B NON-ZERO(1).
Following table gives the operators and their functionality.
Operator Description Example
&& • Called Logical AND operator. If both the operands are (A && B) is false.
non-zero(TRUE), then the condition becomes true.
|| • Called Logical OR Operator. If any of the two operands (A || B) is true.
is non-zero, then the condition becomes true.
! • Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.

March 29, 2025 Programming for Problem Solving 91


MATRUSRI
Bitwise Operators In C ENGINEERING COLLEGE

• These operators &(Bitwise AND),|(Bitwise OR),^(XOR), ~(1’s Complement), <<(Left shift) and
>>(right shift) are bitwise operators because, they are applied on the bits of operands.
• Assume variables ‘p’ and ‘q’ are the corresponding bits of the operands. The result of a bitwise
operation is also either 0 or 1.
• Following table shows the result of bitwise operators for different values of p and q.
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

March 29, 2025 Programming for Problem Solving 92


Bitwise Operators Cntd.. MATRUSRI
ENGINEERING COLLEGE

• Assume variable 'A' holds 60(in binary 111100) and 'B' holds 13(or 001101). Following table
gives the resultant of applying bitwise operators on A and B.
Operator Description Example
• Binary AND Operator performs the bitwise operation on its (A & B) = 12,
& operands. i.e., 0000 1100
• Binary OR Operator biwise OR on the corresponding bits of (A | B) = 61,
| the operands. i.e., 0011 1101
• Binary XOR Operator sets the bit if it is set in one operand but (A ^ B) = 49,
^ not both. i.e., 0011 0001
~ • Binary One's Complement Operator is unary and has the effect (~A ) = ~(60),
of 'flipping' bits. i.e,. 0000 11
<< • Binary Left Shift Operator. The left operands value is moved A << 2 = 240
left by the number of bits specified by the right operand. i.e., 1111 0000
>> • Binary Right Shift Operator. The left operands value is moved A >> 2 = 15
right by the number of bits specified by the right operand. i.e., 0000 1111 93
Assignment Operators MATRUSRI
ENGINEERING COLLEGE

Operator Description Example


• Simple assignment operator. Assigns value of right side
= expression(operand) to the left side expression( operand which
C = A + B will assign the
value of A + B to C
must be a variable).
• Add AND Assign operator. It adds the right operand to the left C += A is equivalent to
+= operand and assign the result to the left operand(variable). C=C+A
• Subtract AND Assign operator. It subtracts the right operand
-= from the left operand and assigns the result to the left
C -= A is equivalent to
C=C–A
operand(variable).
• Multiply AND Assign operator. It multiplies the right operand
*= with the left operand and assigns the result to the left
C *= A is equivalent to
C=C*A
operand(variable).
• Divide AND Assign operator. It divides the left operand with the
/= right operand and assigns the result to the left
C /= A is equivalent to
C=C/A
operand(variable).
• Modulus AND Assign operator. It takes modulus using two
%= operands and assigns the result to the left operand(variable).
C %= A is equivalent to
C=C%A
94
Assignment Operators MATRUSRI
ENGINEERING COLLEGE

Operator Description Example


<<= • Left shift AND Assign operator. C <<= 2 is same as C = C << 2
>>= • Right shift AND Assign operator. C >>= 2 is same as C = C >> 2
&= • Bitwise AND Assign operator. C &= 2 is same as C = C & 2
^= • Bitwise exclusive OR and Assign operator. C ^= 2 is same as C = C ^ 2
|= • Bitwise inclusive OR and Assign operator. C |= 2 is same as C = C | 2

SPECIAL OPERATORS IN C
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 address of variable a
* • Pointer to a variable. *a; Declares variable a as a pointer
A = Condition? X :Y ; If Condition is true ?
?: • Conditional Expression. then value X : otherwise value Y is assigned to
A 95
MATRUSRI
Postfix Operators In C ENGINEERING COLLEGE

Operators Description Example Usage


• Array subscripting operator. A postfix #include <stdio.h>

expression followed by an expression in [ ] int main(void)


(brackets) specifies an element of an array. {
[] • The expression within the brackets is referred int a[3]={11,12,33 };
to as a subscript. printf("a[0]=%d\n",a[0]);
• The first element of an array has the subscript return 0;
zero. }

• Dot operator used to access class, structure,


. or union members type.
• objectVar.memberOfStruc
t

• Arrow operator used to access class, structure


-> or union members using a pointer type.
• aptrTo->memberOfStruct
96
MATRUSRI
Expression Evaluation - Precedence ENGINEERING COLLEGE

And Associativity
 Precedence and Associativity of an operator defines the relative order of its
use in evaluation of an expression
 Precedence: Is defined as the order(or priority) of application of an operator
in a complex(or multi-operator) expression. Such expressions contain more
than one operators with different precedence.
 For example, in evaluation of (x+y*z/-d), which is equal to (x+(((y*z)/(-d)))) ,
we first apply –(uminus) because, it has highest precedence, then * and / with
next highest, and apply + as the last operation.
 Associativity: When two or more operators have the same precedence then
the concept of associativity comes into discussion.
 For example, in evaluation of (x+y-z+d) is equal to (((x+y)-z)+d) because + and –
are left associative
97
Precedence & Associativity of MATRUSRI
ENGINEERING COLLEGE

Operators In C
PRECEDENCE LEVEL) TYPE OPERATOR ASSOCIATIVITY
• L1) Postfix • () [] -> . ++ - - • Left to right
• L2) Unary • + - ! ~ ++ - - (type)* & • Right to left
sizeof
• L3) Multiplicative • */% • Left to right
• L4) Additive • +- • Left to right
• L5) Shift • << >> • Left to right
• L6) Relational • < <= > >= • Left to right
• L7) Equality • == != • Left to right
• L8) Bitwise AND • & • Left to right 98
MATRUSRI
Precedence & Associativity Cntd.. ENGINEERING COLLEGE

PRECEDENCE LEVEL) TYPE OPERATOR ASSOCIATIVITY


• L9) Bitwise XOR • ^ • Left to right

• L10) Bitwise OR • | • Left to right

• L11) Logical AND • && • Left to right

• L12) Logical OR • || • Left to right

• L13) Conditional • ?: • Right to left

• L14) Assignment • = += -= *= /= %=>>= • Right to left


<<= &= ^= |=

• L15) Comma • , • Left to right


99
MATRUSRI
Input / Output Statements in C ENGINEERING COLLEGE

 Every C program, has basic operations for –


 Accepting of data as input,

 Processing of data, and

 Generation of output.

 The acceptance of data refers to input and the presentation of data refers to the
output
 All I/O is classified into 1) Console I/O 2) Disk(or File) I/O 3) Port I/O
 In Console I/O , The source and destination of data is standard I/O devices
 In Disk(File) I/O , In this case, the Source and destination of I/O are the files(HDD)
 In Port I/O, here the Source and destination os data are various ports
 Apart from this we have many string I/O functions that are discussed in
later units of the course.
3/29/2025 Programming for Problem Solving 100
MATRUSRI
Console Input/Output Statements in C ENGINEERING COLLEGE

 C provides various functions to receive inputs from Keyboard, and write outputs on
the VDU. These functions are defined in the library “stdio.h”.So, we must include this
library to use them for I/O operations.
 For example, scanf() and printf() are the fundamental input/output statements in this
libray and
 Are used to perform input(reading from the keyboard) and output(for displaying on
the monitor or an output device) operations respectively.
 The syntax of these statements is,
 scanf("format string",argument_list);

 printf("format string",argument_list);

 The format string contains conversion specifiers like %d (for integer), %c (for
character), %s (for string), and %f (for float) which depends on the type of I/O data
given in the argument_list.
3/29/2025 Programming for Problem Solving 101
MATRUSRI
Format Specifiers ENGINEERING COLLEGE

Format Specifier Description

%d or %i It is used to print the signed integer value where signed


integer means that the variable can hold both positive
and negative values.

%f It is used for printing the decimal floating-point values.


By default, it prints the 6 values after '.'.

%c It is used to print the unsigned character.

%s It is used to print the strings.

3/29/2025 Programming for Problem Solving 102


MATRUSRI
Storage Classes of Variables ENGINEERING COLLEGE

 The storage class of a variable determines the visibility, lifetime, initial


value, and memory location. C defined following five storage classes
 1. Local Variable : A variable that is declared inside the function or block is
called a local variable.
 Lives as long as the function that contains it is alive.
 2. Global Variable : A variable that is declared outside the [main]function or
block is called a global variable.
 It is available to all the functions in the program. So, any function can access and update a
global variable. Lives till the program is alive
 3. Static Variable : A variable that is declared with the static keyword is
called static variable.
 For example, static int num; /*declares num as a static integer. Its stored in RAM, and has initial value
of 0. lives across iterations */ 103
MATRUSRI
Storage Classes Cntd.. ENGINEERING COLLEGE

 4. Register Variable: A variable declared with the register keyword is called


register variable. Stored in processor registers and live only when the variable is
active (during the execution). Life time is with in the function.
 For example, register int x; // declares x as a register variable
 5. Automatic Variable : All variables that are declared inside the block, are
automatic variables by default. We can also, explicitly declare an automatic
variable using auto keyword. For example,
 auto int x; /* declares x as an auto variable and has 0(default initial value) . Its life time is
that of the main program and retains its value across multiple function calls */
 6. 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. For example, extern int empID; /* defines empID as an external variable and it can
be accessed in all those files in which it is declared as extern variable. Its life time is that of the main() */
3/29/2025 Programming for Problem Solving 104
MATRUSRI
TYPE CONVERSIONS IN C ENGINEERING COLLEGE

 C allows conversion of one data type to another if needed. This


technique is called Typecasting.
 Also called as data conversion or type conversion. We must be
careful when converting from larger data type to smaller to avoid
loss of data.
 'C’ supports following two ways of type casting:
 Implicit type casting (Type Coersion)– Is the default method followed
by the C compiler for converting one type to another
 Explicit type casting – Is the method that user explicitly implements in
the program statements using typecasting (type) operator.

3/29/2025 Programming for Problem Solving 105


MATRUSRI
MATRUSRI
Implicit Type Casting ENGINEERING COLLEGE
ENGINEERING COLLEGE

 In Implicit type casting, automatic conversion of one data type to another


without losing its original meaning(value).
 It’s done by the compiler. It normally follows the predefined hierarchy of types
in which a smaller value can be easily converted to larger type.
 // Example Program that demonstrates type coercion
1. #include<stdio.h>

2. int main(){

3. short a=10; // initializing variable of short data type


4. int b; // declaring int variable
5. b=a; /* implicit type casting ,the type of a(short I
nt) is converted to the type of b(int) */
1. printf("%d\n",a);
2. printf("%d\n",b);
3. }
3/29/2025 Programming for Problem Solving 106
MATRUSRI
Arithmetic Conversion Hierarchy ENGINEERING COLLEGE

3/29/2025 Programming for Problem Solving 107


MATRUSRI
Explicit Type Casting ENGINEERING COLLEGE

 There are some scenarios in which we(programmer) may have to


force type conversions using the (type) cast operator.
 This forced conversion is called explicit type conversion
1. // C Program demonstrating explicit type conversions
2. #include<stdio.h>
3. int main(){
4. float a = 1.2;
5. int b = a; // Compiler will throw an error .
6. b = (int)a+1; // Explicit conversion from float to int type of a
7. printf("Value of a is %f\n", a);
8. printf("Value of b is %d\n",b);
9. return 0;
10. }
3/29/2025 Programming for Problem Solving 108
Syntax and Logical Errors? MATRUSRI
ENGINEERING COLLEGE

 Syntax errors: Are the errors caused when rules of writing C code are violated.
 These are normally detected by the compiler during the compilation and are fixed
before the executable code is generated.
 Since, all these errors are detected by compiler, are called as compile-time errors.
 Most frequent syntax errors are:
 Missing Parenthesis (})
 Use or Printing the value of variable without declaring it.
 Missing semicolon like this(;) etc.
 Logical Errors: A logical error, is a 'bug' or mistake in a program's source code(or
logic) that results in incorrect or unexpected results.
 It is a type of runtime or execution time error that may simply produce the wrong
output or cause a program to crash while running.
 So, it’s the responsibility of the programmer to write logically correct programs to
avoid such wrong results.
March 29, 2025 Programming for Problem Solving 109
Object Code & Executable Code MATRUSRI
ENGINEERING COLLEGE

 Object Code: Is the code produced when an interpreter or a compiler


translates source code into machine code.
 It’s a set of instructions that is understood by a computer at the lowest
hardware level.
 Object code might have to link some libraries, resolve some mnemonics
corresponding to addresses to make it executable.
 Though its binary in nature, is not the absolutely executable code.
 Executable Code: Is the output of a linker/loader and is absolutely executable
code.
 A machine code file can be immediately executable (i.e., runnable as a
program), or it might require linking with other object code files (e.g. libraries)
to produce a complete executable program.
March 29, 2025 Programming for Problem Solving 110
Thank you
Any queries? Welcome
Note: You can avail(download) this ppt from google classroom

March 29, 2025 Programming for Problem Solving 111

You might also like