Executing A C Program Executing A C Program Executing A C Program
Executing A C Program Executing A C Program Executing A C Program
Executing a C Program
Executing a program written in C involves a series of steps. They include,
3) Linking the program with functions that are needed from the C library
How to Compile and Run a C Program on Ubuntu Linux using gcc compiler
Step 1: Open up a terminal
Search for the terminal application in the dash tool (located as the topmost item in the
launcher)
For ease of future access to terminal application, right click its icon in the launcher and select
"Lock to Launcher"
First way
$ gcc helloc.c
if there are no errors, executable file a.out (default file) will be created under current
directory.
Second way
if there are no errors, executable file hello (user specified file name) will be created under the
current directory.
The above command will invoke the GNU C compiler to compile the file hello.c and output
(-o) the result to an executable called hello
First way
$ ./a.out
Second way
$ ./hello
Executing the above commands should result in the output Hello World
$ cd
$pwd
/home/kumar
.. (double dots) – This represents the parent directory.
Let us assume that we are placed in /home/kumar/progs/data/text/abc
directory, you can use .. as an argument to cd to move to the parent directory of
the current directory. i.e., /home/kumar/progs/data/text
$ pwd
/home/kumar/progs/data/text/abc
$ cd ..
/home/kumar/progs/data/text
Here the command cd .. means “change your directory to the parent of the
current directory”. You can combine any number of such sets of .. separated by /.
$ pwd
/home/kumar/progs/data/text
To come back to home directory instead of giving cd /home/kumar, you can use
the following command also:
S cd ../..
$ pwd
/home/kumar
mkdir: making Directories
In UNIX, directories are created using mkdir (make a directory) command. The
command is followed by name of the directories to be created.
A directory progs can be created under the current directory as shown below:
$ mkdir progs
User can create a number of subdirectories under the current working directory
in a single command line as shown below,
$ mkdir patch dos disk
User can create a directory tree using mkdir command as
$ mkdir patch patch/sub1 patch/sub2
Above command creates a subdirectories patch under current directory and two
subdirectories under patch directory.
Module 1 Prof. C K Marigowda/Arun K H 6
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
In the above command the order of specifying the arguments is very important.
First you have to specify the directory name followed by subdirectories names.
(Because you cant create subdirectories for a directory which does not exist).
Sometimes system may fail to create a directory:
$ mkdir test
mkdir: Failed to make directory “test”; permission denied.
This can happen in following the situations:
The directory name may already exist.
There may be an ordinary file by same name under current working
directory.
The permission set for the current directory doesn’t permit the creation
of files and directories by the user.
$ rmdir /home/kumar/pis/progs
rmdir: directory “/home/kumar/pis/progs” does not exist.
To remove this directory, you must be placed in the parent directory of progs i.e.,
pis.
$ cd /home/kumar/pis
$ pwd
/home/kumar/pis
$ rmdir progs
ls: listing directory contents
The command ls, list the files and subdirectories present under your current
directory
$ ls
12_list.html /* Numerals first, Uppercase next
Calendar Then lowercase */
Cptyodoc.c
Dept.lst
Progs
file.1
helpdir
toc.sh
rm: Removing a File
rm stands for remove here. rm command is used to remove objects such as files, ,
symbolic links and so on from the file system. By default, it does not remove
directories.
This command normally works silently and you should be very careful while running
rm command because once you delete the files then you are not able to recover the
contents of files and directories.
Syntax
rm [OPTION]... FILE...
Let us consider 5 files having name a.txt, b.txt and so on till e.txt
$ ls
a.txt b.txt c.txt d.txt e.txt
$ ls
b.txt c.txt d.txt e.txt
$ ls
d.txt e.txt
-i (Interactive Deletion): Like in cp, the -i option makes the command ask the user for
confirmation before removing each file, you have to press y for confirm deletion, any
other key leaves the file un-deleted.
$ rm -i d.txt
rm: remove regular empty file 'd.txt'? y
$ ls
e.txt
Programs are generally written using a high level language (Ex: C), however, computers
being binary devices, understand only meaningful sequences of 0s and 1s, commonly called
as the machine level language. The CPU doesn't understand high level languages, so before
execution, programs must be translated into corresponding machine level language by using
translator programs (Ex: Compiler).
o Accuracy
− In addition to being fast, computers are accurate.
− Computers produce results which are error free and all the calculations are 100%
accurate provided there are no errors in the input / program.
o Storage Capability
− A computer can store huge amount of data.
− It can store different types of data which include text, image, audio, video etc.
o Diligence
− Unlike human beings, a computer is free from monotony, tiredness and lack of
concentration.
− It can work continuously without any error or boredom.
− It can do repeated work with the same speed and accuracy.
o Versatility
− A computer is a highly versatile machine which can be used for performing
variety of jobs.
− At one instance, it may be solving a complex scientific problem and the very
next moment it may be used to play a game.
o Automation
− Computers are automatic in operation. It means once the data and instructions
are fed to a computer, human interventions are not required.
− The computers manipulate the data according to the instructions and continue
doing so till the last instruction is executed.
3. Computer Generations
3.1 Vacuum Tubes : The First Generation
This generation of computers used thousands of vacuum tubes for computation.
Memory requirements were met by magnetic drums, program input was provided by
punched cards and output was obtained on paper.
Because of the size of vacuum tubes, they occupied lot of space. They also consumed
enormous amounts of power and generated lot of heat.
They were programmed using first generation language (machine language) which
was low level cryptic language (only 0s and 1s).
They were very expensive to buy and maintain. They were used only for scientific
work and were not deployed commercially.
Example: Colossus andENIAC (Electronic Numerical Integrator and Computer)
− Neural networks and expert systems for decision making : Some financial
institutions are already using these technologies for detection of credit card
fraud.
4. Computer Types
Computers can be classified based on their size. The size of a computer is often an indirect
indicator of its capabilities and the application domains where they are employed.
4.1 Super Computers
Super computers are the fastest computers currently available. They make use of
multiple CPUs for parallel data processing (portions of the same program are handled
independently by multiple processors)
The speed of super computers are measured in flops (floating point operations per
second).
Ex: Tianhe-2 operates at a speed of 34 petaflops (1 peta=1000 tera=1000000 giga)
They have enormous storage, use huge amounts of power and generate a lot of heat.
Because of their exorbitant cost, they are mainly used by government agencies.
They are used in applications that require immense amount of mathematical
calculations.
Ex: Weather forecasting, Analysis of geological data, Nuclear simulation, Space
exploration , graphics, electronic design etc.
Example: Aaditya, PARAM Yuva II, Pratyush
4.2 Mainframes
A mainframe is the powerful central computer in a data processing center, linked to
thousands of users through less powerful devices such as PC or dumb terminals. They
are multi-user machines supporting thousands of users using the feature of time
sharing
They were the largest computers available before the advent of supercomputers. The
speed of mainframesare measured in mips (million instructions per second).
They are used to handle data and applications related to the organization as a whole.
Typically, they are used in organizations like banks, airlines, railways and stock
exchange to handle millions and trillions of online transactions per second.
Example: IBM z
4.3 Minicomputers
Minicomputers are also called mid-range computers. Its size lies between that of a
mainframe and a microcomputer.
They can be considered as downsized mainframes capable of serving few hundreds of
users.They are also multi-user systems where more than one user can work
simultaneously.
They are used in smaller organizations or a department of a large company.
They are typically used for scientific and engineering computations, business
transaction processing, file handling, and database management.
Ex: HP 3000 series, IBM midrange computers
4.4 Microcomputers
Microcomputers are also called personal computers (PC). It was introduced by Apple
and later endorsed by IBM. It is a single user machine powered by a single chip
microprocessor.
It is relatively small in size and less expensive. It can be used in a standalone mode or
in a network.
A microcomputer takes the form of a desktop, notebook(laptop), a netbook (smaller
laptop) or a workstation.
− A notebook is a portable computer which has a processing power similar to a
desktop computer. It weighs around 5kgs. It has a screen size of greater
than 15 inches.The mouse is replaced by a touchpad, It usually comes with
built-in multiple USB ports and contains a CD/DVD drive.
− Netbooks were designed to offer the basic computing functionalities in a
smaller, lightweight, more portable device. Netbooks generally weigh
around 1-2kgs and have smaller screens, which vary from 7 inches to 12
inches diagonally. Since netbooks are smaller in size, they do not come with
any in-built CD/DVD drive.
− A workstation is a computer intended for individual use that is faster and more
capable than a personal computer. It's intended for business or professional use.
Microcomputers are typically used for word processing, spread sheet handling,
desktop publishing, internet browsing, handling multimedia and for entertainment.
Note:
1) 1 kilobyte (1KB) =1024 bytes = 210 bytes
2) 1 megabyte (1MB) =1024 kilobytes = 220 bytes
3) 1 gigabyte (1GB) =1024 megabytes = 230 bytes
4) 1 terabyte (1TB) =1024 gigabytes = 240 bytes
5) 1 petabyte (1PB) =1024 terabytes = 250 bytes
6) It is customary to use 'B' for bytes and 'b' for bits.
Ex: Speed of network is 1 Mbps (megabits per second)
Memory occupied by the program is 1KB (kilo bytes)
The brain of the computer is the Central Processing Unit (CPU), represented by a single chip
on a PC. The CPU carries out every instruction stored in the program, while interacting with
Module 1 Prof. C K Marigowda/ Prof. Arun K H 8
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
other components as and when necessary. A major part of the work is done by the Arithmetic
and Logic Unit (ALU), which is a integral part of the CPU.The CPU needs both fast and slow
memory to work with. Fast memory is represented by the primary memory and slow memory
is represented by the secondary memory.
The primary memory is divided into a number of contiguously numbered cells (numbers
represent the address of the cell). It is used for storing instructions and data of the program
currently in execution. The CPU accesses a memory location by sending its address to the
memory unit. The secondary memory is usually the hard disk, but it can also be the CD-ROM
or DVD-ROM. It is used for storing data that is not required currently. A program that needs
to be executed is first loaded from secondary memory to primary memory.
Input / Output devices are used to facilitate the interaction between the user and the computer.
Data that keyed in through the keyboard (input device) are converted to binary form before
they are saved in the RAM. After processing, the output data have to undergo a reverse
conversion (binary to human readable form) before they are displayed on the monitor or
printer (output device).
There are 3 types of data that move between the various components of the computer. The
data of a specific type move along a distinct pathway, called a bus. Program instructions and
data move along the data bus. Memory addresses travel along the address bus. All control
signals use the control bus.
7. Computer Components
7.1 Central Processing Unit
The CPU is the brain of the computer, which executes instructions one after the other with
the help of ALU and CU. It generates lot of heat and that is the reason it is mounted with a
heat sink and a fan to dissipate heat. It consists of the following components.
Control Unit (CU) - It controls and coordinates the activities of all the components
by issuing appropriate commands. Using signals, the CU controls the way the data is
moved between the various components. It is responsible for the fetch-decode-execute
mechanism i.e. fetching the next instruction to be executed, decoding the instruction
and executing the instruction.
Arithmetic and Logic Unit (ALU) - This is the place where actual operations are
carried out. As the name suggests, ALU performs basic arithmetic and logical
operations.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 9
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Special purpose registers - The CPU has a number of temporary storage units called
registers. They are used to store instructions & intermediate data which may be
generated during processing. One such register is called the program counter, which
stores the address of the next instruction to be executed.
Clock - Clock generates pulses at regular intervals for synchronizing the activities of
the CPU. The CPU cannot execute more than one instruction in one clock pulse even
though one instruction may take several clock pulses to execute. Faster the clock
faster is the execution, for example, clock speed of 3.4GHz means, it emits 3.4 billion
pulses in one second.
− Registers being very few are numbered and a program instruction specifies
those numbers.
EX: The instruction MUL R1 R2 R3 would be interpreted by the CPU as
multiply the operands stored in registers R1 and R2, and store the result in
register R3.
Hard Disk
− It is also known as hard drive or fixed disk because it is fixed inside the
computer. Hard disks have very high capacities with the cheapest cost.
− The hard disk houses the computer’s operating system along with all programs
and data.
− Hard disk structure
Every disk contains a spindle that holds one or more platters made of
non-magnetic material.
Information is encoded onto these platters by changing the direction of
magnetization using a pair of read-write heads.
Each surface is composed of a number of concentric and serially
numbered tracks.
The disk spins constantly in order to access information stored.
Magnetic Tape
− The tape is made of a plastic film with one side coated with magnetic material.
The entire mechanism comprising two spools and the tape is encapsulated in a
small cassette or cartridge.
− Data are read from and written to the tape using a read-write head and an
erasure head.
− Data access is sequential i.e. to locate a file the tape has to rewound before a
sequential search can begin.
− This kind of storage is more suitable for storing data that are not needed
frequently.
Flash Memory
− This device is based on the EEPROM and is available in various forms - pen
drive, solid state disk (SSD) and the magnetic card (SD card).
− They are portable, need little power and quiet reliable.
− Pen drive is small piece of circuit wrapped in plastic which connects to the
USB port of the computer where it is detected by the operating system as yet
another drive.
− SSD is a bigger device meant to replace the traditional hard disk. Many
laptops have their operating system and a small set of programs stored on this
online device.
− Magnetic card is mainly used in cameras, using adapters they can also be
connected to the USB ports of the computer.
Floppy Diskette
− The floppy diskette was once the only form of portable storage that could be
carried in the pocket.
− This storage medium is represented by a rectangular plastic case containing a
thin magnetic disk.
− A read/write head actually makes contact with this disk while it is rotating.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 13
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
− The floppy was available in two sizes 5.25 inch and 3.5 inch, offering
capacities of 1.2 MB and 1.44 MB.
7.4 Ports and Connectors
A computer port is a connection point or interface between a computer and an external or
internal device. Internal ports may connect such devices as hard drives and CD ROM or DVD
drives; external ports may connect modems, printers, mice and other devices.
They are shaped differently, so it is impossible to use a wrong connector for a port. The
following are the different types of ports and connectors
Serial Port −A serial port is an interface through which peripherals can be connected
using a serial protocol which involves the transmission of data one bit at a time over a
single communication line.
Parallel Port −A parallel port, on the other hand, is an interface through which the
communication between a computer and its peripheral device is in a parallel manner
i.e. data is transferred in or out in parallel using more than one communication line or
wire.
Universal Serial Bus (USB) − USB port has virtually replaced the serial and parallel
ports in the motherboard. It has 4 lines, two each for data and power.It can be used to
transfer data, act as an interface for peripherals and even act as power supply for
devices connected to it.
Video Graphics Array (VGA) Port − This is a 15 pin port which allows transfer of
analog video data to monitor. This port is being replaced by DVI (Digital Video
Interface) which offers better video resolution than VGA.
RJ45 Port −Ethernet is a networking technology that is used to connect the computer
to Internet and communicate with other computers or networking devices.The
interface that is used for computer networking is known as Registered Jack (RJ) and
RJ45 port in particular is used for Ethernet over cable.
PS/2 Port − This is used to connect keyboard and mouse. It has 6 pins but occurs as a
pair of 2 different colors. The connectors are color coded as purple for keyboard and
green for mouse.
High Definition Multimedia Interface (HDMI)− This is the digital interface for
transferring audio and video data between computers and HDTVs, Projectors, and
home theaters. A single cable here can handle both audio and video.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 14
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Scanner
− A scanner is a device that creates a digital image of a document by optically
scanning it.
− Working of a Scanner
The document to be scanned is placed on a glass plate that is covered
by a lid before scanning.
A shining light is beamed at the document and the reflected light is
captured by a photosensitive array of charged coupled devices.
The differing levels of brightness are converted into electronic signals.
The signals are processed to create the digital image which is saved as
a file in the hard disk.
− The scanner can also act as a photocopier and print the copied document
without saving it.
Non-Impact Printers
− They are quiet, fast and produce documents of very high resolution. They are
of two types : Laser Printer and Ink Jet Printer.
Laser Printer
− A laser beam creates an image of the page to printed on a light
sensitive drum.
− The charged areas attract black magnetic powder called as toner.
− The image which is created in the form of dots is then transferred from
the drum to the paper by actual contact.
− A separate roller heats up the paper to melt the toner which then gets
fused onto the paper.
− This is suitable for printing text and graphics in high quality.
− They have RAM for storing documents for printing. They also have
ROM for storing different fonts.
Ink Jet Printer
− The print quality of this outperforms dot matrix printer but
underperforms laser printer.
− A printhead sprays tiny drops of ink at high pressure as it moves along
the paper.
− The ink stored in a replaceable cartridge passes through a matrix
comprising a number of tiny nozzles.
− Characters are formed by choosing the nozzles that have to be
activated.
Plotters
− A plotter is a special output device used to produce hard copies of large graphs
and designs on paper, such as construction maps, engineering drawings, and
architectural plans.
− They take commands from vector graphics file.
− The different types of plotter include drum plotter, flat bed plotter, ink jet
plotter, cutting plotter.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 18
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
8. Computer Networks
A computer network is a group of two or more computers and other hardware devices
connected together for the purpose of sharing information and resources.
The following are the benefits of using computer networks
1. Data and Resource Sharing
All the programs, data and peripheral devices such as scanners, printers,
plotters etc can be made available (shared) to anyone on the network without regard to
the physical location of the resource and the user.
2. High Reliability
Alternative sources of supply can be made possible in a computer network.
For example, all data can be replicated on 2 or 3 machines, so that if one of them is
unavailable due to some failure, the other copies could be used.
3. Load Sharing
If one computer is saturated with many jobs, some of the jobs can be
transferred to other machines and executed there.
4. Scalability
This is another networking advantage because of which as the workload
increases the system performance can be increased by adding more number of
processors.
5. Saving of Money
Powerful PC’s used in place of mainframe computers lead to saving of money.
Small computers in network have a much better price/performance ratio than large
mainframe computers.
6. Powerful Communication Medium
A computer network can provide a powerful communication medium via
applications such as Email, chat, video conference, newsgroups etc.
7. Flexible Work Environment
Employees can sit at home or hotel and work form there, after connecting to
the work place through internet. They can send/receive data to/from remote place.
8. Interactive Entertainment
This includes applications such as video on demand, multi person real-time
simulation games (Ex: hide & seek, flight simulation etc).
− Bus Topology: The bus topology uses a single cable as a bus to which all computers
areconnected. Failure of any node in the network does not disrupt the communication
between the remaining nodes.
− Star Topology:The star topology uses a central hub to which all nodes are connected.
Since the network traffic passes through the central hub, failure of the hub results in
failure of the entire network.
− Ring Topology :Nodes are connected in a closed loop without using a hub. Data
moves from one node to the next one for transmission from source to destination.
Failure of one node causes the entire network to shut down.
− Mesh Topology : Nodes are connected to one another, offering a choice of multiple
routes for datato travel. When a node breaks down, an alternate route is always there
for data transmission.
− Wide Area Network (WAN) : It is a computer network that extends over a larger
geographical area. It can connect establishments across different cities and because of
the large distances optical fiber cables, leased telephone lines and radio transmission
are used to connect nodes.
− Metropolitan Area Network (MAN) : This between LAN and WAN. It is employed
for interconnecting computers in the same city.
− Campus Area Network (CAN) : This is smaller than MAN and it is used to connect
an entire university campus.
− Personal Area Network (PAN) :This is the smallest network of allorganized around
a individual person. It operates within a range of few meters. It connects small devices
like cell phones and laptops with infrared or Bluetooth technology.
same network, then the router sends the packet directly to the node. Otherwise,
it sends it to another router that takes it closer to its destination.
9. Computer Software
Need for Software
− A computer is probably the only machine that cannot do anything immediately after it
has been built because the CPU has not been specifically instructed to do any work.
− It’s the software that provides the directives for the CPU to work..
− It was only after Turing and von Neumann introduced the concept of the stored
program that program and data could be stored in memory. That’s the way computers
use software today.
Software Basics
Software Types
System software
− This is the software run by the computer to manage the hardware connected to it.
Users don’t have much control over its functioning, but their own programs
(application software) use the services offered by system software whenever required.
− System software is the intermediary between the application and the hardware, and
because of its direct access to the hardware it provides the services needed by
programs and users.
− System Software include but not restricted to the following
Basic Input Output System (BIOS) - This is a small program that checks the
hardware devices and peripherals at boot time and then loads the operating
system
Operating System - This is the central system software that manages both the
hardware and programs running on the computer. Because all programs need
its service, the operating system remains in memory as along as the computer
is up.
Device Driver - Every hardware needs a special software that know how to
handle it. Programs access a device driver by making a call to the operating
system.
Compilers and Associated Programs - A programmer invokes a compiler
program to convert the source code written by them to machine code.
Application software
− Software of this type relates to a specific application, say, one that makes hotel
bookings or creates special effects in movies. The vast majority of programmers are
engaged in developing application software.
− Software not directly connected with hardware but related to a specific real-life
situation is known as application software.
− Application software include but not restricted to the following
Office Software - When the desktop PC came into being, office software was
one of its first application. This includes 3 applications - word processing,
spreadsheet applications and presentations.
Database Software - This is commonly known as database management
system (DBMS). It allows data having uniform structure to be stored in a
database. Each line of database is made of multiple fields that may be added,
modified and queried using simple instructions.
Example: Microsoft Access, Oracle.
Communication Software - Computer networking led to the development of
software that allowed users to communicate with one another.
Example: Email, Skype, Whatsapp
Entertainment Software - This includes softwares for gaming and
multimedia. The VLC software serves as a one stop shop for playing most of
the audio and video formats.
Antivirus Software - A virus is a small program designed by a person with
malicious intent. A virus can cause your programs to misbehave or not work at
all. It can even wipe out data from the harddisk. Antivirus software is now an
essential program to have on the computer to protect from viruses.
Special purpose Software - Apart from the general purpose software
mentioned earlier there are some special purpose softwares which include but
not limited to CAD/CAM (computer aided design/manufacturing), distance
learning etc.
A Simple C Program
#include<stdio.h>
main( )
{
printf("Hello 2020 Batch ISE");
}
− Any statement that begins with a # is a preprocessor directive used for instructing the
compiler.
− #include tells the compiler to include standard library function from a header file that will be
used in the program.
− stdio.h is the header file for standard input and output. This is useful for getting the input
from the user(Keyboard) and output result to the monitor(screen).
#include<stdio.h>
#define PI 3.14
void main( )
{
int r = 10;
printf("Area of circle = %f", PI*r*r);
}
− #define is preprocessor directive, It is used to define a value for a symbolic constant in the
program. Whenever a symbolic name is encountered, the compiler substitutes the value
associated with the name automatically.
− int r = 10 is used for declaring an integer variable 'r' and storing a value 10 in it.
− printf is used for printing the area of the circle
#include<stdio.h>
#define PI 3.14
void main( )
{
int r = 10;
printf("Area of circle = %f", area(r) );
}
int area(int r)
{
return PI*r*r ;
}
− In this program, the job of finding area of circle is entrusted to another function named area
− int area(int r); is used to declare a user defined function for finding area of a circle
− After the main function, the area function is defined.
− The function area finds the area of the circle as PI*r*r and returns it to the main function
and hence its return type is int.
#include<stdio.h>
#define PI 3.14
int r = 10;
void main( )
{
printf("Area of circle = %f", area(r) );
}
float area( )
{
return PI*r*r ;
}
− In the previous program, the variable 'r' was declared in the main function and was a local
variable to the main function. Local variables are accessible only in the function in which it is
defined, hence it was sent as parameter for the function area to compute the area of the
circle.
− In this program, the variable 'r' is declared outside the main function well before it and is a
global variable. A global variable is accessible by all the functions of the program and hence
it need not be sent as a parameter.
Link Section
Definition Section
Executable Part
}
Subprogram Section
User defined function 1
User defined function 2
.
.
User defined function n
1. Documentation Section - This generally includes the description of the program, name of the
programmer and other useful comments. It is written within /* and */ or //
/* multi line comment*/
2. Link Section - This provides instructions to the compiler to link functions from the system
library.
3. Definition Section - This defines all the symbolic constants
4. Global Declaration Section - This section is used to declare all the global variables.
5. User defined functions declaration - This section is used to declare all the user defined
functions of the program.
6. main() function section - Every C program must have one main function. This has two parts
declaration part and executable part. The declaration part declares all the variables used in
the executable part and the executable part must have atleast one statement.
7. The subprogram section contains all the user defined functions that are called in the main
function.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 3
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Algorithms
Algorithm is a step by step procedure to solve a given problem in a finite number of steps by
accepting a set of inputs and producing the desired output.
3) Each step must be specified with sufficient amount of explanation within [ ] before writing the
instruction.
Read a, b
sum = a + b
Read r
area = 3.14 * r * r
Read l, b
area = l * b
Read P, T and R
SI =P*T*R/100;
print SI
Read a, b
print a, b
temp = a
a=b
b = temp
print a, b
Q6) Write an algorithm to swap or exchange 2 numbers without using third variable
Read a, b
print a, b
b=a/b // b = 200/20 = 10
a=a/b // a = 200/10 = 20
print a, b
Read N
Step 2: [Check if the number if positive or negative and output the result]
Read N
Step 2: [Check if the number if Odd or Even and output the result]
OR
Read a,b
Step 2: [Find the bigger of 2 numbers by comparing and output the bigger number]
Read a,b,c
Read a,b,c
disc = (b * b) - (4 * a * c)
Step 3: [Classify and compute the roots based on the discriminant value]
if disc == 0
else if disc> 0
else
x1 = -b / (2*a)
x2 = sqrt(fabs(disc)) / (2*a)
root1 = x1 + i x2
root2 = x1 - i x2
Flowcharts
The following are the different geometric shapes that are used to represent the symbols while
writing a flow chart.
Start
Read a, b
sum = a + b
Print sum
Stop
Start
Read r
area = 3.14 * r * r
Print area
Stop
Start
Read l, b
area = l * b
Print area
Stop
Start
Read P,T, R
SI = P*T*R/100
Print SI
Stop
Start
Read a, b
Print a, b
temp = a
a=b
b = temp
Print a, b
Stop
Q6) Write a flowchart to swap or exchange 2 numbers without using third variable
Start
Read a, b
Print a, b
a=a*b
b=a/b
a=a/b
Print a, b
Stop
Start
Read N
Yes No
is N > 0
Stop
Start
Read N
Yes No
is N %2 == 0
Stop
Start
Read a, b
Yes No
is a > b
Stop
Start
Read a, b, c
Yes No
is a > b && a > c
Yes No
Print a is largest
is b > c
Stop
Module 1 Prof. C K Marigowda/ Prof. Arun K H 6
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Start
Read a, b, c
disc = (b * b) - (4 * a * c)
Yes No
is disc = 0
Yes No
is disc > 0
Print roots are Print roots are real Print roots are
equal & distinct imaginary
Print root1 & root2 Print root1 & root2 Print root1 & root2
Stop
The data type defines the type of data stored in memory location. It determines how much
memory should be allocated for a variable associated with the data type.
void is generally used with functions that does not return any value or with generic pointers.
The following table gives the details of the primitive data types on a 16-bit Machine
Format
Specifier for
Data Type Keyword Memory Range
input /
output
0 to 216 - 1
0 to 65535 (unsigned)
Variables in C
A variable is a name given to the memory location where the data can be stored. Using this
name the data can be further accessed or manipulated easily.
Example:
int a, b, c; // declaration of 3 integer variables
float x, y; // declaration of 2 floating point variables
With this declaration, memory for 3 integers and 2 floating point variables will be allocated
by the compiler. The memory map is as shown below
a b c x y
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
GV GV GV GV GV
Declaration of variables will only allocate memory, however, the contents inside the memory
will be unknown values (also referred to as garbage values).
Input functions accept the data from input devices (keyboard) and store them in the
memory locations.
Example: scanf(),getchar(), gets() etc.
Output functions retrieve the data from memory locations and send them to output
devices (monitor, printer).
Example: printf(),putchar(), puts() etc.
To output values
– Write text (optional) along with format specifiers within double quotes,
followed by a comma, followed by the names of variables separated by
comma inside printf.
The general syntax of printf ( ) is
printf("control string", var1, var2, var3,...........,varN);
int a = 10;
int b = 20;
float c = 3.14;
float d = 7.25;
The following table gives a set of statements along with its output
printf(“%d %d”, a, b); 10 20
printf(“The value of a is %d”, a); The value of a is 10
printf(“The value of a is %d and b is %d”, a, b); The value of a is 10 and b is 20
printf(“%d %d %f %f”, a, b, c, d); 10 20 3.14 7.25
printf(“%f %d %f %d”, c, a, d, b); 3.14 10 7.25 20
printf(“The value of c is %f and a is %d”, c, a); The value of c is 3.14 and a is 10
Note:
This can be further formatted using \t and \n for making it more readable
Example:
3.14
10
7.25
20
Q1) Write a C program to find the sum of two numbers
#include<stdio.h>
void main( )
{
int a, b, sum;
a = 10;
b = 20;
sum = a + b;
printf("the sum of %d and %d is %d\n", a, b, sum);
}
#include<stdio.h>
void main( )
{
int l, b, area;
l = 10;
b = 20;
area = l * b;
printf("the area of rectangle is %d\n", area);
}
2) scanf( ) function
To read values
– Write the format specifiers within double quotes, followed by a comma,
followed by the address of variables separated by comma inside scanf.
EX: scanf(“%d %d %d”, &a, &b, &c);
The general syntax of scanf ( ) is
scanf("control string", &var1, &var2, &var3,...........,&varN);
int a = 10;
int b = 20;
float c = 3.14;
Module 2 Prof. C K Marigowda/ Prof. Arun K H 4
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
float d = 7.25;
The following table gives description along with the corresponding statement to
accomplish the description
Note:
1) The number of format specifiers and the address of variables must be same.
2) The order/type of format specifiers and the address of variables must be same.
#include<stdio.h>
void main( )
{
int a, b, sum;
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b\n");
scanf("%d",&b);
sum = a + b;
printf("the sum of %d and %d is %d\n", a, b, sum);
}
#include<stdio.h>
void main( )
{
int l, b, area;
printf("Enter the length of rectangle\n");
scanf("%d",&l);
printf("Enter the breadth of rectangle\n");
scanf("%d",&b);
area = l * b;
printf("the area of rectangle is %d\n", area);
}
Simple Programs
#include<stdio.h>
void main( )
{
int p, t, r, si;
printf("Enter the principal amount\n");
scanf("%d",&p);
printf("Enter the time duration\n");
scanf("%d",&t);
printf("Enter the rate of interest\n");
scanf("%d",&r);
si = (p*t*r)/100;
printf("simple interest is %d\n", si);
}
#include<stdio.h>
void main( )
{
int a, b, temp;
printf("Enter the values of a and b\n");
scanf("%d%d",&a, &b);
printf("Before Swapping\n");
printf("The values of a is %d and b is %d\n",a,b);
temp = a;
a = b;
b = temp;
printf("After Swapping\n");
printf("The values of a is %d and b is %d\n",a,b);
}
Q5) Write a C program to swap two numbers without using a third variable
#include<stdio.h>
void main( )
{
int a, b;
printf("Enter the values of a and b\n");
scanf("%d%d",&a, &b);
printf("Before Swapping\n");
printf("The values of a is %d and b is %d\n",a,b);
a = a * b;
b = a / b;
a = a / b;
printf("After Swapping\n");
printf("The values of a is %d and b is %d\n",a,b);
}
printf("%d",m); 9 8 7 6
printf("%6d",m); 9 8 7 6
printf("%-6d",m); 9 8 7 6
printf("%06d",m); 0 0 9 8 7 6
printf("%2d",m); 9 8 7 6
− It is possible to pad the leading blanks with zeros by placing a 0 before the
field width Specifier.
− If a number is greater than the specified field width then it will be printed in
full, overriding the minimum specification.
Printing characters
− For printing characters %wc or %-wc format specification can be used, where
'w' is the minimum field width of the output.
− %wc prints the character in right justified manner, %-wd prints the character
in a left justified manner.
Example: Consider the statement char x = 'A';
Statement Output
printf("%c", x); A
printf("%3c", x); A
printf("%5c", x); A
printf("%7.4f",n); 9 8 . 7 6 5 4
printf("%7.2f", n); 9 8 . 7 7
printf("%-7.2f", n); 9 8 . 7 7
printf("%f", n); 9 8 . 7 6 5 4
printf("%07.2f", n); 0 0 9 8 . 7 7
Printing Strings
− For printing strings %w.ps or %-w.ps format specification can be used, where
'w' is the minimum number for positions that are to be used for displaying the
string and p denotes the number if characters to be displayed from start of the
string.
− %w.ps prints the string in right justified manner, %-w.pf prints the string in a
left justified manner.
Example: Consider the statement char str[20] = "NEW DELHI 110001";
Statement Output
printf("%s", str); N E W D E L H I 1 1 0 0 0 1
printf("%20s", str); N E W D E L H I 1 1 0 0 0 1
printf("%20.10s",
N E W D E L H I
str);
N E W D E L H I
printf("%-20.10s",
Module 2 Prof. C K Marugiwda/ Prof. Arun K H 2
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
str);
2) scanf( ) function
− The specification %[characters] means that only the characters specified in the
brackets are permissible in the input string. While reading the input the string
terminates at the first encounter of any other character.
Example: scanf("%[a-z]", name);
will read a string consisting of any characters from a to z
− The specification %[^characters] means that all other characters other than the
one's mentioned in [^ ] is permitted in the input and the reading of input string
is terminated at the first encounter of any character specified in [^ ].
Example: scanf("%[^\n]", str);
will read a string consisting of any characters except \n.
Operator : An operator is a symbol that specifies the operation to be performed on various types of
operands.
Example: +, -, *etc
− Unary Operators
− An operator that operates on one operand to produce a result is called a unary
operator.
− Example: a++, --b, etc
− Binary Operators
− An operator that operates on two operands in an expression to produce a result is
called a binary operator.
− Example: a+b, a*b etc
− Ternary Operators
− An operator that operates on three operands to produce a result is called a ternary
operator.
− Example: a ? b : c
− Special Operators
− comma ( , ), sizeof( ) etc
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Assignment Operators
6) Conditional Operator
7) Bitwise Operators
8) Special Operators
1) Arithmetic Operators
− The operators that are used to perform arithmetic operations such as addition, subtraction,
multiplication, division and modulus operations are called arithmetic operators.
− They are binary operators. Priority 1 is HIGH and Priority 2 is LOW
Note:
a + b = 18
a - b = 10
a * b = 56
// If one of the operand is real, then the result obtained is a real number.
2) For modulus operation, the sign of the result is always the sign of first operand.
14 % 3 = 2 // 14 is 3 * 4 = 12 remainder = 2
14 % -3 = 3 // 14 is -3 * -4 = 12 remainder = 3
3) Modulus operator is allowed only on integers, it cannot be applied for any other data type.
36 // Final Answer
Conversion of Expressions
The expressions used in mathematics are different from the expressions that are used in C language.
The expressions in C must be written in a single line.
Example
a a/b
b
abc s = (a+b+c) / 2
s
2
area s ( s a )( s b )( s c ) area = sqrt(s* (s-a) * s-b) * (s-c))
2
ax + bx + c a*x*x + b*x + c
b sin( b / sqrt( a*a + b*b) )
sin
a b
2 2
Type Conversion
The process of converting the data from one data type to another data type is called type
conversion. They are of two types.
The C compiler can evaluate expressions if and only if the data types of the two operands are of
same. If the operands are of different data types, compiler cannot evaluate. To ensure that both the
operands are of same data type, the compiler automatically converts the lower data type to higher
data types. This process is called implicit type conversion.
Example:
int a = 7;
float b = 2.0;
c = 3.500000
If the operands are of the same data type, then type conversion is not done by the compiler
implicitly. However, sometimes the type conversion may be required for getting the desired result.
In such cases, we can instruct the compiler to change the type of operand. This forceful conversion
from one data type to another data type is called explicit type conversion or type casting.
Example 1:
c = 3.500000
Example 2:
i = (int) 5.99 / (int) 2.4 // 5.99 is truncated to 5 and 2.4 is truncated to 2 then i = 5/2 = 2
2) Relational Operators
− The operators that are used to find relationship between two operands are called relational
operators
− The result obtained is true (1) or false (0)
− They are binary operators.
Example:
2==2 //output 1
2==3 //output 0
50 <= 10 - 5 + 0 - 20 == 5 >= 1 != 20
5 0<= 5 + 0 - 20 == 5 >= 1 != 20
50 <= 5 - 20 == 5 >= 1 != 20
0 == 5 >= 1 != 20
0 == 1 != 20
0 != 20
3) Logical Operators
− The operators that are used to combine 2 or more relational expressions are called logical
operators
− The result obtained is true (1) or false (0)
Example:
Note:
2) Logical NOT
op !op
TRUE FALSE
FALSE TRUE
3) Logical AND
4) Logical OR
5) Precedence of operators
Brackets
1 && 1 || 11 != 7&& 0
1 && 1 || 1 && 0
1 || 1 && 0
1 || 0
4) Assignment Operators
− An operator which is used to assign the data or result of an expression into a variable is
called an assignment operator.
− It is denoted by '='
− There are 3 types of assignment operators
− Simple Assignment
The syntax of simple assignment is variable = expression;
Example:
a = 10; // RHS is a constant
a = b; // RHS is a variable
a = b+c; // RHS is a expression
− Shorthand Assignment
The assignment statements +=, -=, *=, /= and %= are called short hand assignement
operators.
Example:
a+=10; // means a = a+10
a*=5; //means a = a*5
− Multiple Assignment
The assignment operator can be used to assign values to more than one variable.
Example:
The statements i=10; j=10; k=10 can be written in a single line as ai=j=k=10;
Increment Operator
− It is denoted by ++. It is a unary operator.It increments the value of the variable by 1
− 2 types of increment operator exist, post increment and pre increment
− If the increment operator is placed after the operand then it is called post increment. In this
case, increment after the operand value is used.
− If the increment operator is placed before the operand then it is called pre increment. In this
case, increment before the operand value is used.
Example:
Program 1
void main( )
{
int a =20;
a++;
printf("%d",a);
}
Output: 21
Program 2
void main( )
{
int a =20;
++a;
printf("%d",a);
}
Output: 21
Note: If post increment or pre increment is not a part of any expression, then there is no difference
between them.
Program 3
void main( )
{
int a =20;
int b;
b = a++;
printf("%d",a); //21
printf("%d",b); //20
}
Output:
21
20
Program 4
void main( )
{
int a =20;
int b;
b = ++a;
printf("%d",a); //21
printf("%d",b); //21
}
Output:
21
21
Note:
b = a++ is equivalent to b = a followed by a = a + 1
b = ++a is equivalent to a = a + 1 followed by b = a
Decrement Operator
− It is denoted by --. It is a unary operator.It decrements the value of the variable by 1
− 2 types of decrement operator exist, post decrement and pre decrement
− If the decrement operator is placed after the operand then it is called post increment. In this
case, decrement after the operand value is used.
− If the increment operator is placed before the operand then it is called pre increment. In this
case, decrement before the operand value is used.
Example:
Program 1
void main( )
{
int a =20;
a--;
printf("%d",a);
}
Output: 19
Module 1 Prof. C K Marigowda/ Prof. Arun K H 9
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Program 2
void main( )
{
int a =20;
--a;
printf("%d",a);
}
Output: 19
Note: If post decrement or pre decrement is not a part of any expression, then there is no difference
between them.
Program 3
void main( )
{
int a =20;
int b;
b = a--;
printf("%d",a); //19
printf("%d",b); //20
}
Output:
19
20
Program 4
void main( )
{
int a =20;
int b;
b = --a;
printf("%d",a); //19
printf("%d",b); //19
}
Output:
19
19
Note:
b = a-- is equivalent to b = a followed by a = a - 1
b = --a is equivalent to a = a - 1 followed by b = a
6) Conditional Operator
Example:
Program to find the bigger of two numbers using ternary operator.
#include<stdio.h>
void main( )
{
int a, b, big;
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b\n");
scanf("%d",&b);
big = (a>b) ? a : b;
printf("the bigger of %d and %d is %d\n", a, b, big);
}
#include<stdio.h>
void main( )
{
int a, b, c, large;
printf("Enter three numbers\n");
scanf("%d%d%d", &a, &b, &c);
large = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c);
printf("the largest number is of %d \n", large);
}
7) Bitwise operators
− The operators that are used to manipulate the bits of given data are called bitwise
operators.
Note:
1) Bitwise operators cannot be used on float, double, void or other complex data types.
// For simplicity only 8-bits are shown, else 16 bits needs to be considered.
Program to demonstrate bitwise and, or and exor
#include<stdio.h>
void main( )
{ a=10 0 0 0 0 1 0 1 0
int a, b, c, d, e; b=6 0 0 0 0 0 1 1 0
c 0 0 0 0 0 0 1 0
a =10;
b = 6; a=10 0 0 0 0 1 0 1 0
c = a & b; b=6 0 0 0 0 0 1 1 0
d 0 0 0 0 1 1 1 0
d = a | b;
e = a ^ b; a=10 0 0 0 0 1 0 1 0
b=6 0 0 0 0 0 1 1 0
printf(" c = %d\n", c); // c = 2
e 0 0 0 0 1 1 0 0
printf(" d = %d\n", d); // d = 14
printf(" e = %d\n", e); // e = 12
}
Module 1 Prof. C K Marigowda/ Prof. Arun K H 12
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Note: Bits shifted off do not come back like rotate, they are lost.
Ones Complement
− This operator is used to change every bit from 0 to 1 and 1 to 0 in the specified operand or
expression
− It is denoted by ~
− Syntax is variable = ~ expression
#include<stdio.h>
void main( )
{
int a, b, c, d;
a = 5;
b = 10;
c = a << 1;
d = b >> 1;
printf(" c = %d\n", c); // c = 10 left shift by 1 is multiply by 2
printf(" d = %d\n", d); // d = 5 right shift by 1 is divide by 2
}
8) Special Operators
a) Comma operator
− This operator is used to separating items in a list or for combining 2 or more statements into
a single statement.
− It is left associative and has the least precedence during evaluation
− A comma list of expressions are evaluated from left to right and the value of the right most
expression is the value of the combined expression.
Examples
a = 12,345,678; // a = 12
b = (a=12,345) // b = 345
b) sizeof( ) operator
− This operator is used to determine the number of bytes occupied by a variable or a constant
in the memory.
− The general syntax is sizeof(operand);
#include<stdio.h>
void main( )
{
int a = 10;
float b = 3.14;
char c = 'A';
printf("Size of a is %d\n", sizeof(a)); // 2
printf("Size of int is %d\n", sizeof(int)); // 2
printf("Size of b is %d\n", sizeof(b)); // 4
printf("Size of float is %d\n", sizeof(float)); // 4
printf("Size of c is %d\n", sizeof(c)); // 1
printf("Size of char is %d\n", sizeof(char)); // 1
Control Statements
Normally, the statements in a program are executed sequentially one after the other in the order in
which they appear. However, in practice, we may come across situations where in we need to
− change the sequence of the flow of execution of statements based on certain conditions
OR
− repeat a group of statements until certain specified conditions are met.
All those statements which alter the sequence of execution in the program are called control
statements. Control statements are classified as
− Branching Statements
Conditional branching statements
− These statements allows a programmer to test a condition based on which
the further execution path is decided.
− They include,
− Simple if
− if else
− nested if
− else if ladder
− switch
Unconditional branching statements
− These statements allows a programmer to transfer the control from one
point to another during execution without any condition.
− They include,
− goto
− break
− continue
− return
− Looping Statements
− These statements allows a programmer to executed a sequence of
statements repeatedly until some termination condition is encountered.
− They include,
− for loop
− while loop
− do while loop
1) Simple if
− It is a one way decision making statement where in either a block of statements are
executed or skipped, based on a test expression.
− The general syntax of if statement is
if(test expression)
{
statement 1;
statement 2;
.
.
statement n;
}
statement x;
where the test expression is a logical expression which can have values either true or false.
− If the test expression is evaluated to true, then the block of statements (statement 1 to
statement n) are executed and then the execution continues with statement x.
− If the test expression is evaluated to false, then the block of statements (statement 1 to
statement n) are skipped and the execution will start from statement x.
− Flowchart of simple if
Entry
True
test expression
statement 1;
statement 2;
False .
.
statement n;
statement x;
#include<stdio.h>
void main( )
{
int age;
printf("Enter the age \n");
scanf("%d",&age);
if(age >= 18)
printf(" Person is eligible for voting\n");
if(age < 18)
printf(" Person is not eligible for voting\n");
}
Q2) Write a C program to check whether a given number is positive or negative using
simple if
#include<stdio.h>
void main( )
{
int n;
printf("Enter the number \n");
scanf("%d", &n);
if(n > 0)
printf(" Number is positive\n");
if(n < 0)
printf(" Number is negative\n");
}
Q3) Write a C program to check whether a given number is odd or even using simple if
#include<stdio.h>
void main( )
{
int n;
printf("Enter the number \n");
scanf("%d", &n);
if(n % 2 = = 0)
printf(" Number is even\n");
if(n % 2 ! = 0)
printf(" Number is odd\n");
}
#include<stdio.h>
void main( )
{
int a, b;
printf("Enter 2 numbers \n");
scanf("%d%d", &a,&b);
if(a > b)
printf(" a is big\n");
if(b > a)
printf(" b is big\n");
}
OR
big = a;
if(b > big)
big = b;
printf(" bigger of %d and %d is %d\n", a,b,big);
#include<stdio.h>
void main( )
{
int a, b,c;
printf("Enter 3 numbers \n");
scanf("%d%d%d", &a,&b,&c);
if(a > b && a > c)
printf(" a is big\n");
if(b > a && b > c)
printf(" b is big\n");
if(c > a && c > b)
printf(" c is big\n");
}
OR
big = a;
if(b > big)
big = b;
if(c > big)
big = c;
printf(" largest of %d , %d and %d is %d\n", a,b,c,big);
2) if else statement
− It is a two way decision making statement where in a block of statements are executed if the
test expression is true else another block of statements is executed if the test expression is
false.
− The general syntax of if else statement is
if(test expression)
{
statement block 1;
}
else
{
statement block 2;
}
statement x;
where,
test expression is a logical expression which can have values either true or false
statement block 1 and statement block 2 may be a single statement or a group of
statements.
− If the test expression is evaluated to true, thestatement block 1 will be executed and then
the execution continues with statement x.
− If the test expression is evaluated to false, the statement block 2 will be executed and then
the execution continues with statement x.
− In either case, only one of the block is executed and then control is transferred to statement
x.
− Flowchart of if else
Entry
False True
test expression
statement x;
#include<stdio.h>
void main( )
{
int age;
printf("Enter the age \n");
scanf("%d",&age);
if(age >= 18)
printf(" Person is eligible for voting\n");
else
printf(" Person is not eligible for voting\n");
}
Q2) Write a C program to check whether a given number is positive or negative using if else
#include<stdio.h>
void main( )
{
int n;
printf("Enter the number \n");
scanf("%d", &n);
if(n > 0)
printf(" Number is positive\n");
else
printf(" Number is negative\n");
}
Q3) Write a C program to check whether a given number is odd or even using if else
#include<stdio.h>
void main( )
{
int n;
printf("Enter the number \n");
scanf("%d", &n);
if(n % 2 = = 0)
printf(" Number is even\n");
else
printf(" Number is odd\n");
}
#include<stdio.h>
void main( )
{
int a, b;
printf("Enter 2 numbers \n");
scanf("%d%d", &a,&b);
if(a > b)
printf(" a is big\n");
else
printf(" b is big\n");
}
3) Nested if statement
OR
if(test expression)
{
if / if else statement
}
else
{
if / if else statement
}
statement x;
Example:
if(test expression1)
{
if(test expression2)
{
statement block 1;
}
else
{
statement block 2;
}
}
else
{
statement block 3;
}
statement x;
where,
test expression 1 and test expression 2are logical expressions which can have values
either true or false
statement block 1, statement block 2 and statement block 3 may be a single
statement or a group of statements.
− If the test expression 1 is evaluated to true, then test expression 2 is evaluated. If it is true,
statement block 1 will be executed and then the execution continues with statement x. If it
is false, statement block 2 will be executed and then the execution continues with
statement x.
− If the test expression 1 is evaluated to false, the statement block3 will be executed and then
the execution continues with statement x.
− Flowchart for example
Entry
False True
test expression1
False True
test expression2
statement block 3
statement x;
#include<stdio.h>
void main( )
{
int a, b,c;
printf("Enter 3 numbers \n");
scanf("%d%d%d", &a,&b,&c);
if(a > b)
{
if(a > c)
{
printf(" a is large\n");
}
else
{
printf(" c is large\n");
}
}
else
{
if(b > c)
{
printf(" b is large\n");
}
else
{
printf(" c is large\n");
}
}
}
4) else ifladder
Entry
false
True
test expression1
True false
statement block 1
test expression2
True false
statement block 2 test expression3
True false
statement block 3
test expression n
statement x;
Q1) Write a C program to display the grade obtained by a student based on the marks using
else if ladder.
Marks Grade
0 to 39 F (fail)
40 to 49 E
50 to 59 D
60 to 69 C
70 to 79 B
80 to 89 A
90 to 100 O (outstanding)
#include<stdio.h>
void main( )
{
int marks;
printf("Enter the marks\n");
scanf("%d",&marks);
Q2) Write a C program to simulate the operations of a calculator using else if ladder.
#include<stdio.h>
void main( )
{
int a, b, res;
char op;
if(op = = '+')
res = a + b;
else if(op = = '-')
res = a - b;
else if(op = = '*')
res = a * b;
else if(op = = '/')
{
if( b != 0)
{
res = a / b;
}
else
{
printf("Division not possible\n");
exit(0);
}
}
else
{
printf(" invalid operator");
exit(0);
}
Note:
When one of the many alternatives is to be selected, we can use a form of 'if' statement to control
the selection. The following are the drawbacks of using this
− We may have test all or many conditions and based on the result a particular branch is taken
for execution.
− Program becomes more difficult to read and follow.
− Complexity of such a program increases dramatically when the number of alternatives
increases.
5) switch statement
− It is a multi-way decision making statement that tests the value of a given expression or
variable against a list of case values and when a match is found, a block of statements
associated with that case is executed.
− The general syntax of switchstatement is
switch(expression)
{
case label1 : statement block1;
break;
case label2 : statement block2;
break;
case label3 : statement block3;
break;
.
.
.
case labeln : statement blockn;
break;
− If the expression is evaluated to a value that is not defined in any of the case, then
statmentblockd in default will be executed.
− When a statement block 'i' within the switch is executed, after executing the break
statement, control comes out of the switch statement and continues with the statement x. If
break is absent, then control goes to the next case and so on.
Note:
4) Usually default is written at the end, however, it is not mandatory to write it at the end.
Entry
expression
expression = label1
statement block 1
statement block 2
expression = label2
expression = labeln
statement block n
no match default
statement block d
statement x
1) for addition
2) for subtraction
3) for multiplication
#include<stdio.h>
void main( )
{
int a, b, res;
int choice;
printf("Press 1. for add \t 2. for sub \t 3.for multi \t 4. for div \t any other key to exit\n");
printf("Enter your choice \n");
scanf("%d", &choice);
switch(op)
{
case 1 : res = a + b;
break;
case 2 : res = a - b;
break;
case 3 : res = a * b;
break;
case 4 : if( b != 0)
{
res = a / b;
}
else
{
printf("Division not possible\n");
exit(0);
}
break;
default :printf("invalid operation\");
exit(0);
}
printf(" Result = %d \n", res);
}
void main( )
{
float a, b, res;
char op;
switch(op)
{
case '+' : res = a + b;
break;
case '-' : res = a - b;
break;
case '*' : res = a * b;
break;
case '/' : if( b != 0)
{
res = a / b;
}
else
{
printf("Division not possible\n");
exit(0);
}
break;
default :printf("invalid operator\");
exit(0);
}
Case Studies
Q1) Develop a program to compute the roots of a quadratic equation by the accepting the
coefficients. Print appropriate messages(Lab Program 3)
#include<stdio.h>
#include<math.h>
void main( )
{
float a, b, c, disc, root1, root2, x, y;
printf("Enter the coefficients a,b and c of the quadratic equation \n");
scanf("%f%f%f",&a, &b, &c);
disc = b * b - 4 * a * c;
if(disc = = 0)
{
printf(" Roots are real and Equal\n");
root1 = root2 = - b / (2 * a);
printf(" Root1 = %f and Root2 = %f\n", root1, root2);
}
else if(disc > 0)
{
printf(" Roots are real and Distinct\n");
root1 = ( - b + sqrt(disc) ) / (2 * a);
root2 = ( - b - sqrt(disc) ) / (2 * a);
printf(" Root1 = %f and Root2 = %f\n", root1, root2);
}
else if(disc < 0)
{
printf(" Roots are Complex and Distinct\n");
x = - b / (2 * a);
y = sqrt(fabs(disc) ) / (2 * a);
printf(" Root1 = %f + i %f \n", x, y);
printf(" Root2 = %f - i %f \n", x, y);
}
}
Q2) An electricity board charges the following rates for the use of electricity:
For the first 200 units 80 paise per unit
For the next 100 units 90 paise per unit
Beyond 300 units Rs.1 per unit
All users are charges a minimum of Rs.100 as meter charge.
If the total amount is more than Rs.400, then an additional surcharge of 15% of the total
amount is charged.
Write a program to read the name of the user, number of units consumed and print out the
charges. (Lab Program 5)
#include<stdio.h>
void main( )
{
char name[20];
int units;
float charges, surcharge;
if(units < 0)
{
printf("Invalid input\n");
}
else if(units = = 0)
{
charges = 100;
}
else if(units> 0 and units <=200)
{
charges = 100 + units*0.80;
}
else if(units > 200 and units <=300)
{
charges = 100 + 200 * 0.80 + (units - 200) * 0.90;
}
else if(units > 300)
{
charges = 100 + 200 * 0.80 + 100 * 0.90 + (units - 300) * 1.00;
}
Q3) A transport company charges Rs.500/- for an individual from Bangalore to Mysore. A
discount of 50% is given for children whose age is less than equal to 6 years and a discount
of 40% is given to senior citizens whose age is greater than or equal to 60 years.
The luggage charges are as follows
Upto10kgs, Free
For the next 20kgs,Rs.8 per kg
Anything beyond 30kgs, Rs.5 per kg
Write a C program to calculate the ticket charges of an individual based on his age and
weight of his luggage.
#include<stdio.h>
void main( )
{
char name[20];
Module 2 Prof. C K Marigowda/ Prof. Arun K H 3
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
}
else if(weight<= 10)
{
luggage_charge = 0;
}
else if(weight >10 && weight <= 30)
{
luggage_charge = 8*(weight-10);
}
else
{
luggage_charge = 8*20 + 5*(weight-30);
}
// Compute total charge
total_charge = travel_charge + luggage_charge;
A set of statements may have to be repeatedly executed for a specified number of times or
till a condition is satisfied. The statements that help us to execute a set of statements
repeatedly are called looping statements.
The statements within a loop may be executed for a fixed number of times or until certain
condition is reached.
A loop typically consists of 2 parts, body of the loop and a control statement. The control
statement performs a logical test whose result is either true (body of the loop is executed)
or false (loop is terminated)
Depending on the position of the control statement in the loop, the loop control structure
can be classified as entry-controlled loop and exit-controlled loop
− entry-controlled loop : This is also called as pretest loop. Here the control statement
is placed before the body of the loop to test the control conditions efore the start of
loop execution. If the conditions are not satisfied, then the body of the loopr will not
be executed.
Entry
False
test condition
True
− exit-controlled loop : This is also called as post test loop. Here the control
statements are placed after the body of the loop and therefore the body of the loop
is executed unconditionally for the first time and then the test is performed.
Entry
True
test condition
Module2 False 1
Prof. C K Marigowda/ Prof. Arun K H
Dept. of ISE , Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
Based on the nature of the control variable and the kind of value assigned to it in the control
expression, the loops may be classified as
− Counter controlled loops : When we know in advance exactly how many times the
loop will be executed, a control variable "counter" can be initialized, tested and
updated suitably for the desired loop operations.
Example: To print "welcome" 10 times
i=1;
while(i<=10)
{
printf("welcome\n");
i = i + 1;
}
− Sentinel controlled loops : When we do not know in advance the number of
repetitions needed, a sentinel value can be used to change the loop control
expression from true to false thereby terminating the loop.
Example: To print the numbers entered until it is not -1
num=0;
while(num!=-1)
{
printf("The number is %d\n", num);
printf("Enter a number to print\n");
printf("Enter -1 to stop\n");
scanf("%d", &num);
}
Module2 2
Prof. C K Marigowda/ Prof. Arun K H
Dept. of ISE , Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]
While Statement
It is an entry controlled loop used to execute and repeat a block of statements depending on
a condition.
Syntax
while(test expression)
{
body of the loop
}
statement x;
where, test expression is a relational expression or logical expression which will have value
true or false, body of the loop may be a single statement or a block of statements.
As long as the test expression is true the body of the loop will be executed repeatedly. Once
the test expression is false control comes out of the loop.
Flowchart
Entry
False
test expression
True
Statement x
Note:
Q1) Write a program to display first 'n' natural numbers using while statement
#include<stdio.h>
void main( )
{
int n, i;
i=1;
while(i<=n)
{
printf("%d\n", i);
i = i + 1;
}
}
Q2) Write a program to find the sum of first 'n' natural numbers using while statement
#include<stdio.h>
void main( )
{
int n, i, sum;
sum=0;
i=1;
while(i<=n)
{
sum = sum + i;
i = i + 1;
}
Q3) Write a program to find factorial of a given number using while statement
#include<stdio.h>
void main( )
{
int n, i, fact;
fact=1;
i=1;
while(i<=n)
{
fact = fact * i;
i = i + 1;
}
Q4) Write a program to compute the sum of series 1 + X + X 2 + X3 + X4 + ...... + Xn using while
statement
#include<stdio.h>
void main( )
{
int n, x, sum, i;
sum=1;
i=1;
while(i<=n)
{
sum = sum + pow(x,i);
i = i + 1;
}
Q5) Develop a program to find the reverse of a positive integer and check for palindrome or not.
Display appropriate messages (Lab Program no. 4)
#include<stdio.h>
void main( )
{
int n, num, revnum, remainder,
num = n;
revnum=0;
while(num!=0)
{
remainder = num % 10;
revnum = revnum*10 + remiander;
num = num /10;
}
if(n = = revnum)
printf("%d is a palindrome\n", n);
else
printf("%d is not a palindrome\n", n);
}
Q6) Write a C Program to find GCD and LCM of two numbers using Euclids algorithm
Example: To find GCD and LCM of 10 and 30
The numbers 1,2,5 and 10 can divide 10.
The numbers 1,2,3,5,6,10, 15 and 30 can divide 30.
The common divisors are 1,2,5 and 10. The Greatest Common Divisor (GCD) is 10
LCM = m * n / GCD(m,n)
#include<stdio.h>
void main( )
{
int m, n, gcd, lcm, r, a, b;
a = m;
b = n;
while(n!=0)
{
r = m % n;
m = n;
n = r;
}
gcd = m;
lcm = (a*b) / gcd;
#include<stdio.h>
void main( )
{
float n, x1, x2;
x2 = 0;
x1 = (n + (n/n)) / 2;
while(x1 != x2)
{
x2 = (x1 + (n/x1)) / 2;
x1 = (x2 + (n/x2)) / 2;
}
do while Statement
It is an exit controlled loop used to execute and repeat a block of statements depending on a
condition.
Syntax
do
{
body of the loop
}while(test expression);
statement x;
where, test expression is a relational expression or logical expression which will have value
true or false, body of the loop may be a single statement or a block of statements.
Here the body of the loop will be executed atleast once and then the condition (test
expression) is checked. If it is true, the body of the loop is executed again and again until the
test expression is evaluated to false. Once the test expression is evaluated to false control
comes out of the loop.
Flowchart
Entry
True
test expression
False
Statement x
Q1) Write a program to display first 'n' natural numbers using do while statement
#include<stdio.h>
void main( )
{
int n, i;
i=1;
do
{
printf("%d\n", i);
i = i + 1;
}while(i<=n);
}
Q2) Write a program to find the sum of first 'n' natural numbers using do while statement
#include<stdio.h>
void main( )
{
int n, i, sum;
sum=0;
i=1;
do
{
sum = sum + i;
i = i + 1;
}while(i<=n);
For Statement
It is an entry controlled loop used to execute and repeat a block of statements for a specified
number of times.
Syntax
for(initialization; test expression; updation)
{
body of the loop
}
statement x
where,
− initialization will be executed only once in the beginning i.e. before entering into the
body of the loop.
− Then the test expression will be checked. If test expression is evaluated to true, the
body of the loop will be executed and afterwards the updation is executed followed
by checking of test expression again. If test expression is evaluated to false, control
comes out of the loop and execution continues with statement x.
− Updation of a loop variable can be carried out by incrementing/decrementing by any
step value.
Flowchart
Entry
False
for statement
True
Statement x
Example 1
for(i=1; i<=5; i++)
{
printf("%d\t", i);
}
output
1 2 3 4 5
Example 2
for(i=1; i<=5; )
{
printf("%d\t", i);
i++;
}
output
1 2 3 4 5
Example 3
for(i=1; i<=5; i++ ) ;
{
printf("%d\t", i);
}
output
6
Note:
1. More than one variable can be initialized at a time in the for statement.
Example
for(j=0, i=1; i<=n; i++)
{
}
2. Like the initialization section, the updation section may also have more than one part
Example
for(j=0, i=1; i<=n; i++, j++)
{
}
3. The test expression can be a compound relation and testing need not be limited to only loop
control variable.
Example 1
for(j=0, i=1; i<=n && j <=m ; i++, j++)
{
}
Example 2
for(j=0, i=1; i<=n && flag !=1 ; i++, j++)
{
}
Q1) Write a program to display first 'n' natural numbers using for statement
#include<stdio.h>
void main( )
{
int n, i;
Q2) Write a program to display first 'n' even numbers using for statement
#include<stdio.h>
void main( )
{
int n, i;
Q3) Write a program to display first 'n' odd numbers using for statement
#include<stdio.h>
void main( )
{
int n, i;
Q4) Write a program to find the sum of first 'n' natural numbers using for statement
#include<stdio.h>
void main( )
{
int n, i, sum;
sum=0;
Q5) Write a program to find the sum of odd and even numbers separately in the 'n' natural
numbers using for statement
#include<stdio.h>
void main( )
{
int n, i, esum, osum;
esum=0;
osum=0;
Q6) Write a program to find factorial of a given number using for statement
#include<stdio.h>
void main( )
{
int n, i, fact;
fact=1;
for(i=1; i<=n; i++)
{
fact = fact * i;
}
Q7) Write a program to compute the sum of series 1 + X + X 2 + X3 + X4 + ...... + Xn using for
statement
#include<stdio.h>
void main( )
{
int n, x, sum, i;
sum=1;
Q8) Write a program to check whether a given number is prime or not using for statement
#include<stdio.h>
void main( )
{
int n, i;
0 1 1 2 3 5 8 13 21 ........
#include<stdio.h>
void main( )
{
int n, i, p, q, r;
p=0;
q=1;
if( n==1)
{
printf("%d\t",p);
}
else if (n==2)
{
printf("%d %d\t",p, q);
}
else
{
printf("%d %d\t",p, q);
for(i=3; i<=n; i++)
{
r = p + q;
printf("%d\t", r);
p = q;
q = r;
}
}
}
Nested Loops
Example
output
11 12 13
21 22 23
31 32 33
41 42 43
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
void main( )
{
int i, j, n;
Note : In the above program replace printf("%d ", i); by printf("* "); to get the output
*
* *
* * *
* * * *
* * * * *
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
void main( )
{
int i, j, n;
Example: Program to a read a positive number and check whether it is odd or even
#include<stdio.h>
void main( )
{
int n;
read :
printf("Enter the number \n");
scanf("%d", &n);
if(n < 0 ) goto read;
if(n % 2 = = 0)
printf(" Number is even\n");
else
printf(" Number is odd\n");
}
2) break statement
This is used in switch, for loop, while loop and do-while loop.
If a break is encountered in switch, control comes out of the switch statement.
If a break is encountered in any of the loops, the statements following break will be
skipped and control comes out of the loop.
Eample:
for( i = 1; i <= 5 ; i + + )
{
if(i = = 3)
break;
printf(“%d\t ”, i );
}
OUTPUT
1 2
3) continue statement
Note: break can be used inside a switch statement, whereas continue cannot be used.
4) return statement
The return statement terminates the execution of a function and returns control to the
calling function.
Execution resumes in the calling function at the point immediately following the call.
A return statement can also return a value to the calling function.
Syntax
return expression;