Syllabus - CO Wise - Programming For Problem Solving (KCS-101/KCS-201) - 2020-21

Download as pdf or txt
Download as pdf or txt
You are on page 1of 192

Syllabus_CO Wise || Programming for Problem solving (KCS-101/KCS-201) ||2020-21

CO-1: To develop simple algorithms for arithmetic and logical problems.

Introduction of subject, Syllabus, CO, PO, teaching-learning strategy. Introduction to components of a


computer system: Memory, processor I/O Devices, storage operating system Concept of assembler,
compiler, interpreter, loader and linker. Idea of Algorithm: Representation of Algorithm Flowchart,
Pseudo code with examples, From algorithms to programs, source code.

CO-2:To translate the algorithms to programs & execution (in C language).

Programming Basics: Structure of C Program Writing and executing the first C program, Syntax and
logical errors in compilation, object and executable code. Components of C language.
Standard I/O in C, Fundamental data types, Variables and memory locations, Storage classes
Operators and expression using numeric and relational operators, mixed operands, Type conversion
Logical operators, bit operations, assignment operator, Operator precedence and associativity.

CO-3: To implement conditional branching, iteration and recursion.

Applying if statement Applying switch statement Nesting if and else Use of break and default with switch.
Use of while, do while Use of for loops Multiple loop variables, use of break and continue statements.

CO-4: To decompose a problem into functions and synthesize a complete program using divide and conquer
approach.

Functions: Introduction, Types of functions Passing parameters to functions, call by value Call by
reference Recursive functions. Functions with array

CO-5: To use arrays, pointers and structures to develop algorithms and programs.

Arrays: Array notation and representation, manipulating array elements Using multi-dimensional arrays
passing arrays to functions Character arrays and strings Structure Array of structures Union, enumerated
data types Basic Algorithms: Searching Basic Sorting Algorithms (Bubble, Insertion) Selection Sorting
Finding roots of equations, Notion of order of complexity Pointers: Introduction, declaration, applications
Introduction to dynamic memory allocation (malloc, calloc, realloc, free) Use of pointers in self-
referential structures Notion of linked list (no implementation) File handling: File I/O functions File
handling: File I/O functions Standard C preprocessors Defining and calling macros, command-line
arguments

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 1


PROGRAMME OUTCOMES (POs)

PO Statement
Engineering knowledge: Apply the knowledge of mathematics, science,
PO1 engineering fundamentals, and an engineering specialization to the solution of
complex computer engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex computer engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex computer
engineering problems and design system components or processes that meet the
PO3
specific needs with appropriate considerations for the public health and safety,
and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge
PO4 and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide conclusions
Modern tool usage: Create, select, and apply appropriate techniques, resources,
PO5 and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations
The engineer and society: Apply reasoning informed by the contextual
PO6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent relevant to the professional engineering practices
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norm of the engineering practices
Individual and team work: Function effectively as an individual, and as a
PO9
member or leader in diverse teams, and in multidisciplinary settings
Communications: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
PO10
comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions
Project management and finance: Demonstrate knowledge and understanding
of the engineering and management principles and apply these to one’s own
PO11
work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life learning in the broadest context of
PO12
technological change.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 2


CO || Programming for Problem solving (KCS-101/KCS-201)

CO Course Outcome (Statement)

CO-1 To develop simple algorithms for arithmetic and logical problems.


CO-2 To translate the algorithms to programs & execution (in C language).
CO-3 To implement conditional branching, iteration and recursion.
CO-4 To decompose a problem into functions and synthesize a complete program using divide and
conquer approach.
CO-5 To use arrays, pointers and structures to develop algorithms and programs.

CO-PO Mapping || Programming for Problem solving (KCS-101/KCS-201)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 3


Lecture Notes-Unit Wise

Programming for Problem Solving (KCS-101/KCS-201)

Sarvesh Kumar Swarnakar

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 4


Lecture Notes Index
L. Number Content of Syllabus Page Unit Number
Number
CO-1: To develop simple algorithms for arithmetic and logical problems.
1. Introduction
1 of subject, Syllabus, COs, Teaching-learning strategy. 6
2. Components of a computer system: Memory, processor ,I/O Devices, 12
storage Unit – 1
3. Operating System and its functions 19
4. Idea of Algorithm: Representation of Algorithm, Pseudo code, Flowchart 23
CO-2: To translate the algorithms to programs & execution (in C language).
5. Programming Basics: Concept of assembler, compiler, interpreter, loader and 32
linker Structure of C program, First C program
6. Compilation and Execution steps, Errors 36
7. Components of C language , Fundamental Data Types, Variables and Memory 43
locations, Type Conversion Unit – 1
8. Standard I/O in C 51
9. Storage classes 55
10. Types of Operators 61 Unit – 2
11. Operator Precedence and Associativity & Solving Expressions 66
CO-3: To implement conditional branching, iteration and recursion.
12. Branching: Applying if ,if-else and nested if statements with examples 70
13. Branching-Applying switch statement, Use of Break & Default 74 Unit – 2
14. Iteration- Loops (While, do while,for,multiple loop variable) 76 Unit – 3
CO-4: To decompose a problem into functions and synthesize a program using D &C approach.
15. Functions Basics: Introduction ,Types of functions 85
16. Passing Parameters -Call by Value 89
17. Passing Parameters - Call by Reference 92 Unit – 3
18. Recursive Functions 94
CO-5: To use arrays, pointers and structures to develop algorithms and programs.
19. Single Dimensional Arrays : Notation, Manipulation 98
20. Multi-Dimensional Array :Notation ,Manipulation 101
21. Array and Functions 107
22. Strings 110
23. Structure, Array of structures, Self-referential structures 115
24. Union, Enumerated data types 119
25. Basic Algorithms: Searching 122 Unit – 4
26. Basic Sorting Algorithms: Bubble 125
27. Basic Sorting Algorithms:Insertion 129
28. Basic Sorting Algorithms: Selection 132
29. Finding roots of equations, Notion of order of complexity 135
CO-5: To use arrays, pointers and structures to develop algorithms and programs.
30. Pointers: Introduction, Declaration, Applications 136
31. Introduction to dynamic memory allocation (malloc, calloc, realloc, free) 139
32. Notion of linked list (no implementation) 146
33. File Handling 148 Unit – 5
34. Standard C preprocessors, Defining and calling macros, command-line 152
arguments

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 5


Lecture Notes || Unit -1 || Lecture Number-1

Topic Introduction of subject, Syllabus, COs, Teaching-learning strategy.


Lecture Objective To know about subject, Syllabus, COs and Teaching Learning Strategy.
Lecture structure  What do you mean by the term “Programming for Problem solving”?
 Syllabus
 What is NBA?
 Course Outcome Vs Programme Outcome
 Teaching Learning Strategy
Related a) State COs of PPS.
Questions b) What is NBA?
c) Differentiate PO and CO.

What do you mean by the term “Programming for Problem Solving”?

 Solving problems is the core of computer science. Programmers must first understand
how a human solves a problem, then understand how to translate this "algorithm" into
something a computer can do, and finally how to "write" the specific syntax (required by
a computer) to get the job done. It is sometimes the case that a machine will solve a problem
in a completely different way than a human.
 Especially when it comes to programming, problem-solving is the must. If you do not
develop sound problem-solving skills, you will end up messing around with a given problem,
and you would not be able to obtain a solution for ages.
 Computer Programmers are problem solvers. In order to solve a problem on a computer
you must: Know how to represent the information (data) describing the problem &Determine
the steps to transform the information from one representation into another.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 6


Syllabus Unit Wise

Unit – 1 : (Introduction to Programming)


Introduction to components of a computer system: Memory, processor, I/O Devices,
storage, operating system, Concept of assembler, compiler, interpreter, loader and linker.
Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with
examples, From algorithms to programs, source code.
Programming Basics: Structure of C program, writing and executing the first C program,
Syntax and logical errors in compilation, object and executable code. Components of C
language.
Standard I/O in C, Fundamental data types, Variables and memory locations, Storage
classes.
Unit – 2 : (Arithmetic expressions & Conditional Branching)
Arithmetic expressions and precedence: Operators and expression using numeric and
relational operators, mixed operands, type conversion, logical operators, bit operations,
assignment operator, operator precedence and associativity.
Conditional Branching: Applying if and switch statements, nesting if and else, use of
break and default with switch.
Unit– 3 : (Loops )
Iteration and loops: use of while, do while and for loops, multiple loop variables, use of
break and continue statements.
Functions
Functions: Introduction, types of functions, functions with array, passing parameters to
functions, call by value, call by reference, recursive functions.
Unit – 4 : (Arrays & Basic Algorithms)
Arrays: Array notation and representation, manipulating array elements, using multi-
dimensional arrays. Character arrays and strings, Structure, union, enumerated data types,
Array of structures, passing arrays to functions.
Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and
Selection), Finding roots of equations, Notion of order of complexity.
Unit– 5 :( Pointer& File Handling)
Pointers: Introduction, declaration, applications, Introduction to dynamic memory
allocation (malloc, calloc, realloc, free), Use of pointers in self-referential structures, notion
of linked list (no implementation)
File handling: File I/O functions, Standard C preprocessors, defining and calling
macros, command-line arguments.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 7


Syllabus CO Wise

CO-1: To develop simple algorithms for arithmetic and logical problems.

Introduction of subject, Syllabus, CO, PO, teaching-learning strategy. Introduction to


components of a computer system: Memory, processor I/O Devices, storage operating system
Concept of assembler, compiler, interpreter, loader and linker. Idea of Algorithm:
Representation of Algorithm Flowchart, Pseudo code with examples, From algorithms to
programs, source code.

CO-2:To translate the algorithms to programs & execution (in C language).

Programming Basics: Structure of C Program Writing and executing the first C program,
Syntax and logical errors in compilation, object and executable code. Components of C
language. Standard I/O in C, Fundamental data types, Variables and memory locations,
Storage classes
Operators and expression using numeric and relational operators, mixed operands, Type
conversion Logical operators, bit operations, assignment operator, Operator precedence and
associativity.

CO-3: To implement conditional branching, iteration and recursion.

Applying if statement Applying switch statement Nesting if and else Use of break and
default with switch. Use of while, do while Use of for loops Multiple loop variables, use of
break and continue statements.

CO-4: To decompose a problem into functions and synthesize a complete program using
divide and conquer approach.

Functions: Introduction, Types of functions Passing parameters to functions, call by value


Call by reference Recursive functions. Functions with array

CO-5: To use arrays, pointers and structures to develop algorithms and programs.
Arrays: Array notation and representation, manipulating array elements Using multi-
dimensional arrays passing arrays to functions Character arrays and strings Structure Array
of structures Union, enumerated data types Basic Algorithms: Searching Basic Sorting
Algorithms (Bubble, Insertion) Selection Sorting Finding roots of equations, Notion of order
of complexity Pointers: Introduction, declaration, applications Introduction to dynamic
memory allocation (malloc, calloc, realloc, free) Use of pointers in self-referential structures
Notion of linked list (no implementation) File handling: File I/O functions File handling:
File I/O functions Standard C preprocessors Defining and calling macros, command-line
arguments

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 8


What is NBA?
 The National Board of Accreditation (NBA) is one of the two major bodies responsible
for accreditation of higher education institutions in India, along with the National Assessment and
Accreditation Council (NAAC).
 NBA accredits technical programmes, such engineering and management programmes, while
NAAC accredits general colleges and universities.
 NBA was established by the All India Council for Technical Education (AICTE) in 1994 and
operated as an autonomous body since 2010.
 In 2014 it was granted a full membership status in the Washington Accord.

 The NBA accredits programmes and not institutes.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 9


Course Outcome Vs Programme Outcome
CO Course Outcome(Statement)

CO1 To develop simple algorithms for arithmetic and logical problems.


CO2 To translate the algorithms to programs & execution (in C language).
CO3 To implement conditional branching, iteration and recursion.
CO4 To decompose a problem into functions and synthesize a complete program using
divide and conquer approach.
CO5 To use arrays, pointers and structures to develop algorithms and programs.)

PO Statement
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex computer engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 computer engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex computer engineering problems
and design system components or processes that meet the specific needs with appropriate
PO3
considerations for the public health and safety, and the cultural, societal, and environmental
considerations.

Conduct investigations of complex problems: Use research-based knowledge and research


PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide conclusions

Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent relevant to the professional
engineering practices
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norm
PO8
of the engineering practices
Individual and team work: Function effectively as an individual, and as a member or leader in
PO9
diverse teams, and in multidisciplinary settings
Communications: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
PO10
effective reports and design documentation, make effective presentations, and give and receive
clear instructions
Project management and finance: Demonstrate knowledge and understanding of the
PO11 engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life learning in the broadest context of technological change.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 10


Teaching Learning Strategy

Teaching-
 Syllabus coverage (including revisions and practice programs) through 52 online/offline
lectures
 Lecture Notes/PPT/Video Lectures will be provided just after the completion of lecture.
 Revision /Q & A sessions after each CO syllabus coverage.
 For fast learner’s initiation of project based learning. (As applicable)

Assessment-
 2 test (CAE-1 & CAE-2)
 5 Online /Offline quiz (CO wise)
 Teacher Assessment -10 Marks based on 5 CO wise assignment
 Attendance-10 Marks (Criteria- you`ll get 10 marks if attendance is more than 90%)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 11


Lecture Notes || Unit -1 || CO1 || Lecture Number-2

Topic Introduction to components of a computer system: Memory, Processor, I/O


Devices
CO Covered To develop simple algorithms for arithmetic and logical problems.
Lecture Objective To know about working and components of digital computer.
Lecture structure  Pre-requisite Keywords-Data, Information, Program, Software, Hardware
 Introduction to computer
 Explanation of working of digital computer using Block diagram
 Input Unit
 Storing
 Processing
 Output Unit
 Controlling
 Memory Organization
Related Questions (i) Explain working and components of digital computer with proper block diagram
in detail.
(ii) What do you mean by Memory Hierarchy?
Extra topics for fast Digital Vs analog,Motherboard,Memory organization,ASCII,History of
learners/Topics beyond computers,EBCDIC,ISO,UNICODE
syllabus

Pre-requisite keywords

Program-
A program can be defined as a collection of instructions written to perform any user`s defined task in
computer.
Data-
Any raw facts
Information-
Collection of data that has some meaning (Meaningful Data)
Hardware-
Computer hardware is a collective term used to describe any of the physical components of an analog or
digital computer.
Software-
Software commands the hardware what to do & how to do it. Together, the hardware & software form the
computer system. This software is further classified as system software & application software.
System Software-
System software are a set of programs, responsible for running the computer, controlling various operations
of computer systems and management of computer resources. They act as an interface between the hardware
of the computer & the application software. E.g.: Operating System.
Application software
Application Software is a set of programs designed to solve a particular problem for users. It allows the end
user to do something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 12


Introduction to computers

Right from its inception, to the present day, all computer system (irrespective of their shape & size)
perform the following 5 basic operations. It converts the raw input data into information, which is useful to
the users.
Input: It is the process of entering data & instructions to the computer system.
Storing: The data & instructions are stored for either initial or additional processing, as & when
required.
Processing: It requires performing arithmetic or logical operation on the saved data to convert it
into useful information.
Output: It is the process of producing the output data to the end user.
Controlling: The above operations have to be directed in a particular sequence to be completed.

Explanation of working of digital computer using Block diagram

Input Unit

We need to first enter the data & instruction in the computer system, before any computation begins.
This task is accomplished by the input devices. (The data accepted is in a human readable form. The input
device converts it into a computer readable form).
Input device: The input device is the means through which data and instructions enter in a computer.
1. Camera - The camera transmits a picture from one computer to another, or can be used to record a short
video.

2.Compact Disc (CD) - CDs store information. The CD can then be put into another computer, and the
information can be opened and added or used on the second computer. Note: A CD-R or CD-RW can also
be used as an OUTPUT device.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 13


3.Keyboard - The keyboard is a way to input letters or numbers into different applications or programs. A
keyboard also has special keys that help operate the computer.

4.Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of commands
(to tell the computer what to do) when using different applications.

5.Microphone - A microphone is used to record sound. The sound is then saved as a sound file on the
computer.

6.Scanner - A scanner is used to copy pictures or other things and save them as files on the computer.

7.Joystick - A joystick is used to move the cursor from place to place, and to click on various items in
programs. A joystick is used mostly for computer games.

8.Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The information is
then saved on the computer. Bar code scanners are used in libraries a lot.

Storing/Storage Unit

The data & instruction that are entered have to be stored in the computer. Similarly, the end results & the
intermediate results also have to be stored somewhere before being passed to the output unit. The storage
unit provides solution to all these issues. The storage unit is designed to save the initial data, the intermediate
result & the final result. They are of two types: Primary storage & Secondary storage.

Primary Storage:
The primary storage, also called as the main memory, holds the data when the computer is currently on.
As soon as the system is switched off or restarted, the information held in primary storage disappears (i.e. it
is volatile in nature). Moreover, the primary storage normally has a limited storage capacity, because it is
very expensive as it is made up of semiconductor devices.RAM is a primary storage.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 14


Secondary Storage:
The secondary storage, also called as the auxiliary storage, handles the storage limitation & the volatile
nature of the primary memory. It can retain information even when the system is off. It is basically used for
holding the program instructions & data on which the computer is not working on currently, but needs to
process them later.for example-

a. Magnetic Disk
The Magnetic Disk is Flat, circular platter with metallic coating that is rotated beneath read/write heads. It
is a Random access device; read/write head can be moved to any location on the platter.
b. floppy Disk
These are small removable disks that are plastic coated with magnetic recording material. Floppy disks
are typically 3.5″ in size (diameter) and can hold 1.44 MB of data. This portable storage device is a
rewritable media and can be reused a number of times. Floppy disks are commonly used to move files
between different computers. The main disadvantage of floppy disks is that they can be damaged easily and,
therefore, are not very reliable.
c.Hard disk
A hard disk consists of one or more rigid metal plates coated with a metal oxide material that allows data to
be magnetically recorded on the surface of the platters. The hard disk platters spin at a high rate of speed,
typically 5400 to 7200 revolutions per minute (RPM). Storage capacities of hard disks for personal
computers range from 10 GB to 120 GB (one billion bytes are called a gigabyte).

d.CD:
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold large
amount of information such as music, full-motion videos, and text etc. It contains digital information that
can be read, but cannot be rewritten. Separate drives exist for reading and writing CDs. Since it is a very

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 15


reliable storage media, it is very often used as a medium for distributing large amount of information to large
number of users.

e.DVD
Digital Versatile Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity.
Depending upon the disk type it can store several Gigabytes of data (as opposed to around 650MB of a CD).
DVDs are primarily used to store music or movies and can be played back on your television or the computer
too. They are not rewritable media. It’s also termed DVD (Digital Video Disk)

Processing

Central Processing Unit:

Together the Control Unit & the Arithmetic Logic Unit are called as the Central Processing Unit (CPU).
The CPU is the brain of the computer. Like in humans, the major decisions are taken by the brain itself &
other body parts function as directed by the brain. Similarly, in a computer system, all the major calculations
& comparisons are made inside the CPU. The CPU is responsible for activating & controlling the operation
of other units of the computer system.

Arithmetic Logic Unit:

The actual execution of the instructions (arithmetic or logical operations) takes place over here. The data
& instructions stored in the primary storage are transferred as & when required. No processing is done in the
primary storage. Intermediate results that are generated in ALU are temporarily transferred back to the
primary storage, until needed later. Hence, data may move from the primary storage to ALU & back again
to storage, many times, before the processing is done.

OutputUnit

The job of an output unit is just the opposite of an input unit. It accepts the results produced by the
computer in coded form. It converts these coded results to human readable form. Finally, it displays the
converted results to the outside world with the help of output devices (E.g.: monitors, printers, projectors
etc.).

Output device: Device that lets you see what the computer has accomplished.

1.Monitor - A monitor is the screen on which words, numbers, and graphics can be seem. The monitor is
the most common output device.

2.Compact Disk - Some compact disks can be used to put information on. This is called burning information
to a CD. NOTE: A CD can also be an input device.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 16


3.Printer - A printer prints whatever is on the monitor onto paper. Printers can print words, numbers, or
pictures.

4.Speaker - A speaker gives you sound output from your computer. Some speakers are built into the
computer and some are separate.

5.Headphones - Headphones give sound output from the computer. They are similar to speakers, except
they are worn on the ears so only one person can hear the output at a time.

Control Unit:

This unit controls the operations of all parts of the computer but does not carry out any actual data
processing. It is responsible for the transfer of data and instructions among other units of the computer. It
manages and coordinates all the units of the system. It also communicates with Input/Output devices for
transfer of data or results from the storage units.

Memory Organization in Computer


A memory unit is the collection of storage units or devices together. The memory unit stores the binary
information in the form of bits. Generally, memory/storage is classified into 2 categories:

 Volatile Memory: This loses its data, when power is switched off.
 Non-Volatile Memory: This is a permanent storage and does not lose any data when power is
switched off.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 17


The total memory capacity of a computer can be visualized by hierarchy of components. The memory
hierarchy system consists of all storage devices contained in a computer system from the slow Auxiliary
Memory to fast Main Memory and to smaller Cache memory.

Auxiliary memory access time is generally 1000 times that of the main memory, hence it is at the bottom
of the hierarchy.

The main memory occupies the central position because it is equipped to communicate directly with the
CPU and with auxiliary memory devices through Input/output processor (I/O).

When the program not residing in main memory is needed by the CPU, they are brought in from auxiliary
memory. Programs not currently needed in main memory are transferred into auxiliary memory to provide
space in main memory for other programs that are currently in use.

The cache memory is used to store program data which is currently being executed in the CPU.
Approximate access time ratio between cache memory and main memory is about 1 to 7~10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 18


Lecture Notes || Unit -1 || CO1 || Lecture Number-3

Topic Operating System


CO Covered To develop simple algorithms for arithmetic and logical problems.
Lecture Objective To learn definition of OS and it`s functionality
Lecture structure  Pre-requisite Keywords
 Definition & Importance of OS.
 Functions of OS
Related Questions i.Define Opreating System.Explain functions of OS in detail.
ii.“An OS acts as resource allocator” justify the statement.
Extra topics for fast Kernel, Android, OS, Linux, Virus, DOS, NOS, Device Drivers, DLL,
learners/Topics beyond Multiprogramming,Multitasking,Multiprocessor,Multithreading
syllabus

Pre-requisite keywords

Program-
A program is a set of instruction written to implement any task.
Process-
A program in execution is known as process.
File-
A file can be understood as a container in a computer system for storing information/data. Data/information
Network-
Computer network can be defined as the group of computers connected for the purpose of communicating
data from one computer to other.
Resources-
In computer, resources can be CPU, RAM, Input/Output devices, Processor.
Multiprogramming-
A computer running more than one program at a time (like running Excel and Firefox simultaneously).
Bug-
Bug is a logical error which generate wrong output.
Debugging-
Identification of bug is debugging.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 19


Definition & Importance of OS

An operating system (OS) is a collection of software that manages computer hardware resources and
provides common services for computer programs.

Functions of OS
Following are some of important functions of an operating System.

 Memory Management
 Processor Management
 Device Management
 File Management

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 20


 Security
 Control over system performance
 Job accounting
 Error detecting aids
 Coordination between other software and users

Memory Management
Memory management refers to management of Primary Memory or Main Memory. Main memory is a
large array of words or bytes where each word or byte has its own address.
Main memory provides a fast storage that can be accessed directly by the CPU. For a program to be
executed, it must in the main memory. An Operating System does the following activities for memory
management −
a. Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in
use.
b. In multiprogramming, the OS decides which process will get memory when and how much.
c. Allocates the memory when a process requests it to do so.
d. De-allocates the memory when a process no longer needs it or has been terminated.

Processor Management
In multiprogramming environment, the OS decides which process gets the processor when and for how
much time. This function is called process scheduling. An Operating System does the following activities
for processor management −

 Keeps tracks of processor and status of process. The program responsible for this task is
known as traffic controller.

 Allocates the processor (CPU) to a process.

 De-allocates processor when a process is no longer required.

Device Management
An Operating System manages device communication via their respective drivers. It does the following
activities for device management −

 Keeps tracks of all devices. Program responsible for this task is known as the I/O
controller.

 Decides which process gets the device when and for how much time.

 Allocates the device in the efficient way.

 De-allocates devices.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 21


File Management
A file system is normally organized into directories for easy navigation and usage. These directories may
contain files and other directions.
An Operating System does the following activities for file management −

 Keeps track of information, location, uses, status etc. The collective facilities are often
known as file system.

 Decides who gets the resources.

 Allocates the resources.

 De-allocates the resources.

Other Important Activities


Following are some of the important activities that an Operating System performs −
i.Security − By means of password and similar other techniques, it prevents unauthorized access
to programs and data.
ii.Control over system performance − Recording delays between request for a service and
response from the system.
iii.Job accounting − Keeping track of time and resources used by various jobs and users.
iv.Error detecting aids − Production of error messages, and other debugging and error detecting
aids.
v.Coordination between other softwares and users − Coordination and assignment of compilers,
interpreters, assemblers and other software to the various users of the computer systems.

Common services provided by an operating system −


 Program execution
 I/O operations
 File System manipulation
 Communication
 Error Detection
 Resource Allocation
 Protection

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 22


Lecture Notes || Unit -1 || CO1 || Lecture Number-4

Topic Idea of Algorithm: Representation of Algorithm, Pseudo code, Flowchart


CO Covered To develop simple algorithms for arithmetic and logical problems.
Lecture Objective To explore and learn the algorithm and pseudocode with examples
Lecture structure  Pre-requisite Keywords
 Algorithm with Example
 Characteristics of algorithm
 What is pseudocode?
 Examples of pseudocode
 Flowchart and its representation
Related Questions 1. Define algorithm. Also explain its characteristics.
2. Compare algorithm and pseudocode.
3. Write algorithm and draw flowchart for the following problems-
a. To calculate roots of quadratic equation
b. To find greatest number among three numbers.
c. To calculate the grades of any student
d. To calculate factorial of any given number
Extra topics for fast Design algorithms and draw flowchart for -a)To print Fibonacci Series up to nth term b) To
learners/Topics beyond print first 100 prime numbers c)To reverse digits of any given number
syllabus

Pre-requisite Keywords

Problem statement-
A problem statement is usually one or two sentences to explain the problem you are going to address
by programming.

Algorithm with Example

Algorithm:
It’s an organized logical sequence of the actions or the approach towards a particular problem. A
programmer implements an algorithm to solve a problem. Algorithms are expressed using natural
verbal but somewhat technical annotations.
Example: Algorithm to calculate factorial
1. Start
2. Input number N (for which we want to calculate factorial.)
3. Let M=1 and F=1.
4. F=F*M.
5. Is M=N?
6. If NO then M=M+1 and go to step 3.
7. If YES then output F
8. End

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 23


Characteristics of algorithm

Input specified-The input is the data to be transformed during the computation to produce the output. Input
precision requires that you know what kind of data, how much and what form the data should be required
for algorithm.

Output specified-The output is the data resulting from the computation (your intended result). Output
precision also requires that you know what kind of data, how much and what form the output should be (or
even if there will be any output at all!)

Definiteness-Each statement of algorithm should be clear, well defined and precise in nature.

Effectiveness-For an algorithm to be effective, it means that all those steps that are required to get to output
MUST BE DOABLE!

Finiteness-The algorithm should have sequence of finite instructions.

What is pseudocode?

Pseudo code:
a. It’s simply an implementation of an algorithm in the form of annotations and informative
text written in plain English. It has no syntax like any of the programming language and thus
can’t be compiled or interpreted by the computer.
b. Pseudocode is an artificial and informal language that helps programmers develop
algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool.
c. The rules of Pseudocode are reasonably straightforward. All statements showing
"dependency" are to be indented. These include while, do, for, if, switch. Examples below will
illustrate this notion.
d. It is a methodology that allows the programmer to represent the implementation of an
algorithm. Simply, we can say that it’s the cooked up representation of an algorithm.
e. Often at times, algorithms are represented with the help of pseudo codes as they can be
interpreted by programmers no matter what their programming background or knowledge is.
f. Pseudo code, as the name suggests, is a false code or a representation of code which can
be understood by even a layman with some school level programming knowledge.

Advantages of Pseudocode

 Improves the readability of any approach. It’s one of the best approaches to start implementation
of an algorithm.
 Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code is
written out. In industries, the approach of documentation is essential. And that’s where a pseudo-
code proves vital.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 24


 The main goal of a pseudo code is to explain what exactly each line of a program should do, hence
making the code construction phase easier for the programmer.

How to write a Pseudo-code?

 Arrange the sequence of tasks and write the pseudocode accordingly.


 Start with the statement of a pseudo code which establishes the main goal or the aim.
Example:
This program will allow the user to check

The number whether it's even or odd.

 The way the if-else, for, while loops are indented in a program, indent the statements likewise, as
it helps to comprehend the decision control and execution mechanism. They also improve the
readability to a great extent.
Example:

if "1"
print response
"I am case 1"

if "2"
print response
"I am case 2"
 Use appropriate naming conventions. The human tendency follows the approach to follow what we
see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the
naming must be simple and distinct.
 Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
 Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
 Check whether all the sections of a pseudo code is complete, finite and clear to understand and
comprehend.
 Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.
Examples of pseudocode

*For students: Can you guess for what purpose the following pseudocode has been written?
1.
If student's grade is greater than or equal to 60
Print "passed"
Else
Print "failed"

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 25


2.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.

3.
Initialize total to zero
Initialize counter to zero
Input the first grade
while the user has not as yet entered the sentinel
add this grade into the running total
add one to the grade counter
input the next grade (possibly the sentinel)
if the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
print 'no grades were entered'

4.
initialize passes to zero
initialize failures to zero
initialize student to one
while student counter is less than or equal to ten
input the next exam result
if the student passed
add one to passes
else
add one to failures
add one to student counter
print the number of passes
print the number of failures
if eight or more students passed
print "raise tuition"

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 26


Flowchart and its representation

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation can give
a step-by-step solution to a given problem.

Example: For factorial.

Advantages of Using Flowchart: -


Communication: - Flowcharts are better way of communicating the logic of a system to all
concerned.
Effective analysis: - With the help of flowchart, problem can be analyzed in more effective way.
Proper documentation: - Program flowcharts serve as a good program documentation, which is
needed for various purposes.
Efficient Program Maintenance: - The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part

Disadvantages of Using Flowchart: -


Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
Alterations and Modifications: - If alterations are required the flowchart may require re-drawing
completely.
Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem. The essentials of what is done can easily be lost in the technical details of how it is done.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 27


Some examples of flow chart and algorithm

1. Example: Calculate the Interest of a Bank Deposit

Algorithm:
(i) Step 1: Read amount,
(ii) Step 2: Read years,
(iii) Step 3: Read rate,
(iv) Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
(v) Step 5: Print interest,

Flowchart:

2. Example: Determine and Output Whether Number N is Even or Odd

Algorithm:
(i) Step 1: Read number N,
(ii) Step 2: Set remainder as N modulo 2,
(iii) Step 3: If remainder is equal to 0 then number N is even, else number N is odd,
(iv) Step 4: Print output.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 28


Flowchart:

3. Example: Determine Whether a Student Passed the Exam or Not:

Algorithm:
(i) Step 1: Input grades of 4 courses M1, M2, M3 and M4,
(ii) Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
(iii) Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 29


4. Draw flowchart to find the largest among three different numbers entered by user.

5. Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 30


6. Draw a flowchart to find the Fibonacci series till term≤1000.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 31


Lecture Notes || Unit -1 || CO2 || Lecture Number-5

Topic Programming Basics: Concept of assembler, compiler, interpreter, loader and linker
Structure of C program, First C program
CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of programing language translators and structure of C program
Lecture structure  Pre-requisite Keywords
 Programming Language Translators
 Structure of C Program
 First C program
Related Questions 1. Explain structure of a C program with example.
2. Explain following terms-a)Assembler b)Interpreter c)Loader d)Linker e)Compiler
Extra topics for fast History of computer languages, Compiler design issues, Types of compiler
learners/Topics beyond
syllabus

Pre-requisite Keywords

Computer Language-
 A language that is acceptable to a computer system is called a computer language or
programming language and the process of creating a sequence of instructions in such a language is
called programming or coding.
 A program is a set of instructions, written to perform a specific task by the computer. A set of large
program is called software. To develop software, one must have knowledge of a programming
language.
 Before moving on to any programming language, it is important to know about the various types
of languages used by the computer.
 Just as every language like English, Hindi has its own grammatical rules; every computer language
is also bounded by rules known as syntax of that language. The user is bound by that syntax while
communicating with the computer system.

Computer languages are broadly classified as:


a. Low Level Language:

The term low level highlights the fact that it is closer to a language which the machine
understands. The low level languages are classified as:
Machine Language:
This is the language (in the form of 0’s and 1’s, called binary numbers) understood
directly by the computer. It is machine dependent. It is difficult to learn and even more difficult
to write programs.
Assembly Language:
This is the language where the machine codes comprising of 0’sand 1’s are substituted
by symbolic codes (called mnemonics) to improve their understanding. It is the first step to
improve programming structure. Assembly language programming is simpler and less time

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 32


consuming than machine level programming, it is easier to locate and correct errors in assembly
language than in machine language programs. It is also machine dependent. Programmers must
have knowledge of the machine on which the program will run.

b.High Level Language:


a) Low level language requires extensive knowledge of the hardware since it is machine
dependent. To overcome this limitation, high level language has been evolved which uses normal
English, which is easy to understand to solve any problem. High level languages are computer
independent and programming becomes quite easy and simple. Various high level languages are
given below:
b) BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.
c) COBOL (Common Business Oriented language): A standardized language used for
commercial applications.
d) FORTRAN (Formula Translation): Developed for solving mathematical and scientific
problems. One of the most popular languages among scientific community.
e) C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
f) C++: Popular object oriented programming language, used for general purpose.

Programming Language Translators

 As you know that high level language is machine independent and assembly language though it is
machine dependent yet mnemonics that are being used to represent instructions are not directly
understandable by the machine. Hence to make the machine understand the instructions provided by
both the languages, programming language instructors are used.
 They transform the instruction prepared by programmers into a form which can be interpreted &
executed by the computer. Flowing are the various tools to achieve this purpose:

Compiler: The software that reads a program written in high level language and translates it into an
equivalent program in machine language is called as compiler. The program written by the programmer in
high level language is called source program and the program generated by the compiler after translation is
called as object program.

Interpreter: it also executes instructions written in a high level language. Both complier & interpreter have
the same goal i.e. to convert high level language into binary instructions, but their method of execution is
different. The complier converts the entire source code into machine level program, while the interpreter
takes 1 statement, translates it, executes it & then again takes the next statement.

Assembler: The software that reads a program written in assembly language and translates it into an
equivalent program in machine language is called as assembler.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 33


Linker: A linker or link editor is a computer program that takes one or more object files generated by a
compiler and combines them into a single executable file, library file, or another object file.

Structure of C Program

The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.

First C program
Based on the structure, we can sketch a C program.

Example:
/* this program accepts a number & displays it to the user*/
#include <stdio.h>
void main(void)
{
int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;
}

#include
The part of the compiler which actually gets your program from the source file is called the
preprocessor.

#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an
instruction to the compiler to make it do something. It tells the C compiler to include the contents of a
file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special place, by the
fact that the filename is enclosed in <> characters

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 34


<stdio.h>
stdio.h is the name of the standard library definition file for all Standard Input and Output functions.
Your program will almost certainly want to send information to the screen and read things from the
keyboard, and stdio.h is the name of the file in which the functions that we want to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in later by the
linker.
The ".h" portion of the filename is the language extension, which denotes an include file.

void
This literally means that this means nothing. In this case, it is referring to the function whose name
follows.Void tells to C compiler that a given entity has no meaning, and produces no error.

Main
In this particular example, the only function in the program is called main. A C program is typically
made up of large number of functions. Each of these is given a name by the programmer and they refer
to each other as the program runs.C regards the name main as a special case and will run this function
first i.e. the program execution starts from main. A parameter to a function gives the function something
to work on.

{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open
brace there must be a matching close one. Braces allow us to group pieces of program together, often
called a block. A block can contain the declaration of variable used within it, followed by a sequence of
program statements. In this case the braces enclose the working parts of the function main.

;( semicolon)
The semicolon marks the end of the list of variable names, and also the end of that declaration
statement.
All statements in C programs are separated by ";" (semicolon) characters. The ";" character is
actually very important. It tells the compiler where a given statement ends. If the compiler does not find
one of these characters where it expects to see one, then it will produce an error.

scanf
In other programming languages, the printing and reading functions are a part of the language. In C
this is not the case; instead they are defined as standard functions which are part of the language
specification, but are not a part of the language itself. The standard input/output library contains a
number of functions for formatted data transfer; the two we are going to use are scanf (scan formatted)
and printf (print formatted).

printf
The printf function is the opposite of scanf. It takes text and values from within the program and
sends it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is
described in the system file stdio.h.The first parameter to a printf is the format string, which contains
text, value descriptions and formatting instructions.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 35


Lecture Notes || Unit -1 || CO-2 || Lecture Number-6

Topic Compilation and Execution steps, Errors


CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of steps behind C program execution and types of errors
Lecture structure  Pre-requisite Keywords
 IDE Introduction
 Compilation and Execution steps
 Errors

Related Questions i. Explain Execution steps of any C program.


ii. Explain the types of errors occurred in an program

Extra topics for fast Explore Floating exception error,Parse error ,Implicit declaration error,Parsing
learners/Topics beyond
syllabus

Pre-requisite Keywords

Source File- This file contains the source code of the program. The file extension of any c file is .c.
The file contains C source code that defines the main function & maybe other functions.

Header File- A header file is a file with extension .h which contains the C function declarations and
macro definitions and to be shared between several source files.

Object File- An object file is a file containing object code, with an extension .obj, meaning relocatable
format machine code that is usually not directly executable. Object files are produced by an assembler,
compiler, or other language translator, and used as input to the linker, which in turn typically generates
an executable or library by combining parts of object files.

Executable File- The binary executable file is generated by the linker. The linker links the various
object files to produce a binary file that can be directly executed.

IDE Introduction

Integrated Development Environment or IDE for short is an application or software which


programmers use for programming. It helps a programmer to program easily by providing all
comprehensive facilities required for the development of software.

IDE can improve the productivity of a programmer or developer because of its fast setup and various
tools. Without this, a programmer takes a lot of time deciding various tools to use for their tasks.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 36


Mainly, an IDE includes 3 parts i.e. source code editor, build automation tool (compiler) and a
debugger.

The source code editor is something where programmers can write the code, whereas, build automation
tool is used by the programmers for compiling the codes and the debugger is used to test or debug the
program in order to resolve any errors in the code. Furthermore, these IDEs also comes with additional
features like object and data modeling, unit testing, source code library, and a lot more.
As a teacher I am going to use following IDE (Because this is the lab setup@GCET and you can
relate your learning easily)

But, you can use any one of the following integrated development environment (IDE) for C
programming-

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 37


Compilation and Execution steps
Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension. Which
is un-compiled (when written for the first time or whenever a change is made in it and saved).

Object code is the output of a compiler after it processes the source code. The object code is usually
a machine code, also called a machine language, which can be understood directly by a specific type
of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some
compilers are designed to convert source code into an assembly language or some other another
programming language.

An assembly language is a human-readable notation using the mnemonics (mnemonics


a symbolic name for a single executable machine language instruction called an opcode) in the ISA
(Instruction Set Architecture) of that particular CPU.

Executable (also called the Binary) is the output of a linker after it processes the object code. A
machine code file can be immediately executable (i.e., runnable as a program), or it might
require linking with other object code files (e.g. libraries) to produce a complete executable program.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 38


Types of Error

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

Type of errors

 Syntax errors:
Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This
compiler error indicates something that must be fixed before the code can be compiled. All these errors
are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
1. Missing Parenthesis (})
2. Printing the value of variable without declaring it
3. Missing semicolon like this:

// C program to illustrate // syntax error


#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}

Error:

error: expected ';' before '}'

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 39


Syntax of a basic construct is written wrong. For example : while loop

// C program to illustrate // syntax error


#include<stdio.h>
int main(void)
{
// while() cannot contain "." as an argument.
while(.)
{
printf("hello");
}
return 0;
}
Error:

error: expected expression before '.'


while(.)
In the given example, the syntax of while loop is incorrect. This causes a syntax error.

 Run-time Errors:
Errors which occur during program execution (run-time) after successful compilation are called
run-time errors. One of the most common run-time error is division by zero also known as Division
error. These types of error are hard to find as the compiler doesn’t point to the line at which the
error occurs.
For more understanding run the example given below.

// C program to illustrate // run-time error


#include<stdio.h>
void main()
{
int n = 9, div = 0;

// wrong logic // number is divided by 0, // so this program abnormally terminates


div = n/0;

printf("resut = %d", div);


}
Error:

warning: division by zero div = n/0;

In the given example, there is Division by zero error. This is an example of run-time error i.e errors
occurring while running the program.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 40


 Linker Errors:
These error occurs when after compilation we link the different object files with main’s object
using Ctrl+F9 key (RUN). These are errors generated when the executable of the program cannot be
generated. This may be due to wrong function prototyping, incorrect header files. One of the most
common linker error is writing Main() instead of main().

// C program to illustrate // linker error


#include<stdio.h>

void Main() // Here Main() should be main()


{
int a = 10;
printf("%d", a);
}
Error:
(.text+0x20): undefined reference to `main'

 Logical Errors:
On compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are called
logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.

// C program to illustrate // logical error


int main()
{
int i = 0;

// logical error : a semicolon after loop


for(i = 0; i < 3; i++);
{
printf("loop ");
continue;
}
getchar();
return 0;
}
No output

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 41


 Semantic errors :
This error occurs when the statements written in the program are not meaningful to the compiler.

// C program to illustrate // semantic error


void main()
{
int a, b, c;
a + b = c; //semantic error
}
Error
error: lvalue required as left operand of assignment a + b = c; //semantic error

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 42


Lecture Notes || Unit -1 || CO-2 || Lecture Number-7

Topic Components of C language , Fundamental Data Types, Variables and Memory locations,
Type Conversion
CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of different components of C language
Lecture structure  Components of C Language
 Fundamental Data Types
 Type Casting

Related Questions i. Explain different components of C Language in detail.


ii. Explain rules to construct constants.
iii. Explain different data types in terms of their size,range,and way of declaration.

Extra topics for fast Comparative analysis of components of C,C++,JAVA,Python


learners/Topics beyond
syllabus

Components of C language

Every language has some basic elements & grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language.

Character Set
Communicating with a computer involves speaking the language the computer understands. In C, various
characters have been given to communicate. Character set in C consists of;

Types Character Set


Lower case a-z
Upper case A-Z
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or space

Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning
to the keyword, which is not allowed by the computer. There are only 32 keywords available in C.
Below figure gives a list of these keywords for your ready reference.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 43


Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the first
being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any
numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the same as
using "index" and neither of them is the same as using "InDeX" for a variable. All three refer to different
variables.
2. As C is defined, up to 32 significant characters can be used and will be considered significant by
most compilers. If more than 32 are used, they will be ignored by the compiler.

Data Type
In the C programming language, data types refer to a domain of allowed values & the operations
that can be performed on those values. The type of a variable determines how much space it occupies
in storage and how the bit pattern stored is interpreted. There are 4 fundamental data types in C, which
are- char, int, float &, double. Char is used to store any single character; int is used to store any integer
value, float is used to store any single precision floating point number & double is used to store any
double precision floating point number.
We can use 2 qualifiers with these basic types to get more types.
Sign qualifier- signed & unsigned
Size qualifier- short & long
The data types in C can be classified as follows:

Type Storage size Value range


Char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
Integrity 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned integrity 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

Type Storage size Value range Precision


Float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places
double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places
long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 44


Constants
A constant is an entity that doesn’t change whereas a variable is an entity that may change constants can be
divided into two major categories: Primary Constants, Secondary Constants

Rules for Constructing Integer Constants:


 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can be either positive or negative.
 If no sign precedes an integer constant it is assumed to be positive.
 No commas or blanks are allowed within an integer constant
 The allowable range for integer constants is -32768to 32767.
 Ex.: 426, +782,-8000, -7605

Rules for Constructing Real Constants:


 Real constants are often called Floating Point constants. The real constants could be written in two
forms—Fractional form and Exponential form.
 A real constant must have at least one digit.
 It must have a decimal point.
 It could be either positive or negative.
 Default sign is positive.
 No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -48.5792

Rules for constructing real constants expressed in exponential form:


 The mantissa part and the exponential part should be separated by a letter e.
 The mantissa part may have a positive or negative sign.
 Default sign of mantissa part is positive.
 The exponent must have at least one digit, which must be a positive or negative integer. Default
sign is positive.
 Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 45


 Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5

Rules for Constructing Character Constants:


A character constant is a single alphabet, a single digit or a single special symbol enclosed within single
inverted commas.The maximum length of a character constant can be 1 character.Ex.: ‘M’, ‘6’, ‘+’

Variables-
Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. Variable
declaration requires that you inform C of the variable's name and data type.
Syntax – data type variable name;
Eg:int page_no;
char grade;
float salary;
long y;

Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various examples:

Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If we
want we can assign some initial value to the variables during the declaration itself. This is called
initialization of the variable.
Eg-int pageno=10;

Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation a
== b - logical operation
func (a,b) – function call

Statements
Statements are the primary building blocks of a program. A program is a series of statements with
some necessary punctuation. A statement is a complete instruction to the computer. In C, statements
are indicated by a semicolon at the end. a semicolon is needed to identify instructions that truly are
statements.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 46


Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens −

printf("Hello, World! \n");


The individual tokens are −

printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the following statement −

int age;
There must be at least one whitespace character (usually a space) between int and age for the compiler to
be able to distinguish them. On the other hand, in the following statement −

fruit = apples + oranges; // get the total fruit


No whitespace characters are necessary between fruit and =, or between = and apples, although you are free
to include some if you wish to increase readability.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 47


Type casting

Type casting /type conversion is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then you can typecast
long to int.
You can convert values from one type to another explicitly using the cast operator. There are two
types of type casting in c languages that are implicit conversions and Explicit Conversions.
New data type should be mentioned before the variable name or value in brackets which to be
typecast.

Example-
In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done before
division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf(“%f”,x);
}
Output:
1.400000

Types of typecasting in C
Implicit Conversion
Explicit Conversion
Implicit Conversion
Implicit conversions do not require any operator for converted. They are automatically performed when
a value is copied to a compatible type in the program.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 48


printf(“implicit value is %d”,p);
getch();}

Output:-
implicit value is 20.

Explicit Conversion
In C language, Many conversions, especially those that imply a different interpretation of the value,
require an explicit conversion.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
short p;
clrscr();
p = (short) i; // Explicit conversion
printf(“Explicit value is %d”,p);
getch();
}
Output:-
Explicit value is 20.

Usual Arithmetic Conversion


The usual arithmetic conversions are implicitly performed to cast their values in a common type,
C uses the rule that in all expressions except assignments, any implicit type conversions made from
a lower size type to a higher size type as shown below:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 49


Inbuilt Typecast Functions in C:
There are many inbuilt type casting functions available in C language which performs data type
conversion from one type to another.

S.No Typecast Function Description


1 atof() Convert string to Float
2 atoi() Convert string to int
3 atol() Convert string to long
4 itoa() Convert int to string
5 ltoa() Convert long to string

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 50


Lecture Notes || Unit -1 || CO-2 || Lecture Number-8

Topic Standard I/O in C


CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of different Standard Input and output methods in C
Lecture structure  What is library functions?
 Working of scanf () and printf function
 Working of getchar () and putchar () function
 Working of gets () and puts () function
 Use of format specifier and escape sequences in formatting the input and output

Related Questions i. What do you mean by formatted input output in C Language?


ii. Explain the working of different standard input output method/functions with proper
examples.

Extra topics for fast Explore getc(),putc(),fprintf(),fscanf(),fgets(),fputs()


learners/Topics beyond
syllabus

Standard I/O in C

When we say Input, it means to feed some data into a program. An input can be given in the form of a file
or from the command line. C programming provides a set of built-in functions to read the given input and
feed it to the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in any file. C programming
provides a set of built-in functions to output the data on the computer screen as well as to save it in text or
binary files.

The Standard Files


C programming treats all the devices as files. So devices such as the display are addressed in the same way
as files and the following three files are automatically opened when a program executes to provide access
to the keyboard and screen.

File
Standard File Device
Pointer
Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen

The getchar() and putchar() Functions


The int getchar(void) function reads the next available character from the screen and returns it as an integer.
This function reads only single character at a time. You can use this method in the loop in case you want to
read more than one character from the screen.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 51


The int putchar(int c) function puts the passed character on the screen and returns the same character. This
function puts only single character at a time. You can use this method in the loop in case you want to display
more than one character on the screen. Check the following example −

#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads only a single character and displays it as follows −

Enter a value: this is test


You entered: t

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).

The int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing newline to stdout.

#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −

Enter a value : this is test

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 52


You entered: this is test

The scanf() and printf() Functions


The int scanf(const char *format, …) function reads the input from the standard input stream stdin and
scans that input according to the format provided.

The int printf(const char *format, …) function writes the output to the standard output stream stdout and
produces the output according to the format provided.

The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings,
integer, character or float respectively. There are many other formatting options available which can be
used based on requirements. Let us now proceed with a simple example to understand the concepts better -

#include <stdio.h>
int main( ) {

char str[100];
int i;

printf( "Enter a value :");


scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it as follows −

Enter a value : seven 7


You entered: seven 7

Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which
means you have to provide valid inputs like “string integer”. If you provide “string string” or “integer
integer”, then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as
soon as it encounters a space, so “this is test” are three strings for scanf().

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 53


Formatted Input and Output-
Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.

#include<stdio.h>
int main()
{printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right
justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation (scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 54


Lecture Notes || Unit -1 || CO-2 || Lecture Number-9

Topic Storage Classes


CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To explore and understand the storage classes
Lecture structure  Memory Vs CPU Registers
 Initial value of variable, Scope
 Importance of storage class
 Automatic storage class
 Static storage class
 Register storage class
 Extern storage class
Related Questions i. Explain the terms-scope, initial value of any variable, visibility, life of variable.
ii. What is storage class? Explain importance of storage class in programming.
iii. Explain different types of storage classes with programming examples.

Extra topics for fast CPU registers,Microprocessors,Types of CPU registers,Cost of CPU registers
learners/Topics beyond
syllabus

Storage classes

Generally, there are two kinds of locations in a computer where such a value can be present, these are Memory
and CPU registers. The storage class of a particular variable determines in which of the above two locations
the variable’s value is stored.
There are four properties by which storage class of a variable can be recognized. These are scope, default
initial value, scope and life.
A variable’s storage class reveals the following things about a variable
(i) Where the variable is stored.
(ii) What is the initial value of the variable if the value of the variable is not specified?
(iii) What is the scope of the variable (To which function or block the variable is available)?
(iv) What is the life of particular variable (Up to what extent the variable exists in a program)?

In c there are four types of storage class. They are: 1. Auto 2. Register 3. Static 4. Extern

Visibility of a variable in c:
Visibility means accessibility. Up to witch part or area of a program, we can access a variable, that
area or part is known as visibility of that variable. For example: In the following figure yellow color
represents visibility of variable a.
Scope of a variable in c:
Meaning of scope is to check either variable is alive or dead. Alive means data of a variable has not
destroyed from memory. Up to which part or area of the program a variable is alive, that area or part
is known as scope of a variable. There are four type of scope in c:
1. Block scope.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 55


2. Function scope.
3. File scope.
3. Program scope.

Automatic Storage Class


Syntax to declare automatic variable is:
auto datatype variablename;

Example:
auto int i;

Features of Automatic Storage Class are as follows


Storage: Memory
Default Initial Value: Garbage Value
Scope: Local to the block in which the variable is defined
Life: Till the control remains within the block in which the variable is defined by default every variable is automatic
variable
The following program illustrates the work of automatic variables.
void test();
void main()
{
test();
test();
test();
}
void test()
{
auto int k=10;
printf(“%d\n”,k);
k++;
}
Output:
10
10
10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 56


In the above program when the function test() is called for the first time ,variable k is created and initialized
to 10. When the control returns to main(), k is destroyed. When function test() is called for the second time again
k is created , initialized and destroyed after execution of the function. Hence automatic variables came into
existence each time the function is executed and destroyed when execution of the function completes.

Register Storage Class


Syntax to declare register variable is:
register datatype variablename;

Features of Register Storage Class are as follows:


Storage: CPU Registers
Default Initial Value: Garbage Value
Scope: Local to the block in which the variable is defined
Life: Till the control remains within the block in which the variable is defined

For example loop counters are declared as register variables, which are defined as follows:
int main()
{
register int a;
for(a=0;i<50000;i++)
printf(“%d\t”,a);
return 0;

In the above program, variable a was used frequently as a loop counter so the variable a is defined as a
register variable. Register is a not a command but just a request to the compiler to allocate the memory for the
variable into the register. If free registers are available than memory will be allocated in to the registers. And if
there are no free registers then memory will be allocated in the RAM only (Storage is in memory i.e. it will act
as automatic variable).

Every type of variables can be stored in CPU registers. Suppose the microprocessor has 16 bit registers then
they can’t hold a float or a double value which requires 4 and 8 bytes respectively.But if you use register storage
class for a float or double variable then you will not get any error message rather the compiler will treat the float
and double variable as be of automatic storage class(i.e. Will treat them like automatic variables).

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 57


Static Storage Class
Syntax to declare static variable is:
static datatype variablename;
Example:
static int i;

Features of Static Storage Class are as follows


Storage: Memory
Default Initial Value: Zero
Scope: Local to the block in which the variable is defined
Life: Value of the variable continues to exist between different function calls

Now look at the previous program with k is declared as static instead of automatic.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int k=10;
printf(“%d\n”,k);
k++;
}

Output:10 11 12
Here in the above program the output is 10, 11, 12, because if a variable is declared as static then it is
initialized only once and that variable will never be initialized again. Here variable k is declared as static, so
when test() is called for the first time k value is initialized to 10 and its value is incremented by 1 and becomes
11. Because k is static its value persists. When test() is called for the second time k is not reinitialized to 10
instead its old value 11 is available. So now 11 is get printed and it value is incremented by 1 to become 12.
Similarly, for the third time when test() is called 12(Old value) is printed and its value becomes 13 when executes
the statement ‘k++;’

So the main difference between automatic and static variables is that static variables are initialized to zero if
not initialized but automatic variables contain an unpredictable value(Garbage Value) if not initialized and static
variables does not disappear when the function is no longer active , their value persists, i.e. if the control comes
back to the same function again the static variables have the same values they had last time.

General advice is avoid using static variables in a program unless you need them, because their values are
kept in memory when the variables are not active which means they occupies space in memory that could
otherwise be used by other variables.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 58


External Storage Class
Syntax to declare static variable is:
extern datatype variablename;
Example:
extern int i;

Features of External Storage Class are as follows


Storage: Memory
Default Initial Value: Zero
Scope: Global
Life: Till the program’s execution doesn’t come to an end
External variables differ from automatic, register and static variables in the context of scope, external
variables are global on the contrary automatic, register and static variables are local. External variables are
declared outside all functions, therefore are available to all functions that want to use them.
If the program size is very big then code may be distributed into several files and these files are compiled
and object codes are generated. These object codes linked together with the help of linker and generate “.exe”
file. In the compilation process if one file is using global variable but it is declared in some other file then it
generates error called undefined symbol error. To overcome this we need to specify global variables and global
functions with the keyword extern before using them into any file. If the global variable is declared in the middle
of the program then we will get undefined symbol error, so in that case we have to specify its prototype using
the keyword extern.

So if a variable is to be used by many functions and in different files can be declared as external variables.
The value of an uninitialized external variable is zero. The declaration of an external variable declares the type
and name of the variable, while the definition reserves storage for the variable as well as behaves as a declaration.
The keyword extern is specified in declaration but not in definition. Now look at the following four statements

1. auto int a;
2. register int b;
3. static int c;
4. extern int d;
Out of the above statements first three are definitions where as the last one is a declaration.

Suppose there are two files and their names are File1.c and File2.c respectively. Their contents are as
follows:
File1.c
int n=10;
void hello()
{
printf(“Hello”);
}
File2.c
extern int n;
extern void hello();

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 59


void main()
{printf(“%d”, n);
hello();}

In the above program File1.obj+ File2.obj=File2.exe and in File2.c value of n will be 10.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 60


Lecture Notes || Unit -2 || CO-2 || Lecture Number-10

Topic Types of Operators


CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To explore different types of operators used in C language
Lecture structure  Arithmatic Operator
 Relational Operator
 Logical Operator
 Bitwise Operator
 Assignment Operator
 Increment /Decrement Operator
 Conditional Operator
 Sizeof operator
 Comma operator
 Address of operator

Related Questions i. Explain different types of operators with proper examples.


ii.Explain Bitwise operators in detail.
iii.Explain Logical operators with proper examples.

Extra topics for fast Examples of increment and decrement (Pre/Post) operators on different IDEs.
learners/Topics beyond Working of Bitwise operators via program
syllabus

Operators-
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Types are-

Arithmetic operator: Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A – B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by one A–will give 9

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 61


Relational Operators:
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition (A == B) is not true.
becomes true.
!= Checks if the values of two operands are equal or not, if values are not equal (A != B) is true.
then condition becomes true.
> Checks if the value of left operand is greater than the value of right operand, (A>B) is true.not
if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right (A >= B) is not (A >=
operand, if yes then condition becomes true. B) is not
<= Checks if the value of left operand is less than or equal to the value of right (A <= B) is true.
operand, if yes then condition becomes true.

Logical Operators:
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND operator. If both the operands are nonzero, then condition (A && B)
becomes true. is
false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then condition (A || B) is
becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a !(A && B)
condition is true then Logical NOT operator will make false. is true.

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. These operators can operate upon int
and char but not on float and double..Bit wise operators in C language are; & (bitwise AND), | (bitwise
OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).The truth tables for &, |, and ^ are as
follows:
P Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 62


Assume variable A holds 60 (00111100) and variable B holds 13 (00001101), then:

Operator Description Example


Binary AND Operator copies a bit to the result if it (A & B) will give 12,
& exists in both operands. which is 0000 1100
Binary OR Operator copies a bit if it exists in either (A | B) will give 61,
| operand. which is 0011 1101
Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49,
^ one operand but not both. which is 0011 0001
(~A ) will give -61, which
Binary Ones Complement Operator is unary and has is 1100 0011 in 2’s
~ the effect of ‘flipping’ bits. complement form.
Binary Left Shift Operator. The left operands value
is moved left by the number of bits specified by the A << 2 will give 240
<< right operand. which is 1111 0000
Binary Right Shift Operator. The left operands
value is moved right by the number of bits specified A >> 2 will give 15
>> by the right operand. which is 0000 1111

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 63


Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.There are following
assignment operators supported by C language:
Operator Description Example
C = A + B will
Simple assignment operator, Assigns values from right side assign value of A +
= operands to left side operand B into C
C += A is
Add AND assignment operator, It adds right operand to the equivalent to C = C
+= left operand and assign the result to left operand +A
Subtract AND assignment operator, It subtracts right C -= A is
operand from the left operand and assign the result to left equivalent to C = C
-= Operand –A
Multiply AND assignment operator, It multiplies right C *= A is
operand with the left operand and assign the result to left equivalent to C = C
*= Operand *A
C /= A is
Divide AND assignment operator, It divides left operand equivalent to C = C
/= with the right operand and assign the result to left operand /A
C %= A is
Modulus AND assignment operator, It takes modulus using equivalent to C = C
%= two operands and assign the result to left operand %A
C <<= 2 is same as
<<= Left shift AND assignment operator C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator C = C >> 2
C &= 2 is same as
&= Bitwise AND assignment operator C=C&2
C ^= 2 is same as C
^= bitwise exclusive OR and assignment operator =C^2
C |= 2 is same as C
|= bitwise inclusive OR and assignment operator =C|2

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 64


Increment/Decrement OPERATOR
In C, ++ and – are called increment and decrement operators respectively. Both of these operators are unary
operators, i.e, used on single operand. ++ adds 1 to operand and – subtracts 1 to operand respectively. For
example:
Let a=5 and b=10
a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++
is used as postfix(like: var++), operator will return the value of operand first and then only increment it.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{int c=2,d=2;
printf(“%d\n”,c++); //this statement displays 2 then, only c incremented by 1 to 3.
Printf(“%d”,++c); //this statement increments 1 to c then, only c is displayed.
Return 0;
}
Output:2 4

Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different statements
according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false expression2
is returned.
y = ( x> 5 ? 3 : 4 ) ;this statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

Misc Operators:
There are few other operators supported by c language.
Operator Description Example
It is a unary operator which is used in
finding the size of data type, constant, sizeof(a), where a is integer, will
sizeof() arrays, structure etc. return 4.
&a; will give actual address of
& Returns the address of a variable. the variable.
* Pointer to a variable. *a; will pointer to a variable.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 65


Lecture Notes || Unit -2 || CO-2 || Lecture Number-11

Topic Operator Precedence and Associativity & Solving Expressions


CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To know about precedence of different operators in C language and to understand the
concept of associativity by solving some examples.
Lecture structure  Operator Precedence in C language
 Solving Expressions Example 1
 Solving Expressions Example 2

Related Questions 1. What do you mean by operator precedence and associativity? Explain with examples.
2. What will be the output of the following code?
void main( )
{
int a=5,b=6,c;
c=a++>b&&++b<10||b++;
printf("%d%d%d",a,b,c);
}
3. If int a = 2 , b = 3, x = 0; Find the value of x = (++a, b+=a).
4. Find the value of Y (assume Y is integer data type) Y=4 * 2 / 4 – 6 /2 + 3 % 2 *
6 / 2 + 2 > 2 && 4 != 2.
5. Find the output of the statement printf("%d%d%d",n++,++n,--n);if n=3.
Extra topics for fast Solve at least 10 example of expression solving which includes logical
learners/Topics beyond operator,bitwise operator, assignment operator from any book or from internet.
syllabus

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.For Example-

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 66


Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 67
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 68


Example 1: Let age = 10, height = 45 solve the following expression for K-
K= (age < 12 && height < 48) || (age > 65 && height > 72)

Solution: In this case, the order of evaluation of operators will be parentheses ( () ), relational operators
(<, >), AND ( && ) operator, OR ( || ) operator.

(age < 12 && height < 48) || (age > 65 && height > 72)
1
=> (10 < 12 && 45 < 48) || (10 > 65 && 45 > 72)
2
=> (1 && 1) || (10 > 65 && 45 > 72)
3
=> 1 || (10 > 65 && 45 > 72)
4
=> 1 || (0 && 0)
5
=> 1 || 0
6
=> 1
7

Example 2: Let year = 2000 solve the following expression for K-


K= (year % 4 == 0 && year % 100! = 0 ) || (year % 400 == 0)

Solution: In this case, the order of evaluation of operators will be parentheses ( () ), Modular division
(%), Relational operators (==, !=) AND ( && ) operator, OR ( || ) operator.

(year % 4 == 0 && year % 100 != 0 ) || (year % 400 == 0)


1
=> (2000 % 4 == 0 && 2000 % 100 != 0 ) || (2000 % 400 == 0)
2
=> (0 == 0 && 2000 % 100 != 0 ) || (2000 % 400 == 0)
3
=> (0 == 0 && 0 != 0 ) || (2000 % 400 == 0)
4
=> (1 && 0 != 0 ) || (2000 % 400 == 0)
5
=> (1 && 0 ) || (2000 % 400 == 0)
6
=> 0 || (2000 % 400 == 0)
7
=> 0 || (0 == 0)
8
=> 0 || 1
9
=> 1
10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 69


Lecture Notes || Unit -2 || CO-3 || Lecture Number-12

Topic Branching: Applying if ,if-else and nested if statements with examples


CO Covered To implement Conditional Branching,Iteration and Recursion
Lecture Objective To explore the Branching /Selection statements in C language
Lecture structure  Control Statements need and importance
 Branching Statement-If
 Branching Statement-If-else
 Branching Statement-If-else nesting

Related Questions 1. What is the purpose of control statements in C language.?


2. When we use selection statements in C language?
3.Explain selection statements in terms of their syntax with proper examples.
4.Check whether given year is leap year or not by C program.
Extra topics for fast 1.Write a C program to compare three numbers to get max number using nested if
learners/Topics beyond structure.
syllabus 2.Write a C program to identify location of any point on 2D system if coordinates are
given using if-else ladder construct.

Control Statements-
Control statements enable us to specify the order in which the various instructions in the program are to be
executed. They define how the control is transferred to other parts of the program. Control statements are
classified in the following ways:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 70


a) If statement
Syntax:

if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code after the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:

Example:
#include <stdio.h>
int main ()
{ int a = 10;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
Printf("value of a is : %d\n", a);
}
When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 71


(b) if –else statement
Syntax: The syntax of an if...else statement in C programming language is:

if(boolean_expression)
{ /* statement(s) will execute if the boolean expression is true */
}
else
{ /* statement(s) will execute if the boolean expression is false */
}

If the Boolean expression evaluates to true then the if block of code will be executed otherwise else
block of code will be executed programming language assumes any non-zero and non-null values
as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:

Example:
#include <stdio.h>
main ()
{ int a = 100;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
else
{ Printf("a is not less than 20\n" );
} Printf("value of a is : %d\n", a);}
When the above code is compiled and executed, it produces following result:
a is not less than 20;
value of a is : 100

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 72


(c) Nested if-else statement
The syntax for a nested if statement is as follows:

if( boolean_expression 1)
{ /* Executes when the Boolean expression 1 is true */
if(boolean_expression 2)
{ /* Executes when the Boolean expression 2 is true */
}
}
Example:
#include <stdio.h>
main ()
{ int a = 100;
int b = 200;
if( a == 100 )
{ if( b == 200 )
{ printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 73


Lecture Notes || Unit -2 || CO-3 || Lecture Number-13

Topic Branching-Applying switch statement, Use of Break & Default


CO Covered To implement Conditional Branching,Iteration and Recursion
Lecture Objective To design menu driven programs using switch statements in C language.
Lecture structure  Switch Statement need and importance
 Example of switch statement

Related Questions 1. What is the purpose of switch statement in C language.?


2. When we use default section in switch construct?
3. Explain the working of break statement with example.
Extra topics for fast Design a menu driven program to handle activities of a library.
learners/Topics beyond
syllabus

A switch statement
Allows a variable to be tested for equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each switch case.
Syntax:
switch(expression)
{ case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement:


 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the switch, and it
must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 74


 A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is needed in
the default case.

Flow Diagram:

Example:
main ()
{ char grade = 'B';
switch(grade)
{ case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
} printf("Your grade is %c\n", grade );
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 75


Lecture Notes || Unit -3 || CO-3 || Lecture Number-14

Topic Iteration- Loops (While, do while,for,multiple loop variable)


CO Covered To implement Conditional Branching,Iteration and Recursion
Lecture Objective To learn different iterative/looping constructs
Lecture structure  Importance of iterative statements
 While loop
 Do-While loop
 For loop
 Nested for loop
 Multiple loop variable
 Jump Statements

Related Questions 1. Why we use iterative statements?


2. What are difference between while and do-while loop?
3. Explain the working of break statement with example.
4. Explain jump statements with example.
5. Write program for following-
a. To check any number is perfect or not?
b. To check any number is palindrome or not?
c. To print Fibonacci series up to nth term
d. To reverse the digits of any number
e. To calculate factorial of any number

Extra topics for fast 1.Write a C program to count and print prime numbers within given range.
learners/Topics beyond 2.Write a C program to convert a 10 base number into 2 base number.(Binary)
syllabus

Program Loops and Iteration A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the programming languages:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 76


(a) Uses of while loop
A while loop statement in C programming language repeatedly executes a target statement as long as a given
condition is true.
Syntax:
while(condition)
{ statement(s);
}
Here statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true.When the condition becomes false,
program control passes to the line immediately following the loop. Flow Diagram:

Example:
#include <stdio.h>
main ()
{ int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 77


(b) Do-while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming language checks its condition at the bottom of the loop. A do...while loop is similar to a while
loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:
do
{ Statement;
} while ( condition );
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again.
This process repeats until the given condition becomes false. Flow Diagram:

Example:
#include <stdio.h>
main ()
{ int a = 10;
do
{ printf("value of a: %d\n", a);
a = a + 1;
} while ( a < 20 );
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 78


(c) For loops
for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times. Syntax:
for ( initialization ; condition; increment )
{ statement(s);
}
Flow Diagram:

Example:
#include <stdio.h>
main ()
{ for( int a = 10; a < 20; a = a + 1 )
{ printf("value of a: %d\n", a);
}
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 79


Nested for Loop in C
Nesting of loop is also possible. Lets take an example to understand this:

#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:

0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In the above example we have a for loop inside another for loop, this is called nesting of loops. One of the
example where we use nested for loop is Two dimensional array.

Multiple initialization inside for Loop in C

We can have multiple initialization in the for loop as shown below.

for (i=1,j=1;i<10 && j<10; i++, j++)

What’s the difference between above for loop and a simple for loop?

1. It is initializing two variables. Note: both are separated by comma (,).


2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot use
multiple test conditions separated by comma, you must use logical operator such as && or || to join
conditions.
3. It has two variables in increment part. Note: Should be separated by comma.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 80


Example of for loop with multiple test conditions

#include <stdio.h>
int main()
{
int i,j;
for (i=1,j=1 ; i<3 || j<5; i++,j++)
{
printf("%d, %d\n",i ,j);
}
return 0;
}

Jump statements

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. C supports the following
control statements.
(i) Break statement: Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch. The break statement in C programming
language has following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.

Syntax:
Break;
Flow Diagram:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 81


Example:
#include <stdio.h>
main ()
{ int a = 10;
while( a < 20 )
{ printf("value of a: %d\n", a);
a++;
if( a > 15)
{ break;
}
}
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

(ii) Continue statement: Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating. The continue statement in C programming language works
somewhat like the break statement. Instead of forcing termination, however, continue forces the
next iteration of the loop to take place, skipping any code in between. Syntax: continue;

Flow Diagram:

Example:
#include <stdio.h>
main ()
{ int a = 10;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 82


do
{ if( a == 15)
{ a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(iii) Goto Statement: Transfers control to the labeled statement. Though it is not advised to use
goto statement in your program A goto statement in C programming language provides an
unconditional jump from the goto to a labeled statement in the same function. Syntax:
goto label;
label: statement;

Flow Diagram:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 83


Example:
#include <stdio.h>
main ()
{ int a = 10;
LOOP: do
{ if( a == 15)
{ a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 84


Lecture Notes || Unit -3 || CO-4 || Lecture Number-15

Topic Functions Basics: Introduction ,Types of functions


CO Covered To decompose a problem into functions and synthesize a complete program using divide and
conquer approach.
Lecture Objective To understand basics of modular programming
Lecture structure  Function-Inbuilt Vs User Defined
 Monolithic Vs Modular Programming: Advantage and Disadvantage
 Function Declaration/Prototyping, Definition, Calling
 Function Categories

Related Questions 1. Write advantages and disadvantages of modular programming.


2. Explain categories of function with examples.
3. What do you mean by prototyping in context of function?
Extra topics for fast Explore the working of function in terms of memory utilization.
learners/Topics beyond
syllabus

Monolithic Vs Modular Programming-


1. Monolithic Programming indicates the program which contains a single function for the large
program.
2. Modular programming helps the programmer to divide the whole program into different Units and
each Unit is separately developed and tested. Then the linker will link all these Units to form the
complete program.
3. On the other hand, monolithic programming will not divide the program and it is a single thread of
execution. When the program size increases it leads inconvenience and difficult to maintain.

Disadvantages of monolithic programming:


1. Difficult to check error on large programs.
2. Difficult to maintain.
3. Code can be specific to a particular problem. i.e. it cannot be reused.

Advantage of modular programming:


1. Modular program are easier to code and debug.
2. Reduces the programming size.
3. Code can be reused in other programs.
4. Problem can be isolated to specific Unit so easier to find the error and correct it.

Function-
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main (), and all the most trivial programs can define additional functions.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 85


Function Declaration OR Function Prototype:
3. It is also known as function prototype.
4. It informs the computer about the three things
Name of the function
Number and type of arguments received by the function.
Type of value return by the function

Syntax:
return type function name (type1 arg1 , type2 arg2);
OR
return type function name (type1 type2);
1. Calling function need information about called function. If called function is place before calling
function, then the declaration is not needed.

Function Definition:
2. It consists of code description and code of a function. It consists of two parts
Function header
Function coding

Function definition tells what the I/O functions are and what is going to do.
Syntax:
return type function name (type1 arg1 , type2 arg2)
{local variable; statements ;
return (expression);
}

Function definition can be placed anywhere in the program but generally placed after the main
function.Local variable declared inside the function is local to that function. It cannot be used anywhere in
the program and its existence is only within the function.Function definition cannot be nested.Return type
denote the type of value that function will return and return type is optional if omitted it is assumed to be
integer by default.

User Defined Function:


A function that is declare, calling and define by the user is called user define function. Every user define
function has three parts as:
1. Prototype or Declaration
2. Calling
3. Definition

Function Categories-
There are four main categories of the functions these are as follows:
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 86


Function with no arguments and no return values:
syntax:
void funct (void); main ( )
{
funct ( );
}
void funct ( void );
{
}

Function with no arguments and a return value:


This type of functions has no arguments but a return value
example:
int msg (void) ; int main ( )
{
int s = msg ( );
printf( “summation = %d” , s);
}
int msg ( void )
{
int a, b, sum ; sum = a+b ; return (sum) ;
}

Function with arguments and no return values:


Example:
void msg ( int , int );
int main ( )
{
int a,b;
a= 2; b=3; msg( a, b);
}
void msg ( int a , int b)
{
int s ;
sum = a+b;
printf (“sum = %d” , s ) ;
}

Function with arguments and return value:


Here calling function of arguments that passed to the called function and called function return value to
calling function.
example:
int msg ( int , int ) ;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 87


int main ( )
{
int a, b;
a= 2; b=3;
int s = msg (a, b);
printf (“sum = %d” , s ) ;
}
int msg( int a , int b)
{
int sum ;
sum =a+b ; return (sum);
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 88


Lecture Notes || Unit -3 || CO-4 || Lecture Number-16

Topic Passing Parameters -Call by Value


CO Covered To decompose a problem into functions and synthesize a complete program using divide and
conquer approach.
Lecture Objective To learn function calling method-Call by Value
Lecture structure  Actual Vs Formal arguments
 Parameter passing methods
 Call by value Example

Related Questions 1. Differentiate formal arguments and actual arguments.


2. Explain call by value method of function calling with proper example.
Extra topics for fast Design user defined functions to implement different types of operators learned in
learners/Topics beyond previous lectures. Say a ‘mult’ named function is able to multiply two numbers given
syllabus by the user.

Actual Arguments:
1. Arguments which are mentioned in the function in the function call are known as calling function.
2. These are the values which are actual arguments called to the function.
Formal Arguments:
a) Arguments which are mentioned in function definition are called dummy or formal argument.
b) These arguments are used to just hold the value that is sent by calling function.
c) Formal arguments are like other local variables of the function which are created when function
call starts and destroyed when end function.

Basic difference between formal and local argument are:


 Formal arguments are declared within the ( ) where as local variables are declared at beginning.
 Formal arguments are automatically initialized when a value of actual argument is passed.
 Where other local variables are assigned variable through the statement inside the function body.

Parameter Passing methods-

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 89


There are two ways to pass value or data to function in C language which is given below;
 call by value
 call by reference

Call by value
In call by value, original value can not be changed or modified. In call by value, when you passed
value to the function it is locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function only but it not change the
value of variable inside the caller method such as main().
// C program to illustrate
// call by value

#include

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b);

printf("a=%d b=%d\n", a, b);

return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y)
{
int t;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 90


t = x;
x = y;
y = t;

printf("x=%d y=%d\n", x, y);


}

Output:
x=20 y=10
a=10 b=20

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 91


Lecture Notes || Unit -3 || CO-4 || Lecture Number-17

Topic Passing Parameters -Call by Reference


CO Covered To decompose a problem into functions and synthesize a complete program using divide and
conquer approach.
Lecture Objective To learn function calling method-Call by Reference
Lecture structure  Pointer brief introduction
 & and * operator
 Example of Call by Reference

Related Questions 1. Differentiate Call by Value and Call by Reference method of function calling.
2. Explain call by reference method of function calling with proper example.
Extra topics for fast Pointer,Address Mapping,Importance of pointer,Risks while using pointers
learners/Topics beyond
syllabus

Call by reference
In call by reference, original value is changed or modified because we pass reference (address). Here,
address of the value is passed in the function, so actual and formal arguments shares the same address
space. Hence, any value changed inside the function, is reflected inside as well as outside the function.

Difference between call by value and call by reference.

call by value call by reference

This method copy address of


This method copy original value
arguments into function as a
into function as a arguments.
arguments.

Changes made to the parameter


Changes made to the parameter
affect the argument. Because
inside the function have no effect on
address is used to access the actual
the argument.
argument.

Actual and formal arguments Actual and formal arguments


will be created in different memory will be created in same memory
location location

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 92


Example-
// C program to illustrate
// Call by Reference

#include

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b);

printf("a=%d b=%d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y)
{
int t;

t = *x;
*x = *y;
*y = t;

printf("x=%d y=%d\n", *x, *y);


}

Output:
x=20 y=10
a=20 b=10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 93


Lecture Notes || Unit -3 || CO-4 || Lecture Number-18

Topic Recursion and Recursive Functions


CO Covered To decompose a problem into functions and synthesize a complete program using divide and
conquer approach.
Lecture Objective To learn concept of recursion and working of recursive functions
Lecture structure  What is Recursion?
 Advantage and disadvantage of recursion
 Example of recursion

Related Questions i. Write C program to calculate factorial of any number using recursion.
ii. Write a C program to print terms of Fibonacci series up to given term.

Extra topics for fast Stack overflow,Infix/Prefix notation,Recursive function`s behavior in context of
learners/Topics beyond memory
syllabus

Recursion
When Function is call within same function is called Recursion. The function which calls same function
is called recursive function. In other word when a function calls itself then that function is
called Recursive function.

How recursion works?

void recurse()
{ ... .. ...
recurse();
... .. ...
}
int main()
{ ... .. ...
recurse();
... .. ...
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 94


Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Output

Enter a positive integer:3


sum = 6

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 95


Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 96
Advantage of Recursion
a) Function calling related information will be maintained by recursion.
b) Stack evaluation will be take place by using recursion.
c) In fix prefix, post-fix notation will be evaluated by using recursion.

Disadvantage of Recursion
1. It is a very slow process due to stack overlapping.
2. Recursive programs can create stack overflow.
3. Recursive functions can create as loops.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 97


Lecture Notes || Unit -4 || CO-5 || Lecture Number-19

Topic Single Dimensional Arrays : Notation, Manipulation


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To learn basics of array and understand the processing of single dimension array
Lecture structure  What is an array?
 One dimensional array –declaration
 One dimensional array –initialization
 One dimensional array –processing
 Example-Finding Max value in a given array

Related Questions 1. How to declare an array? Explain about various operations of an array.
2. Write a ‘C’ program to read in 10 integers and print their average, minimum and
maximum numbers.
Extra topics for fast Data structure,Derived data types
learners/Topics beyond
syllabus

Introduction
 A data structure is the way data is stored in the machine and the functions used to access that data.
An easy way to think of a data structure is a collection of related data items.
 An array is a data structure that is a collection of variables of one type that are accessed through a
common name.
 Each element of an array is given a number by which we can access that element which is called
an index. It solves the problem of storing a large number of values and manipulating them.
 In an Array values of same type are stored. An array is a group of memory locations related by the
fact that they all have the same name and same type. To refer to a particular location or element in
the array we specify the name to the array and position number of particular element in the array.

One Dimensional Array


Declaration:
Before using the array in the program it must be declared
Syntax:
data_type array_name[size];

data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.

Example:
int age[100];
float sal[15];
char grade[20];

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 98


Here age is an integer type array, which can store 100 elements of integer type. The array sal is floating type
array of size 15, can hold float values. Grade is a character type array which holds 20 characters.

Initialization:
We can explicitly initialize arrays at the time of declaration.
Syntax:
data_type array_name[size]={value1, value2,……..valueN};

Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements
one after another.

Example:
int marks[5]={10,2,0,23,4};

The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0,
marks[3]=23, marks[4]=4

Note-:
 In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the
compiler assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here
the size of array marks is initialized to 5.
 We can’t copy the elements of one array to another array by simply assigning it. Example:

int a[5]={9,8,7,6,5}; int b[5];


b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++) b[i]=a[i];

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 99


Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements present in
the array and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{
printf(“%d”,a[i]);
printf(“\n”);
}
}
This program reads and displays 3 elements of integer type.

C program to find the largest element in an array


#include<stdio.h>
int main()
{ int a[50],size,i,big;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d elements in to the array: ”, size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<size;i++)
{ if(big<a[i])
big=a[i];
}
printf("\nBiggest: %d",big);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 100


Lecture Notes || Unit -4 || CO-5 || Lecture Number-20

Topic Multi-Dimensional Array :Notation ,Manipulation


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To learn basics of array and understand the processing of two dimensional array
Lecture structure  Two dimensional array
 2D Array-Declaration
 2D Array-Initialization
 2D Array-Processing
 Example-Sum of two Matrices

Related Questions i. Write C program to multiply two matrices of 3x3 order


ii. Write a program to check whether a square matrix is symmetric or not.

Extra topics for fast Explore multidimensional array


learners/Topics beyond Write a program in C to read 5X5 matrix using array and calculate product of diagonal
syllabus elements

Two Dimensional Arrays-

Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come
naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.

Declaration:
The syntax is same as for 1-D array but here 2 subscripts are used.
Syntax:
data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows
Columnsize specifies the no.of columns.

Example:
int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the
array is a[3][4] and total no.of elements is 4*5=20.

Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example:
int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
The values are assigned as follows:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 101


Note:
In 2-D arrays it is optional to specify the first dimension but the second dimension should always be present.
Example: int m[][3]={
{1,10},
{2,20,200},
{3}, {4,40,400} };
Here the first dimension is taken 4 since there are 4 roes in the initialization list. A 2-D array is known as matrix.

Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop
indicates the columns.
Example:
int a[4][5];

Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);

Examples:1.Matrix addition in c language


#include<stdio.h>
int main()
{ int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix->");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n");
for(i=0;i<3;i++)
{ printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
printf("\nThe Second matrix is\n");
for(i=0;i<3;i++)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 102


{ printf("\n");
for(j=0;j<3;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++)
{ printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return 0;
}

Algorithm: Addition of two matrixes:

Rule: Addition of two matrixes is only possible if both matrixes are of same size. Suppose two
matrixes A and B is of same size m X n
Sum of two marixes is defined as
(A + B)ij = Aij + Bij
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n
For example:
Suppose two matrixes A and B of size of 2 X 3 is as follow:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 103


Example 2.C code for matrix multiplication
#include<stdio.h>
int main()
{ int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
printf("\nEnter the row and column of first matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the row and column of second matrix");
scanf("%d %d",&o,&p);
if(n!=o)
{ printf("Matrix mutiplication is not possible");
printf("\nColumn of first matrix must be same as row of second matrix");
}
else{
printf("\nEnter the First matrix->");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->");
for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n");
for(i=0;i<m;i++)
{ printf("\n");
for(j=0;j<n;j++)
{ printf("%d\t",a[i][j]);
}
}
printf("\nThe Second matrix is\n");
for(i=0;i<o;i++)
{ printf("\n");
for(j=0;j<p;j++)
{ printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
for(j=0;j<p;j++)
c[i][j]=0;
for(i=0;i<m;i++)
{ //row of first matrix
for(j=0;j<p;j++)
{ //column of second matrix
sum=0;
for(k=0;k<n;k++)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 104


sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{ printf("\n");
for(j=0;j<p;j++)
{ printf("%d\t",c[i][j]);
}
}
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 105


Lecture Notes || Unit -4 || CO-5 || Lecture Number-21

Topic Array and Functions


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To explore the methods of passing array as a parameter to a user defined function.
Lecture structure  Revisiting function-CBV and CBR
 Passing individual array element to a function-CBV
 Passing individual array element to a function-CBR
 Passing whole 1D array to a function-CBR

Related Questions i. Write a user defined function that receives an array of 10 elements and return the
biggest element of that array.
ii. Write a user defined function that accept 10 integer element, count the number of
prime numbers and return the total number of prime numbers present in that array.

Extra topics for fast *Passing array using pointers


learners/Topics beyond * Write a program to create an integer array of n elements, pass this array as an argument to a
syllabus
function where it is sorted and displayed.

Passing individual array elements to a function-CBV

As we already know in this type of function call, the actual parameter is copied to the formal parameters.

#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}
Output:a b c d e f g h i j

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 106


Passing individual array elements to a function-CBR
When we pass the address of an array while calling a function then this is called function call by
reference. When we pass an address as an argument, the function declaration should have a pointer as a
parameter to receive the passed address.

#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}

return 0;
}
Output:1 2 3 4 5 6 7 8 9 0

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 107


How to pass an entire array to a function as an argument?

In the above example, we have passed the address of each array element one by one using a for loop in C.
However you can also pass an entire array to a function like this:

Note: The array name itself is the address of first element of that array. For example if array name is arr
then you can say that arr is equivalent to the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}

int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:

Value of var_arr[0] is: 11


Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 108


Lecture Notes || Unit -4 || CO-5 || Lecture Number-22

Topic Strings
CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the the concept of string in C language
Lecture structure  What is string?
 Fundamentals of string
 How to read string in C language?
 How to write string in C language?
 Some predefined functions used in string manipulations

Related Questions i. Write a program in C that reads the two strings of length at least 7, then concatenate
these strings.
ii. Explain at least 6 predefined function used in handling strings in C language.
Extra topics for fast *Design user defined function to copy string.
learners/Topics beyond *Design user defined function co concatenate two strings.
syllabus

String Fundamentals-
A string is a series of characters treated as a single unit. A string may include letters, digits and various
special characters such as +, -, *, / and $. String literals or string constants in C are written in double
quotation marks as follows:
“1000 Main Street” (a street address)

“(080)329-7082” (a telephone number)


“Kalamazoo, New York” (a city)

In C language strings are stored in array of char type along with null terminating character ‘\0’ at the end.
When sizing the string array we need to add plus one to the actual size of the string to make space for the
null terminating character, ‘\0’.

syntax:
char fname[4];

The above statement declares a string called fname that can take up to 3 characters. It can be indexed just
as a regular array as well.
fname[]={‘t’,’w’,’o’};

Generalized syntax is:-


char str[size];
when we declare the string in this way, we can store size-1 characters in the array because the last character
would be the null character.
For example,

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 109


char mesg[10]; can store maximum of 9 characters.

If we want to print a string from a variable, such as four name string above we can do this.
e.g., printf(“First name:%s”,fname);

We can insert more than one variable. Conversion specification %s is used to insert a string and then go to
each %s in our string, we are printing.

A string is an array of characters. Hence it can be indexed like an array.

char ourstr[6] = “EED”;


– ourstr[0] is ‘E’
– ourstr[1] is ‘E’
– ourstr[2] is ‘D’
– ourstr[3] is ‘\0’
– ourstr[4] is ‘\0’
– ourstr[5] is ‘\0’

Reading strings:
If we declare a string by writing
char str[100];
then str can be read from the user by using three ways;
Using scanf() function
The string can be read using scanf() by writing scanf(“%s”,str);
Although the syntax of scanf() function is well known and easy to use, the main pitfall with this
function is that it terminates as soon as it finds a blank space. For example, if the user enters
Hello World, then str will contain only Hello. This is because the moment a blank space is
encountered, the string is terminated by the scanf() function.
Example:
char str[10];
printf(“Enter a string\n”); scanf(“%s”,str);

Using gets() function


The next method of reading a string a string is by using gets() function. The string can be read by
writing
gets(str);

gets() is a function that overcomes the drawbacks of scanf(). The gets() function takes the starting
address of the string which will hold the input. The string inputted using gets() is automatically
terminated with a null character.
Example:
char str[10];
printf(“Enter a string\n”); gets(str);

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 110


Using getchar(), getch(), or getche() function repeatedly

The string can also be read by calling the getchar() repeatedly to read a sequence of single
characters (unless a terminating character is encountered) and simultaneously storing it in a character array
as follows:

int i=0;
char str[10],ch;
getchar(ch);
while(ch!=’\0’)
{
str[i]=ch; // store the read character in str
i++;
getch(ch); // get another character
}
str[i]=’\0’; // terminate str with null character

Writing string

Using printf () function


The string can be displayed using pintf() by writing printf(“%s”,str);

We can use width and precision specification along with %s. The width specifies the minimum output field
width and the precision specifies the maximum number of characters to be displayed. Example:

printf(“%5.3s”,str);

this statement would print only the first three characters in a total field of five charaters; also these three
characters are right justified in the allocated width.

Using puts() function


The next method of writing a string is by using the puts() function. The string can be displayed by writing:
puts(str);

It terminates the line with a newline character (‘\n’). It returns an EOF(-1) if an error occurs and returns a
positive number on success.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 111


Using putchar() function repeatedly
Finally the string can be written by calling the putchar( ) function repeatedly to print a sequence of single
characters.

int i=0;
char str[10];
while(str[i]!=’\0’)
{putchar(str[i]); // print the character on the screen
i++;
}

Example: Read and display a string


#include<stdio.h>
#include<conio.h> void main()
{char str[20]; clrscr();
printf(“\n Enter a string:\n”); gets(str);
scanf(“The string is:\n”); puts(str);
getch(); }

Type Method Description


char strcpy(s1, s2) Copy string
char strcat(s1, s2) Append string
int strcmp(s1, s2) Compare 2 strings
int strlen(s) Return string length
char strchr(s, int c) Find a character in string
char strstr(s1, s2) Find string s2 in string s1

strcpy():
It is used to copy one string to another string. The content of the second string is copied to the content of
the first string.
Syntax:
strcpy (string 1, string 2);
Example:
char mystr[10];
mystr = “Hello”; // Error! Illegal !!! Because we are assigning the value to mystr which is not possible in
case of an string. We can only use "=" at declarations of C-String.
strcpy(mystr, “Hello”);
It sets value of mystr equal to “Hello”.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 112


strcmp():
It is used to compare the contents of the two strings. If any mismatch occurs then it results the difference
of ASCII values between the first occurrence of 2 different characters.
Syntax:
int strcmp(string 1, string 2);
Example:
char mystr_a[10] = “Hello”; char mystr_b[10] = “Goodbye”;
– mystr_a == mystr_b; // NOT allowed! The correct way is
if (strcmp(mystr_a, mystr_b ))
printf ("Strings are NOT the same."); else
printf( "Strings are the same.");
Here it will check the ASCII value of H and G i.e, 72 and 71 and return the diference 1.

strcat():
It is used to concatenate i.e, combine the content of two strings.
Syntax:
strcat(string 1, string 2);
Example:
char fname[30]={“bob”};
char lname[]={“by”};
printf(“%s”, strcat(fname,lname));
Output:
bobby.

strlen():
It is used to return the length of a string.
Syntax:
int strlen(string);

Example:
char fname[30]={“bob”};
int length=strlen(fname);
It will return 3

strchr():
It is used to find a character in the string and returns the index of occurrence of the character for the first
time in the string.
Syntax:
strchr(cstr);
Example:
char mystr[] = "This is a simple string";
char pch = strchr(mystr,‘s’);

The output of pch is mystr[3]

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 113


strstr():
It is used to return the existence of one string inside another string and it results the starting index of the
string.
Syntax:
strstr(cstr1, cstr2);
Example:
Char mystr[]="This is a simple string";
char pch = strstr(mystr, “simple”);
here pch will point to mystr[10]

String input/output library functions

Function prototype Function description


Inputs the next character from the
int getchar(void); standard input and returns it as integer
Prints the character stored in c and
int putchar(int c); returns it as an integer
Prints the string s followed by new line
character. Returns a non-zero integer if
int puts( char s); possible or EOF if an error occurs
Equivalent to printf,except the output is
stored in the array s instead of printed in
the screen. Returns the no.of characters
int sprint(char s, char format,….) written to s, or EOF if an error occurs

Equivalent to scanf, except the input is


read from the array s rather than from
the keyboard. Returns the no.of items
successfully read by the function , or
int sprint(char s, char format,….) EOF if an error occurs

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 114


Lecture Notes || Unit -4 || CO-5 || Lecture Number-23

Topic Structure, Array of structures ,Self-referential structures


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the concept of structure and it`s use
Lecture structure  Requirement of structure
 Definition of structure
 Structure Declaration
 Structure Initialization
 Structure access
 Arrays of structure
 Self-referential structures

Related Questions i.Write a program using structures to read and display the information about an employee.
ii.Write a program to read, display, add and subtract two complex numbers.
iii.Write a program to enter two points and then calculate the distance between them.
iv.Write a program to define a structure named employee having empid, name and
designation. Use this structure to store the data in a file named "employee.dat. Once all the
records are entered display the employee details stored in a file.
v.Create the database of students in C having the following attributes: Roll_no, Stud_name,
Stud_address; Stud_city, Stud_PINCode, Stud_Semester, Rank, and Branch. Also write the
program in C to enter the data for 100 students in any order and then display the list of
students for a given branch and Semester on display.
Extra topics for fast Develop structures for Library Management System,Hostel Management System,Hospital
learners/Topics beyond Management System
syllabus

Definition
A Structure is a user defined data type that can store related information together. The variable within a
structure are of different data types and each has a name that is used to select it from the structure. C arrays
allow you to define type of variables that can hold several data items of the same kind but structure is
another user defined data type available in C programming, which allows you to combine data items of
different kinds.

Structures are used to represent a record; suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book:
1. Title
2. Author
3. Subject
4. Book ID

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 115


Structure Declaration-
It is declared using a keyword struct followed by the name of the structure. The variables of the structure
are declared within the structure.
Example:
Struct struct-name
{
data_type var-name;
data_type var-name;
};

Structure Initialization-
Assigning constants to the members of the structure is called initializing of structure.
Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};

Accessing the Members of a structure-


A structure member variable is generally accessed using a ‘.’ operator.
Syntax: strcut_var. member_name;
The dot operator is used to select a particular member of the structure. To assign value to the individual
Data members of the structure variable stud, we write, stud.roll=01;
stud.name=”Rahul”;
To input values for data members of the structure variable stud, can be written as, scanf(“%d”,&stud.roll);
scanf(‘’%s”,&stud.name);
To print the values of structure variable stud, can be written as: printf(“%s”,stud.roll);
printf(“%f”,stud.name);

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 116


Array of Structures in C

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a
collection of elements of the same type. In an array of structures, each element of an array is of the
structure type.

Let's take an example:

struct car
{
char make[20];
char model[30];
int year;
};

Here is how we can declare an array of structure car.

struct car arr_car[10];

Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to
store 10 structure variables of type struct car. To access individual elements we will use subscript notation
([]) and to access the members of each element we will use dot (.) operator as usual.

arr_stu[0] : points to the 0th element of the array.


arr_stu[1] : points to the 1st element of the array.

and so on. Similarly,

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 117


arr_stu[0].name : refers to the name member of the 0th element of the array.
arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the array.
arr_stu[0].marks : refers to the marks member of the 0th element of the array.

Recall that the precedence of [] array subscript and dot(.) operator is same and they evaluates from left to
right. Therefore in the above expression first array subscript([]) is applied followed by dot (.) operator.
The array subscript ([]) and dot(.) operator is same and they evaluates from left to right. Therefore in the
above expression first [] array subscript is applied followed by dot (.) operator.

Initializing Array of Structures

We can also initialize the array of structures using the same syntax as that for initializing arrays. Let's take
an example:

struct car
{
char make[20];
char model[30];
int year;
};
struct car arr_car[2] = {
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 118


Lecture Notes || Unit -4 || CO-5 || Lecture Number-24

Topic Union, Enumerated data types


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the concept of Union, Enumerated data types
Lecture structure  Union
 Enumeration

Related Questions i-Explain working of union with example


ii-Explain working of enumeration with example
iii- Write a program to define a union and a structure both having exactly the same members.
Using the sizeof operator, print the size of structure variable as well as union variable and
comment on the result.
Extra topics for fast Search - practical examples of union and enumeration
learners/Topics beyond
syllabus

Union-
Union is a collection of variables of different data types, in case of union information can only be stored In
one field at any one time.

A union is a special data type available in C that enables you to store different data types in the same
memory location.

You can define a union with many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.

Declaring Union
union union-name
{
data_type var-name;
data_type var-name;
};

The union tag is optional and each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you
can specify one or more union variables but it is optional.

Here is the way you would define a union type named Data which has the three members i, f, and str. Now,
a variable of Data type can store an integer, a floating-point number, or a string of characters. This means
that a single variable ie. same memory location can be used to store multiple types of data. You can use any
built-in or user defined data types inside a union based on your requirement.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 119


The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in above example Data type will occupy 20 bytes of memory space because this is the maximum
space which can be occupied by character string. Following is the example which will display total memory
size occupied by the above union:
Accessing a Member of a Union
#include <stdio.h>
#include <string.h>
union Data
{int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}

Enumerated Types
Enumerations are integer types that you define in a program. The definition of an enumeration begins with
the keyword enum, possibly followed by an identifier for the enumeration, and contains a list of the type's
possible values, with a name for each value:
enum [identifier] { enumerator-list };

The following example defines the enumerated type enum color:


enum color { black, red, green, yellow, blue, white=7, gray };

The identifier color is the tag of this enumeration. The identifiers in the listblack, red, and so onare the
enumeration constants , and have the type int. You can use these constants anywhere within their scopeas
case constants in a switch statement, for example.

Each enumeration constant of a given enumerated type represents a certain value, which is determined
either implicitly by its position in the list, or explicitly by initialization with a constant expression. A
constant without an initialization has the value 0 if it is the first constant in the list, or the value of the
preceding constant plus one. Thus in the previous example, the constants listed have the values 0, 1, 2, 3,
4, 7, 8.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 120


Within an enumerated type's scope, you can use the type in declarations:
enum color bgColor = blue, // Define two variables
fgColor = yellow; // of type enum color.
void setFgColor( enum color fgc ); // Declare a function with a parameter
// of type enum color.

An enumerated type always corresponds to one of the standard integer types. Thus your C programs
may perform ordinary arithmetic operations with variables of enumerated types. The compiler may
select the appropriate integer type depending on the defined values of the enumeration constants. In the
previous example, the type char would be sufficient to represent all the values of the enumerated type
enum color.Different constants in an enumeration may have the same value:
enum { OFF, ON, STOP = 0, GO = 1, CLOSED = 0, OPEN = 1 };

As the preceding example also illustrates, the definition of an enumerated type does not necessarily have to
include a tag. Omitting the tag makes sense if you want only to define constants, and not declare any
variables of the given type. Defining integer constants in this way is generally preferable to using a long
list of #define directives, as the enumeration provides the compiler with the names of the constants as well
as their numeric values.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 121


Lecture Notes || Unit -4 || CO-5 || Lecture Number-25

Topic Basic Algorithms: Searching


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To know about searching methods and learn program
Lecture structure  Searching
 Searching Techniques
 Sequential Searching
 Binary Searching

Related Questions i-What do you mean by searching? Explain types of searching


ii-Write algorithm and C code to demonstrate linear searching in detail.
iii- Write algorithm and C code to demonstrate binary searching in detail.
Extra topics for fast Search-Practical utilization of searching techniques used in real life/software/program.
learners/Topics beyond
syllabus

What is Searching?
 Searching is the process of finding a given value position in a list of values.
 It decides whether a search key is present in the data or not.
 It is the algorithmic process of finding a particular item in a collection of items.
 It can be done on internal data structure or on external data structure.

Searching Techniques
To search an element in a given array, it can be done in following ways:

1. Sequential Search
2. Binary Search

Sequential Search
 Sequential search is also called as Linear Search.
 Sequential search starts at the beginning of the list and checks every element of the list.
 It is a basic and simple search algorithm.
 Sequential search compares the element with all the other elements given in the list. If the element is
matched, it returns the value index, else it returns -1.

The above figure shows how sequential search works. It searches an element or value from an array till
the desired element or value is not found. If we search the element 25, it will go step by step in a sequence

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 122


order. It searches in a sequence order. Sequential search is applied on the unsorted or unordered list when
there are fewer elements in a list.

The following code snippet shows the sequential search operation:

function searchValue(value, target)


{
for (var i = 0; i < value.length; i++)
{
if (value[i] == target)
{
return i;
}
}
return -1;
}
searchValue([10, 5, 15, 20, 25, 35] , 25); // Call the function with array and number to be searched

Example: Program for Sequential Search


#include <stdio.h>
int main()
{
int arr[50], search, cnt, num;
printf("Enter the number of elements in array\n");
scanf("%d",&num);
printf("Enter %d integer(s)\n", num);
for (cnt = 0; cnt < num; cnt++)
scanf("%d", &arr[cnt]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (cnt = 0; cnt < num; cnt++)
{
if (arr[cnt] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, cnt+1);
break;
}
}
if (cnt == num)
printf("%d is not present in array.\n", search);
return 0;
}
Output:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 123


Binary Search
 Binary Search is used for searching an element in a sorted array.
 It is a fast search algorithm with run-time complexity of O(log n).
 Binary search works on the principle of divide and conquer.This searching technique looks for a
particular element by comparing the middle most element of the collection.
 It is useful when there are large number of elements in an array.

 The above array is sorted in ascending order. As we know binary search is applied on sorted lists
only for fast searching.For example, if searching an element 25 in the 7-element array, following figure
shows how binary search works:

Binary searching starts with middle element. If the element is equal to the element that we are searching
then return true. If the element is less than then move to the right of the list or if the element is greater
than then move to the left of the list. Repeat this, till you find an element.

Example: Program for Binary Search


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

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 124


void main()
{ int f, l, m, size, i, sElement, list[50]; //int f, l ,m : First, Last, Middle
clrscr();
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values : \n", size);
for (i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter value to be search: ");
scanf("%d", &sElement);
f = 0;
l = size - 1;
m = (f+l)/2;
while (f <= l) {
if (list[m] < sElement)
f = m + 1;
else if (list[m] == sElement) {
printf("Element found at index %d.\n",m);
break;
}
else
l = m - 1;
m = (f + l)/2;
}
if (f > l)
printf("Element Not found in the list.");
getch();
}

Output:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 125


Lecture Notes || Unit -4 || CO-5 || Lecture Number-26

Topic Basic Sorting Algorithms: Bubble Sort


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand basic sorting method-Bubble Sort
Lecture structure  What is sorting?
 Types of Sorting
 Bubble sort working
 Bubble sort code

Related Questions i-What do you mean by sorting? Explain types of sorting


ii-Differentiate searching and sorting.
iii- Write algorithm and C code to demonstrate Bubble Sorting in detail.
Extra topics for fast Search-Practical utilization of sorting techniques used in real life/software/program.
learners/Topics beyond
syllabus

Sorting-
Sorting is nothing but storage of data in sorted order, it can be in ascending or descending order. The term
Sorting comes into picture with the term Searching. There are so many things in our real life that we need
to search, like a particular record in database, roll numbers in merit list, a particular telephone number,
any particular page in a book etc.

Sorting Efficiency
There are many techniques for sorting. Implementation of particular sorting technique depends upon
situation. Sorting techniques mainly depends on two parameters. First parameter is the execution time of
program, which means time taken for execution of program.Second is the space, which means space taken
by the program.

Types of Sorting-
An internal sort is any data sorting process that takes place entirely within the main memory of a
computer. This is possible whenever the data to be sorted is small enough to all be held in the main
memory.

External sorting is a term for a class of sorting algorithms that can handle massive amounts of data.
External sorting is required when the data being sorted do not fit into the main memory of a computing
device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive).
External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small
enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the
sorted sub files are combined into a single larger file.

We can say a sorting algorithm is stable if two objects with equal keys appear in the same order in sorted
output as they appear in the input unsorted array.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 126


Bubble Sort

Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for eg: an Array
with N number of elements. Bubble Sort compares all the element one by one and sort them based on their
values.

It is called Bubble sort, because with each iteration the smaller element in the list bubbles up towards the
first place, just like a water bubble rises up to the water surface.

Sorting takes place by stepping through all the data items one-by-one in pairs and comparing adjacent
data items and swapping each pair that is out of order.

How Bubble Sort Works

Following are the steps involved in bubble sort (for sorting a given array in ascending order):

1. Starting with the first element (index = 0), compare the current element with the next element of
the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat Step 1.

Let's consider an array with values {5, 1, 6, 2, 4, 3}


Below, we have a pictorial representation of how bubble sort will sort the given array.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 127


So as we can see in the representation above, after the first iteration, 6 is placed at the last index, which is
the correct position for it.
Similarly, after the second iteration, 5 will be at the second last index, and so on.
Code-
// C program for implementation of Bubble sort
#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
# Output:
Sorted array:
11 12 22 25 34 64 90

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 128


Lecture Notes || Unit -4 || CO-5 || Lecture Number-27

Topic Basic Sorting Algorithms: Insertion Sort


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand basic sorting method-Insertion Sort
Lecture structure  Insertion sort working
 Insertion sort code

Related Questions i- Write algorithm and C code to demonstrate Insertion sort in detail.

Extra topics for fast Search-Practical utilization of sorting techniques used in real life/software/program.
learners/Topics beyond
syllabus

Insertion sort
It is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. This algorithm
is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
However, insertion sort provides several advantages:

1. Simple implementation
2. Efficient for small data sets
3. Stable; i.e., does not change the relative order of elements with equal keys
4. In-place; i.e., only requires a constant amount O(1) of additional memory space.

How Insertion Sort Works

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 129


Code-
/ C program for insertion sort
#include <math.h>
#include <stdio.h>
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{ int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);

return 0;
}

Output:

5 6 11 12 13

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 130


Lecture Notes || Unit -4 || CO-5 || Lecture Number-28

Topic Basic Sorting Algorithms: Selection Sort


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand basic sorting method-selection Sort
Lecture structure  Selection sort working
 Selection sort code

Related Questions i- Write algorithm and C code to demonstrate Selection sort in detail.

Extra topics for fast Search-Practical utilization of sorting techniques used in real life/software/program.
learners/Topics beyond
syllabus

Selection Sort
Selection sorting is conceptually the simplest sorting algorithm. This algorithm first finds the smallest
element in the array and exchanges it with the element in the first position, then find the second smallest
element and exchange it with the element in the second position, and continues in this way until the entire
array is sorted
How Selection Sort works

In the first pass, the smallest element found is 1, so it is placed at the first position, then leaving first
element, smallest element is searched from the rest of the elements, 3 is the smallest, so it is then placed
at the second position. Then we leave 1 and 3, from the rest of the elements, we search for the smallest
and put it at third position and keep doing this, until array is sorted

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 131


Code-
// C program for implementation of selection sort
#include <stdio.h>
void swap(int *xp, int *yp)
{ int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{ int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{ // Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{ int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output:
Sorted array:
11 12 22 25 64

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 132


Lecture Notes || Unit -4 || CO-5 || Lecture Number-29

Topic Notion of order of complexity


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the meaning of complexity
Lecture structure  Complexity
 What effects run time of an algorithm
 Analysis of Algorithm
 Asymptotic Notations

Related Questions i-What do you mean by term “algorithmic complexity”?


ii-What are the factors that effect runtime of an algorithm?
iii-Explain asymptotic notations.
Extra topics for fast Try to get idea of calculation of complexity of at least 5 sorting algorithms.
learners/Topics beyond
syllabus

Complexity-

Algorithmic complexity is concerned about how fast or slow particular algorithm performs. We define
complexity as a numerical function T(n) - time versus the input size n. We want to define time taken by an
algorithm without depending on the implementation details. But you agree that T(n) does depend on the
implementation! A given algorithm will take different amounts of time on the same inputs depending on
such factors as: processor speed; instruction set, disk speed, brand of compiler and etc. The way around is
to estimate efficiency of each algorithm asymptotically. We will measure time T(n) as the number of
elementary "steps" (defined in any way), provided each such step takes constant time.

Let us consider two classical examples: addition of two integers. We will add two integers digit by digit (or
bit by bit), and this will define a "step" in our computational model. Therefore, we say that addition of two
n-bit integers takes n steps. Consequently, the total computational time is T(n) = c * n, where c is time taken
by addition of two bits. On different computers, additon of two bits might take different time, say c1 and c2,
thus the additon of two n-bit integers takes T(n) = c1 * n and T(n) = c2* n respectively. This shows that
different machines result in different slopes, but time T(n) grows linearly as input size increases.

The process of abstracting away details and determining the rate of resource usage in terms of the input size
is one of the fundamental ideas in computer science.

What effects run time of an algorithm?


(a) Computer used, the hardware platform
(b) Representation of abstract data types (ADT's)
(c) Efficiency of compiler
(d) Competence of implementer (programming skills)
(e) Complexity of underlying algorithm
(f) size of the input

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 133


What do we measure?
In analyzing an algorithm, rather than a piece of code, we will try and predict the number of times
"the principle activity" of that algorithm is performed. For example, if we are analyzing a sorting
algorithm we might count the number of comparisons performed, and if it is an algorithm to find
some optimal solution, the number of times it evaluates a solution.
Analysis of Algorithms
The term analysis of algorithms is used to describe approaches to the study of the performance of
algorithms. Following types of analysis are there -
 the worst-case runtime complexity of the algorithm is the function defined by the maximum
number of steps taken on any instance of size a.
 the best-case runtime complexity of the algorithm is the function defined by the minimum
number of steps taken on any instance of size a.
 the average case runtime complexity of the algorithm is the function defined by an average
number of steps taken on any instance of size a.

Example. Let us consider an algorithm of sequential searching in an array. of size n.


Its worst-case runtime complexity is O(n)
Its best-case runtime complexity is O(1)
Its average case runtime complexity is O(n/2)=O(n)

** Asymptotic Notations
The goal of computational complexity is to classify algorithms according to their performances. We will
represent the time function T(n) using the "big-O" notation to express an algorithm runtime complexity.
For example, the following statement

T(n) = O(n2)
says that an algorithm has a quadratic time complexity.

Definition of "big Oh"


For any monotonic functions f(n) and g(n) from the positive integers to the positive integers, we say
that f(n) = O(g(n)) when there exist constants c > 0 and n0 > 0 such that
f(n) ≤ c * g(n), for all n ≥ n0
Intuitively, this means that function f(n) does not grow faster than g(n), or that function g(n) is an upper
bound for f(n), for all sufficiently large n→∞

Here is a graphic representation of f(n) = O(g(n)) relation:

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 134


Examples:

 1 = O(n)
 n = O(n2)
 log(n) = O(n)
 2 n + 1 = O(n)

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input
size. Examples:

 array: accessing any element


 fixed-size stack: push and pop methods
 fixed-size queue: enqueue and dequeue methods

Linear Time: O(n)


An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e.
time grows linearly as input size increases. Examples:

 array: linear search, traversing, find minimum


 ArrayList: contains method
 queue: contains method

Logarithmic Time: O(log n)


An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the
input size. Example:

 binary search

Quadratic Time: O(n2)


An algorithm is said to run in logarithmic time if its time execution is proportional to the square of the
input size. Examples:

 bubble sort, selection sort, insertion sort

Definition of "big Omega"


We need the notation for the lower bound. A capital omega Ω notation is used in this case. We say that
f(n) = Ω(g(n)) when there exist constant c that f(n) ≥ c*g(n) for for all sufficiently large n. Examples
 n = Ω(1)
 n2 = Ω(n)
 n2 = Ω(n log(n))
 2 n + 1 = O(n)

Definition of "big Theta"


To measure the complexity of a particular algorithm, means to find the upper and lower bounds. A new
notation is used in this case. We say that f(n) = Θ(g(n)) if and only f(n) = O(g(n)) and f(n) = Ω(g(n)).
Examples
 2 n = Θ(n)
 n2 + 2 n + 1 = Θ( n2)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 135


Lecture Notes || Unit -5 || CO-5 || Lecture Number-30

Topic Pointers: Introduction, Declaration, Applications


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the concept of pointers and it`s applications
Lecture structure  Pointer Notation and memory mapping
 Pointer Application 1- Call by Reference
 Pointer Application 2- DMA
 Pointer Application 3- File Handling

Related Questions i-What do mean by pointers? How pointer variables are initialized? Write a program in C to
swap the values of any two integer variables using pointers.

Extra topics for fast Explore importance of pointers in C language.


learners/Topics beyond
syllabus

An Introduction to Pointers
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.

We may represent i’s location in memory by the following memory map.

We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.
We can print this address number through the following program:
main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 136


printf ( "\nValue of i = %d", i ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3

Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The
expression &i returns the address of the variable i, which in this case happens to be 65524. Since 65524
represents an address, there is no question of a sign being associated with it. Hence it is printed out using
%u, which is a format specifier for printing an unsigned integer.

We have been using the ‘&’ operator all the time in the scanf( ) statement. The other pointer operator
available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The
‘value at address’ operator is also called ‘indirection’ operator.

Observe carefully the output of the following program:


main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Value of i = 3

Note that printing the value of *( &i ) is same as printing the value of i. The expression &i gives the address
of the variable i. This address can be collected in a variable, by saying, j = &i ;

Here is a program another program.


main( )
{
int i = 3 ;
int *j ; j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 137


The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3

Look at the following declarations,


int *alpha ;
char *ch ;
float *s ;

Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding addresses.
Remember that, addresses (location nos.) are always going to be whole numbers, therefore pointers always
contain whole numbers.

Now we can put these two facts together and say—pointers are variables that contain addresses, and since
addresses are always whole numbers, pointers would always contain whole numbers.

The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s
is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to
contain the address of a char value. Or in other words, the value at address stored in ch is going to be a
char.

Pointers
Consider the following example:
main( )
{ int i = 3, *x ;
float j = 1.5, *y ;
char k = 'c', *z ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of j = %f", j ) ;
printf ( "\nValue of k = %c", k ) ;
x = &i ;
y = &j ;
z = &k ;
printf ( "\nOriginal address in x = %u", x ) ;
printf ( "\nOriginal address in y = %u", y ) ;
printf ( "\nOriginal address in z = %u", z ) ;
x++ ;
y++ ;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 138


z++ ;
printf ( "\nNew address in x = %u", x ) ;
printf ( "\nNew address in y = %u", y ) ;
printf ( "\nNew address in z = %u", z ) ;
}
Here is the output of the program.
Value of i = 3
Value of j = 1.500000
Value of k = c
Original address in x = 65524
Original address in y = 65520
Original address in z = 65519
New address in x = 65526
New address in y = 65524
New address in z = 65520

Observe the last three lines of the output. 65526 is original value in x plus 2, 65524 is original value in y
plus 4, and 65520 is original value in z plus 1. This so happens because every time a pointer is incremented
it points to the immediately next location of its type.

That is why, when the integer pointer x is incremented, it points to an address two locations after the current
location, since an int is always 2 bytes long (under Windows/Linux since int is 4 bytes long, new value of
x would be 65528).

Similarly, y points to an address 4 locations after the current location and z points 1 location after the current
location. This is a very important result and can be effectively used while passing the entire array to a
function.

The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus, the
following operations can be performed on a pointer:

(a) Addition of a number to a pointer. For example,


int i = 4, *j, *k ; j = &i ; j = j + 1 ; j = j + 9 ; k = j + 3 ;

(b) Subtraction of a number from a pointer. For example,


j = &i ; j = j - 2 ; j = j - 5 ; k = j - 6 ;

(c) Subtraction of one pointer from another.

One pointer variable can be subtracted from another provided both variables point to elements of the
same array. The resulting value indicates the number of bytes separating the corresponding array
elements. This is illustrated in the following program.
main( ) {
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 139


i = &arr[1] ;
j = &arr[5] ;
printf ( "%d %d", j - i, *j - *i ) ;
}
Here i and j have been declared as integer pointers holding addresses of first and fifth element of the
array respectively.
Suppose the array begins at location 65502, then the elements arr[1] and arr[5] would be present at
locations 65504 and 65512 respectively, since each integer in the array occupies two bytes in memory.
The expression j - i would print a value 4 and not 8. This is because j and i are pointing to locations
that are 4 integers apart. What would be the result of the expression *j - *i? 36, since *j and *i return
the values present at addresses contained in the pointers j and i.

(d) Comparison of two pointer variables


Pointer variables can be compared provided both variables point to objects of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array. The
comparison can test for either equality or inequality. Moreover, a pointer variable can be compared
with zero (usually expressed as NULL). The following program illustrates how the comparison is
carried out.
main( )
{ int arr[ ] = { 10, 20, 36, 72, 45, 36 } ; int *j, *k ;
j = &arr [ 4 ] ; k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same location" ) ;
}

**A word of caution! Do not attempt the following operations on pointers... they would never work
out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 140


Lecture Notes || Unit -5 || CO-5 || Lecture Number-31

Topic Introduction to dynamic memory allocation (malloc, calloc, realloc, free)


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the concept of Dynamic Memory Allocation and working of DMA functions.
Lecture structure  Static Memory Allocation Vs DMA
 DMA function-malloc()
 DMA function-calloc()
 DMA function-realloc()
 DMA function-free()

Related Questions Explain DMA functions in detail with proper examples

Extra topics for fast Explore Importance and utilization of DMA functions.
learners/Topics beyond
syllabus

DMA-
Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.

Although C inherently does not have any technique to allocate memory dynamically, there are 4 library
functions defined under <stdlib.h> for dynamic memory allocation.

Function Use of Function

Allocates requested size of bytes and returns a pointer first byte of


malloc()
allocated space

Allocates space for an array elements, initializes to zero and then


calloc()
returns a pointer to memory

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 141


malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of type void which
can be casted into pointer of any form.

Syntax of malloc()

ptr = (cast-type*) malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.

ptr = (int*) malloc(100 * sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.

Syntax of calloc()

ptr = (cast-type*)calloc(n, element-size);

This statement will allocate contiguous space in memory for an array of n elements. For example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.

free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 142


syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

Example #1: Using C malloc() and free()

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 143


Example #2: Using C calloc() and free()

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 144


C realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().
Syntax of realloc()

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.

Example #3: Using realloc()


#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Address of previously allocated memory: ");


for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2 * sizeof(int));
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 145


Lecture Notes || Unit -5 || CO-5 || Lecture Number-32

Topic Notion of linked list (no implementation)


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To learn basic concepts of linked list
Lecture structure  What is Linked List
 Representation of Linked List
 Types of Linked List
 Applications of Linked List

Related Questions Explain Linked List in detail.

Extra topics for fast Search and explore-Applications of linked list


learners/Topics beyond
syllabus

Notion of linked list (no implementation)

Introduction
One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot
be easily extended or reduced to fit the data set. Arrays are also expensive to maintain new
insertions and deletions. In this chapter we consider another data structure called Linked Lists that
addresses some of the limitations of arrays.

A linked list is a linear data structure where each element is a separate object.

Each element (we will call it a node) of a list is comprising of two items - the data and a reference
to the next node. The last node has a reference to null. The entry point into a linked list is called
the head of the list. It should be noted that head is not a separate node, but the reference to the first
node. If the list is empty then the head is a null reference.

A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink
on demand. Any application which has to deal with an unknown number of objects will need to use a linked
list.

One disadvantage of a linked list against an array is that it does not allow direct access to the individual
elements. If you want to access a particular item then you have to start at the head and follow the references
until you get to that item.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 146


Another disadvantage is that a linked list uses more memory compare with an array - we extra 4 bytes (on
32-bit CPU) to store a reference to the next node.

Types of Linked Lists

A singly linked list is described above

A doubly linked list is a list that has two references, one to the next node and another to previous node.

Another important type of a linked list is called a circular linked list where last node of the list
points back to the first node (or the head) of the list.

Applications of linked list data structure

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations.
The elements in a linked list are linked using pointers as shown in the below image:

Applications of linked list in computer science –


1. Implementation of stacks and queues
2. Implementation of graphs : Adjacency list representation of graphs is most popular which
is uses linked list to store adjacent vertices.
3. Dynamic memory allocation: We use linked list of free blocks.
4. Performing arithmetic operations on long integers
5. Manipulation of polynomials by storing constants in the node of linked list
6. representing sparse matrices

Applications of linked list in real world-


1. Image viewer – Previous and next images are linked, hence can be accessed by next and
previous button.
2. Previous and next page in web browser – We can access previous and next url searched in
web browser by pressing back and next button since, they are linked as linked list.
3. Music Player – Songs in music player are linked to previous and next song. you can play
songs either from starting or ending of the list.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 147


Lecture Notes || Unit -5 || CO-5 || Lecture Number-33

Topic File handling


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand file handling
Lecture structure  File
 File Modes
 File Operations
 File Handling functions
 File handling examples

Related Questions 1. . a) List out various file operations in C. Write a C program to count the number of
characters in a file. b) Write a C program to copy the content of one file into another file.
2. A file name DATA contains a series of integer numbers write a program to read these
numbers and then write all ‘odd’ numbers to a file to be called ODD and all even numbers
to a file to be called EVEN.
3. Write a program in ‘C’ that takes 10 integers from al file and write square of these integers
into another file.
Extra topics for fast Complete any MIS type project using file handling
learners/Topics beyond
syllabus

File-
A File is a collection of data stored on a secondary storage device like hard disk. File operation is to combine
all the input data into a file and then to operate through the C program.

Various operations like insertion, deletion, opening closing etc can be done upon a file. When the program
is terminated, the entire data is lost in C programming.

If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created
these information can be accessed using few commands.

There are large numbers of functions to handle file I/O in C language. High level file I/O functions can be
categorized as: Text file & Binary file

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 148


File Modes-
A file can be open in several modes for these operations. The various modes are:
r
Open a text file for reading
w
truncate to zero length or create a text file for writing
a
append; open or create text file for writing at end-of-file
rb
open binary file for reading
wb
truncate to zero length or create a binary file for writing ab append; open or create binary file for writing at
end-of-file r+ open text file for update (reading and writing)
w+
truncate to zero length or create a text file for update a+ append; open or create text file for update
r+b or rb+
open binary file for update (reading and writing)
w+b or wb+
truncate to zero length or create a binary file for update a+b or ab+ append; open or create binary file for
update

File Operations

In C, you can perform four major operations on files, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Q1. Write a program to open a file using fopen().


Ans:
#include<stdio.h> void main()
{
fopen() file *fp;
fp=fopen(“student.DAT”, “r”);
if(fp==NULL)
{
printf(“The file could not be open”); exit(0);
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 149


Q2. Write a C program to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.
Ans:
#include <stdio.h>
int main()
{
char name[50]; int marks, i,n;
printf(“Enter number of students”);
scanf(“%d”, &n);
FILE *fptr; fptr=(fopen(“C:\\student.txt”,”a”));
if (fptr==NULL){ printf("Error!"); exit(1);
}
for(i=0;i<n;++i)
{ printf("For student%d\nEnter name: ",i+1); scanf("%s",name);

printf(“Enter marks”);
scanf(“%d”, &marks);
fprintf(fptr, “\nName: %s\nMarks=%d\n”, name, marks);
}
fclose(fptr);
Return 0;
}

The fclose function causes the stream pointed to be flushed and the associated file to be closed. Any
unwritten buffered data for the stream are delivered to the host environment to be written to the file; any
unread buffered data are discarded. The stream is disassociated from the file. If the associated buffer was
automatically allocated, it is deallocated. The function returns zero if the stream was successfully closed or
EOF if any errors were detected.

Q.3. Write a program to read data from file and close using fclose function.
Ans:
#include <stdio.h>
int main()
int n
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); // Program exits if file pointer returns NULL.
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 150


Q4. Write a C program to write all the members of an array of structure to a file using fwrite(). Read
the array from the file and display on the screen.
Ans:
#include<stdio.h>
Struct s
{
Char name[50];
Int height;
};
Int main()
{
Struct s a[5], b[5];
FILE *fptr;
Int I;
Fptr=fopen(“file.txt”, “wb”);
For(i=0; i<5; ++i)
{
fflush(stdin);
printf("Enter name: ") ;
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 151


Lecture Notes || Unit -5 || CO-5 || Lecture Number-34

Topic Standard C preprocessors, Defining and calling macros, command-line arguments


CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To explore the Standard C preprocessors
Lecture structure  Preprocessor features
 Macro expansion
 File inclusion
 Conditional Compilation
 Miscellaneous directives
 command-line arguments

Related Questions i-Explain Macros in detail with examples.


ii-what do you mean by conditional compilation? Explain
iii-Explain working of #pragma.
iv-Explain command line arguments stating some examples.
Extra topics for fast How to make header file? Try to make your own header file that include all the lab work
learners/Topics beyond done in semester.
syllabus

Features of C Preprocessor
There are several steps involved from the stage of writing a C program to the stage of getting it executed.

Note that if the source code is stored in a file PR1.C then the expanded source code gets stored in a file
PR1.I. When this expanded source code is compiled the object code gets stored in PR1.OBJ. When this
object code is linked with the object code of library functions the resultant executable code gets stored in
PR1.EXE.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 152


We would learn the following preprocessor directives here:
(a) Macro expansion
b) File inclusion
(c) Conditional Compilation
(d) Miscellaneous directives
Let us understand these features of preprocessor one by one.

Macro Expansion
Have a look at the following program.
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has
already been defined before main( ) through the statement,

#define UPPER 25
This statement is called ‘macro definition’ or more commonly, just a ‘macro’. What purpose does it
serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program
with 25.

When we compile the program, before the source code passes to the compiler it is examined by the C
preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire
program in search of the macro templates; wherever it finds one, it replaces the macro template with
the appropriate macro expansion. Only after this procedure has been completed is the program handed
over to the compiler.

Remember that a macro definition is never to be terminated by a semicolon.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 153


Macros with Arguments
The macros that we have used so far are called simple macros. Macros can have arguments, just as functions
can. Here is an example that illustrates this fact.
#define AREA(x) ( 3.14 * x * x )
main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "\nArea of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "\nArea of circle = %f", a ) ;
}
Here’s the output of the program...
Area of circle = 122.656250
Area of circle = 19.625000

In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the statement ( 3.14
* x * x ). However, that’s not all that it does. The x in the macro template AREA(x) is an argument that
matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the
variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to:

Be careful not to leave a blank between the macro template and its argument while defining the macro. For
example, there should be no blank between AREA and (x) in the definition, #define AREA(x) ( 3.14 * x *
x)

Macros versus Functions


when is it best to use macros with arguments and when is it better to use a function? Usually macros make
the program run faster but increase the program size, whereas functions make the program smaller and
compact.

If we use a macro hundred times in a program, the macro expansion goes into our source code at hundred
different places, thus increasing the program size. On the other hand, if a function is used, then even if it is
called from hundred different places in the program, it would take the same amount of space in the program.

But passing arguments to a function and getting back the returned value does take time and would therefore
slow down the program. This gets avoided with macros since they have already been expanded and placed
in the source code before compilation.
Moral of the story is—if the macro is simple and sweet like in our examples, it makes nice shorthand and
avoids the overheads associated with function calls. On the other hand, if we have a fairly large macro and
it is used fairly often, perhaps we ought to replace it with a function.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 154


File Inclusion
The second preprocessor directive we’ll explore in this chapter is file inclusion. This directive causes one
file to be included in another. The preprocessor command for file inclusion looks like this:
#include "filename"
and it simply causes the entire contents of filename to be inserted into the source code at that point in the
program.

Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the preprocessing
commands #ifdef and #endif, which have the general form:

#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif

If macroname has been #defined, the block of code will be processed as usual; otherwise not.

#if and #elif Directives


The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result
of the expression is nonzero, then subsequent lines upto a #else, #elif or #endif are compiled, otherwise
they are skipped. A simple example of #if directive is shown below:

main( )
{
#if TEST <= 5
statement 1 ;
statement 2 ;
statement 3 ;
#else
statement 4 ;
statement 5 ;
statement 6 ;
#endif
}

If the expression, TEST <= 5 evaluates to true then statements 1, 2 and 3 are compiled otherwise statements
4, 5 and 6 are compiled. In place of the expression TEST <= 5 other expressions like ( LEVEL == HIGH
|| LEVEL == LOW ) or ADAPTER == CGA can also be used.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 155


If we so desire we can have nested conditional compilation directives. An example that uses such directives
is shown below.

#if ADAPTER == VGA


code for video graphics array
#else
#if ADAPTER == SVGA
code for super video graphics array
#else
code for extended graphics adapter
#endif
#endif

The above program segment can be made more compact by using another conditional compilation directive
called #elif. The same program using this directive can be rewritten as shown below. Observe that by using
the #elif directives the number of #endifs used in the program get reduced.

#if ADAPTER == VGA


code for video graphics array
#elif ADAPTER == SVGA
code for super video graphics array
#else
code for extended graphics adapter
#endif

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 156


Miscellaneous Directives
There are two more preprocessor directives available, though they are not very commonly used. They are:
(a) #undef
(b) #pragma

#undef Directive
On some occasions it may be desirable to cause a defined name to become ‘undefined’. This can be
accomplished by means of the #undef directive.

#pragma Directive
This directive is another special-purpose directive that you can use to turn on or off certain features.
Pragmas vary from one compiler to another. There are certain pragmas available with Microsoft C compiler
that deal with formatting source listings and placing comments in the object file generated by the compiler.
Turbo C/C++ compiler has got a pragma that allows you to suppress warnings generated by the compiler.
Some of these pragmas are discussed below.

(a) #pragma startup and #pragma exit: These directives allow us to specify functions that are called upon
program startup (before main( )) or program exit (just before the program terminates). Their usage is as
follows:
void fun1( ) ;
void fun2( ) ;
#pragma startup fun1
#pragma exit fun2
main( )
{
printf ( "\nInside maim" ) ;
}
void fun1( )
{
printf ( "\nInside fun1" ) ;
}
void fun2( )
{
printf ( "\nInside fun2" ) ;
}

And here is the output of the program.


Inside fun1
Inside main
Inside fun2
Note that the functions fun1( ) and fun2( ) should neither receive nor return any value. If we want two
functions to get executed at startup then their pragmas should be defined in the reverse order in which
you want to get them called.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 157


(b) #pragma warn: This directive tells the compiler whether or not we want to suppress a specific
warning. Usage of this pragma is shown below.
#pragma warn –rvl /* return value */
#pragma warn –par /* parameter not used */
#pragma warn –rch /* unreachable code */
int f1( )
{
int a = 5 ;
}
void f2 ( int x )
{
printf ( "\nInside f2" ) ;
}
int f3( )
{
int x = 6 ;
return x ;
x++ ;
}
void main( )

{
f1( ) ;
f2 ( 7 ) ;
f3( ) ;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 158


Command Line Arguments in C –

So far, we have seen that no arguments were passed in the main function. But the C programming
language gives the programmer the provision to add parameters or arguments inside the main function to
reduce the length of the code. These arguments are called Command Line Arguments in C.
In this lecture , we will discuss:

 Components of Command Line Arguments


 C program to understand command line arguments

What are Command Line Arguments in C?

Command line arguments are simply arguments that are specified after the name of the program in the
system’s command line, and these argument values are passed on to your program during program
execution.

Components of Command Line Arguments

There are 2 components of Command Line Argument in C:

1. argc: It refers to “argument count”. It is the first parameter that we use to store the number of
command line arguments. It is important to note that the value of argc should be greater than or
equal to 0.
2. agrv: It refers to “argument vector”. It is basically an array of character pointer which we use to list
all the command line arguments.
In order to implement command line arguments, generally, 2 parameters are passed into the main
function:

1. Number of command line arguments


2. The list of command line arguments
The basic syntax is:
int main( int argc, char *argv[] )
{
// BODY OF THE MAIN FUNCTION
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 159


Example of C Command Line Arguments

Here is a code in C that illustrates the use of command line arguments.

// The program name is cl.c


#include<stdio.h>
int main(int argc, char** argv)
{
printf("Welcome to DataFlair tutorials!\n\n");
int i;
printf("The number of arguments are: %d\n",argc);
printf("The arguments are:");
for ( i = 0; i < argc; i++)
{
printf("%s\n", argv[i]);
}
return 0;
}
Code on Screen-

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 160


Output-

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 161


Important Programs with solution

Program to find area and circumference of circle.

#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float pi=3.14,area,ci;
clrscr();
printf(“enter radius of circle: ”);
scanf(“%d”,&r);
area=pi*r*r;
printf(“area of circle=%f ”,area);
ci=2*pi*r;
printf(“circumference=%f ”,ci);
getch();
}
Output:
enter radius of a circle: 5
area of circle=78.000
circumference=31.4

Program to find the simple interest.

#include<stdio.h>
#include<conio.h>
void main()
{
int p,r,t,si;
clrscr();
printf(“enter principle, Rate of interest & time to find simple interest: ”);
scanf(“%d%d%d”,&p,&r,&t);
si=(p*r*t)/100;
printf(“simple intrest= %d”,si);
getch();
}
Output:
enter principle, rate of interest & time to find simple interest: 500
5
2
simple interest=50

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 162


Program to convert temperature from degree centigrade to Fahrenheit.

#include<stdio.h>
#include<conio.h>
void main()
{
float c,f;
clrscr();
printf(“enter temp in centigrade: ”);
scanf(“%f”,&c);
f=(1.8*c)+32;
printf(“temp in Fahrenheit=%f ”,f);
getch();
}
Output:
enter temp in centigrade: 32
temp in Fahrenheit=89.59998

Program to calculate sum of 5 subjects and find percentage.

#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,s5,sum,total=500;
float per;
clrscr();
printf(“enter marks of 5 subjects: ”);
scanf(“%d%d%d%d%d”,&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
printf(“sum=%d”,sum);
per=(sum*100)/total;
printf(“percentage=%f”,per);
getch();
}
Output:
enter marks of 5 subjects: 60
65
50
60
60
sum=300
percentage=60.000

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 163


Program to find maximum between three numbers using nested if
#include <stdio.h>
int main()
{ int num1, num2, num3, maximum;
printf("Enter three numbers to find maximum: \n");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1>num2)
{ if(num1>num3)
{ maximum = num1;
}
else
{ maximum = num3;
}
}
else
{ if(num2>num3)
{ maximum = num2;
}
else
{ maximum = num3;
}
}
printf("\nMaximum among all three numbers = %d", maximum);
return 0;
}

C program check even or odd using if else


#include <stdio.h>
int main()
{ int num;
printf("Enter any number to check even or odd: ");
scanf("%d", &num);
if(num%2 == 0)
{ printf("Number is Even.\n");
}
else
{ printf("Number is Odd.\n");
}
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 164


C program to check Leap Year
It is a special year containing one extra day i.e. total 366 days in ayear. If the year is exactly
divisible by 4 and not divisible by 100 then its Leap Year Else if the year is exactly divisible by
400 then its Leap Year Else its a common year.
#include <stdio.h>
int main()
{ int year;
printf("Enter year : ");
scanf("%d", &year);
if(((year%4 == 0) && (year%100 !=0)) || (year%400==0))
{ printf("LEAP YEAR");
}
else
{ printf("COMMON YEAR");
}
return 0;
}

Program to print day of week


#include <stdio.h>
int main()
{ int week;
printf("Enter week number (1-7): ");
scanf("%d", &week);
if(week == 1)
{ printf("MONDAY\n");
}
else if(week == 2)
{ printf("TUESDAY\n");
}
else if(week == 3)
{ printf("WEDNESDAY\n");
}
else if(week == 4)
{ printf("THURSDAY\n");
}
else if(week == 5)
{ printf("FRIDAY\n");
}
else if(week == 6)
{ printf("SATURDAY\n");
}
else if(week == 7)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 165


{ printf("SUNDAY\n");
}
else
{ printf("Invalid Input! Please enter week number between 1-7.\n");
}
return 0;
}

C program to find all roots of a quadratic equation


#include <stdio.h>
#include <math.h> //Used for sqrt()
int main()
{ float a, b, c;
float root1, root2, imaginary;
float discriminant;
printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
scanf("%f%f%f", &a, &b, &c);
discriminant = (b*b) - (4*a*c);
if(discriminant > 0)
{ root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
printf("Two distinct and real roots exists: %.2f and %.2f\n", root1, root2);
}
else if(discriminant == 0)
{ root1 = root2 = -b / (2*a);
printf("Two equal and real roots exists: %.2f and %.2f\n", root1, root2);
}
else if(discriminant < 0)
{ root1 = root2 = -b / (2*a);
imaginary = sqrt(-discriminant) / (2*a);
printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f\n", root1, imaginary, root2,
imaginary);
}
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 166


C program to create calculator using switch case and functions
#include <stdio.h>
int main()
{ char op;
float num1, num2, result=0;
printf("WELCOME TO SIMPLE CALCULATOR\n");
printf("----------------------------\n");
printf("Enter [number 1] [+ - * /] [number 2]\n");
scanf("%f %c %f", &num1, &op, &num2);
switch(op)
{ case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("Invalid operator");
return 0;
}
printf("%.2f %c %.2f = %.2f\n", num1, op, num2, result);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 167


C program to count number of digits in an integer
Method to count number of digits in an integer.
1. Initialize a variable count to 0.
2. Increment count by 1 if num > 0 (where num is the number whose digits count is to be
found).
3. Remove the last digit from the number as it isn't needed anymore. Hence divide the
number by 10 i.e num = num / 10.
4. If number is greater than 0 then repeat steps 2-4.
#include <stdio.h>
int main()
{ long long num;
int count = 0;
printf("Enter any number: ");
scanf("%lld", &num);
while(num != 0)
{ count++;
num /= 10; // num = num / 10
}
printf("Total digits: %d", count);
return 0;
}

C program to find sum of digits of a number


logic of this program can be divided in three basic steps:
1. Find the last digit of number by performing modular division.
2. Add the last digit just found above to sum.
3. Remove the last digit from number by dividing the number by 10.
Repeat the above three steps till the number becomes 0 and you will be left with the sum of digits.
#include <stdio.h>
int main()
{ int num, sum=0;
printf("Enter any number to find sum of its digit: ");
scanf("%d", &num);
while(num!=0)
{ sum += num % 10;
num = num / 10;
}
printf("\nSum of digits = %d", sum);
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 168


C program to calculate product of digits of a number
logic of this program can be divided in three basic steps:
1. Find the last digit of number by performing modular division.
2. Multiply the last digit just found above to product.
3. Remove the last digit from number by dividing the number by 10.
Repeat the above three steps till the number becomes 0 and you will be left with the product of
digits.
#include <stdio.h>
int main()
{ int n;
long product=1;
printf("Enter any number to calculate product of digit: ");
scanf("%d", &n);
while(n!=0)
{ product = product * (n % 10);
n = n / 10;
}
printf("\nProduct of digits = %ld", product);
return 0;
}

C program to find reverse of any number


The process of reversing involves four basic steps:
1. Multiply the rev variable by 10.
2. Find the last digit of the given number.
3. Add the last digit just found to rev.
4. Divide the original number by 10 to eliminate the last digit, which is not needed
anymore.
Repeat the above four steps till the original number becomes 0 and finally we will be left with the
reversed number in rev variable.
#include <stdio.h>
int main()
{ int n, rev = 0;
/* Reads the number from user */
printf("Enter any number to find reverse: ");
scanf("%d", &n);
/* Repeats the steps till n becomes 0 */
while(n!=0)
{
/* Multiples rev by 10 and adds the last digit to it*/
rev = (rev * 10) + (n % 10);
/* Eliminates the last digit from num */

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 169


n = n/10;
}
printf("Reverse = %d", rev);
return 0;
}

C program to check whether a number is palindrome or not


After retrieving the reverse of number we just need to make a conditional check that whether the
given number is equal to its reverse or not. If the given number and its reverse are same then the
number is palindrome otherwise not.
#include <stdio.h>
int main()
{ int n, num, rev = 0;
/* Reads a number from user */
printf("Enter any number to check palindrome: ");
scanf("%d", &n);
num = n; //Copies original value to num.
/* Finds reverse of n and stores in rev */
while(n!=0)
{ rev = (rev * 10) + (n % 10);
n = n/10;
}
/* Check if reverse is equal to original num or not */
if(rev==num)
{ printf("%d is palindrome.", num);
}
else
{ printf("%d is not palindrome.", num);
}
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 170


C program to find factorial of any number
Example:
Input number: 5
Output factorial: 120
Logic to find factorial
Finding factorial is really easy you just need to know how to iterate over a loop. Finding factorial
can be basically divided two steps:
1. Run a loop from 1 to n (where n is the number whose factorial is to be found).
2. Multiply the current loop counter value with fact (where fact is a variable that stores
factorial and is initially initialized with 1).
#include <stdio.h>
int main()
{
int i, num;
long long fact=1;
/* Reads a number from user */
printf("Enter any number to calculate factorial: ");
scanf("%d", &num);
/* Runs a loop from 1 to n */
for(i=1; i<=num; i++)
{
fact = fact * i;
}
printf("Factorial of %d = %lld", num, fact);
return 0;
}

C program to check whether a number is prime number or not


Example:
Enter any number: 17
Output: Number is Prime number
Prime numbers
Prime numbers are the positive integers greater than 1 that is only divisible by 1 and self. For
example: 2, 3, 5, 7, 11 etc...

#include <stdio.h>
int main()
{
int i, n, flag;
//Flag is used as notification. Initially we have supposed that the number is prime.
flag = 1;

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 171


/* Reads a number from user */
printf("Enter any number to check prime: ");
scanf("%d", &n);

for(i=2; i<=n/2; i++)


{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if(n%i==0)
{
flag = 0;
break;
}
}

/*
* If flag contains 1 then it is prime
*/
if(flag==1)
{
printf("\n%d is prime number", n);
}
else
{
printf("\n%d is not prime number", n);
}
return 0;
}

C program to check whether a number is Armstrong number or not


Example:
Input: 371
Output: Armstrong number
Armstrong number
Armstrong number is a special number whose sum of cube of its digits is equal to the original
number. For example: 371 is an Armstrong number because

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 172


33 + 73 + 13 = 371
Logic to check armstrong number
Checking of armstrong number can be divided into basic three steps:
1. Find last digit of the given number simply by performing modular division by 10.
2. Find cube of the last digit just found and add it to a variable called sum.
3. Repeat above two steps till the number becomes 0. And at the completion of the iteration
check whether sum equals to original number or not. If it does then the given number is
armstrong number otherwise not.

#include <stdio.h>
int main()
{
int n, num, lastDigit, sum = 0;

/* Reads a number from user */


printf("Enter any number to check Armstrong number: ");
scanf("%d", &n);

/* Copies the original value of n to num */


num = n;

/*
* Finds the sum of cubes of each digit of number
*/
while(n != 0)
{
/* Finds last digit of number */
lastDigit = n % 10;
/* Finds cube of last digit and adds to sum */
sum += (lastDigit * lastDigit * lastDigit);

n = n / 10;
}
/* Checks if sum of cube of digits is equal to original value or not. */
if(num == sum)
{
printf("\n%d is Armstrong number.", num);
}
else
{
printf("\n%d is not Armstrong number.", num);
}
return 0;}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 173


C program to check whether a number is perfect number or not
Example:
Input number: 6
Output: 6 is perfect number
Perfect number
A perfect number is a positive integer which is equal to the sum of its proper positive divisors.
For example: 6 is the first perfect number
Proper divisors of 6 are 1, 2, 3
And 1+2+3 = 6. Hence 6 is a perfect number

#include <stdio.h>
int main()
{ int i, num, sum = 0;

/* Reads a number from user */


printf("Enter any number to check perfect number: ");
scanf("%d", &num);

/* Finds the sum of all proper divisors */


for(i=1; i<num; i++)
{
/* If i is a divisor of num */
if(num%i==0)
{
sum += i;
}
}

/* Checks whether the sum of proper divisors is equal to num */


if(sum == num)
{
printf("\n%d is a Perfect number", num);
}
else
{
printf("\n%d is not a Perfect number", num);
}
return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 174


C program to print all prime numbers between 1 to n
Example:
Input lower limit: 1
Input upper limit: 10
Output prime numbers between 1-10: 2, 3, 5, 7
Prime number is a positive integer greater than 1 that is only divisible by 1 and self.
Example: 2, 3 , 5, 7, 11 are the first five prime numbers

#include <stdio.h>
int main()
{
int i, j, n, isPrime; //isPrime is used as flag variable

/* Reads upper limit to print prime */


printf("Find prime numbers between 1 to : ");
scanf("%d", &n);
printf("\nAll prime numbers between 1 to %d are:\n", n);

/* Finds all Prime numbers between 1 to n */


for(i=2; i<=n; i++)
{
/* Assume that the current number is Prime */
isPrime = 1;

/* Check if the current number i is prime or not */


for(j=2; j<=i/2; j++)
{
/*
* If i is divisible by any number other than 1 and self
* then it is not prime number
*/
if(i%j==0)
{
isPrime = 0;
break;
}
}

/* If the number is prime then print */


if(isPrime==1)
{
printf("%d is Prime number\n", i);
}
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 175


return 0;
}

C program to find sum of all prime numbers between 1 to n


Example:
Input: n=10
Output: Sum of all prime numbers between 1 to 10 = 2 + 3 + 5 + 7 = 17
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);

/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{

/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}

/*
* If i is Prime then add to sum
*/
if(isPrime==1)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 176


{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

C program to find fibonacci series upto n terms


Example:
Input upper limit: 10
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Fibonacci series
Fibonacci series is a series of numbers where the current number is the sum of previous two
terms.
For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21...

Fibonacci series algorithm


If you look to the given series very carefully you will find a specific pattern i.e. the current
number is the sum of previous two numbers.
Fibonacci series : 0, 1, 1, 2, 3, 5, 8, 13, 21...
1 is the sum of 0 + 1
2 is the sum of 1 + 1
3 is the sum of 2 + 1
5 is the sum of 3 + 2
and so on....

Lets suppose the first number as a i.e. a = 0


Second number as b i.e. b = 1
And lets suppose c as our current number in Fibonacci series also initialize the value with 0 i.e. c
=0

Now Fibonacci series algorithm is simple and contains only four steps.
Step 1: Print the value of c.
Step 2: a = b.
Step 3: b = c.
Step 4: c = a + b.

#include <stdio.h>
int main()

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 177


{
int a, b, c, i, n;
printf("Enter value of n to print Fibonacci series : ");
scanf("%d", &n);
a = 0;
b = 1;
c = 0;

for(i=1; i<=n; i++)


{
printf("%d, ", c);

a=b;
b=c;
c=a+b;
}

return 0;}

C program to check prime, Armstrong, perfect number using functions


Example:
Input any number: 11
Output: 11 is prime number
11 is not a armstrong number
11 is not a perfect number

#include <stdio.h>
/* Function declarations */
int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);

int main()
{
int num;

printf("Enter any number: ");


scanf("%d", &num);

//Calls the isPrime() functions


if(isPrime(num))
{

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 178


printf("%d is Prime number.\n", num);
}
else
{
printf("%d is not Prime number.\n", num);
}

//Calls the isArmstrong() function


if(isArmstrong(num))
{
printf("%d is Armstrong number.\n", num);
}
else
{
printf("%d is not Armstrong number.\n", num);
}

//Calls the isPerfect() function


if(isPerfect(num))
{
printf("%d is Perfect number.\n", num);
}
else
{
printf("%d is not Perfect number.\n", num);
}

return 0;
}

/**
* Checks whether a number is prime or not. Returns 1 if the number is prime
* otherwise returns 0.
*/
int isPrime(int num)
{
int i;

for(i=2; i<=num/2; i++)


{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 179


*/
if(num%i == 0)
{
return 0;
}
}
return 1;
}

/**
* Checks whether a number is Armstrong number or not. Returns 1 if the number
* is Armstrong number otherwise returns 0.
*/
int isArmstrong(int num)
{
int lastDigit, sum, n;
sum = 0;
n = num;

while(n!=0)
{
/* Finds last digit of number */
lastDigit = n % 10;

/* Finds cube of last digit and adds to sum */


sum += lastDigit * lastDigit * lastDigit;

n = n/10;
}

return (num == sum);


}

/**
* Checks whether the number is perfect number or not. Returns 1 if the number
* is perfect otherwise returns 0.
*/
int isPerfect(int num)
{
int i, sum, n;
sum = 0;
n = num;

for(i=1; i<n; i++)

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 180


{
/* If i is a divisor of num */
if(n%i == 0)
{
sum += i;
}
}
return (num == sum);
}

C program to find reverse of a number using recursion


Example:
Input number: 12345
Output reverse: 54321
Logic to find reverse of number using recursion
basic steps i.e.
 Multiply the rev variable by 10.
 Find the last digit of the given number.
 Add the last digit just found to rev.
 Divide the original number by 10 to eliminate the last digit, which is not needed
anymore.
And we repeat the above four steps till the number becomes 0 and we are left with the reversed
number in rev variable. Here also we will use the above four steps to find the reverse using
recursive approach with the given base condition:
reverse(0) = 0 {Base condition}
reverse(n) = (n%10 * pow(10, digits)) + reverse(n/10) {where digit is the total number of digits in
number}

#include <stdio.h>
#include <math.h>
/* Fuction declaration */
int reverse(int num);

int main()
{
int num, rev;

/* Reads number from user */


printf("Enter any number: ");
scanf("%d", &num);

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 181


/*Calls the function to reverse number */
rev = reverse(num);

printf("Reverse of %d = %d", num, rev);

return 0;
}

/**
* Recursive function to find reverse of any number
*/
int reverse(int num)
{
int digit;

//Base condition
if(num==0)
return 0;

//Finds total number of digits


digit = (int)log10(num);

return ((num%10 * pow(10, digit)) + reverse(num/10));


}

C program to generate nth fibonacci term using recursion


Example:
Input any number: 10
Output 10th fibonacci term: 55
Logic to find nth Fibonacci term
base condition of the recursion which is explained below.

fibo(0) = 0 {Base condition}


fibo(1) = 1 {Base condition}
fibo(num) = fibo(num-1) + fibo(num+2)

#include <stdio.h>
//Function declaration
long long fibo(int num);
int main()
{

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 182


int num;
long long fibonacci;

//Reads number from user to find nth fibonacci term


printf("Enter any number to find nth fiboacci term: ");
scanf("%d", &num);

fibonacci = fibo(num);

printf("%dth fibonacci term is %lld", num, fibonacci);

return 0;
}
/**
* Recursive function to find nth Fibonacci term
*/
long long fibo(int num)
{
if(num == 0) //Base condition
return 0;
else if(num == 1) //Base condition
return 1;
else
return fibo(num-1) + fibo(num-2); //Recursively calls fibo() to find nth fibonacci term.
}

C program to find sum of all elements of an array


Example:
Input elements: 10, 20, 30, 40, 50
Sum of all elements = 150
#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;

/*
* Reads size and elements in array from user
*/
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter %d elements in the array: ", n);

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 183


for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

/*
* Adds each element of array to sum
*/
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}

printf("Sum of all elements of array = %d", sum);

return 0;
}

C program to find maximum and minimum element in array


Example: If the elements of the array are: 10, 50, 12, 16, 2
Maximum = 50
Minimum = 2
Logic to find maximum/minimum in array
Step 1: Read element in array.
Step 2: Let's suppose the first element of array as maximum. Set max=array[0]
Step 3: Set i=0
Step 4: If array[i] > max then Set max=array[i]
Step 5: Increment i by 1. Set i=i+1
Step 6: Repeat Step 4-5 till i<size (Where size is the size of array).
#include <stdio.h>

int main()
{
int arr[100];
int i, max, min, size;

/*
* Reads size array and elements in the array
*/
printf("Enter size of the array: ");

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 184


scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

/* Supposes the first element as maximum and minimum */


max = arr[0];
min = arr[0];

/*
* Finds maximum and minimum in all array elements.
*/
for(i=1; i<size; i++)
{
/* If current element of array is greater than max */
if(arr[i]>max)
{
max = arr[i];
}

/* If current element of array is smaller than min */


if(arr[i]<min)
{
min = arr[i];
}
}

/*
* Prints the maximum and minimum element
*/
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);

return 0;
}

C program to find reverse of an array


Example:
If the elements of the array are: 10, 5, 16, 35, 500
Then its reverse would be: 500, 35, 16, 5, 10

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 185


That is if
array[0] = 10
array[1] = 5
array[2] = 16
array[3] = 35
array[4] = 500

Then after reversing array elements should be


array[0] = 500
array[1] = 35
array[2] = 16
array[3] = 5
array[4] = 10
Algorithm:
Basic algorithm for reversing any array.
Step 1: Take two array say A and B. A will hold the original values and B will hold the reversed
values.
Step 2: Read elements in array A.
Step 3: Set i=size - 1, j=0 (Where size is the size of array).
Step 4: Set B[j] = A[i]
Step 5: Set j = j + 1 and i = i - 1.
Step 6: Repeat Step 4-5 till i>=0.
Step 7: Print the reversed array in B.
Program:
#include <stdio.h>

int main()
{
int arr[100], reverse[100];
int size, i, j;

/*
* Reads the size of array and elements in array
*/
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

/*
* Reverse the array

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 186


*/
j=0;
for(i=size-1; i>=0; i--)
{
reverse[j] = arr[i];
j++;
}

/*
* Prints the reversed array
*/
printf("\nReversed array : ");
for(i=0; i<size; i++)
{
printf("%d\t", reverse[i]);
}

return 0;
}

C program to search an element in the array


Example: If the elements of array are: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5
Element to search is: 25
Output: Element exists
Algorithm:
Step 1: Read elements in array A.
Step 2: Read element to be searched in num.
Step 3: Set i=0, flag=0. We have initially supposed that the number doesn't exists in the array
hence we set flag=0.
Step 4: If A[i]==num then set flag=1 and print "Element found" and goto Step 6.
Step 5: Set i=i+1 and repeat Step 4 till i<size (Where size is the size of array).
Step 6: If the value of flag=0 then print "Element not found".
Program:
#include <stdio.h>

int main()
{
int arr[100];
int size, i, num, flag;

/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 187


scanf("%d", &size);

printf("Enter elements in array: ");


for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

printf("\nEnter the element to search within the array: ");


scanf("%d", &num);

/* Supposes that element is not in the array */


flag = 0;
for(i=0; i<size; i++)
{
/*
* If element is found in the array
*/
if(arr[i]==num)
{
flag = 1;
printf("\n%d is found at position %d", num, i+1);
break;
}
}

/*
* If element is not found in array
*/
if(flag==0)
{
printf("\n%d is not found in the array", num);
}

return 0;
}

C program to sort an array in ascending order


Example:
If the elements of array are: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40
Array sorted in ascending order: 0, 2, 6, 10, 20, 31, 40, 45, 52, 79
Algorithm:
Here we will use basic algorithm to sort arrays in ascending order:
Step 1: Read elements in array.

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 188


Step 2: Set i=0
Step 3: Set j=i+1
Step 4: If array[i] > array[j] then swap value of array[i] and array[j].
Step 5: Set j=j+1
Step 6: Repeat Step 4-5 till j<n (Where n is the size of the array)
Step 7: Set i=i+1
Step 8: Repeat Step 3-7 till i<n
Program:
#include <stdio.h>

int main()
{
int arr[100];
int size, i, j, temp;

/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);

printf("Enter elements in array: ");


for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

/*
* Array sorting code
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/*
* If there is a smaller element towards right of the array then swap it.
*/
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 189


}

/*
* Prints the sorted array
*/
printf("\nElements of array in sorted ascending order: ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}

return 0;
}

C program to find total number of alphabets, digits or special characters in a string


Example:
Input string: I love programming.
Output: Alphabets = 16
Digits = 0
Special character = 3
Total length = 19

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the string


int main()
{
char string[MAX_SIZE];
int alphabets, digits, others, i;

alphabets = digits = others = i = 0;

/* Reads a string from user */


printf("Enter any string : ");
gets(string);

/*
* Checks each character of string
*/
while(string[i]!='\0')
{

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 190


if((string[i]>='a' && string[i]<='z') || (string[i]>='A' && string[i]<='Z'))
{
alphabets++;
}
else if(string[i]>='0' && string[i]<='9')
{
digits++;
}
else
{
others++;
}

i++;
}

printf("Alphabets = %d\n", alphabets);


printf("Digits = %d\n", digits);
printf("Special characters = %d\n", others);

return 0;
}

= C program to convert Decimal to Binary number system

Example:
Input any decimal number: 112
Output binary number: 0111000
Decimal number system:
Decimal number system is a base 10 number system. Decimal number system uses only 10
symbols to represent all number i.e. 0 1 2 3 4 5 6 7 8 9
Binary number system:
Binary number system is a base 2 number system. Binary number system uses only 2 symbols to
represent all numbers i.e. 0 and 1

Algorithm to convert from Decimal to Binary number system:


Algorithm Decimal to Binary conversion
begin:
read (DECIMAL);
BINARY ← 0; PLACE ← 1; REM ← 0;
while (DECIMAL !=0) do
begin

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 191


REM ← DECIMAL % 2;
BINARY ← (REM * PLACE) + BINARY;
PLACE ← PLACE * 10;
DECIMAL ← DECIMAL / 2;
end
write('Binary = ' BINARY)
end

Program:
#include <stdio.h>

int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;

binary = 0;

/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;

/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;

binary = (rem * place) + binary;

tempDecimal /= 2;
place *= 10;
}

printf("\nDecimal number = %lld\n", decimal);


printf("Binary number = %lld", binary);

return 0;
}

Programming for Problem Solving (KCS-101/KCS-201) || S.K. Swarnakar@IT-GCET 192

You might also like