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

POP Module 1 & Module 2 Notes

The document provides an overview of the principles of programming using C, focusing on the introduction to computers, their characteristics, historical development, and various generations. It categorizes computers based on work, size, and brand, detailing digital, analog, and hybrid computers, as well as supercomputers and mainframes. Additionally, it discusses the evolution of computing technology from mechanical devices to modern computers, highlighting key milestones and advancements in the field.

Uploaded by

santhrupthin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

POP Module 1 & Module 2 Notes

The document provides an overview of the principles of programming using C, focusing on the introduction to computers, their characteristics, historical development, and various generations. It categorizes computers based on work, size, and brand, detailing digital, analog, and hybrid computers, as well as supercomputers and mainframes. Additionally, it discusses the evolution of computing technology from mechanical devices to modern computers, highlighting key milestones and advancements in the field.

Uploaded by

santhrupthin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Principles Of Programming Using C Notes 24BPOPS103

MODULE 01
INRODUCTION TO C
1.1 Introduction
Computers have become the basic necessity of any organization with serious
objectives. They have made great inroads in everyone’s everyday life and thinking. They are
used in engineering simulations, teaching, satellite control weather forecasting, etc. Literally,
there is no field left without the use of computers. Types of computers, characteristics, details
about software, input and output devices and role of computers in network is dealt in this
particular topic.

1.2 Definition of a Computer


You get many definitions of computer. Different authors interpret in different way.
I define it something like this:
“It is a electronic device capable of performing complex calculations at an
incomprehensive speed.”

1.3 Characteristics of Computers


The characteristics possessed by computers can be listed as follows:
1. Speed: Computers perform various operations at a tremendous speed. The
speed varies from few micro second (millionth of a second) to nanoseconds (billionth of a
second).
2. Accuracy: Computers are very accurate. They can perform their hundreds
and thousands of operations with great accuracy as their circuits have no mechanical parts to
wear and malfunction. They can run error-less for days at a time.
3. Reliability: Computer output is generally very reliable, subject to the
condition that the input data entering the computer should be correct and the program of
instructions should be reliable and correct. Incorrect input data and unreliable programs give us
computer errors and wrong results. Hence, the phrase
“GARBAGE IN – GARBAGE OUT (GIGO)”

1.4 Historical Development of Computers


The development of computing dates back from the early Sumerian civilization
(4000-1200 BC) when people started to keep records of transactions on clay tables. The actual
computing using a machine started around 3000 BC when Babylons invented the abacus and
Chinese people started usingthem around 1200 BC.
No significant development took place until seventeenth century. In 1642-43,
Blaise Pascal created a gear-driven adding machine named Pascalene. It was the first
mechanical adding machine. Later, in 1673-74, Leibnitz joined the crew with his version of
mechanical calculator named “Stepped Reckoner” that could multiply. In 1801, Jacquard
constructed a Loom, which is the first machine programmed with punched cards. In 1822,
Charles Babbage designed and built his first Difference Engine, which is credited the first
mechanical computer. For this machine, Babbage is known as the “Father of Computer”.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 1
Principles Of Programming Using C Notes 24BPOPS103

Engine made by Babbage. A programming language (Ada) has been named after
her. In 1847-49, Babbage designed his second version of Difference Engine but he could not
complete it. The same machine was conceived in 1991 by the Science Museum in Kensington,
England, and it worked!
In 185, George Bool developed Boolean Logic, which is a system for symbolic and
logical reasoning and the basis for computer design. In 1890, computations for the US Census
were carried out by Herman Hollerith’s punched card machine. Hollerith started Tabulating
Company, which eventually became IBM.
Before the 20th century, all the machines were mechanical. With the advent of
vacuum tubes, the electronics era of computers started. In 1944, Harvard Mark I, the first large
scale, automatic, general purpose, electromechanical calculator driven by a paper tape
containing the instructions was constructed. In the second version of this machine, Grace
Hopper, found the first computer bug, a bug beaten to death in the jaws of a relay, which she
glued into the logbook. The logbook is now in the National Museum of American History of
the Smithsonian.
The first electronic computer, ENIAC (Electronic Numerical Integrator And
Computer) was built in 1946. It was programmed through rewiring between the various
components. After this, many machines like EDVAC, IBM 701, 704 were built and some of
them were commercially successful at that time because they used transistors in place of
vacuum tubes thereby increasing the reliability and performance.

1.5 Computer Generations


First Generation (1945-1956)
➢ The computers of this generation were entirely mechanical or electromechanical that
use vacuum tubes and relays.
➢ Ex: Colossus, Mark I, ENIAC, EDVAC, etc. The machines were very slow (3-5
seconds per calculation to few thousands of calculations per second) and inflexible
(mostly built for special purpose) and could perform basic operations. The machines
were huge (e.g., ENIAC – 18000 ft3, 18000 vacuum tubes) and consume alot of power
(160 KW for ENIAC).
Second Generation Computers (1957-1963)
➢ The transistor replaced the large, cumbersome vacuum tube in televisions,
radios and computers. As a result, the size of electronic machinery has been
shrinking ever since. The transistor was at work in the computer by 1956.
➢ The magnetic-core memory, transistors led to second generation computers
that were smaller, faster, more reliable and more energy-efficient than their
predecessors.
➢ Example: IBM 1401. High-level languages such as COBOL (Common
Business-Oriented Language) and FORTRAN (Formula Translator).
➢ These languages replaced cryptic binary machine code with words,
sentences, and mathematical formulas, making it much easier to program a
computer. New types of careers (programmer, analyst, and computer
systems expert) and the entire software industry began with second-
generation computers.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 2
Principles Of Programming Using C Notes 24BPOPS103

Third Generation Computers (1964-1971)


➢ The Integrated Circuits (IC) were invented and used to fit even more
components on a single chip. As a result, computers became ever smaller as
more components were squeezed onto the chip.
➢ Third-generation development included the use of an operating system that
allowed machines to run many different programs at once with a central
program that monitored and coordinated the computer’s memory and other
resources.
Fourth Generation (1971-Present)
➢ After the integrated circuits, the only place to go was down – in size. Large
Scale Integration (LSI) could fit hundreds of components onto one chip.
➢ By the 1980s, Very Large-Scale Integration (VLSI) squeezed hundreds of
thousands of components onto a chip. Ultra Large Scale Integration (ULSI)
increased that number into the millions.
➢ It also increased their power, efficiency and reliability. The Intel 4004 chip,
developed in 1971, took the integrated circuit one step further by locating
all the components of a computer (central processing unit, memory, and
input and output controls) on a minuscule chip.
➢ One microprocessor could be manufactured and then programmed to meet
any number of demands. Soon everyday household items such as
microwave ovens, television sets and automobiles with electronic fuel
injection incorporated microprocessors.
➢ They were no longer developed exclusively for large business or
government contracts. By the mid-1970s, computer manufacturers sought to
bring computers to general consumers.
➢ These minicomputers came complete with user-friendly software packages
that offered even non-technical users an array of applications, most
popularly word processing and spreadsheet programs. Pioneers in this field
were Commodore, RadioShack and Apple Computers.
➢ which was one powerful computer that shared time with many terminals for
many applications, networked computers allowed individual computers to
communicate with each other. A global web of computer circuitry, the
Internet, for example, links computers worldwide into a single network of
information.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 3
Principles Of Programming Using C Notes 24BPOPS103

Fifth Generation (Present and Beyond)


The fifth generation of computers is somewhat difficult because the
field is in its infancy. With artificial intelligence, these computers will
be able to hold conversations with its human operators, use visual
input, and learn from its own experiences.
This feat seemed a simple objective at first, but appeared much more
difficult when programmers realized that human understanding relies as
much on context and meaning as it does on the simple translation of
words.
Many advances in the science of computer design and technology are
coming together to enable the creation of fifth-generation computers.
Two such engineering advances are parallel processing, which replaces
von Neumann’s single central processing unit design with a system
harnessing the power of many CPUs to work as one.
which allows the flow of electricity with little or no resistance, greatly
improving the speed of information flow. Computers today have some
attributes of fifth generation computers.
For example, expert systems assist doctors in making diagnoses by
applying the problem-solving steps a doctor might use in assessing a
patient’s needs. It will take several more years of development before
expert systems are in widespread use.

1.6 Computer Types


The computer is divided into three broad categories, and a category has
its own categories given as below:
➢ On the basis of Work: Digital, Analog and Hybrid Computer
➢ On the basis of Size: Supercomputer, Mainframe, Minicomputer and
Microcomputer
➢ On the basis of Brand: IBM PC and Apple/Macintosh Computer
➢ On the basis of Model: xT Computer (eXtra echnology), AT Computer
(Advance Technology) and PS/2 Computer

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 4
Principles Of Programming Using C Notes 24BPOPS103

On the Basis of Work: Digital, Analog and Hybrid Computer

Digital Computers:
➢ Class of devices capable of solving problems by processing information
in discrete forms. It operates on data, including magnitudes, letters and
symbols that are expressed in binary code, i.e., using only the two digits 0
and 1.
➢ By counting, comparing and manipulating these digits or their combinations
according to a set of instructions held in its memory, a digital computer can
perform such tasks as to control industrial processes and regulate the
operations of machines; analyze and organize vast amounts of business
data; and simulate the behavior of dynamic systems (e.g., global weather
patterns and chemical reactions) in scientific research.
Functional Elements:
A typical digital computer system has four basic functional elements:
(1) input-output equipment, (2) main memory, (3) control unit, and (4) arithmetic
logic unit.
➢ Any of a number of devices is used to enter data and program instructions
into a computer and to gain access to the results of the processing operation.
Common input devices include keyboards and optical scanners; output
devices include printers and monitors.
➢ The information received by a computer from its input unit is stored in the
main memory or, if not for immediate use, in an auxiliary storage device.
➢ The control unit selects and calls up instructions from the memory in
appropriate sequence and relays the proper commands to the appropriate unit.
➢ It also synchronizes the varied operating speeds of the input and output
devices to that of the arithmetic logic unit (ALU) so as to ensure the proper
movement of data through the entire computer system.
➢ The ALU performs the arithmetic and logic algorithms selected to process the
incoming data at extremely high speeds—in many cases in nanoseconds
(billionths of a second).
➢ The main memory, control unit and ALU, together make up the Central
Processing Unit (CPU) of most digital computer systems, while the input-
output devices and auxiliary storage units constitute peripheral equipment.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 5
Principles Of Programming Using C Notes 24BPOPS103

Analog Computers
➢ An analog computer is a computer which is used to process analog data.
Analog computers store data in a continuous form of physical quantities
and perform calculations with the help of measures.
➢ It is quite different from the digital computer, which makes use of symbolic
numbers to represent results. Analog computers are excellent for situations
which require data to be measured directly without converting into
numerals or codes. Analog computers, although available and used in
industrial and scientific applications like control systems and aircraft, have
been largely replaced by digital computers due to the wide range of
complexities involved.
➢ Analog computers were the earliest computer machines developed and were
among the most complicated machines for analog computation and process
control. Analog data is not discrete, but rather is of a continuous nature.
➢ Examples of such data are pressure, temperature, voltage, speed and weight.
An analog computer makes use of continuous values and not discrete
values. Because of this, processes with an analog computer cannot be
repeated for exact equivalent results.
➢ Unlike digital computers, analog computers are immune to quantization
noise. Some of the common computing elements found in analog computers
are function generators, integrators, comparators and multipliers. Depending
on the application, other specialized components can also be used.
Programming on an analog computer involves
➢ Real-time operation and simultaneous computation are possible with the
help of analog computers. Analog computers can also provide the insight of
the problems and errors in case of analog issues for users.

Hybrid Computer
➢ A hybrid is a combination of digital and analog computers. It combines the
best features of both types of computers, i.e., it has the speed of analog
computer and the memory and accuracy of digital computer.
➢ Hybrid computers are used mainly in specialized applications where both
kinds of data need to be processed. they help the user to process both
continuous and discrete data.
➢ For example, a petrol pump contains a processor that converts fuel flow
measurements into quantity and price values.
➢ In hospital Intensive Care Unit (ICU), an analog device is used which
measures patient’s blood pressure and temperature, etc., which are then
converted and displayed in the form of digits. Hybrid computers, for
example, are used for scientific calculations, in defense and radar systems.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 6
Principles Of Programming Using C Notes 24BPOPS103

On the Basis of Size:

➢ Supercomputer,
➢ Mainframe,
➢ Minicomputer and
➢ Microcomputer
Supercomputer
➢ The most powerful computers in terms of performance and
data processing are the Supercomputers.
➢ These are specialized and task specific computers used by
large organizations.
➢ These computers are used for research and exploration
purposes, like NASA uses supercomputers for launching
space shuttles, controlling them and for space exploration
purpose.
➢ The supercomputers are very expensive and very large in
size. It can be accommodated in large air-conditioned
rooms, some super computers can span an entire building.

Applications of Supercomputer
➢ Used to forecast the weather and global climates
➢ Used in military research and defence systems
➢ In automobile, aircraft and space craft designing
➢ In encrypting and decoding sensitive intelligence information
➢ Used in seismography, plasma and nuclear research
➢ Protein folding analysis
➢ Study of DNA structure and gene engineering
➢ Digital film rendering

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 7
Principles Of Programming Using C Notes 24BPOPS103

Mainframe Computer
➢ Although Mainframes are not as powerful as supercomputers, but certainly they are
quite expensive nonetheless, and many large firms and government organizations
uses mainframes to run their business operations.
➢ The Mainframe computers can be accommodated in large air- conditioned rooms
because of its size. Supercomputers are the fastest computers with large data storage
capacity.
➢ Mainframes can also process and store large amount of data. Banks educational
institutions and insurance companies use mainframe computers to store data about
their customers, students and insurance policy holders.

Popular Mainframe Computers


➢ Fujitsu’s ICL VME
➢ Hitachi’s Z800
Applications of Mainframe Computer
➢ Government and civilian
➢ Credit card processing
➢ Bank
➢ Marketing
➢ Business data processing in large organization
➢ Air traffic control system
➢ Industrial design

Minicomputer
➢ Minicomputers are used by small businesses and firms. Minicomputers are
also called as “Mid- range Computers”.
➢ These are small machines and can be accommodated on a disk with not as
processing and data storage capabilities as supercomputers and mainframes.
These computers are not designed for a single user.
➢ Individual departments of a large company or organizations use
Minicomputers for specific purposes. For example, a production department
can use Minicomputers for monitoring certain production process.
Popular Minicomputers
➢ K-202
➢ Texas Instrument TI-990
➢ SDS-92
➢ IBM Mid-range Computers

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 8
Principles Of Programming Using C Notes 24BPOPS103
Microcomputer
➢ Desktop computers, laptops, personal digital assistants (PDAs), tablets and
smartphones are all types of microcomputers.
➢ The microcomputers are widely used and the fastest growing computers.
These computers are the cheapest among the other three types of computers.
➢ The Microcomputers are specially designed for general usage like
entertainment, education and work purposes. Well-known manufacturers of
Microcomputers are Dell, Apple, Samsung, Sony and Toshiba.
➢ Desktop computers, Gaming consoles, Sound and Navigation system of a car,
Netbooks, Notebooks, PDAs, Tablet PCs, Smartphones, Calculators are all
type of Microcomputer.

Basic Structure of Computer

CPU

MemoryUnit

InputUnit OutputUnit
ControlUnit

Arithmeticand
Logic Unit

➢ Input device accepts the coded information as source program i.e. high-level
language. This is either stored in the memory or immediately used by the
processor to perform the desired operations.

➢ The program stored in the memory determines the processing steps.


Basically, the computer converts one source program to an object program.
i.e. into machine language.

➢ Finally, the results are sent to the outside world through output device. All of
these actions are coordinated by the control unit.

➢ Input-unit: The source program/high level language program/coded


information/simply data is fed to a computer through input devices keyboard
is a most common type.
Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.
Page 9
Principles Of Programming Using C Notes 24BPOPS103
➢ Whenever a key is pressed, one corresponding word or number is translated into its
equivalent binary code over a cable & fed either to memory or processor. Joysticks,
trackballs, mouse, scanners etc are other input devices.

➢ Memory unit: - Its function into store programs and data. It is basically to two types
1. Primary memory 2. Secondary memory 1. Primary memory: - Is the one
exclusively associated with the processor and operates at the electronics speeds
programs must be stored in this memory while they are being executed.

➢ The memory contains a large number of semiconductors storage cells. Each ALU
Processor Control Unit www.edutechlearners.com 3 of 268 COMPUTER
ORGANIZATION capable of storing one bit of information. These are processed in
a group of fixed sites called word.

To provide easy access to a word in memory, a distinct address is associated with


each word location.

o Addresses are numbers that identify memory location.

o Number of bits in each word is called word length of the computer.


Programs must reside in the memory during execution.

o Arithmetic logic unit (ALU):- Most of the computer operators are executed
in ALU of the processor like addition, subtraction, division, multiplication,
etc. the operands are brought into the ALU from memory and stored in high
speed storage elements called register.

o The control and the ALU are may times faster than other devices connected
to a computer system.

o This enables a single processor to control a number of external devices such


as key boards, displays, magnetic and optical disks, sensors and other
mechanical controllers.

➢ Output unit:- These actually are the counterparts of input unit. Its basic function is
to send the processed results to the outside world.

Examples:- Printer, speakers, monitor etc.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 10
Principles Of Programming Using C Notes 24BPOPS103
Central Processing Unit (CPU)
The central processing unit (CPU) is the unit which performs most of the processing
inside a computer. To control instructions and data flow to and from other parts of the
computer, the CPU relies heavily on a chipset, which is a group of microchips located
on the motherboard.
The CPU has two components:
Control Unit: It extracts instructions from memory and decodes and executes them.
Arithmetic Logic Unit (ALU): It handles arithmetic and logical operations.
To function properly, the CPU relies on the system clock, memory, secondary storage,
and data and address buses. This term is also known as a central processor,
microprocessor or chip.

➢ The CPU is the heart and brain of a computer. It receives


data input, executes instructions and processes CPU

information. It communicates with input/output (I/O) Contro


Instructions
lUnit
devices, which send and receive data to and from the
Processo
CPU. r

➢ The CPU has an internal bus for communication with the Combina-
Output
internal cache memory, called the backside bus. Input tional
Logic

➢ The main bus for data transfer to and from the CPU,
memory, chipset, and AGP socket is called the front-side Main
Memor
y
bus.
➢ The CPU contains internal memory units, which are called registers. These
registers contain data, instructions, counters and addresses used in the ALU’s
information processing.
➢ These consist of separate physical CPUs located side by side on the same board or
on separate boards. Each CPU has an independent interface, separate cache, and
individual paths to the system front-side bus.
➢ Multiple processors are ideal for intensive parallel tasks requiring multitasking.
Multicore CPUs are also common, in which a single chip contains multiple CPUs.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 11
Principles Of Programming Using C Notes 24BPOPS103

Overview of C
INTRODUCTION
➢ A program is a set of instructions for a computer to perform a specified task. C is
a high-level language.

➢ Programs written in C are easy to create, read and understand. C is a general-


purpose programming

➢ A language which was developed by Dennis Ritchie at Bell Lab in 1972.

BASIC CONCEPTS OF A C PROGRAM

Preprocessor directives
Comment lines
Global Declarations
void main()
{
declaration section
statements
input statement
operational statements
output statements
}

Preprocessor Directives

➢ The preprocessor accepts the source program and prepare the source program for
compilation.

➢ The preprocessor-statements start with symbol #.


➢ The normal preprocessor used in all programs is include.

➢ The #include directive instructs the preprocessor to include the specified file-contents in
the beginning of the program.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 12
Principles Of Programming Using C Notes 24BPOPS103
• For ex:

#include<stdio.h>
Global Declarations
Variables which are declared globally can be used by or accessible from any function
present in a program.

main()
➢ Function is a set of statements which performs a specific task.
➢ Every C program should have a function called as main().
➢ This the first function to be executed always.
➢ The statements enclosed within left and right brace is called body of the
function.

The main() function is divided into 2 parts:


Declaration Section
The variables that are used within the function main() should be declared in the
declaration-section only.

The variables declared inside a function are called local- variables.

Ex: int a,b,c;

Executable Section
This contains the instructions given to the computer to perform a specific task.

The task may be to display a message, read data, Comments are portions of the code
ignored by the compiler. The comments allow the user to make simple notes in the
source-code.

// this is an example for single line comment, /* this is an example


for multiple line comment */
Example:
// C program to add two numbers
#include<stdio.h>
void main()
{
int a, b, c;
printf(“enter the values of a and b\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“the result is %d\n”,c);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 13
Principles Of Programming Using C Notes 24BPOPS103
HOW TO LEARN C LANGUAGE?
English is a universal language used to communicate with others.
In the same way, C is a language used to communicate with computer. In other words, C is
used to instruct computer to perform particular task.
The task can be
➢ simple task like adding 2 numbers or
➢ complex task like building a railway reservation system

Before you play the game, you should learn rules of the game. So that you can play better and
win easily. In the same way, to write C programs, you should learn rules of C language.

STEPS TO LEARN C LANGUAGE


Step 1: Before speaking any language, you should first learn alphabets. In the same way, to learn C
language, you should first learn alphabets in C.

Step 2: Then, you should learn how to group alphabets in particular sequence to form a meaningful
word. In the same way, in C language, you should learn tokens (i.e. words).

Step 3: Then, you should learn how to group the words in particular sequence to form a meaningful
sentence. In the same way, in C language, you should learn instruction (i.e. sentence).

Step 4: Then, you should learn how to group the sentences in particular sequence to form a
meaningful paragraph. In the same way, in C language, you should learn program (i.e.
paragraph).

CHARACTER SET

➢ Character-set refers to the set of alphabets, letters and some special characters that are
valid in C language.
➢ There are 256 characters in a Character set.

For example, the characters in C are:


➢ Letters A-X, a-z, both upper and lower
➢ Digits 0-9
➢ Symbols such as + - * / %
➢ White spaces \t \n

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 14
Principles Of Programming Using C Notes 24BPOPS103
C TOKENS

➢ A token is a smallest element of a C program.


➢ One or more characters are grouped in sequence to form meaningful words. These
meaningful words are called tokens.

The tokens are broadly classified as follows

➢ Keywords ex: if, for, while


➢ Identifiers ex: sum, length
➢ Constants ex: 10, 10.5, 'a', "sri"
➢ Operators ex: + - * /
➢ Special symbols ex: [], (), {}

KEYWORDS
A token which has predefined meaning in C language is called a keyword.
➢ Keywords are tokens which are used for their intended purpose only.
➢ Keywords are the instructions given to the Compiler.
➢ Each keyword has fixed meaning and that cannot be changed by user. Hence, they are also
called reserved-words.
➢ There are 32 keywords.
int, float, char, double, void, case, switch, if, else, elseif, return, auto, register, static,
const, for, while, do-while, default etc.

➢ Rules for using keywords


Keywords cannot be used as a variable or function.
All keywords should be written in lower letters.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 15
Principles Of Programming Using C Notes 24BPOPS103
IDENTIFIERS
Identifiers do not have any predefined meaning in C language.
➢ As the name indicates, identifier is used to identify various entities of program such as
variables, constants, functions etc.
➢ Identifiers are not the instructions given to the Compiler In other words, an identifier is
a word consisting of sequence of
Letters
Digits or
"_"(underscore)
• For ex:
area, length, breadth
Rules for Constructing an Identifier:
1. The first character must be a letter or an underscore, and then followed by any number of
digits, letters and underscores.
2. Keywords cannot be used as an identifier.
3. No extra symbols and spaces are allowed (other than letters, digits and underscore)
4. Identifier should not have two consecutive underscores.
5. Length of an identifier can be up to a maximum of 31 characters
Example to Identify valid /Invalid Identifiers:

1. num
Valid identifier

2. a_one
valid identifier as first character begins with letter

3. 2sum
Invalid Identifier because first character begins with digit

4. $sum
Invalid because no extra symbols are allowed other than under score

5. for
Invalid as for is a keyword

6. area length
Invalid because no spaces are allowed

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 16
Principles Of Programming Using C Notes 24BPOPS103

File Used in C Program


A C program uses four types of files as follows:

Source Code File


This file includes the source code of the program.
The extension for these kinds of files are '.c'. It defines the main and many more functions written
in C.
main() is the starting point of the program. It may also contain other source code files.

Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions
that are shared between various source files.
Advantages of header files:

At times the programmer may want to use the same subroutines for different programs. To do
this, he would just compile the code of the subroutine once and link to the resulting object file in
any file in which the functionalities of this subroutine are required.
At times the programmer may want to change or add the subroutines and reflect those changes in
all the programs. For doing this, he will have to only change the source file for the subroutines,
recompile the source code and then recompile and re-link the program.

This tells us that including a header file will make it easier at all levels of the program. If we need
to modify anything then changes are made only in the subroutines after which all the changes will
be reflected.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 17
Principles Of Programming Using C Notes 24BPOPS103

Standard header files


C provides us with some standard header files which are available easily.
Common standard header files are:
i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.
The header files are added at the start of the source code so that they can be used by more than
one function of the same file.

Object files
➢ They are the files that are generated by the compiler as the source code file is
processed.
➢ These files generally contain the binary code of the function definitions.
➢ The object file is used by the linker for producing an executable file for
combining the object files together. It has a ‘. o' extension.

Executable file
This file is generated by the linker.

Various object files are linked by the linker for producing a binary file which will be executed
directly. They have an '.exe' extension.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 18
Principles Of Programming Using C Notes 24BPOPS103
Compilers in C

➢ A compiler is a special program that translates a programming language's source


code into machine code, bytecode or another programming language.

➢ The source code is typically written in a high-level, human-readable language such


as Java or C++.

➢ A programmer writes the source code in a code editor or an integrated development


environment (IDE) that includes an editor, saving the source code to one or more
text files.

➢ A compiler that supports the source programming language reads the files, analyzes
the code, and translates it into a format suitable for the target platform.

➢ Compilers that translate source code to machine code target specific operating
systems and computer architectures.

➢ This type of output is sometimes referred to as object code (which is not related
to object-oriented programming).

➢ The outputted machine code is made up entirely of binary bits -- 1s and 0s -- so it


can be read and executed by the processors on the target computers.

➢ For example, a compiler might output machine code for the Linux x64 platform or
Linux ARM 64-bit platform

The complete set of escape sequences are:


Escape Sequences purpose

\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 19
Principles Of Programming Using C Notes 24BPOPS103

Example:

#include<stdio.h>
void main()
{
printf(“Welcome to C \n”);
printf (“Hello\tWorld\n”);

}
Output:

Welcome to C
Hello World

Data Types
C supports 5 primary data types:
1) int
An int is a keyword which is used to define integers.
Using int keyword, the programmer can inform the compiler that the data
associated with this keyword should be treated as integer.

C supports 3 different sizes of integer:


→ short int
→ int
→ long int

2) float
A float is a keyword which is used to define floating point numbers.
3) double
A double is a keyword used to define long floating point numbers.
4) char
A char is a keyword which is used to define single character.
5) void
void is an empty data type. Since no value is associated with this data type, it does
not occupy any space in the memory.
This is normally used in functions to indicate that the function does not return any
value.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 20
Principles Of Programming Using C Notes 24BPOPS103

VARIABLES
A variable is an identifier whose value can be changed during execution of the program.
In other words, a variable is a name given to a memory-location where the data can be
stored. Using the variable-name, the data can be stored in a memory-location and
accessed or manipulated

Rules for defining a variable

The first character must be a letter or an underscore, and then followed by any
number of digits, letters and underscores.
Keywords cannot be used as a variable.
No extra symbols and spaces are allowed (other than letters, digits and underscore)
Variable should not have two consecutive underscores.
Length of a variable can be up to a maximum of 31 characters

Examples:
Valid variables:
A11
Aaa
A_5
abcd principle_amount,
sum_of_digits

Invalid variables:
3fact //violates rule 1
sum= sum-of-digits 62$ //violates rule 3
for int if //violates rule 2

Declaration of Variable
➢ The declaration tells the complier
➢ what is the name of the variable used
➢ what type of date is held by the variable

The syntax is shown below:

Datatype v1,v2..
int a,b;
char ch1, ch2;

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 21
Principles Of Programming Using C Notes 24BPOPS103

CONSTANTS

A constant is an identifier whose value remains fixed throughout the execution of the
program.
• The constantscannot be modified in the program.
For example: 1, 3.14512,’a’

Different types of constants are:

1) Integer Constant
• An integer is a whole number without any fraction part. It consists of sequence of
digits.

• There are 3 types of integer constants:

Binary constants : 0 and 1 values

Decimal constants (0 1 2 3 4 5 6 7 8 9) : Combination of digits from 0-9


For ex: 0, -9, 22

Octal constants (0 1 2 3 4 5 6 7) : combination of digits with 0-7 with prefix 0 is called Octal
constant.
For ex: 021, 077, 033

Hexadecimal constants: (0 1 2 3 4 5 6 7 8 9 A B C D E F)
Combination of digits with 0-9 and then followed with A-F.
It must begin with 0x.
For ex: 0x7f, 0x2a, 0x521

2) Floating Point Constant


The floating point constant is a real number.
The floating point constants can be represented using 2 forms:

Fractional Form
A floating-point number represented using fractional form has an integer part followed
by a dot and a fractional part.
For ex: 0.5, -0.99

Scientific Notation (Exponent Form)


The floating-point number represented using scientific notation has three parts
namely: mantissa, E and exponent.
For ex: 9.86E3 imply 9.86*103

3. Character Constant
➢ A symbol enclosed within a pair of single quotes (' ‘) is called a character constant.
➢ Each character is associated with a unique value called an ASCII (American
Standard Code for Information Interchange) code.
➢ For ex: '9', 'a', '\n'

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 22
Principles Of Programming Using C Notes 24BPOPS103

4. String Constant
A sequence of characters enclosed within a pair of double quotes(“) is called a string
constant.
The string always ends with NULL (denoted by \0) character.
For ex: "9" "a" "hello" "\n”

5. Escape Sequence Characters/Backslash Constants

An escape sequence character begins with a backslash and is followed by one character.
A backslash (\) along with some characters give rise to special print effects by
changing (escaping) the meaning of some characters.

INPUT/OUTPUT STATEMENTS

In C Language input and output function are available as C compiler functions or C


libraries provided with each C compiler implementation. These all functions are
collectively known as Standard I/O Library function. Here I/O stands for Input and
Output used for different inputting and outputting statements. These I/O functions are
categorized into three processing functions. Console input/output function (deals with
keyboard and monitor), disk input/output function (deals with floppy or hard disk), and
port input/output function (deals with a serial or parallel port). As all the input/output
statements deals with the console, so these are also Console Input/Output functions.
Console Input/Output function access the three major files before the execution of a C
Program. These are as follows:

• stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
• stdout: This file is used to send or direct the output (usually is a monitor file, but
can also send the output to a disk file or any other device).
• stderr: This file is used to display or store error messages.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 23
Principles Of Programming Using C Notes 24BPOPS103

Input Output Statement

Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).

Input means to provide the program with some data to be used in the program and

Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.

There are mainly two of Input/Output functions are used for this purpose. These are
discussed as:

• Unformatted I/O functions


• Formatted I/O functions

Unformatted I/O functions

There are mainly six unformatted I/O functions discussed as follows:

• getchar()
• putchar()
• gets()
• puts()
• getch()
• getche()

getchar()

This function is an Input function. It is used for reading a single character from the
keyboard. It is a buffered function. Buffered functions get the input from the keyboard and
store it in the memory buffer temporally until you press the Enter key.

The general syntax is as:

v = getchar();

where v is the variable of character type. For example:

char n;
n = getchar();

A simple C-program to read a single character from the keyboard is as:

/*To read a single character from the keyboard using the getchar() function*/
#include <stdio.h>

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 24
Principles Of Programming Using C Notes 24BPOPS103

main()
{
char n;
n = getchar();
}

putchar()

This function is an output function. It is used to display a single character on the screen.
The general syntax is as:

putchar(v);

where v is the variable of character type. For example:

char n;
putchar(n);

A simple program is written as below, which will read a single character using getchar()
function and display inputted data using putchar() function:

/*Program illustrate the use of getchar() and putchar() functions*/


#include <stdio.h>
main()
{
char n;
n = getchar();
putchar(n);
}
gets()

This function is an input function. It is used to read a string from the keyboard. It is also a
buffered function. It will read a string when you type the string from the keyboard and
press the Enter key from the keyboard. It will mark null character (‘\0’) in the memory at
the end of the string when you press the enter key. The general syntax is as:

gets(v);

where v is the variable of character type. For example:

char n[20];
gets(n);

A simple C program to illustrate the use of gets() function:

/*Program to explain the use of gets() function*/


#include <stdio.h>
Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.
Page 25
Principles Of Programming Using C Notes 24BPOPS103

main()
{
char n[20];
gets(n);
}
puts()

This is an output function. It is used to display a string inputted by gets() function. It is also
used to display a text (message) on the screen for program simplicity. This function
appends a newline (“\n”) character to the output.

The general syntax is as:

puts(v);

or

puts("text line");

where v is the variable of character type.

A simple C program to illustrate the use of puts() function:

/*Program to illustrate the concept of puts() with gets() functions*/


#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}

The Output is as follows:

Enter the Name


Geek
Name is:
Geek

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 26
Principles Of Programming Using C Notes 24BPOPS103

getch()

This is also an input function. This is used to read a single character from the keyboard like
getchar() function. But getchar() function is a buffered is function, getchar() function is a
non-buffered function. The character data read by this function is directly assigned to a
variable rather it goes to the memory buffer, the character data is directly assigned to a
variable without the need to press the Enter key.

Another use of this function is to maintain the output on the screen till you have not press
the Enter Key. The general syntax is as:

v = getch();

where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
getch();
}

The output is as follows:

Enter the Char


Char is L

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 27
Principles Of Programming Using C Notes 24BPOPS103

getche()

All are same as getch(0 function execpt it is an echoed function. It means when you type
the character data from the keyboard it will visible on the screen. The general syntax is as:

v = getche();

where v is the variable of character type.

A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}

The output is as follows:

Enter the Char L


Char is L

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 28
Principles Of Programming Using C Notes 24BPOPS103

Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a
particular format. There are mainly two formatted I/O functions discussed as follows:

• scanf()
• printf()

scanf()

The scanf() function is an input function. It used to read the mixed type of data from
keyboard. You can read integer, float and character data by using its control codes or
format codes. The general syntax is as:

scanf("control strings",arg1,arg2,..............argn);

or

scanf("control strings",&v1,&v2,&v3,................&vn);

Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all are
the variables.

The scanf() format code (spedifier) is as shown in the below table:

Format Code Meaning

%c To read a single character

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%e To read a float value exponential

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%g To read double float value

%h To read short integer

%i To read an integer (decimal, octal, hexadecimal)

%o To read an octal integer only

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 29
Principles Of Programming Using C Notes 24BPOPS103

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

%s To read a string

%[..] To read a string of words from the defined range

%[^] To read string of words which are not from the defined range

Example Program:

/*Program to illustrate the use of formatted code by using the formatted scanf()
function */

#include <stdio.h>
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}

printf()

This ia an output function. It is used to display a text message and to display the mixed
type (int, float, char) of data on screen. The general syntax is as:

printf("control strings",&v1,&v2,&v3,................&vn);
or
printf("Message line or text line");

Where v1,v2,v3,……..vn all are the variables.

The control strings use some printf() format codes or format specifiers or conversion
characters. These all are discussed in the below table as:

Format Code Meaning

%c To read a single character

%s To read a string

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 30
Principles Of Programming Using C Notes 24BPOPS103

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%e To read a float value exponential

%g To read double float value

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

Example Program:
/*Below the program which show the use of printf() function*/

#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 31
Principles Of Programming Using C Notes 24BPOPS103

QUESTION BANK

1. Define Computer. Explain the organization of basic computer model with a neat
diagram.

2. Explain the generation of computers

3. List and explain the types of computers

4. List and explain any 4 input and output devices.

5. With a suitable example, Explain the basic structure of C program

6. What are the basic data types available in C.

7. Define the variable, Explain the rules to declare a variable with an example.

8. Write a c program

i. Find the area of circle

ii. Area of rectangle

iii. Area of square

iv. Area of parallelogram

v. Area of Triagle

vi. Volume of a sphere

vii. Newtons law of motion

viii. Perimeter of a circle

ix. Addition of 4 numbers

x. Subtraction of 2 numbers

xi. Multiplication of 4 numbers

xii. Printing your home address

9. List and explain Files used in C program.

10. Explain Variables and Constants in C programming.

11. Explain Formatted I/O functions with an example for each.

12. Explain Unformatted I/O functions with an example for each

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Page 32
Principles of Programming using C 24BPOPS103

MODULE 02
OPERATORS IN C, TYPE CONVERSION AND
TYPECASTING. DECISION CONTROL AND LOOPING
STATEMENTS
2.1 Operators in C & Type conversion and typecasting
OPERATOR
• An operator can be any symbol like + - * / that specifies what operation need to be
performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation
Operand
• An operand can be a constant or a variable.

Expression
• An expression is combination of operands and operator that reduces to a single value.
• For ex:
Consider the following expression a+b here a and b are operands while + is an operator
Types of Expressions:

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

CLASSIFICATION /TYPES OF OPERATORS

There are 8 types of operators:


Operator Name For Example
Arithmetic operators + - * / % Increment/decrement operators
++ -- Assignment operators =
Relational operators < > ==
Logical operators && || ~
Conditional operator ?:
Bitwise operators & | ^
Special operators []

1. ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations such as addition,
subtraction, multiplication, division and modulos.
• There are 5 arithmetic operators:
Operator Meaning of Operator
+ addition
- subtraction
* multiplication
/ division
% modulos

• Division symbol (/)


→ divides the first operand by second operand and
→ returns the quotient.
Quotient is the result obtained after division operation.

• Modulus symbol (%)


→ divides the first operand by second operand and
→ returns the remainder.
Remainder is the result obtained after modulus operation.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

• To perform modulus operation, both operands must be integers.

• Program to demonstrate the working of arithmetic operators.

#include<stdio.h>
void main()
{
int a,b,sum,sub,mul,div,mod;
sum=a+b;
sub=a-b;
mul=a*b;
div=a/b;
mod=a%b;
printf("sum=%d\n sub=%d\n mul=%d\n div=%d\n mod=%d\n”,sum,sub,mul,div,mod);
}
Output:
a=3 b=2
a+b=5
a-b=1

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

2. INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is used to
increase the value of a variable by 1.
• For example:
If a=5
then a++ or ++a; // a becomes 6
• The increment operator is classified into 2 categories:
1. Post increment Ex: a++
2. Pre increment Ex: ++a
• As the name indicates, post-increment means first use
the value of variable and then increase the value of
variable by 1.
• As the name indicates, pre-increment means first increase the
value of variable by 1 and then use the updated value of variable.
• For ex:
If a is 5,
then z= a++; sets z to 5
but z = ++a; sets z to 6

• Example: Program to illustrate the use of increment operators.


#include<stdio.h> void
main()
{
int a=5, b=5, z ;
z= a++;
printf(“ z=%d a= %d\n”, z, a); z = ++b;
printf(“ z=%d b= %d”, z, b);
}
Output: z=5
a=6 z=6 b=6

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

3. DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used to
decrease the value of a variable by 1.
• For example:
If a=5
then a-- or --a; // a becomes 4
• Similar to increment operator, the decrement operator is classified into 2 categories:
1. Post decrement: means first use the value of variable
and then decrease the value of variable by 1. Ex:
a--
2. Pre decrement: means first decrease the value of variable by 1
and then use the updated value of variable. Ex: --a

• Example: Program to illustrate the use of decrement operators.


void main()
{
int a=5,b=5, z ;
z= a--;
printf(“ z=%d x= %d\n”, z, a); z = --
b;
printf(“ z=%d y= %d”, z, b);
}
Output:
z=5 a=4
z=4 b=4

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

4. ASSIGNMENT OPERATOR
The most common assignment operator is =.
This operator assigns the value in right side to the left side.
The syntax is shown below:
variable=expression;
For ex:
c=5; //5 is assigned to c
b=c; //value
of c is
assigned to b
5=c; //
Error! 5 is a
constant.
The operators such as +=,*= are called shorthand assignment operators.
For ex,
a=a+10: can be written as a+=10;
In the same way, we have:
Operator Example Same as
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a%=b a=a/b
%= a=a%b

5. RELATIONAL OPERATORS
Relational operators are used to find the relationship between two operands.
The output of relational expression is either true(1) or false(0).
For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
The 2 operands may be constants, variables or expressions.
There are 6 relational operators:
Operator Meaning of Operator Example
> Greater than a>b returns true (1)
< Less than a<b returns false (0)
>= Greater than or equal to a>=b returns true (1)
<= Less than or equal to a<=b return false (0)
== Equal to Not a==b returns false (0)
!= equal to a!=b returns true(1)

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to illustrate the use of all relational operators.

#include<stdio.h> void main()


{
int a,b;
printf(“enter a and b:\n”);
scanf(“%d%d”,&a,&b);
if(a==b)
printf(“a and b are equal”);
else if(a>b)
printf(“ a is largest”);
else
printf(“ b is largest”);
}

6. LOGICAL OPERATORS
These operators are used to perform logical operations like negation, conjunction and
disjunction.
The output of logical expression is either true(1) or false(0).
There are 3 logical operators:

Operator Meaning Example


&& Logical AND If c=5 and d=2 then ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then ((c==5) || (d>5)) returns true. If c=5
! Logical NOT then !(c==5) returns false.
All non zero values(i.e. 1, -1, 2, -2)
will be treated as true. While zero
value(i.e. 0 ) will be treated as
false.
Truth Table
A B A&&B A||B !A
0 0 0 0 1
0 1 0 1
1 0 0 1 0
1 1 1 1

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to illustrate the use of all logical operators.


#include<stdio.h> void main()
{
int a,b,c;
printf(“enter 3 numbers a,b and c\n”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
printf(“ a is largest\n”);
else if((b>a)&&(b>c))
printf(“ b is largest\n”);
else
printf(“c is largest\n”);
}
Output:
1
2
3
c is largest

7. CONDITIONAL OPERATOR
The conditional operator is also called ternary operator it takes three operands.
Conditional operators are used for decision making in C.
The syntax is shown below:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false;
If exp1 is evaluated to true, exp2 is executed;
If exp1 is evaluated to false, exp3 is executed.
Example: Program to find largest of 2 numbers using conditional operator.
#include<stdio.h> void main()
{
int a,b, max ;
printf(“ enter 2 distinct numbers \n”); scanf(“%d %d”, &a, &b);
max=(a>b)? a : b;
printf(“ largest number =%d ”, max);
}
Output:
enter 2 distinct numbers 3 4
largest number = 4

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

8. BITWISE OPERATORS
These operators are used to perform logical operation (and, or, not) on individual
bits of a binary number. There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1
1 0 0 1 1 0
1 1 1 1 0
Ex for ~ (bitwise complement) Ex for & (bitwise AND)
a = 13 0000 1101 a = 13 0000 1101
~a= 1111 0010 b=6 0000 0110
a&b 0000 0100
Ex for || (bitwise OR) Ex for ^ (bitwise xor)
a = 13 0000 1101 a = 13 0000 1101
b=6 0000 0110 b=6 0000 0110
a|b 0000 1111 a^b 0000 1011

The operator that is used to shift the data by a specified number of bit positions towards
left or right is called shift operator. b=a >> num; where a is value to be shifted num is
number of bits to be shifted
Ex for <<(left shift): Ex for >>(right shift):
a = 13 0000 1101 a = 13 0000 1101
b=a<<1 0001 1010 b=a>>1 0000 0110

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

#include<stdio.h>
void main()
{
int x=5, y=4;
x=x>>1;
y=y<<2;
printf(“Rightshift x=%d\n”,x);
printf(“Leftshift y=%d\n”,y);
}

9. Special Operators
Special operators in C are used to perform special functions such as combining multiple
expressions into a single expression using comma operator,getting size of data type using
sizeof() operator.
➢ Comma Operator:
It combines multiple expressions into a single expression.
The value of right most expression is assigned to left variable.
Example.
a=(c=2,b=3);
a=b=3
a=3
➢ sizeof( ) operator:
It is used to determine size of the operand based on its data type.
Example:
float x=3.142;
int y;
y=sizeof(x); // size of float is 4 bytes.

Example: Program to illustrate sizeof() operator


Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.
Principles of Programming using C 24BPOPS103

#include<stdio.h>
void main( )
{
int a=10;
float b=3.142;
char c=’a’;
double d=1.234;
printf(“size of integer is: %d bytes”,sizeof(a)); // int is 2 bytes
printf(“size of float is: %d bytes”,sizeof(b)); // float is 4 bytes
printf(“size of char is: %d bytes”,sizeof(c)); //char is 1 byte
printf(“size of double is: %d bytes”,sizeof(d)); //double is 8 bytes
}

TYPE CONVERSION/TYPE CASTING


Type conversion is used to convert data of one type to data of another type.
Type conversion is of 2 types

1. IMPLICIT CONVERSION
• If a compiler converts one type of data into another type of data automatically,
it is known as implicit conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
For ex:
int a = 22, b=11;
float c = a; //c becomes 21.000000
float d=b/c=11/22.000000=11.000000/22.000000=0.500000
• If one operand type is same as other operand type, no conversion takes
place and type of result remains same as the operands
i.e. int+int=int
float+float=float
Conversion rules are as follows:
→ If either operand is long double, convert the other to long double.
→ Otherwise, if either operand is double, convert the other to double.
→ Otherwise, if either operand is float, convert the other to float.
→ Otherwise, convert char and short to int.
→ Then, if either operand is long, convert the other to long.
Example: Program to illustrate implicit conversion.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

#include<stdio.h> void main()


{
char c=’A’;
int a;
a=c;
printf(“a=%d\n”,a);

}
Output:
a=65

2. EXPLICIT CONVERSION
• When the data of one type is converted explicitly to another type with the
help of some pre-defined functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
The syntax is shown below:

data_type1
var1;
data_type2 v2= (data_type2) v1;
where v1 can be expression or variable
For ex:
float b=11.000000; int c = 22;
float d=b/(float)c=11.000000/22.000000=0.500000

• Example: Program to illustrate explicit conversion.


#include<stdio.h> void main()
{
int a=5;
float b;
b=1/(float)a;
printf("b=%f\n ", b );
}
Output:
b=0.200000

THE PRECEDENCE OF OPERATORS AND ASSOCIATIVITY

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Precedence is used to determine the order in which different operators in an


expression are evaluated.
Associativity is used to determine the order in which operators with same precedence are
evaluated in an expression.

Precedence Table

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

2.2 DECISION CONTROL AND LOOPING STATEMENTS


2.2.1 STATEMENT
• A statement is also called instruction.
• As the name indicates, instruction is used to instruct computer to perform a particular task
like
→ adding two numbers
→ reading data from keyboard or computation.
• For example:
sum=a+b; scanf("%d ", &n);
• In C,the semicolon(;)is a statement terminator. A statement must be terminated by a
semicolon.
Compound Statement
• The sequence of statement enclosed within a pair of braces{}is called a compound
statement.
• For example:
{
a=l*b;
printf("area =%d", a);
}
CONTROL STATEMENTS
• Aprogramisnothingbuttheexecutionofsequenceofoneormoreinstructions.
• The order in which the statements are executed is called control flow.
• The statements that are used to control the flow of execution of the program are
called control statements.
• The statements that are executed sequentially are called sequential control
statements.
• Based on application, it is necessary/essential
i. To alter the flow of a program
ii. Test the logical conditions
iii. Control the flow of execution as per the selection these conditions can be
placed in the program using decision-making statements.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

C SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS


1) Conditional Control Statements/Decision making/ Conditional Branching statements

i) if statement
ii) if else statement
iii) nested if statement
iv) else-if ladder/cascaded if statement
v) switch statement

2) Looping statements/Loop Constructs i) for loop


ii) while loop
iii) do-while loop

3) Unconditional control/ Unconditional Branching Statements/Jump Statements


i) break
ii) continue
iii) goto
iv) return

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

BASIC CONCEPTS CONDITIONAL CONTROL/DECISION MAKING


STATEMENTS
• Decision making is critical to computer programming.
• There will be many situations when you will be given 2 or more options and you will
have to select an option based on the given conditions.
• C language provides conditional i.e., decision making statements which work based
on the following flow diagram.

Branching Statements:
The statements that transfer the control from one place to other place in the program with or
without any condition are called branch statements.
They are classified into 2 types:
1. Conditional control statements
2. Unconditional control statements

1. Conditional Control Statements:


• In Sequential Control Statement all statements are executed in the order which they
are written.
• A set of statements may have to be skipped during execution when some other
condition is met. The statements that transfer the control from one place to other place
so as to execute a set of instructions if some condition is met or to skip the execution
of some statements if the condition is not met are called conditional control
statements.
• They are also called as Decision Making or Conditional Branching Statements.
• There are 5 types of Conditional control statements:

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

i. if statement
ii. if-else statement
iii. nested if statement
iv. else-if ladder
v. switch statement
1) simple if (one-way Selection)
• It is basically a “one-way” decision statement.
• This is used when we have only one alternative.

Syntax:
if(expression/condition)
{
statement(s);
}
Firstly, the expression is evaluated to true or false. If the expression/condition is evaluated to
true, then statement is executed. If the expression is evaluated to false, then statement is
skipped.

The flow diagram:

Example: Program to illustrate the use of if statement.


#include<stdio.h> void main()
{
int a,b;;
printf(“Enter a and b: \n”) ;
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“a is largest\n”);
}
Output:
Enter a and b: 7 5
a is largest

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

2) if-else (two-way selection)


• This is basically a “two-way” decision statement.
• This is used when we must choose between two alternatives.
syntax:
if(expression/Condition)
{
}
else
{
}
statement1;
statement2;
• Firstly, the expression/condition is evaluated to true or false.
If the condition is evaluated to true, then statement1 is executed.
If the condition is evaluated to false, then statement2 is executed.
Flow diagram

Example: Program to illustrate the use of if-else statement.


#include<stdio.h>
void main()
{
int a,b;
printf(“Enter values of a and b\n”) ;
scanf(“%d%d”, &a,&b);
if(a>b)
printf(“a is largest\n”);
else
printf(“b is largest\n”);
}
Output:
Enter a and b:
75
a is largest

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Program to illustrate positive and negative number:

#include<stdio.h> void main()


{
int num;
printf(“Enter number: \n”) ;
scanf(“%d”, &num);
if(num>0)
printf(“Number is positive number”);
else
printf(“Number is negative number”);
}
Output:
Enter number:
7
Number is positive number

Program to illustrate Even and Odd numbers

#include<stdio.h>void main()
{
int num;
printf(“Enter number\n”) ;
scanf(“%d”, &num);
if(num%2==0)
printf(“Num is even number”);
else
printf(“Num is odd number”);
}

Program to check whether a person is eligible for voting based on his age.

#include<stdio.h>void main()
{
int age;
printf(“enter age of a person\n”);
scanf(“%d”,&age);
if(age>=18)
printf(“eligible\n”);
else
printf(“not eligible\n”);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

3) Nested if STATEMENT
• An if-else statement with in another if-else statement is called nested if statement.
• This is used when an action has to be performed based on many decisions. Hence, it is
called as

multi-way decision statement.


Syntax:
if(expr1/condition1)
{
if(expr2/condition2)
{
statement-1;
}
}
else
{ else
{
statement-2;
}
if(expr3/condition3)
statement-3;
else
}
statement-4;

• Here, firstly expr1 is evaluated to true or false.

If the expr1 is evaluated to true, then expr2 is evaluated to true or false.


If the expr2 is evaluated to true, then statement1 is executed. If the expr2 is evaluated to false,
then statement2 is executed.
If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
If the expr3 is evaluated to true, then statement3 is executed.
If the expr3 is evaluated to false, then statement4 is executed.
Flow diagram:

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to print the largest of the 3 numbers using nested-if statements.
#include<stdio.h>void main()
{
int a,b,c;
printf(“Enter Three Values: \n”); scanf(“%d %d %d ”, &a, &b, &c); if(a>b)
{
if(a>c)
printf(“ a is largest”);
else
printf(“ c is largest”);
}
else
{
if(b>c)
printf(“ b is largest”);
else
printf(“ c is largest”);
}
}
Output:
Enter Three Values: 7 8 6
Largest Value is: 8

Dangling else problem in C:


Dangling else problem is the association of single else statement in a nested if statement. In
nested if statements, when a single “else clause” occurs, the situation happens to be dangling
else.
Syntax:
if(condition)
if(condition)
if(condition)
else
statement;
• In such situations else clause belongs to the closest if statement which is incomplete that
is the innermost if statement.
• else clause belong to the desired if statement by enclosing all if statements in block outer
to which if statement to associate the else clause.
Example:
if(condition)
{
if(condition)
if(condition)
}
else
printf(“dangling else\n”);

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

4) else-if ladder/Cascaded if (multi-way selection) statement


• This is basically “multi-way” decision statement.
• This is used when we must choose among many alternatives.
• Here, nesting takes place in the else part

Syntax:
if(exp1/condition1)
statement1;
else if(exp2/condition2)
statement2;
else if(exp3/condition3)
statement3;
else if(exp4/condition4)
statement4;
else
statement-n;

• The expressions are evaluated in order(i.e.top to bottom).


• If an expression is evaluated to true, then

→ statement associated with the expression is executed &


→ control comes out of the entire else if ladder
• For example, if exprression1 is evaluated to true, then statement1 is executed.

If all the expressions are evaluated to false, the last statement-n is executed.
Flow diagram

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to illustrate the use of else if ladder statement. (Type of Triangle)
#include<stdio.h>
void main ()
{
int a,b,c;
printf(“Enter 3 sides \n:”) ;
scanf(“%d%d%d”, &a,&b,&c);
if((a==b)&&(b==c)&&(a==c))
printf ("Equilateral triangle");
else if((a==b)||(b==c)||(a==c))
printf ("Isosceles triangle\n");
else
printf(“Scalene triangle\n”);
}
Output:
Enter 3 sides:
333
Equilateral Traingle

Program to display a grade of a student based on his percentage (using else if ladder)

#include<stdio.h>void main()
{
float percentage;
printf(“enter percentage:\n);
scanf(“%f”,&percentage);
if( percentage>=70)
printf(“FCD\n”);
else if (percentage<70 && percentage>=60)
printf(“First class”);
else if(percentage<60 && percentage>=35)
printf(“Second Class”);
else
printf(“Fail”);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

1. switch (multi-way selection) statement

• This is basically a “multi-way” decision statement.


• This statement is used when we must choose among many alternatives.

syntax & flow diagram is shown below:

Here, choice can be either any integer value or a character.


• Based on this integer value, the control is transferred to a particular case-value where
necessary statements are executed.
• During executing, if break statement is encountered, then the control comes out of the
switch block.
• If the value of the choice does not match with any of the case values (i.e. value1, value2,
value3) then control goes to default label.
• All case-values must be different.

• Program to Illustrate switch statement (to check vowel and Consonants)


#include<stdio.h>void main()
{
char choice;
printf(“enter your choice:\n”);
scanf(“%c”,&choice);
switch(choice)
{
case ‘a’ : printf(“It is a vowel”);
break;
case ‘e’ : printf(“It is a vowel”);
break;
case ‘i’ : printf(“It is a vowel”);
break;
case ‘o’ : printf(“It is a vowel”);
break;
case ‘u’ : printf(“It is a vowel”);
break;
default: printf(“It is a consonant”);
}
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Output:
Enter your choice: a
It is a vowel

2. Looping statements/Loop Constructs/Iterative statements:


• Let's consider a situation when you want to write a message “Welcome to C
language” five times. Here is a simple C program
#include<stdio.h>
void main()
{
printf( " Welcome to C language \n");
printf( " Welcome to C language \n");
printf( " Welcome to C language \n");
printf( " Welcome to C language \n");
printf( " Welcome to C language \n");
}
Output:
Welcome to C language
Welcome to C language
Welcome to C language
Welcome to C language
Welcome to C language

• When the program is executed, it produces the above result.


• It was simple, but again let's consider another situation when you want to write the
same message thousand times, what you will do in such situations?
• Are we going to write printf() statement thousand times? No,not at all.
• C language provides a concept called loop, which helps in executing one or more
statements up to desired number of times.
• Loops are used to execute one or more statements repeatedly.
• The flow diagram is shown below:

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Looping:
• Loops refer to repetitive execution of same set of instructions for a given number of
times until a result is obtained.
• A set of statements may have to be repeatedly executed for a specified number of
times or till a condition is satisfied are called looping statements or loop constructs.
• There are 3 types of loops in C programming/Loop Constructs:
1) for loop
2) while loop
3) do-while loop

1) for loop
• It repeats given true block of statements repeatedly till the expression is true.
Whenever the given condition becomes false then the loop gets terminated.
Syntax:
for(expr1;expr2;expr3)
{
statement(s);
}
statement-X;

OR
for(initialization; condition; updating-expression)
{
statement(s);
}
statement-X;

• It consists of 3 parts :Initialization, conditional expression and updating expression


• expr1 contains initialization statement
• expr2 contains conditional expression
• expr3 contains updating expression(increment/decrement)
• Firstly,expr1 is evaluated. It is executed only once.
• Then, expr2 is evaluated to true or false.
• If expr2 is evaluated to false, that is if the conditional expression is false then the control
comes out of the loop without executing the body of the loop. The loop is terminated.
• If expr2 is evaluated to true, the body of the loop (i.e. statement) is executed.
• After executing the body of the loop, expr3 is evaluated.
• Then expr2 is again evaluated to true or false. This cycle continues until expression
becomes false.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to display 1-100 numbers using for loop


#include<stdio.h>void main()
{
inti;
for(i=1;i<=100;i++)
{
printf(“%d\n”,i);
}
}

2) while loop

• A while loop statement can be used to execute a set of statements repeatedly as long
as a given condition is true.
Syntax :
while(condition)
{
statement(s);
}
statement-X;
OR
while(expression)
{
statement(s);
}
statement-X;

• Firstly, the expression/condition is evaluated to true or false.


• If the expression is evaluated to false, the control comes out of the loop without
executing the body of the loop.
• If the expression is evaluated to true, the body of the loop(i.e. statement) is executed.
• After executing the body of the loop, control goes back to the beginning of the while
statement and expression/condition is again evaluated to true or false.
• This cycle continues until condition becomes false.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to display 1-100 numbers using while loop


#include<stdio.h>
void main()
{
int i;
i=1;
while(i<=100)
{
printf(“%d\n”,i);
i++;
}
}

3) do-while loop
• When we do not know exactly how many times a set of statements have to be
repeated, do-while statement can be used.
Syntax :
do
{
statement(s);
} while(condition);
statement-X;
• Firstly, the body of the loop is executed .i.e. the body of the loop is executed at least
once.
• Then, the expression is evaluated to true or false.
• If the expression is evaluated to true, the body of the loop (i.e. statement) is executed
• After executing the body of the loop, the expression is again evaluated to true or false.
This cycle continues until expression becomes false.
Example: Program to illustrate do-while Loop
#include<stdio.h>
void main()
{
int i;
i=1;
do
{
printf(“%d\n”,i);
i++;
} while(i<=100);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Differences between while and do-while loop


while loop do-while loop
1. The condition is executed first, if it is 1. Block of statements within do is
true then block of statements are executed first then the condition is
executed or else skipped. It repeats the checked, if the condition is true then
given true block of statements block execution is repeated. When the
repeatedly till the condition is true. condition becomes false then the loop
When the condition becomes false terminates.
then the loop terminates.
2. It is a top-testing/entry-controlled loop 2. It is a bottom testing/exit-controlled
since the condition is checked at the loop since the condition is checked at
beginning itself. the bottom of loop.
3. It is also called as pre-test loop 3. It is also called as post-test loop
4. Syntax: 4. Syntax:
do
while(expression) {
{ statements;
statements; }while(expression);
} statement-X;
statement-X;
5. Example: 5. Example:

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
i=1; i=1;
while(i<=100) do
{ {
printf(“%d\n”,i); printf(“%d\n”,i);
i++; i++;
} } while(i<=100);
} }

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

UNCONDITIONAL CONTROL STATEMENTS/JUMP STATEMENTS


The statements which transfer control or flow of execution unconditionally to another block
of statements are unconditional control statements. These are also called as jump statements.
There are 4 types of jump statements:
1) break
The break statement stops the current and succeeding iteration. Then it transfers the control
out of the loop. It stops the loop execution.
• The break statement is jump statement which can be used in switch statement and
loops.
• The break statement works as shown below:
1) If break is executed in a switch block, the control comes out of the switch block and the
statement following the switch block will be executed.
2) If break is executed in a loop, the control comes out of the loop and the statement
following the loop will be executed.
Syntax:
for(expr1;expr2;expr3)
{
statement(s);
if(condition)
break;
statements;
}
statement-X;
Example: Program to illustrate break statement
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
printf(“%d\n”,i);
}
}
Output:
12

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

2) continue
• During execution of a loop, it may be necessary to skip a part of the loop based on some
condition.

In such cases, we use continue statement.


• The continue statement is used only in the loop to terminate the current iteration. It stops the
current iteration and continues the next iteration.

Syntax:
for(expr1;expr2;expr3)
{
statement(s);
if(condition)
continue;
statements;
}
statement-X;
Example: Program to illustrate continue statement
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf(“%d\n”,i);
}
}
Output:
1245

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

3) goto
• goto statement can be used to branch unconditionally from one point to another in the
program. It transfers the program execution flow from one point of the program to another
point.
• goto requires a label in order to identify the place where the branch is to be made.
• A label is any valid variable name and must be followed by a colon(:)
• The label is placed immediately before the statement where the control is to be transferred.

Syntax:

Example: Program to illustrate use of goto statement.


#include<stdio.h>void main()
{
printf(“welcome\t”);
goto label;
printf(“to\t”);
label:printf(“C programming\n”);
}
Output:
Welcome c programming

Why goto statements are not recommended to use in C?


• It is an unstructured programming style.
• It is very difficult to read, write and understand the program
• It is also very difficult to debug the program.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

4. return statement
• It terminates the execution of a function and returns control to the calling function. It
returns a value to the calling function.

Syntax:
return expression;
Example:
return 0;
Differences between break and continue statements
1. When break is executed the statements 1. When continue statements are executed
following break are skipped and causes the statements following continue are
the loop to be terminated skipped and causes the loop to be
continued with the next iteration.
2. It can be used in switch statement to 2. It cannot be used inside a switch
transfer the control outside the switch. statement.
3. Syntax: 3. Syntax:
for(exp1;exp2;exp3;) for(exp1;exp2;exp3;)
{ {
if(condition); if(condition);
break; continue;
statements; statements;
} }
statement-X; statement-X;
4. Example: 4. Example:
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
if(i==3) if(i==3)
break; continue;
printf(“%d\n”,i); printf(“%d\n”,i);
} }
} }
Output: Output:
12 1245

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Nested Loops:
A loop enclosed within another loop is called nesting of loops. A for statement can be inside
a for/while/do-while.
• Example:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
statements;
}
statements;
}
• The outer most loop is executed many times. Each time the control enters inside the
innermost loop.
• The index value of each loop must be different.
• The inner loop must be completely enclosed within the outer loop.
• Program to print the values in right triangle form:

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

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

#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(“* “);
}
printf(“\n”);
}
}

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

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

PLOTTING OF PASCALS TRIANGLE:

• In Pascal’s triangle all the numbers outside the triangle are “0”s.

• To build the triangle start with a “1” at the top then continue putting the numbers

below in a triangular pattern so as to form a triangular array.

• So each new number added below the top “1” is just the sum of two numbers above,

except for the edge which are all “1”s.Thus, the left and right edges of pascal’s

triangle are filled with “1”s only.

0 row=1
1 row=(0+1),(1+0)=1,1
2 row=(0+1),(1+1)(1+0)=1,2,1
3 row=(0+1),(1+2),(2+1),(1+0)=1,3,3,1
4 row=(0+1),(1+3),(3+3),(3+1),(1+0)=1,4,6,4,1
5 row=(0+1),(1+4),(4+6),(6+4),(4+1),(1+0)=1,5,10,10,5,1

• The sum of all elements of a row is twice the sum of all the elements of its preceding
row.
Example:
Sum of first row=1
Sum of second row is 1+1=2
Sum of third row is 1+2+1=4
Sum of fourth row is 1+3+3+1= 8
Sum of fifth row is 1+4+6+4+1=16
Sum of sixth row is 1+5+10+10+5+1=32 and so on….

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example: Program to illustrate Pascal’s triangle


#include<stdio.h>
void main()
{
int i,j,rows,num=1,space;
printf(“enter the number of rows:\n”);
scanf(“%d”,&rows);
for(i=0; i<rows; i++)
{
for(space=1; space<=rows-i; space++)
printf(“ “);
for(j=0; j<=i; j++)
{
if(j==0 || i==0)
num=1;
else
num=num*(i-j+1)/j;
printf(“%4d”,num);
}
printf(“\n”);
}
}

COMPUTATION OF BINOMIAL COEFFICIENTS


• The binomial coefficient C(n,r) or nCr is the number of ways of picking ‘r’ unordered
outcomes from ‘n’ possibilities also known as a combination.
• nCr=n!/((n-r)!*r!)
• ! represents factorial of a number.
• if n=5
• n!=5!=5*4*3*2*1=120
consider:
x=n!
y=(n-r)!
z=r!
nCr=x/(y*z)

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Program To compute binomial coefficient (nCr)


#include<stdio.h>
void main()
{
int n,r,x,y,z,nCr;
printf(“enter the value of n and r:\n”);
scanf(“%d%d”,&n,&r);
x=y=z=1;
for(i=n;i>=1;i--)
{
x=x*i;
}
for(i=n-r;i>=1;i--)
{
y=y*i;
}
for(i=r;i>=1;i--)
{
z=z*i;
}
nCr=x/(y*z);
printf(“nCr=%d\n”,nCr);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Programming Examples:
1. Write a C program to find the factorial of a given number
#include<stdio.h>
void main()
{
int i,n,fact=1;
printf(“enter n:\n”);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
printf(“factorial=%d\n”,fact);
}

2. Write a program to find sum of first 1 to n natural numbers /sum of series


1+2+3+…+n
#include<stdio.h>
void main()
{
int i,n,sum;
printf(“enter the value of n:\n”);
scanf(“%d”,&n);
i=1;
sum=0;
while(i<=n)
{
sum=sum+i;
i++;
}
printf(“sum of natural numbers=%d\n, sum);
}

3. Write a C program to check a given year is leap year or not


#include<stdio.h>
void main()
{
int year;
printf(“enter year:\n”);
scanf(“%d”,&year);
if((year%4==0)&&(year%100!=0)||(year%400==0))
{
printf(“ %d is a leap year\n”,year);
}
else
printf(“%d is not a leap year\n”,year);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

4. Write a C program to print numbers from 4 to 9 and their squares.


#include<stdio.h>
void main()
{
int i,n,square;
i=4;
n=9;
while(i<=9)
{
square=i*i;
printf(“%d\n”,square);
i++;
}
}

5. Write a C program to compute GCD(m,n) and LCM(m,n) of a number


#include<stdio.h>
void main()
{
intm,n,a,b,GCD,LCM,rem;
printf(“enter the values of m and n:\n”);
scanf(“%d%d”,&m,&n);
a=m;
b=n;
while(n!=0)
{
rem=(m%n);
m=n;
n=rem;
}
GCD=m;
LCM=(a*b)/GCD;
printf(“GCD(m,n)=%d\n”,GCD);
printf(“LCM(m,n)=%d\n”,LCM);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

6. Write a C program to compute GCD of a given number using Ternary and for loop
#include<stdio.h>
void main()
{
int i,gcd,x,y;
printf(“enter the values of x and y:\n”);
scanf(“%d%d”,&x,&y);
for(i=x;i>=1;i--)
{
(x%i==0 && y%i==0)?(gcd=i): (gcd=1);
if(gcd==i)
break;
}
printf(“GCD of %d and %d is %d\n”,x,y,gcd);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

QUESTION BANK
Q. No Questions

1. List the Operators in c and explain in brief?


2. Explain increment decrement operators?
3. Explain ternary operator with an example?
4. Explain type casting with suitable example?
5. Define recursion explain with an example?
6. Write C program to calculate nPr using function?
7. Write a C program to print pascal triangle?
8. Write a C program to find factorial of a number using loops?
9. List and Explain different types of loop supported by C program with syntax and
suitable examples?
10. Write a C program to check whether a number is palindrome or not?
11. Write a C program to print the following pattern?
*
**
***
****
12. Write a C program to print the following pattern?
1
12
123
1234
13. Write a C program to print the following pattern?
1
11
111
1111
14. Explain break and continue statement with suitable example in C
OR
Compare & contrast break and continue statement in C
15. Illustrate goto statement with suitable example in c

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

MODULE-III
FUNCTIONS AND ARRAYS

FUNCTION IN C
• A function is a collection of statements that performs a specific task.
• Functions are very useful to read, write, debug and modify complex programs. A
function can also be referred as a method or a sub-routine or a procedure.
• One reason to use functions is that they break a program into small, manageable units.
Each unit is called module which performs a specific task.
• Another reason to use function is that they simplify programs.
• Every C program has at least one function main( ).Without main() function, there is
technically no C program.

• Advantages of a functions/Why Functions?


➢ It will help us to divide the large programs into small groups so that, we can
understand and debug the program quicker and better.
➢ Multiple persons can work on same program by assigning different functions to
each of them.
➢ Prevent us from writing same logic multiple times (duplicating).
• Program to print a sentence using function is shown below

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

TYPES OF C FUNCTIONS
• There are 2 types of functions in C programming:
1. Library Functions/built-in functions/pre-defined functions
2. User defined functions

1. Library Function
• Libraryfunctionsarethein-builtfunctioninCcompiler.
• Functions which are defined in C library are called library functions or built-in functions.
• These functions are also called as pre-defined functions.
• For example:

→main() //The execution of every C program starts from this main() function
→printf() //printf() is used for displaying output inC
→scanf() //scanf() is used for reading/taking input inC

1. Program to find square root of a number using built-in function (sqrt)

#include<stdio.h>
#include<math.h>
void main()
{
int n;
float x;
printf(“enter number:\n”);
scanf(“%d”,&n);
x=sqrt(n);
printf(“square root=%f\n”,x);
}

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

ARRAYS
BASIC CONCEPT OF ARRAYS
• Consider a situation, where we need to store 5 integer numbers.
• If we use simple variable and data type concepts, then we need 5 variables of int data
type and program will be something as follows:
#include<stdio.h>void main()
{
int a,b,c,d,e;
a=10;
b=20;
c=30;
d=40;
e=50;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
printf("d=%d\n",d);
printf("e=%d\n",e);
}
Output:
a=10
b=20
c=30
d=40
e=50

• It was simple, because we had to store just 5 integer numbers. Now let's assume we
have to store 5000integernumbers,so what is next? Are we going to use 5000
variables?
The main disadvantage of using above simple program are:
➢ Difficult to declare more number of variables.
➢ Difficult to read and write a program. It is difficult to print the data stored in
more number of variables.
➢ Very difficult to process large amount of data.
➢ Length of a program increases as the number of variable increases.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

➢ Consumes too much time to write, modify and correct.


➢ It is not a good programming style.
• How to process large amount of data?
➢ All these disadvantages can overcome by using a very powerful data
structure called Arrays along with looping constructs.
ARRAY
• Array is a collection of elements of same data type.
• It is used to store, process and print large amount of data.
• The elements are stored sequentially one after the other in memory.
• It is also known as homogeneous collection of elements of same type.
• Array data type: data type of an array can be int, double, float and char
• Any element can be accessed by using
→ name of the array
→ position of element in the array

Representation of an array:
array[0] array[1] array[2] ………… array[n-1]

Examples:

➢ Array of 5 integers:

a[0] a[1] a[2] a[3] a[4]


10 20 30 40 50

➢ Array of 5 floating point numbers:

b[0] b[1] b[2] b[3] b[4]


10.0 20.0 30.0 40.0 50.0

➢ Array of 5 characters:

c[0] c[1] c[2] c[3] c[4]


‘A’ ‘B’ ‘C’ ‘D’ ‘E’

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

How to access the elements of the array:

Consider the pictorial representation of an array of 5 integers.

a[0] a[1] a[2] a[3] a[4]


10 20 30 40 50

• The array is identified by name a i.e, any element in the array can be accessed using
the common name.
• The element can be accessed using the subscript 0 ( also called index 0 ) along with
name of array
• Index: An index is also called the subscript is the position of an element in the array.
• Using the index, we can access the elements.

Example to access the elements of an array:


• 0th element 10 can be accessed by specifying a[0]
• 1st element 20 can be accessed by specifying a[1]
• 2ndelement 30 can be accessed by specifying a[2]
• 3rd element 40 can be accessed by specifying a[3]
• 4thelement 50 can be accessed by specifying a[4]

Basic Properties of an array:


• The data items(called elements) stored in an array should be of the same data type.
• The data items are stored contiguously in memory (one after other).
• The subscript of first item is always zero.
• Each data item is accessed using the name of the array, but, with different subscripts.
• The index of the array is always an integer.
Example: a[1] // OK Index is an integer.
a[1.5] // Error Index has to be integer not floating point.
a[‘5’] // Ok Index is an integer. ‘5’ has an ASCII value which
is integer.

CLASSIFICATION/TYPES OF ARRAYS:

Arrays are of 2types:

1) Single dimensionalarray(One Dimensional-1D array)


2) Multi-dimensionalarray (Two Dimensional-2D array)
1. Single dimensional array(1D array):
• Single dimensional array is the simplest type of array that contains only one row
(linear list) for storing the values of same type.
• Inmemory,all the elements are stored in continuous memory-location one after the
other.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Declaration of Single Dimensional Array (1D array)


An array must be declared and defined before it is used.
syntax:

data_typearray_name[array_size];

where,data_type can be int,float or char


array_nameis name of the array
array_size indicates number of elements in the array

example:

int a[5];

Pictorial representation of an Array of 5 integers

a[10 a[1] a[2] a[3] a[4]

Note that, the first element is numbered 0 and so on….

• Since sizeof(int) is 2 bytes. 2*5=10 bytes. 10 memory locations are reserved for an
array of 5 integers.

example:

float b[5];

Since sizeof(float) is 4 bytes. 4*5=20 bytes. 20 memory locations are reserved for an
array of 5 floating point numbers.

example:

char c[5];

Since sizeof(char) is 1 bytes. 1*5=5 bytes. 5 memory locations are reserved for an array
of 5 characters.

STORING VALUES IN ARRAYS

• The values can be stored in array using following three methods:


1) Initialization
2) Assigning values
3) Input values from keyboard

1. Initialization of Single-Dimensional Array(1D array)

• Assigning or providing the required values to a variable before processing is called


initialization.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Syntax:

data_type
array_name[array_size]={v1,v2,...,vn};

where,v1, v2,…, vn are values

example:

int a[5]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

a[0] a[1] a[2] a[3] a[4]


10 20 30 40 50

There are various ways of initializing arrays:


• Initializing all specified memory locations
• Partial array initialization
• Initialization without size
• Array initializing with a string

1. Initializing all specified memory locations:

Arrays can be initialized at the time of declaration when their initial values are known
in advance. During compilation 5 contiguous memory locations are reserved by the
compiler for the variable a. The size is 2 bytes then 10 memory locations will be
allocated for variable a.
Example:

int a[5]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

a[0] a[1] a[2] a[3] a[4]


10 20 30 40 50

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

2. Partial Array Initialization:

If the number of values to be initialized is less than the size of array, then the elements
are initialized in the order from 0th location. The remaining locations will be
initialized to zero automatically.
Example:

int a[5]={10,20};

Pictorial representation of partial array:


Append 0’s

10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]

3. Initialization without size:

In this method even if the size is not specified the array size will be set to the total
number of initial values specified. Since the number of elements is 5 , totally 5*2=10
bytes are reserved.
Example:

int a[]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

a[0] a[1] a[2] a[3] a[4]


10 20 30 40 50

4. Array Initialization with a string:

Sequence of characters enclosed within a double quotes is a string. The string always
ends with NULL character ‘\0’.
Example:

char c[]=”COMPUTER”;

C 0 M P U T E R \0

Size of array is 9 bytes ( i.e String length+1 byte for null character)

5. Assigning values to array:


• How to assign values to array without initialization?
We can assign values to individual elements of the array using the assignment
operator.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Declaration: Memory representation:

a[0] a[1] a[2] a[3] a[4]


int a[5];

• The elements 10,20,30,40 and 50 can be inserted into array at positions 0,1,2,3,4,5, as
shown below.

➢ After executing the instruction: The value 10 is stored in array a at position 0.

a[0] a[1] a[2] a[3] a[4]


a[0]=10; 10

➢ After executing the instruction: The value 20 is stored in array a at position 1.

a[0] a[1] a[2] a[3] a[4]


a[1]=20; 10 20

➢ After executing the instruction: The value 30 is stored in array a at position 2.

a[0] a[1] a[2] a[3] a[4]


a[2]=30; 10 20 30

➢ After executing the instruction: The value 40 is stored in array a at position 3.


a[0] a[1] a[2] a[3] a[4]
a[3]=40; 10 20 30 40

➢ After executing the instruction: The value 50 is stored in array a at position 5.


a[0] a[1] a[2] a[3] a[4]
a[4]=50; 10 20 30 40 50

• Is it possible to assign one array to another?

➢ It is not possible to assign one array to other array.


Example:
int a[5]={10,20,30,40,50};
int b[5];
b=a; // Error Cannot assign one array to other array

➢ But we can copy all individual elements of one array a into other array b.

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Example:
b[0]=a[0]; // b[0] is assigned the value of a[0]
b[1]=a[1]; // b[1] is assigned the value of a[1]
b[2]=a[2]; // b[2] is assigned the value of a[2]
b[3]=a[3]; // b[3] is assigned the value of a[3]
b[4]=a[4]; // b[4] is assigned the value of a[4]
b[i]=a[i];
i=0 to 4

➢ b[i]=a[i] can be executed for all values of i=0 to 4 using for loop.

Example:

for(i=0;i<=4;i++)
{
b[i]=a[i];
}
or
for(i=0;i<5;i++)
{
b[i]=a[i];
}

6. Reading/Writing ID Arrays:
• How to read the data from keyboard and how to display data items stored in the array?
We can easily read, write or process the array elements using loop constructs (for,
while and do-while).
• We can read ‘n’ array elements from keyboard using scanf().
Example:
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
• Similarly to display ‘n’ elements stored in the array replace scanf() by printf()
statement.
Example:

for(i=0;i<n;i++)
{
printf(“%d”,a[i]);

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.


Principles of Programming using C 24BPOPS103

Question Bank
1. Define function. List application of function or advantages of functions
2. Write a C Program to swap two numbers using functions.
3. Explain general categories of functions
4. Explain different parameter passing techniques
5. List and explain various categories of user-defined functions.
6. Compare and contract actual and formal parameters
7. Write a c program to find factorial of n
8. Write a c program for calculating nCr using functions
9. Write a C Program for a sequential search
10. Write a C Program for binary search
11. What are the applications of 1-d array
12. Write a C Program to sort n number of elements in an array using bubble sort
13. Write a C Program to print even and odd number in array of an n elements
14. Illustrate the declaration of 2-D array with suitable examples
15. Write a C Program to print transpose of the given matrix of order m X n
16. Write a C Program to print principle diagonal elements of given matric a of order pXq
17. Write a C Program to add two matrix a and b . Print matrix a matrix b and resultant matrix
18. Write a C Program to subtract two matrix a and b . Print matrix a matrix b and resultant
matrix
19. Write a C Program to multiply two matrix a and b . Print matrix a matrix b and resultant
matrix

Prepared By, Suhasini Bagalkot Dept. Of CSE-AIML, RNSIT, Bangalore.

You might also like