pps final
pps final
Unit -1
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.
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.
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).
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 2
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.
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.
9.
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.
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 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.
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 4
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.
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
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.
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.
• Memory Management
• Processor Management
• Device Management
• File Management
• 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
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 6
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.
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.
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.
Problem statement-
A problem statement is usually one or two sentences to explain the problem you are going to address by
programming.
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
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.
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 8
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.
• 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
• 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"
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"
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 10
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
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:
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.
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:
4. Draw flowchart to find the largest among three different numbers entered by user.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 12
5. Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 14
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.
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.
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
<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.
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 16
{ (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.
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).
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.
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.
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-
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.
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 18
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:
Error:
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.
// wrong logic // number is divided by 0, // so this program abnormally terminates div = n/0;
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
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 20
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.
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;
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.
||
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:
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 22
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
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
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.
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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 24
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.
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.
Standard I/O in C
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 26
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.
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 int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing newline to stdout.
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 −
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( ) {
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 −
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().
Formatted Input and Output-
Data can be entered & displayed in a particular format. Through format specifications, better presentation of results
can be obtained.
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.
2. Function scope.
3. File scope.
3. Program scope.
Exampl
e: 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
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.
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;
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 30
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).
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.
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(); 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.
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 32
Unit 2
Operators-
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Types
are-
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 (A >= B) is not (A >=
right 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
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 exists in (A & B) will give 12, which is 0000
& both operands. 1100
Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011
| 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49, which is
^ operand but not both. 0011 0001
(~A ) will give -61, which is
Binary Ones Complement Operator is unary and has the 1100 0011 in 2’s complement
~ effect of ‘flipping’ bits. form.
Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the right A << 2 will give 240 which is
<< operand. 1111 0000
Binary Right Shift Operator. The left operands value is
moved right by the number of bits specified by the right A >> 2 will give 15 which is 0000
>> operand. 1111
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 34
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 assign value
Simple assignment operator, Assigns values from right side operands of A + B into C
= to left side operand
C += A is equivalent to C =
Add AND assignment operator, It adds right operand to the left C+A
+= operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to
from the left operand and assign the result to left Operand C=C–A
-=
Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C =
with the left operand and assign the result to left Operand C*A
*=
C /= A is equivalent to
Divide AND assignment operator, It divides left operand with the C=C/A
/= right operand and assign the result to left operand
C %= A is equivalent to C =
Modulus AND assignment operator, It takes modulus using two operands C % A
%= and assign the result to left operand
<<= C <<= 2 is same as C = C <<
Left shift AND assignment operator 2
C >>= 2 is same as C = C >>
>>= Right shift AND assignment operator 2
C &= 2 is same as C = C &
&= Bitwise AND assignment operator 2
bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
^=
bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
|=
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
sizeof() It is a unary operator which is used in
finding the size of data type, constant, arrays,
sizeof(a), where a is integer, will return 4.
structure etc.
&a; will give actual address of the
& Returns the address of a variable. variable.
* Pointer to a variable. *a; will pointer to a variable.
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-
Lecture Notes || Programming for Problem Solving (BCS -101/BCS-201) || Mahesh Singh CSE-GCET 36
e, 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.
Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 37
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.
1 (age < 12 && height < 48) || (age > 65 && height > 72)
2 => (10 < 12 && 45 < 48) || (10 > 65 && 45 > 72)
3 => (1 && 1) || (10 > 65 && 45 > 72)
4 => 1 || (10 > 65 && 45 > 72)
5 => 1 || (0 && 0)
6 => 1 || 0
7 => 1
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.
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 38
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:
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 ()
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 39
{ 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 (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 (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 )
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 40
{ 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
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 */
Flow Diagram:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 41
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
Unit 3
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:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 42
{ 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 (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:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 43
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 (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:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 44
#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 Nested
for Loop in C
Nesting of loop is also possible. Lets take an example to understand this:
#inc
lude
<std
io.h
> int
mai
n()
{ for
(int
i=0;
i<2;
i++)
{ for (int j=0; j<4; j++)
{ printf("%d, %d\
n",i ,j);
}
}
r
e
t
u
r
n
0
;
}
Output:
0, 0
0, 1
0, 2
0, 3
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 45
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.
What’s the difference between above for loop and a simple for loop?
#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
Syntax:
Break;
Flow Diagram:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 46
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:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 47
Example:
#include <stdio.h> main () { int a = 10;
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:
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 48
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
Unit 3
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.
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 49
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.
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.
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);
Calling function need information about called function. If called function is place before calling function, then
the declaration is not needed.
Function Definition:
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.
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 50
Prototype or Declaration
Calling
Definition
Function Categories-
There are four main categories of the functions these are as follows:
. Function with no arguments and no return values.
. Function with no arguments and a return value.
. Function with arguments and no return values.
. Function with arguments and return values.
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 51
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);
}
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.
There are two ways to pass value or data to function in C language which is given below;
• call by value
• call by reference
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 52
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
return 0; }
t = x; x = y; y = t;
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 53
Difference between call by value and call by reference.
call by reference
This method copy original value into This method copy address of arguments
function as a arguments. into function as a arguments.
Changes made to the parameter inside the Changes made to the parameter affect the
function have no effect on the argument. argument. Because address is used to access
the actual argument.
Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
Example-
// C program to illustrate // Call
by Reference
#include
return 0;
}
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 54
Output: x=20 y=10
a=20 b=10
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.
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.
Lecture Notes || Progra Programming for Problem Solving (BCS -101/BCS-201) Mahesh Singh CSE_GCET 55
Example: Sum of Natural Numbers Using
Recursion
#include
<stdio.h> int
sum(int n);
result = sum(number);
int
sum(int
n) { if (n
!= 0)
// sum() function calls itself
return n + sum(n-1);
else
retur
n n;
}
Output
Enter a positive
integer:3 sum = 6
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-:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 58
• 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:
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:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 59
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.
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]);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 60
}
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;
}
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:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 61
{ //column of second matrix sum=0; for(k=0;k<n;k++)
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;
}
As we already know in this type of function call, the actual parameter is copied to the formal parameters.
#i
n
cl
u
d
e
<
st
di
o.
h
>
v
oi
d
di
s
p
(
c
h
ar
c
h
)
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j'};
for (int x=0; x<10; x++)
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 62
{
/* 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
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
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++)
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 63
{ 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:
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)
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,
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);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 64
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.
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);
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); 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:
Writing string
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.
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.
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(); }
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 66
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.
at():
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
hr():
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’);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 67
Prints the string s followed by new line character.
Returns a non-zero integer if possible or EOF if
int puts( char s); 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 written to s, or EOF
if an error occurs
int sprint(char s, char format,….)
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
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
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};
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 68
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);
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;
};
of structure .
Here is how we can declare an array
car
Here is an array arr_car of 10 elements where each element is of type struct car. We can use arr_car to store
structure 10 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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 69
arr_stu[0] : points to the 0th element of the array.
arr_stu[1] : points to the 1st 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.
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}
};
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 70
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.
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 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.
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 71
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.
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 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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 72
}
return -1;
}
searchValue([10, 5, 15, 20, 25, 35] , 25); // Call the function with array and number to be searched
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:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 73
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.
Output:
Sorting-
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 74
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.
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.
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 75
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>
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 77
Lecture Notes || Unit -4 || CO-5 || Lecture Number
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.
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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 78
}
return 0; }
Output:
5 6 11 12 13
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
Code-
// C program for implementation of selection sort
#include <stdio.h> void swap(int *xp, int *yp)
{ int temp = *xp;
*xp = *yp;
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 79
Lecture Notes || Unit -4 || CO-5 || Lecture Number
*yp = temp; }
// 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
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 80
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
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.
** 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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 81
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:
• binary search
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 82
Unit 5
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 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 ) ;
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 83
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, 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 ;
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 84
printf ( "\nOriginal address in x = %u", x ) ; printf ( "\
nOriginal address in y = %u", y ) ; printf ( "\nOriginal
address in z = %u", z ) ; x++ ; y++ ;
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:
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 ;
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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 85
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.
**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
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.
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc()
Allocates space for an array elements, initializes to zero and then returns a pointer to memory
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 86
Syntax of malloc()
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.
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()
This statement will allocate contiguous space in memory for an array of n elements. For example:
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
()
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.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically
using malloc() function.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 87
#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);
}
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);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 88
0; i < num; ++i)
{ scanf("%d", ptr + i); sum
+= *(ptr + i);
}
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()
#include <stdio.h>
#include <stdlib.h>
int main()
{ int *ptr, i , n1, n2;
printf("Enter size of array: "); scanf("%d",
&n1);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 89
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.
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.
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.
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:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 90
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
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
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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 91
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
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.
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);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 92
fclose(fptr); return 0;
}
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);
}
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 93
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;
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 94
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.
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 )
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.
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 95
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:
If macroname has been #defined, the block of code will be processed as usual; otherwise not.
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.
If we so desire we can have nested conditional compilation directives. An example that uses such directives is shown
below.
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.
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 96
#elif ADAPTER == SVGA
code for super video graphics array
#else
code for extended graphics adapter #endif
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.
(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" ) ;
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 97
} int f3( ) { int x = 6 ; return
x ; x++ ; }
void main( )
{ f1( ) ; f2 ( 7 ) ; f3( ) ;
}
CommandLineArguments inC–
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:
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.
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:
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 98
{
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-
Output-
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 99
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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 100
#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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 101
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)
{ printf("SUNDAY\n");
} else
{ printf("Invalid Input! Please enter week number between 1-7.\n");
} return 0;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 103
}
printf("\nSum of digits = %d", sum); return 0;
}
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 */
n = n/10;
} printf("Reverse = %d", rev);
return 0;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 104
/* 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;
}
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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 105
*/
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;
}
/*
* 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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 106
/* 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;} 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
/* 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;
}
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
/*
* 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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 108
*/ if(isPrime==1) { sum += i;
}
} printf("Sum of all prime numbers between 1 to %d = %d", n, sum); return 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>
/* Function declarations */ int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);
int main()
{ int 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;
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 110
{ 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;
}
/**
* 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;
#include <stdio.h>
#include <math.h>
/* Fuction declaration */ int reverse(int num);
return 0;
}
/**
* Recursive function to find reverse of any number
*/ int reverse(int num)
{ int digit;
//Base condition if(num==0) return 0;
#include <stdio.h>
//Function declaration long long fibo(int num);
int main()
{
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);
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 112
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.
}
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 thearray: ", n);
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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 113
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>
/*
* Reads size array and elements in the array
*/
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array: "); for(i=0; i<size; i++)
{ scanf("%d", &arr[i]); }
/*
* Prints the maximum and minimum element
*/
printf("Maximum element = %d\n", max); printf("Minimum element = %d", min);
return 0;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 114
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
*/ 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;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 115
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: "); scanf("%d", &size);
printf("\nEnter the element to search within the array: "); scanf("%d", &num);
/*
* If element is not found in array
*/ if(flag==0)
{ printf("\n%d is not found in the array", num);
}
return 0;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 116
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);
/*
* 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;
}
}
}
/*
* 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>
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 117
#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;
/*
* Checks each character of string
*/ while(string[i]!='\0')
{
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++;
}
return 0;
}
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
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 118
while (DECIMAL !=0) do begin
REM ← DECIMAL % 2;
BINARY ← (REM * PLACE) + BINARY;
PLACE ← PLACE * 10;
DECIMAL ← DECIMAL / 2;
end
write('Binary = ' BINARY) end
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;
return 0;
}
Lecture Notes || Programming for Problem Solving ((BCS -101/BCS-201) Mahesh Singh CSE_GCET 119