0% found this document useful (0 votes)
93 views

Executing A C Program Executing A C Program Executing A C Program

The document discusses the process of compiling and running a C program on Ubuntu Linux using the gcc compiler. It involves 4 main steps: 1) Creating the C source code using a text editor like gedit 2) Compiling the source code using the gcc compiler 3) Executing the compiled program 4) Important commands for working with directories like pwd, cd, mkdir, rmdir and listing files with ls are also explained.

Uploaded by

himanshu malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Executing A C Program Executing A C Program Executing A C Program

The document discusses the process of compiling and running a C program on Ubuntu Linux using the gcc compiler. It involves 4 main steps: 1) Creating the C source code using a text editor like gedit 2) Compiling the source code using the gcc compiler 3) Executing the compiled program 4) Important commands for working with directories like pwd, cd, mkdir, rmdir and listing files with ls are also explained.

Uploaded by

himanshu malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

Lecture Notes C Programming for Problem Solving [18CPS23]

Executing a C Program
Executing a program written in C involves a series of steps. They include,

1) Creating the program

2) Compiling the program

3) Linking the program with functions that are needed from the C library

4) Executing the program

This process of compiling and running a C program is as shown

Module 1 Prof. C K Marigowda/Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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)

Open up the terminal by clicking on the icon.

For ease of future access to terminal application, right click its icon in the launcher and select
"Lock to Launcher"

Module 1 Prof. C K Marigowda/Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Step 2: Use a text editor to create the C source code

Type the command $ gedit hello.c

Now enter the following C source code


#include<stdio.h>
void main( )
{
printf("Hello World\n");
}

Close the editor window


Module 1 Prof. C K Marigowda/Arun K H 3
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Step 3: Compile the program

First way

Type the command

$ gcc helloc.c

if there are no errors, executable file a.out (default file) will be created under current
directory.

Second way

Type the command

$ gcc helloc.c -o hello

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

Step 4: Execute the program

First way

Type the command

$ ./a.out

./ represents under current directory a.out is present

Second way

$ ./hello

./ represents under current directory hello is present

Executing the above commands should result in the output Hello World

Module 1 Prof. C K Marigowda/Arun K H 4


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

FEW COMMANDS TO BE REMEMBERED


PWD: Checking your current directory
 At any given point of time user will be working under only one directory, and
that directory will called as current directory.
 Whenever user want to know in which directory he is working currently, i.e.,
current working directory then he can use the pwd (print working directory)
command.
$ pwd
/home/kumar
 If user move around the file system using the cd command, then at any point of a
time he can use pwd command to know his current directory.

Cd: Changing the current directory


 User can move around the file system by using the cd (change directory)
command. When command is used with an argument, it changes the current
directory to the directory specified as argument.
 For eg: if user want to change his current working directory to DIR1 directory
(DIR1 must exist as subdirectory in current directory) then he can use the
following command to do so,
$ pwd
/ home/kumar
$ cd DIR1
$ pwd
/home/kumar/ DIR1
 The command $cd DIR1 means that: “make subdirectory DIR1 as the current
directory”.
 Instead of $cd DIR1you can also give $ cd /home/kumar/ DIR1. This command
also does the same job.
 Command cd can also be used without any arguments. When it is used so, it will
directly take you back to the home directory (the directory where the user
originally logged into) from your current working directory. i.e.,
$ pwd
/home/kumar/DIR1
Module 1 Prof. C K Marigowda/Arun K H 5
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

$ 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: Removing Directories


 The rmdir (remove a directory) command removes directories.
 To remove a directory user has to pass the directory name as a argument to
rmdir command.
$ rmdir progs
 rmdir command can be used to delete more than one directory in a single slot.
$ rmdir patch/sub1 patch/sub2 patch
 Instead of giving the command like above, if we give it in reverse order then we
will get an error message i.e.,

 Few things to remember when deleting the directory:


 You can’t delete a directory unless it is empty.
 You can’t remove a subdirectory unless you are placed in a directory
which is hierarchically above the one you have chosen to remove.
 You are not able to delete a directory when your working directory is the
same directory i.e.,
$ cd progs
$ pwd
/home/kumar/pis/progs

Module 1 Prof. C K Marigowda/Arun K H 7


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

$ 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

Module 1 Prof. C K Marigowda/Arun K H 8


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Removing one file at a time


$ rm a.txt

$ ls
b.txt c.txt d.txt e.txt

Removing more than one file at a time


$ rm b.txt c.txt

$ ls
d.txt e.txt

Note: No output is produced by rm, since it typically only generates messages in


the case of an error.

-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

Module 1 Prof. C K Marigowda/Arun K H 9


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

1. Computer and Program


A computer is a electronic device that can automatically perform a set of instructions. The
data needed for the instructions are provided by means of input devices (Ex: Keyboard),
processing of the instructions is done by the central processing unit (CPU) and the desired
output is written on to a output device (Ex: Monitor).
A set of instructions given to the computer to do a specific task is called a program. Typically,
the program is held in a file normally stored on the computer's hard disk. To execute this
program, the contents of the file must be loaded into the main memory.

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).

2. Characteristics or features of a computer


o Speed
− A computer is very fast device. It can perform large amount of work in a few
seconds.
− Computers can perform millions of computations in a few seconds. The speed
of computers are measured in terms of microseconds, Nano seconds and Pico
seconds.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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).

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

 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)

3.2 Transistors : The Second Generation


 This generation of computers used transistors. Memory requirements were met by
smaller magnetic cores. Input-Output mechanism were largely unchanged.
 Transistors were faster, smaller and consumed less power when compared to vacuum
tubes, hence, second generation computers were smaller in size, generated less heat
and consumed less electricity when compared to first generation computers.
 They were programmed using symbolic or assembly language which used human
understandable words and symbols for programming.
 The concept of stored program (Allowing both program and data to reside in memory)
was implemented in these computers.High level languages like C, Fortran and
COBOL began to make their appearance.
 Example: IBM 1401, Honeywell 400

3.3 Integrated Circuits : The Third Generation


 This generation of computers used Integrated Circuits. Memory requirements were
met by magnetic hard disks. Input-Output mechanism adopted keyboard and monitor
to interact with the user.
 Integrated Circuits made it possible for the components of an electronic circuit
(transistors, resistors, capacitors and diodes) to be integrated onto a single chip.
Because of this computers got smaller, cheaper and energy efficient.
 The existing programming languages were supplemented by BASIC, C, C++, and
JAVA.
 The computers now had an operating system (program meant to control the resources
of the computer)
 Example: IBM 360 / 370, Honeywell 6000

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]

3.4 Microprocessors : The Fourth Generation


 This generation of computers used the microprocessors and VLSI (Very Large Scale
Integration) Circuits.
 VLSI made it possible to have the entire CPU, its associated memory and input/output
control circuitry on a single chip.
 Microprocessors have invaded our homes to drive desktops, laptops, smart-phones,
microwave ovens and washing machines.
 Fourth generation languages which resemble natural languages have also come into
being.
 The operating systems in this generation moved from rudimentary MSDOS to GUI
based Windows and Linux.
 This generation also made a rapid stride in networking technology with the
introduction of Internet.
 Example: ALTAIR 8800, IBM PC, Apple Computers

3.5 Artificial Intelligence : The Fifth Generation


 This generation represents a vision of the computers of the future. Artificial
Intelligence, ULSI (Ultra Large Scale Integration) and use of natural language are the
main features of this generation.
 Apart from improvement in the conventional parameters of computing (speed, size,
energy consumption), the fifth generation systems should be capable of producing
human like behavior.
 The systems are expected to interact with the users in natural language and learn from
experience. Speech recognition and speech output should also be possible with these
systems.
 Few of the objectives of this generation have been partially realized.
− Exponential jump in the speed of computers : Google's D-Wave 2X quantum
computer is 100 million times faster than today's machine.
− Parallel processing for concurrently handling different aspects of a problem:
This is already introduced as quad-core and octa-core processors in laptops
and smart-phones.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 4


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− 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

Module 1 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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.

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]

4.5 Smartphones and Embedded Computers


 Smartphone is a general purpose computer that is also capable of making phone calls.
It has a powerful processor (Ex: quadcore, octacore), gigabytes of main memory but
no hard disk for secondary storage. This requirement is met by flash memory. Just
like a computer, smartphones have a keyboard and high resolution display.
 Two popular operating systems used for smartphones today are Android and iOS.
Applications used in smartphones are written in high level language Java for Android
phones and Objective-C for iPhones.
 Embedded computers are also called micro controllers. These are very small circuits
containing a CPU, non-volatile memory, and input/output handling facilities.
 They are embedded into many of the machines we use like cars, washing machines,
MP3 players and cameras. The processor here runs a single unmodifiable program
stored in memory, i.e. the processor here is dedicated to do only a specific task.

5. Bits, Bytes and Words


 Bit is the smallest unit of data in a computer. Bit is short form for 'binary digit'. It has
a single binary value either 0 or 1. Bits can be implemented in computer hardware
using switches. If the switch is on then the bit is one and if the switch is off then the
bit is zero.
 Byte is a sequence of 8 bits. 0000 0001 is an example of a byte. Since there are 8 bits
in a byte there are 28 different possible sequences for one byte, ranging from 0000
0000 to 1111 1111.With 8 bits you can store any number between 0 and 255.
 Since the number of symbols that we can enter from a keyboard is less than 256, each
keystroke can be given with a unique code within a byte. There are two standard
codes that use one byte to represent a character, ASCII (American Standard Code for
Information Interchange)and EBCDIC (Extended Binary Coded Decimal Interchange
Code).
 A word is the number of bits that are manipulated as a unit by the particular CPU of
the computer. Today most CPUs have a word size of 32 or 64 bits. Data is fetched
from memory to the processor in word size chunks and manipulated by the ALU in
word size chunks. Larger word size implies faster processing.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 7


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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)

6. Architecture of a Computer / Block diagram of a computer

The architecture of a computer with a single processor is as shown in the diagram.

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.

7.2 Primary Memory


Primary memory is the computer memory that is directly accessed by the CPU. The
following are the different types of primary memories
 Random Access Memory (RAM)
− RAM is made up of densely packed transistorized cells fabricated into IC. The
motherboard contains slots where this memory module can be fit into.
− RAM stores the code and data of the currently running program. It is fast,
volatile and more expensive than secondary memory.
− RAM is made up of a number of cells, each cell with a unique number called
as address. The CPU picks up data and instructions from RAM using these
addresses.
− RAM are of two types, static and dynamic. Static RAM (SRAM) is a type of
semiconductor memory that uses flipflops to store each bit. Dynamic RAM
(DRAM) is a type of semiconductor memory that uses a tiny capacitor to store
each bit. Both are volatile meaning that data is lost when memory is not
powered. SRAM is faster, bigger and more expensive than DRAM.
Note:The electric charge on the capacitors slowly leaks off, so without intervention the data
on the chip would soon be lost. To prevent this, DRAM requires an external memory refresh
circuit which periodically rewrites the data in the capacitors, restoring them to their original
charge. Because of this refresh requirement, it is dynamic memory as opposed to SRAM
which does not require data to be refreshed.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 10


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

 Read Only Memory (ROM)


− ROMsignifies permanent memory that can be read but not written.
− It stores a special program called the BIOS (Basic Input Output System). This
program initiates the computer’s startup process before transferring control to
the operating system.
− ROMs are non-volatile, i.e. their contents are retained after withdrawal of
power.
− ROMs are of three types, Programmable Read Only Memory (PROM),
Eraseable Programmable Read Only Memory (EPROM) and Electrically
Eraseable Read Only Memory (EEPROM).
− PROMs are initially left blank at the time of manufacture. Based on the
choice of the customer it is programmed using a device called PROM
programmer. Once written the contents cannot be changed.
− EPROM is one step ahead of PROM in that it can be rewritten (but only once)
by exposing it to ultra violet radiation.
− EEPROM cab be erased and rewritten multiple times. A higher than normal
electric voltage is used to erase an EEPROM. However, there is limit to the
number of times EEPROM can be programmed.
 Cache Memory
− Cache memory holds those portions of a program that are frequently used by
the CPU. It is available as a buffer between CPU and RAM.
− When executing a program, the CPU first looks for instruction and data in
cache. If it finds them there (cache hit), access of the slower RAM is avoided.
If the data is not found in the cache (cache miss), the operating system places
it there.
− Modern computers support multiple levels of cache. The CPU itself contains
level 1 (L1) cache. Level 2 (L2) cache could be located outside the CPU but
close to it.
 CPU Registers
− Registers represent the fastest memory of the computer. They are the
workplace where the CPU does all of its work.
− Each register has the length of the computer’s word. The computer loads an
instruction and its data from main memory to registers before processing them.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 11
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− 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.

7.3 Secondary Memory


Secondary memory is the computer memory that is not directly accessed by the CPU i.e they
are not directly connected to the CPU but can exist both in the machine or external to it. They
are non-volatile and thus meets the requirements of offline and long-term storage.They are
slower than primary memory but have larger capacities.They are also way cheaper than
primary memory. The following are the different types of secondary memories

 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.

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]

− 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.

 Optical Disks (CD, DVD and Blu-Ray Disks)


− Optical disks are made of carbonate material with a thin layer or two of
reflective film.
− A laser beam is used to construct pits and lands by burning (writing) selected
areas along its tracks. The laser beam controls the read and write operations.
− These disks are generally of two types "R" (recordable) and "RW" (rewritable)
EX: CD-R, DVD-R : Data can be recorded only once.
CD-RW, DVD-RW : Data can be recorded multiple times.

 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]

7.5 Input Devices


Input devices are the components that a user uses to send data, information or control signals
to computer. CPU of computer receives the input and processes it to produce output. The
following are the different input devices
 Keyboard
− The central portion of the keyboard has the QWERTY layout (First six
alphabets from left to right) and numbers are placed above three layers of
letters.
− Each letter, numeral or symbol is known as a character, All characters have
unique values assigned to them, called the ASCII value.
− The [Enter] key terminates a line. The backspace key erases input from right
to left, while delete key erases text from left to right.
− The [Ctrl] key is found in duplicate on the lowest row. It is always used in
combination with other keys.
EX: [Ctrl c] copies selected input, [Ctrl v] pastes it elsewhere
− The 12 function keys labeled [F1], [F2]..,[F12] are located in the top most row.
 Pointing Device
− Graphical user interfaces (GUI) need a pointing device to control the
movement of the cursor on the screen . This is supported by pointing devices
like mouse or touchpad.
− Mouse has two buttons (left and right). Clicking on any object with the left
button selects the object. Clicking on the right button activates a context
sensitive menu that can be used to change the attributes of the selected object.
− Mouse also has scroll wheel which is used for scrolling the document up and
down.
− Mouse are of three types, mechanical, optical and wireless.
 In mechanical mouse, the movement of cursor is tracked by the
mechanical sensors and the rolling ball.
 In optical mouse, the movement of cursor is tracked using an infrared
laser or LED.
 The wireless mouse uses the radio frequency technology to
communicate with the computer. The transmitter in the mouse
communicates with a USB connected receiver
Module 1 Prof. C K Marigowda/ Prof. Arun K H 15
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.

7.6 Output Devices


CPU of a computer receives the input and processes it to produce output.Devices that are
used to receive this output from the CPU in the form of display or print so that user can
understand and use it are called output devices.The following are the different output devices
 Monitor
− Programs use it to display text or graphical output, while users also need a
monitor to view the input that they key in.
− It forms images from tiny dots, called pixels that are arranged in a rectangular
form. The performance of a monitor is judged mainly by its image quality,
resolution, energy consumption and its effect on eyes.
− They are of 2 types : CRT Monitors and LCD Monitors
 The CRT (Cathode Ray Tube) monitor is large, energy inefficient and
generates lot of heat. It uses a rarefield tube containing three electron
guns and a screen coated with phosphorescent material. The guns emit
electrons to create images on the screen by selectively lighting up the
phosphors.
 LCD monitors are slimmer, consume less power and generate less heat.
They are made up of thousands of liquid crystals which allow or block
the passage of light through them. An image is formed by selectively
Module 1 Prof. C K Marigowda/ Prof. Arun K H 16
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

applying a voltage to these crystals and using a separate light source


for light to pass through them. The backlight is provided either by
fluorescent light (LCD) or by LEDs.
 Printers
Printers produce hard copies of output which include text and graphics. There are
currently two technologies for printing - Impact and Non-impact.
 Impact Printers
− They use a printhead to strike a ribbon placed between the printhead and paper.
they are noisy and are being phased out. They include
 Dot Matrix Printer
− The printhead of this printer has either 9 or 24 pins which are fired in
multiple combinations to generate letters, numbers and symbols.
− The ribbon has the ink, and when the pins fire against the ribbon, an
impression is created on the paper.
− The paper is moved by a drum after one line of printing has been
completed.
− It is possible to print graphics, however, multiple fonts can't be used.
 Daisy Wheel Printer
− This has a wheel with separate characters distributed long its outer
edge.
− The characters are preformed and not generated.
− For printing a character, the wheel is rotated so that the desired
character directly faces the ribbon.
− It is not possible to print graphics, however, the wheel can be changed
to get different set of fonts.
 Line Printer
− They can print one line at a time. They are a form of high speed impact
printers.
− They use a print chain containing the characters. A number of
Hammers are Placed in Front of the Chain, and Paper is Placed
between the Hammer and the Inked Ribbon.
− The Total Number of Hammers will be Equals to the Total Number of
Print Positions.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 17
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− The Chain Rotates at a Very High Speed and Character is printed by


activating the Appropriate Hammer of the Character.

 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).

Module 1 Prof. C K Marigowda/ Prof. Arun K H 19


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

8.1 Network Topologies


A network topology is the arrangement with which computer systems / network devices are
connected to each other. The following are the different kinds of topologies

Bus Star Ring Mesh

− 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.

8.2 Network Types


Networks are classified based on their size. The general classification of networks include
LAN and WAN. However, technology advances have led to the birth of MAN, CAN and
PAN.
− Local Area Network (LAN) : It is a computer network that links devices within a
building or group of adjacent buildings. They are typically used by smaller
organizations where the area of operation is confined to a building or group of
adjacent buildings. They use the Ethernet technology.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 20


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− 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.

8.3 Internet and internet


 Internet
− It is the worldwide network comprising of all other networks interconnected
and communicating on the open Web.
− It is a network of networks and can be accessed globally by everyone.
 internet or intranet
− It is derived from two words, "intra" meaning "within" and "net" meaning
group of interconnected computers.
− It is an internal system of connected computers that enables people within an
organization to share data and communicate with each other.
− It is a private network accessible only to an organization's staff.
− Because of restricted access, intranet is much secure than Internet.

8.4 Network Hardware


Connecting computers in a network require additional devices that are not part of the
computer's basic configuration. The following are the essential devices and components of a
network.
 Network Interface Card
− It is s a hardware component that connects a computer to a computer network.
− It is also referred to as Ethernet card because most of the networks use
Ethernet technology.
Module 1 Prof. C K Marigowda/ Prof. Arun K H 21
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− The card functionality is implemented using one of the following ways


 Built into the motherboard of laptops and current desktops.
 As a separate card inserted into a slot on the motherboard.
 As a wireless card inserted in the same manner but needs no cabling to
connect to the network.
 As a USB adapter that runs on the USB port
− Every card has a unique address hard-coded into the board by the card
manufacturer. This address is called as the MAC (Media Access
Control)address. They are permanent and cannot be changed.

 Hub and Switch


− Computers in a single network and using the star topology need a central
device to connect to, andthis device is either a hub or a switch.
− A hub accepts network datafrom a computer and simply broadcasts the data to
all nodes. Since the data contains the MAC address of the destination, only the
node having that address will accept the data.
− Switch isa intelligent device because it has a table of all MAC addresses of the
connecteddevices. The switch extracts the MAC address from the data and
then looks up the table to determine the node the packet is meant for. The
packet is sent only to that node.

 Bridge and Router


− Electrical signals tend to become weak as they travel along the cable and
hence Ethernet sets a limit to the maximum size of the cable as 100 meters.
− Also at any given point of time only one device is able to transmit and hence
too many nodes can lead to network congestion.
− Because of the above reasons, a network supporting many nodes is usually
split into a number of segments.
− Bridge is a device that connects these segments. It maintains a table of MAC
addresses of all machines in the segments connected to it.
− A router connects two similar or dissimilar networks which may be separated
by long distances. A router looks up its routing table to determinethe path a
packet has to travel to reach its destination. If the destination node is on the
Module 1 Prof. C K Marigowda/ Prof. Arun K H 22
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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 is a collection of code that drives a computer to perform a related group of


tasks.
− It comprises one or more programs, supported by libraries and configuration files that
programs need to access.
− Software may reside in a ROM, RAM, secondary storage (the hard disk) or may be
loaded from a network.
− Most software are modifiable or removable, but software embedded in a ROM or
PROM is usually permanent
− Programs in software use a language. There are a number of standard programming
languages to choose from - C, C++, Java, Python, to name a few.
− The source code that is created by a programmer using any of these languages is
different from the machine language that actually runs on the CPU.
− A special category of software (called compilers) convert source code to machine
code and it is the latter that is distributed by software vendors.
− It is not possible to retrieve the source code by reverse-engineering the machine code.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 23


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Software Types

Computer software can be broadly divided into two 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

Module 1 Prof. C K Marigowda/ Prof. Arun K H 24


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

 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.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 25


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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).

All C programs need a main function. The format of a main function is

− The execution of a C program starts from the main function.


− The parenthesis ( ) is used as an indicator for functions in C language
− Curly braces or Flower brackets { } are used for enclosing a set of statements (body of the
program). { is used to begin a block and } is used to end a block.
− Generally the keyword int or void will be placed before the word main
 The keyword void means that the function does not return anything to the operating
system.
 The keyword int means that the function returns an integer value to the operating
system.

Program to find area of a circle

#include<stdio.h>

#define PI 3.14

void main( )
{
int r = 10;
printf("Area of circle = %f", PI*r*r);
}

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− #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

Program to find area of a circle using functions

#include<stdio.h>

#define PI 3.14

int area(int r);

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.

Program to find area of a circle using functions and global variables

#include<stdio.h>

#define PI 3.14

int r = 10;

float area(int r);

void main( )
{
printf("Area of circle = %f", area(r) );
}

float area( )
{
return PI*r*r ;
}

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− 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.

Basic Structure of a C Program


Documentation Section

Link Section

Definition Section

Global Declaration Section

User Defined Function Declaration

main( ) Function Section


{
Declaration Part

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*/

// single 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.

The criteria’s or properties that an algorithm must be satisfy are

1. Input: Zero or more quantities are externally supplied.


2. Output: At least one quantity is produced.
3. Definiteness: Each instruction must be clear and unambiguous.
4. Finiteness: The algorithm always terminates after a finite number of steps and uses finite
sources.

Steps to write an algorithm

1) The name of the algorithm must be written first

2) Each instruction must have a step number

3) Each step must be specified with sufficient amount of explanation within [ ] before writing the
instruction.

4) The end of the algorithm must be specified as the the last

Q1) Write an algorithm to find the sum of two numbers

Algorithm : Addition of two numbers

Step 1: [ Input the value of a and b]

Read a, b

Step 2: [Compute the addition of a and b]

sum = a + b

Step 3: [Output the value of sum]

print the addition of a and b is sum

Step 4: [Finished] Stop

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q2) Write an algorithm to find the area of a circle

Algorithm : Area of Circle

Step 1: [ Input the value of radius r]

Read r

Step 2: [Compute the area of circle]

area = 3.14 * r * r

Step 3: [Output the area of circle]

print the area

Step 4: [Finished] Stop

Q3) Write an algorithm to find the area of a rectangle

Algorithm : Area of Rectangle

Step 1: [ Input the value of length l and breadth b]

Read l, b

Step 2: [Compute the area of rectangle]

area = l * b

Step 3: [Output the area of rectangle]

print the area

Step 4: [Finished] Stop

Q4) Write an algorithm to find Simple Interest

Algorithm :Simple Interest

Step 1: [ Input the value of P, T and R]

Read P, T and R

Step 2: [Compute the Simple Interest]

SI =P*T*R/100;

Step 3: [Output the Simple Interest]

print SI

Step 4: [Finished] Stop

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q5) Write an algorithm to swap or exchange 2 numbers

Algorithm : Swap 2 numbers

Step 1: [ Input the value of a and b]

Read a, b

Step 2: [Print the values of a and b before swapping]

print a, b

Step 3: [Exchange the values of a and b using a temp variable]

temp = a

a=b

b = temp

Step 4: [Print the values of a and b after swapping]

print a, b

Step 5: [Finished] Stop

Q6) Write an algorithm to swap or exchange 2 numbers without using third variable

Algorithm : Swap 2 numbers

Step 1: [ Input the value of a and b]

Read a, b

Step 2: [Print the values of a and b before swapping]

print a, b

Step 3: [Exchange the values of a and b] Ex: a=10, b=20

a=a*b // a = 10*20 = 200

b=a/b // b = 200/20 = 10

a=a/b // a = 200/10 = 20

Step 4: [Print the values of a and b after swapping]

print a, b

Step 5: [Finished] Stop

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]

Q7) Write an algorithm to find whether a given number is positive or negative

Algorithm : Check for Positive or Negative

Step 1: [ Input the value of number N]

Read N

Step 2: [Check if the number if positive or negative and output the result]

if N > 0 print N is a positive number

if N < 0 print N is a negative number

OR Assuming the number is not equal to zero

if N > 0 print N is a positive number

else print N is a negative number

Step 3: [Finished] Stop

Q8) Write an algorithm to find whether a given number is odd or even

Algorithm : Check for Odd or Even

Step 1: [ Input the value of number N]

Read N

Step 2: [Check if the number if Odd or Even and output the result]

if N % 2 == 0 print N is a even number

if N %2 != 0 print N is a odd number

OR

if N % 2 == 0 print N is a even number

else print N is a odd number

Step 3: [Finished] Stop

Q9) Write an algorithm to find the bigger of 2 numbers

Algorithm : Bigger of 2 numbers

Step 1: [ Input the value of a and b ]

Read a,b

Module 1 Prof. C K Marigowda/ Prof. Arun K H 4


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Step 2: [Find the bigger of 2 numbers by comparing and output the bigger number]

if a > b print a is bigger

if b > a print b is bigger

OR Assuming the two numbers are not equal

if a > b print a is bigger

else print b is bigger

Step 3: [Finished] Stop

Q10) Write an algorithm to find the largest of 3 numbers

Algorithm : Largest of 3 numbers

Step 1: [ Input the value of a, b and c ]

Read a,b,c

Step 2: [Find the largest of 3 numbers by comparing]

if a > b && a > c print a is bigger

else if b > c print b is bigger

else print c is bigger

Step 3: [Finished] Stop

Q11) Write an algorithm to find the roots of a quadratic equation

Algorithm : Roots of a Quadratic Equation

Step 1: [ Input the value of a, b and c ]

Read a,b,c

Step 2: [Compute the discriminant value disc = b2 - 4ac]

disc = (b * b) - (4 * a * c)

Step 3: [Classify and compute the roots based on the discriminant value]

if disc == 0

print roots are equal

root1 = root2 = -b / (2*a)

print root1 and root2

Module 1 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

else if disc> 0

print roots are real and distinct

root1 = (-b + sqrt(disc)) / (2*a)

root1 = (-b - sqrt(disc)) / (2*a)

print root1 and root2

else

print roots are imaginary

x1 = -b / (2*a)

x2 = sqrt(fabs(disc)) / (2*a)

root1 = x1 + i x2

root2 = x1 - i x2

print root1 and root2

Step 4: [Finished] 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]

Flowcharts

It is a pictorial representation of an algorithm.

The following are the different geometric shapes that are used to represent the symbols while
writing a flow chart.

Sl. No. Action or Symbol Name Geometric Shape Description


1. Start and Stop Denotes start or end of
algorithm
Oval

2. Input and Output Input & output


statements must be
Parallelogram written inside this.

3. Processing or Computation All computation and


processing statements
Rectangle must be written in this.

4. Decision All comparisons or


decision making
Rhombus statements must be
written in this.

5. Connector Used to show the


continuity in next page
Circle

6. Repetition or Loop Repetitive statements


(group of instructions
Hexagon that need to be
executed a number of
times) must be written
in this

7. Predefined Process or User defined functions


function are written in this

Rectangle with double


struck vertical edges

8. Control flow Arrows are used to show


↑ ↓ ← → the flow of control
Arrows

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write aflowchart to find the sum of two numbers

Start

Read a, b

sum = a + b

Print sum

Stop

Q2) Write aflowchart to find the area of a circle

Start

Read r

area = 3.14 * r * r

Print area

Stop

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q3) Write aflowchart to find the area of a rectangle

Start

Read l, b

area = l * b

Print area

Stop

Q4) Write aflowchart to find Simple Interest

Start

Read P,T, R

SI = P*T*R/100

Print SI

Stop

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]

Q5) Write a flowchart to swap or exchange 2 numbers

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

Module 1 Prof. C K Marigowda/ Prof. Arun K H 4


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q7) Write a flowchart to find whether a given number is positive or negative

Start

Read N

Yes No
is N > 0

Print N is Positive Print N is Negative

Stop

Q8) Write a flowchart to find whether a given number is odd or even

Start

Read N

Yes No
is N %2 == 0

Print N is Even Print N is odd

Stop

Module 1 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q9) Write a flowchart to find the bigger of 2 numbers

Start

Read a, b

Yes No
is a > b

Print a is bigger Print b is bigger

Stop

Q9) Write a flowchart to find the largest of 3 numbers

Start

Read a, b, c

Yes No
is a > b && a > c

Yes No
Print a is largest
is b > c

Print b is largest Print c is largest

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]

Q11) Write a flowchart to find the roots of a quadratic equation

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

root1 = -b / (2*a) root1 = (-b + sqrt(disc)) / (2*a) x1 = -b / (2*a)


x2 = sqrt(fabs(disc)) / (2*a)
root2 = -b / (2*a) root1 = (-b - sqrt(disc)) / (2*a) root1 = x1 + i x2
root2 = x1 - i x2

Print root1 & root2 Print root1 & root2 Print root1 & root2

Stop

Module 1 Prof. C K Marigowda/ Prof. Arun K H 7


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Basic Data Types in C


All C compilers support 5 primitive data types, namely
 integer (int)
 character (char)
 floating point (float)
 double precision floating point (double)
 void

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)

Integer int 2 bytes %d


-215 to + 215 -1
-32768 to 32767
(signed)
0 to 28 - 1
0 to 255 (unsigned)
1 byte
Character char %c
-27 to + 27 -1
-128 to 127 (signed)
floating point float 4 bytes 3.4 E -38 to 3.4 E +38 %f
Double
1.7 E -308 to 1.7 E
precision double 8 bytes %lf
+308
floating point

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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.

The following is the general syntax for declaring variables


data type var1, var2, var3,........, varn;

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).

Values to variables can be assigned using assignment operator =

Example: After the above declaration, values can be assigned like


a = 20;
b = 100;
x = 3.14;

With this initialization, 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
20 100 GV 3.14 GV

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Input and Output Functions in C

 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.

I/O Functions Classification

 I/O functions can be classified as formatted I/O and unformatted I/O.


 Formatted I/O
− Formatted input refers to the data that has been arranged in a particular format.
Example: 20 5.6 John
This line contains three pieces of data, arranged in a particular form. Such data
has to be read conforming to the format of its appearance. The first part should
be read into a int variable, second part into a float variable and third part into a
char.
− Examples of formatted I/O functions include printf() and scanf()
 Unformatted I/O
− C supports unformatted I/O for characters, strings and files
− Examples of unformatted I/O include getchar(), putchar(), gets(), puts() etc

Unformatted I/O Functions

1) getchar( ) and putchar( )


Syntax Description
ch = getchar( ); This function is used to read a character from the keyboard and store
it into the memory location.
It waits for the user to press the ENTER key.
putchar(ch); This function is used to display a character stored in memory on the
screen.

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Example Program Input / Output


#include<stdio.h> Input
void main( ) M⏎
{
char ch; Output
ch = getchar( ); M
putchar(ch);
} Note: ⏎ means Enter key is pressed

2) gets( ) and puts( )


Syntax Description
gets(str ); This function is used to read a string of characters from the keyboard
and store it into the memory location.
It waits for the user to press the ENTER key.
puts(str); This function is used to display a string of characters stored in
memory on the screen.

Example Program Input / Output


#include<stdio.h> Input
ISEACIT⏎
void main( )
{ Output
char str[15]; ISEACIT
gets(str );
puts(str); Note: ⏎ means Enter key is pressed
}

Formatted I/O Functions


1) printf( ) function
 printf( ) can be used to print only text or text with values

 To output only text


– Write the text within double quotes inside printf.
EX: printf(“Hello 2020 Batch ISE”);
Module 2 Prof. C K Marigowda/ Prof. Arun K H 2
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

 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);

EX: Consider the following declarations,

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:

1) The number of format specifiers and the variables must be same.

2) The order/type of format specifiers and the variables must be same.

3) Use of \t and \n (tab and newline)

The output of the statement printf(“%f %d %f %d”, c, a, d, b); is 3.14107.2520

This can be further formatted using \t and \n for making it more readable

Example:

printf(“%f \t%d\t %f\t %d\t”, c, a, d, b); will print


3.14 10 7.25 20
printf(“%f \n%d\n %f\n %d\n”, c, a, d, b); will print
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]

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);
}

Q2) Write a C program to find the area of a rectangle

#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);

EX: Consider the following declarations,

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

To read a scanf("%d", &a);


To read a and b scanf("%d%d",&a,&b);
To read b and c scanf("%d%f",&b,&c);
To read c followed by a followed by d followed by b scanf("%f%d%f%d",&c,&a,&d,&b);

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.

3) Do not use of \t or \n with scanf( )

4) Do not use any text inside scanf( )

Q1) Write a C program to find the sum of two numbers

#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);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q2) Write a C program to find the area of a rectangle

#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);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 6


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Simple Programs

Q3) Write a C program to find Simple Interest

#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);
}

Q4) Write a C program to swap two numbers

#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);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

More about I/O functions


1) printf( ) function
 Printing integer numbers
− For printing integer numbers %wd or %-wd format specification can be used,
where 'w' is the minimum field width of the output.
− %wd prints the number in right justified manner, %-wd prints the number in a
left justified manner.
Example: Consider the statement int m = 9876;
Statement Output

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

Module 2 Prof. C K Marugiwda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

 Printing floating point or real numbers


− For printing floating point numbers %w.pf or %-w.pf format specification can
be used, where 'w' is the minimum number for positions that are to be used for
displaying the value and p is the number of digits to be displayed after the
decimal point.
− %w.pf prints the number in right justified manner, %-w.pf prints the number
in a left justified manner.
Example: Consider the statement float n = 98.7654;
Statement Output

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

 Reading characters and strings


− The format Specifier %ws or %wc can be used to read character strings
− When using %wc the system waits until the wth character is keyed in.
− %s can be used but it stops reading after encountering a blank space.

− scanf also supports conversion specification of strings like %[characters] or


%[^characters].

− 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.

 Detection of Errors in the input


− When scanf completes reading, it returns the number of items that it read
successfully. This value can be used to check whether any error occurred
when reading the input.

Example: scanf("%d %f %s", &a, &b, name);


will return 3 if the input given is 20 150.25 John
will return 1 if the input given is 20 John 150.25

Module 2 Prof. C K Marugiwda/ Prof. Arun K H 3


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Operators and Expressions

Operator : An operator is a symbol that specifies the operation to be performed on various types of
operands.

Example: +, -, *etc

Operators classification based on number of operands

− 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

Operators classification based on the type of operation

1) Arithmetic Operators

2) Relational Operators

3) Logical Operators

4) Assignment Operators

5) Increment / Decrement Operators

6) Conditional Operator

7) Bitwise Operators

8) Special Operators

Module 1 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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

Description Operator Priority Associativity


Multiplication * 1 L→R
Division / 1 L→R
Modulus % 1 L→R
Addition + 2 L→R
Subtraction - 2 L→R

Note:

1) If a = 14 and b = 4, then the result of the operations

a + b = 18

a - b = 10

a * b = 56

a%b=2 // remainder of division

a/b=3 // decimal part is truncated

15 / 10 = 1 whereas 15 / 10.0 = 1.5 or 15.0 / 10 = 1.5

// 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 = -2 // -14 is -3 * 4 = -12 remainder = -2

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.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q) Evaluate the expression 2 * ( ( a % 5 ) * ( 4 + ( b - 3 ) / ( c + 2 ) ) ) assuming a = 8, b = 15 and c = 4

2 * ( ( 8 % 5 ) * ( 4 + ( 15 - 3 ) / ( 4 + 2 ) ) ) // substitute for a b and c

2 * ( ( 8 % 5 ) * ( 4 + ( 15 - 3 ) / ( 4 + 2 ) ) ) // Expression inside parenthesis

2 * ( 3 * ( 4 + ( 15 - 3 ) / ( 4 + 2 ) ) ) // Expression inside parenthesis

2 * ( 3 * ( 4 + 12 / ( 4 + 2 ) ) ) // Expression inside parenthesis

2 * ( 3 * ( 4 + 12 / 6 ) ) // Expression inside parenthesis but division operator

2*(3*(4+ 2)) // Expression inside parenthesis

2*(3*6) // Expression inside parenthesis

2 * 18 // Expression inside parenthesis

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
abc 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

5x10 + 7x3 + 8 (5 * pow(x,10) ) + ( 7 * pow(x,3) )+ 8


e a b ( exp ( abs(a) + b ) / (x + y) ) * (2*x + 3)
(2 x  3)
x y
b  b 2  4ac root = ( -b + sqrt( b*b - 4*a*c) ) / (2*a)
root 
2a

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]

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.

1) Implicit Type Conversion

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 = a/b // as given by the programmer

c = 7 / 2.0 // values substituted as given by the programmer

c = 7.0 / 2.0 // compiler converts 7 to 7.0 by implicit type conversion

c = 3.500000

2) Explicit Type Conversion

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.

Syntax: (data type required) expression

Example 1:

c = 7/2 // as given by the programmer

c = (float) 7/2 // programmers instruction to the compiler

c = 7.0 / 2 // compiler changes 7 to 7.0 (explicit conversion)

c = 7.0 / 2.0 // compiler changes 2 to 2.0 (implicit conversion)

c = 3.500000

Example 2:

i = (int) 8.9999 // 8.9999 is truncated to 8 and stored in i

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

Module 1 Prof. C K Marigowda/ Prof. Arun K H 4


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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.

Description Operator Priority Associativity


Less Than < 1 L→R
Less Than or Equal <= 1 L→R
Greater Than > 1 L→R
Greater Than or Equal >= 1 L→R
Equal == 2 L→R
Not Equal != 2 L→R

Example:

3.5 > 2 // output 1

2.5 >3 // output 0

2==2 //output 1

2==3 //output 0

Note: Arithmetic expressions have higher priority than relational expressions

Q) Evaluate the expression 100 / 2 <= 10 - 5 + 100 % 10 - 20 == 5 >= 1 != 20

100 / 2<= 10 - 5 + 100 % 10 - 20 == 5 >= 1 != 20

50 <= 10 - 5 + 100 % 10 - 20 == 5 >= 1 != 20

50 <= 10 - 5 + 0 - 20 == 5 >= 1 != 20

5 0<= 5 + 0 - 20 == 5 >= 1 != 20

50 <= 5 - 20 == 5 >= 1 != 20

50 <= -15 == 5 >= 1 != 20

0 == 5 >= 1 != 20

0 == 1 != 20

0 != 20

Module 1 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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)

Description Operator Priority Associativity


Logical NOT ! 1 L→R
Logical AND && 2 L→R
Logical OR || 3 L→R

Example:

if a > b && a > c then a is big

Note:

1) Zero is false and any non zero value is considered as true in c.

Ex: 5, -2, 100, 1 are all true in C

2) Logical NOT

op !op
TRUE FALSE
FALSE TRUE

3) Logical AND

op1 op2 Result


TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

4) Logical OR

op1 op2 Result


TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

5) Precedence of operators

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]

Brackets

Q) Evaluate the expression, a + 2 > b && !c || a != d && a - 2 <= e

where a=11, b=6, c=0, d=7 and e=5

a + 2 > b && !c || a != d && a - 2 <= e

11 + 2 > 6 &&!0 || 11 != 7 && 11 - 2 <= 5

11 + 2> 6 &&1 || 11 != 7 && 11 - 2 <= 5

13 > 6 && 1 || 11 != 7 &&11 - 2<= 5

13 > 6&& 1 || 11 != 7 && 9 <= 5

1 && 1 || 11 != 7 &&9 <= 5

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.

Module 1 Prof. C K Marigowda/ Prof. Arun K H 7


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Example:
The statements i=10; j=10; k=10 can be written in a single line as ai=j=k=10;

Note: Assignment operator is right associative

Example: Simplify the expression

a += b *= c -= 5 where a=1, b=3 and c= 7

First c -= 5 is evaluated as c = c - 5 = 7-5 =2

The expression reduces to a += b *= 2

Next the expression b *= 2 is evaluated as b = b*2 = 3 * 2 = 6

The expression reduces to a += 6

This is evaluated as a = a+6 = 1 + 6 = 7

5) Increment and Decrement Operators

 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

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]

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

Description Operator Priority Associativity


Post Increment a++ 1 L→R
Post Decrement a-- 1 L→R
Pre Increment ++a 2 R→L
Pre Decrement --a 2 R→L

Module 1 Prof. C K Marigowda/ Prof. Arun K H 10


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

6) Conditional Operator

− It is a ternary operator represented by ? :


− The general syntax of conditional operator is
variable = (exp1) ? exp2 : exp3 ;

First exp1 is evaluated.


If exp1 is true, then exp2 is evaluated and its value is assigned to the variable.
If exp1 is false, then exp3 is evaluated and its value is assigned to the variable.

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);
}

Program to find the largest of three numbers using ternary operator.

#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);
}

Module 1 Prof. C K Marigowda/ Prof. Arun K H 11


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

7) Bitwise operators

− The operators that are used to manipulate the bits of given data are called bitwise
operators.

− The following includes the various bitwise operators

Description Operator Priority Associativity


Ones Complement
~ 1 L→R
(Negate)
Left Shift Operator << 2 L→R
Right Shift Operator >> 2 L→R
Bitwise AND & 3 L→R
Bitwise Ex-OR ^ 4 L→R
Bitwise OR | 5 L→R

Note:
1) Bitwise operators cannot be used on float, double, void or other complex data types.

2) The following table summarizes bitwise and, or and xor

x y x&y x|y x^y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

// 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]

Left Shift Operator


− This operator is used to shift the data by a specified number of bit positions towards left.
− It is denoted by <<
− Syntax is variable = expression << nwhere 'n' is the number if bit positions to be shifted

Right Shift Operator


− This operator is used to shift the data by a specified number of bit positions towards right.
− It is denoted by >>
− Syntax is variable = expression>> nwhere 'n' is the number if bit positions to be shifted

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

Program to demonstrate left shift and right shift

#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
}

a=5 Discard MSB → 0 0 0 0 0 1 0 1


↙ ↙ ↙ ↙ ↙ ↙ ↙
c 0 0 0 0 1 0 1 0 ← Append 0 to LSB

b=10 0 0 0 0 1 0 1 0 ←Discard LSB


↘ ↘ ↘ ↘ ↘ ↘ ↘
d Append 0 to MSB → 0 0 0 0 0 1 0 1

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]

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

value = ( x = 10, y = 5, x+y); // value = 15

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);

Program to demonstrate sizeof( ) operator

#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

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]

Decision Making Branching and Looping

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

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Conditional Branching Statements

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;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a C program to check voting eligibility of a person using simple if

#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");
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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");
}

Q4) Write a C program to find bigger of 2 numbers using simple if

#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);

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]

Q5) Write a C program to find largest of 3 numbers using simple if

#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);

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]

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 block 2 statement block 1

statement x;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a C program to check voting eligibility of a person using if else

#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");
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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");
}

Q4) Write a C program to find bigger of 2 numbers using if else

#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");
}

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]

3) Nested if statement

− An if or a if else statement within another if or if else statement is called a nested if


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 nested if is
if(test expression)
{
if / if else statement
}
statement x;

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;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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 block 2 statement block 1

statement x;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a C program to find largest of 3 numbers using nested if

#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");
}
}
}

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]

4) else ifladder

− It is a multipath decision making statement which uses a chain of if else.


− The general syntax of if else statement is
if(test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
else if (test expression 3)
{
statement block 3;
}
.
.
.
else if (test expression n)
{
statement block n;
}
else
{
default statement;
}
statement x;
where,
 test expression1, test expression 2,.......,test expression n, are logical expressions
which can have values either true or false
 statement block 1, statement block 2, ........., statement block n may be a single
statement or a group of statements.
− Here the conditions are evaluated from top of the ladder downwards
− If an of the condition is found to be true, the statement block associated with it is executed
and the control is transferred to statement x by skipping the rest of the ladder.
− if all the n test expressions are false, then the final else containing the default statement is
executed and then control is transferred to statement x.

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− Flowchart of else if ladder

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 block n default statement

statement x;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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);

if(marks <= 39)


printf(" Grade F\n");
elseif(marks <= 49)
printf(" Grade E\n");
else if(marks <= 59)
printf(" Grade D\n");
else if(marks <= 69)
printf(" Grade C\n");
else if(marks <= 79)
printf(" Grade B\n");
else if(marks <= 89)
printf(" Grade A\n");
else
printf(" Grade O\n");
}

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]

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;

printf("Enter the two operands \n");


scanf("%d%d",&a, &b);

printf("Enter the operator \n");


scanf("%c",&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);
}

printf(" Result = %d \n", res);


}

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]

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.

The solution for these problems is to use a switch statement.

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;

default : statement blockd;


}
statement x;
where,
 expression is any int or char expression or a variable which results in an integer
value.
 label1, label2,.........,labeln are unique values which will match with the value of the
expression.
− if the expression is evaluated to be
label1 then statement block1 will be executed.
label2 then statement block2 will be executed.
and so on
Module 2 Prof. C K Marigowda/ Prof. Arun K H 1
Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

− 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:

1) The expression in switch must be of type int or char only

2) Space between the keyword case and value is mandatory

3) Writing default case is optional.

4) Usually default is written at the end, however, it is not mandatory to write it at the end.

− Flowchart of switch statement

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

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a C program to create a menu as follows

1) for addition

2) for subtraction

3) for multiplication

4) for division exit for any other number

and then simulate the operations of a calculator using switch statement

#include<stdio.h>

void main( )
{

int a, b, res;
int choice;

printf("Enter the two operands \n");


scanf("%d%d",&a, &b);

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);
}

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]

Q2) Write a C program to simulate the operations of a calculator using switch


statement

(Lab Program No.2)


#include<stdio.h>

void main( )
{

float a, b, res;
char op;

printf("Enter the two operands \n");


scanf("%f%f",&a, &b);

printf("Enter the operator \n");


scanf("%c",&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);
}

printf(" Result = %f \n", res);


}

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]

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);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

}
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;

printf("Enter the name of the customer \n");


scanf("%s", name);
printf("Enter the total number of units consumed \n");
scanf("%d", &units);

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;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

}
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;
}

if(charges > 400)


{
surcharge = charges * 0.15;
charges = charges + surcharge;
}
printf("Name of the customer is %s\n", name);
printf("Number of units consumer is %d\n", units);
printf("Total amount to be payed is %f\n", charges);
}

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]

int age, weight;


int total_charge, travel_charge, luggage_charge;

printf("Enter the name of the customer \n");


scanf("%s", name);
printf("Enter the age of customer \n");
scanf("%d", &age);
printf("Enter the weight of luggage\n");
scanf("%d", &weight);

// Compute travel charge


if(age< 0)
{
printf("Invalid age\n");
exit(0);
}
else if(age <= 6)
{
travel_charge = (50/100) * 500;
}
else if(age >= 60)
{
travel_charge = (40/100) * 500;
}
else
{
travel_charge= 500;
}
// Compute luggage charge
if(weight < 0)
{
printf("Invalid weight\n");
exit(0);

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]

}
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;

printf("Name of the customer is %s\n", name);


printf("Age of the customer is %d\n", age);
printf("Total amount to be payed is %d\n", total_charge);
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Looping / Repetitive / Iterative Statements

 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

Body of the loop

− 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

Body of the loop

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

Body of the loop

Statement x

Note:

Infinite while loop


while(1)
{
body of the loop
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a program to display first 'n' natural numbers using while statement

#include<stdio.h>

void main( )
{
int n, i;

printf("Enter the value of n\n");


scanf("%d", &n);

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;

printf("Enter the value of n\n");


scanf("%d", &n);

sum=0;
i=1;

while(i<=n)
{
sum = sum + i;
i = i + 1;
}

printf("sum of first %d natural number is %d\n", n, sum);


}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q3) Write a program to find factorial of a given number using while statement

#include<stdio.h>

void main( )
{
int n, i, fact;

printf("Enter the value of n\n");


scanf("%d", &n);

fact=1;
i=1;

while(i<=n)
{
fact = fact * i;
i = i + 1;
}

printf("Factorial of %d is %d\n", n, fact);


}

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;

printf("Enter the value of x and n\n");


scanf("%d%d", &x, &n);

sum=1;
i=1;

while(i<=n)
{
sum = sum + pow(x,i);
i = i + 1;
}

printf("sum of series is %d\n", sum);


}

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]

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,

printf("Enter the number\n");


scanf("%d", &n);

num = n;
revnum=0;

while(num!=0)
{
remainder = num % 10;
revnum = revnum*10 + remiander;
num = num /10;
}

printf("The reverse of %d is %d\n", n, revnum);

if(n = = revnum)
printf("%d is a palindrome\n", n);
else
printf("%d is not a palindrome\n", n);
}

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]

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;

printf("Enter the values of m and n\n");


scanf("%d%d", &m, &n);

a = m;
b = n;

while(n!=0)
{
r = m % n;
m = n;
n = r;
}

gcd = m;
lcm = (a*b) / gcd;

printf("GCD = %d\n", gcd);


printf("LCM = %d\n", lcm);
}

Note: Alternate way to find GCD


while(m!=n)
{
if(m>n)
m = m - n;
else
n = n - m;
}
gcd = m;

Method 1 while n != 0 Method 2 while m != n


m n r m n
10 30 10 30
30 10 10 10 20 m<n
10 0 0 10 10 m<n

Module 2 Prof. C K Marigowda/ Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

GCD = m = 10 GCD = m or n = 10 m==n


Q7) Develop a program to find the square root of a given number N and execute for all possible
inputs with appropriate message. Note: Don't use library function sqrt(n) (Lab Program no. 12)

#include<stdio.h>

void main( )
{
float n, x1, x2;

printf("Enter the number\n");


scanf("%f", &n);

x2 = 0;
x1 = (n + (n/n)) / 2;

while(x1 != x2)
{
x2 = (x1 + (n/x1)) / 2;
x1 = (x2 + (n/x2)) / 2;
}

printf("Square root of %f is %f\n", n, x1);


}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 6


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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

Body of the loop

True
test expression

False

Statement x

Note: Semicolon is a must at the end of do-while

Example: To read a the input as a positive number only


do
{
print("Enter a positive number\n");
scanf("%d", &n);
}while(n < 0);

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a program to display first 'n' natural numbers using do while statement

#include<stdio.h>

void main( )
{
int n, i;

printf("Enter the value of n\n");


scanf("%d", &n);

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;

printf("Enter the value of n\n");


scanf("%d", &n);

sum=0;
i=1;

do
{
sum = sum + i;
i = i + 1;
}while(i<=n);

printf("sum of first %d natural number is %d\n", n, sum);


}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Difference between while and do-while

Sl No. While do while


1 Condition is tested at the beginning, hence Condition is tested at the beginning, hence
called entry controlled loop or top tested called exit controlled loop or bottom tested
loop loop.
2 Syntax Syntax
while(test expression) do
{ {
body of the loop body of the loop
} }while(test expression);
statement x; statement x;
3 It is a pre test loop, hence if the test It is a post test loop and hence the body of the
expression is evaluated to false in the loop will be executed atleast once.
beginning, then the body of the loop will
not be executed.

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]

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

Body of the loop

Statement x

Example 1
for(i=1; i<=5; i++)
{
printf("%d\t", i);
}
output
1 2 3 4 5

Module 2 Prof. C K Marigowda/Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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

Example 4 //Infinite for loop


for( ; ; )
{
}

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++)
{
}

Module 2 Prof. C K Marigowda/Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q1) Write a program to display first 'n' natural numbers using for statement

#include<stdio.h>

void main( )
{
int n, i;

printf("Enter the value of n\n");


scanf("%d", &n);

for(i=1; i<=n; i++)


{
printf("%d\n", i);
}
}

Q2) Write a program to display first 'n' even numbers using for statement

#include<stdio.h>

void main( )
{
int n, i;

printf("Enter the value of n\n");


scanf("%d", &n);

for(i=0; i<=n; i+=2)


{
printf("%d\n", i);
}
}

Q3) Write a program to display first 'n' odd numbers using for statement

#include<stdio.h>

void main( )
{
int n, i;

printf("Enter the value of n\n");


scanf("%d", &n);

for(i=1; i<=n; i+=2)


{
printf("%d\n", i);
}
}
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]

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;

printf("Enter the value of n\n");


scanf("%d", &n);

sum=0;

for(i=1; i<=n; i++)


{
sum = sum + i;
}

printf("sum of first %d natural number is %d\n", n, sum);


}

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;

printf("Enter the value of n\n");


scanf("%d", &n);

esum=0;
osum=0;

for(i=1; i<=n; i++)


{
if(i%2 ==0)
esum = esum + i;
else
osum = osum + i;
}

printf("Even sum is %d\n", n, esum);


printf("Odd sum is %d\n", n, esum);
}

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]

Q6) Write a program to find factorial of a given number using for statement

#include<stdio.h>

void main( )
{
int n, i, fact;

printf("Enter the value of n\n");


scanf("%d", &n);

fact=1;
for(i=1; i<=n; i++)
{
fact = fact * i;
}

printf("Factorial of %d is %d\n", n, fact);


}

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;

printf("Enter the value of x and n\n");


scanf("%d%d", &x, &n);

sum=1;

for(i=1; i<=n; i++)


{
sum = sum + pow(x,i);
}

printf("sum of series is %d\n", sum);


}

Module 2 Prof. C K Marigowda/Prof. Arun K H 5


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

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;

printf("Enter the value of n\n");


scanf("%d", &n);

if( n== 0 || n==1)


{
printf("Number is neither prime nor composite\n");
exit(0);
}
for(i=2; i<=n; i++)
{
if( n % i = = 0 )
{
printf("Number is not prime\n");
exit(0);
}
}
printf("Number is prime\n");
}

Module 2 Prof. C K Marigowda/Prof. Arun K H 6


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q9) Write a program to print fibonacci series

0 1 1 2 3 5 8 13 21 ........

#include<stdio.h>

void main( )
{
int n, i, p, q, r;

printf("Enter the value of n\n");


scanf("%d", &n);

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;
}
}
}

Module 2 Prof. C K Marigowda/Prof. Arun K H 7


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Q10) Write a program to compute ex using Taylor series


e =1+ + !
+ !
+ !
+ !
…........

Module 2 Prof. C K Marigowda/Prof. Arun K H 8


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Nested Loops

A loop enclosed within another loop is called as nested loops.

Example

for( i=1; i<=4; i++)


{
for(j=1; j<=3; j++)
{
printf("%d%d \t", i, j);
}
printf("\n");
}

output
11 12 13
21 22 23
31 32 33
41 42 43

Q1) Write a program to generate the following output

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

#include<stdio.h>

void main( )
{
int i, j, n;

printf("Enter the value of n\n");


scanf("%d", &n);

for(i=1; i<=n; i++)


{
for(j=1; j<=i; j++)
{
printf("%d", i);
}
printf("\n");
}
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Note : In the above program replace printf("%d ", i); by printf("* "); to get the output
*
* *
* * *
* * * *
* * * * *

Q2) Write a program to generate the following 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;

printf("Enter the value of n\n");


scanf("%d", &n);

for(i=1; i<=n; i++)


{
for(j=1; j<=i; j++)
{
printf("%d ", j);
}
printf("\n");
}
}

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

Unconditional Branching Statements / Jumps in Loops


1) goto statement

 It is a jump statement that transfers the control to a specified statement identified by a


symbolic name in the program.
 Syntax
goto label;

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

Module 2 Prof. C K Marigowda/ Prof. Arun K H 1


Dept. of ISE
Acharya IT, Bangalore
Lecture Notes C Programming for Problem Solving [18CPS23]

3) continue statement

 This is used in for, while and do-while loops.


 If a continue statement is executed in a for loop, then the statements following
continue will be skipped and control goes to the next iteration of the loop.
 If a continue statement is executed in a while loop, the statements following continue
will be skipped and control goes to the beginning of the while loop i.e. condition is
checked and depending upon the condition control can either enter into the loop or
come out of the loop.
 In do-while once a continue statement is executed, control goes to the beginning of
the loop.
Example:
for( i = 1; i<=5 ; i + + )
{
if(i = = 3)
continue;
printf(“%d ”, i );
}
OUTPUT
1 2 4 5

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;

Module 2 Prof. C K Marigowda/ Prof. Arun K H 2


Dept. of ISE
Acharya IT, Bangalore

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy