PPSC Notes Unit I

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

Programming for Problem Solving using C - 20CS01

UNIT-I: - Introduction to Problem solving through C-Programming

What is a computer?
It is an electronic device for storing and processing data, typically in binary form, according to
instructions given to it in a program.
A computer is a machine that can be programmed to carry out sequences of arithmetic or logical
operations automatically. Modern computers can perform generic sets of operations known as
programs. These programs enable computers to perform a wide range of tasks.

The Memory unit is classified into two types.


They are 1) Primary Memory.
2) Secondary Memory
Primary memory: The following are the types of memories which are treated as primary.
ROM: It represents Read Only Memory that stores data and instructions even when the computer
is turned off. The Contents in the ROM can ‘t be modified once if they are written. It is used to
store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions when the computer
is turned on. The contents in the RAM can be modified any no. of times by instructions. It is
used to store the programs under execution.
Cache memory: It is used to store the data and instructions referred by processor.
Secondary Memory: The following are the different kinds of memories.

1|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Magnetic Storage: The Magnetic Storage devices store information that can be read, erased and
rewritten several times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes
Optical Storage: The optical storage devices that use laser beams to read and write stored data.
Example: CD (Compact Disk), DVD (Digital Versatile Disk)
Output Devices: -
Output devices are pieces of equipment that are used to get information or any other response out
from computer. These devices display information that has been held or generated within a
computer. Output devices display information in a way that you can understand. The most
common output device is a monitor.
Types of Output Device
Printing: Plotter, Printer
Sound: Speakers
Visual: Monitor
A Printer is another common part of a computer system. It takes what you see on the computer
screen and prints it on paper. There are two types of printers: Impact Printers and Non -Impact
Printers.
Speakers are output devices that allow you to hear sound from your computer. Computer
speakers are just like stereo speakers. There are usually two of them and they come in various
sizes.
CPU OPERATION
The fundamental operation of most CPUs
To execute a sequence of stored instructions called a program.
1. The program is represented by a series of numbers that are kept in computer memory.
2. There are four steps that nearly all CPUs use in their operation: fetch, decode, execute, and
write back.
3. Fetch:
o Retrieving an instruction from program memory.

2|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

o The location in program memory is determined by a program counter (PC)


o After an instruction is fetched, the PC is incremented by the length of the instruction
word in terms of memory units.
INTRODUCTION TO COMPUTER SOFTWARE
When we talk about a computer, we mean two things. The first is the computer hardware which
does all the physical work on computers are known for.
The second part is computer software which tells the hardware what to do and how to do it.

COMPUTER
SYSTEM
COMPUTER HARDWARE COMPUTER SOFTWARE

SYSTEM SOFTWARE APPLICATION SOFTWARE

The computer hardware cannot think and make decisions on its own. So, it cannot be used to
analyze a given set of data and find a solution on its own. The hardware needs a software (a set of
programs) to instruct what must be done. A program is a set of in structions that is arranged in a
sequence to guide a computer to find a solution for the given problem. The process of writing a
program is called programming.
CLASSIFICATION OF COMPUTER SOFTWARE
Computer software can be broadly classified into two groups: system software and application
software.
Application software is designed to solve a particular problem for users. It is generally what we
think of when we say the word computer programs. Examp les of application software include
spreadsheets, database systems, desktop publishing systems, program development software,
games, web browser, so on and so forth. Simply put, application software represents programs that
allow users to do something besides simply run the hardware.
System Software
On the contrary, system software provides a general programming environment in which
programmers can create specific applications to suit their needs. This environment provides new
functions that are not available at the hardware level and performs tasks related to executing the
application program. System software represents programs that allow the hardware to run properly.

3|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

OPERATING SYSTEM
An operating system ensures that the system resources (like CPU, memory, I/O devices, etc) are
utilized efficiently. For example, there may be many service requests on a web server and each
user request need to be serviced. Similarly, there may be many programs residing in the main
memory. Therefore, the system needs to determine which programs are active and which need to
wait for some I/O operation. Since, the programs that need to wait can be suspended temporarily
from engaging the processor. Hence, it is important for an operating system to have a control policy
and algorithm to allocate the system resources.

USER 1 USER 2 USER N

Application programs
For example, games, spreadsheets, word processor, database,
web browsers

System Software
For example, Operating System

Computer Hardware
For example, printer, mouse, scanner, keyboard, CPU, disk

4|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

COMPILER
A compiler is a special type of program that transforms source code written in a programming
language (the source language) into machine language comprising of just two digits- 1s and 0s
(the target language). The resultant code in 1s and 0s is known as the object code. The object code
is the one which will be used to create an executable program.
If the source code contains errors, then the compiler will not be able to its intended task. Errors
that limit the compiler in understanding a program are called syntax errors. Syntax errors are like
spelling mistakes, typing mistakes, etc. Another type of error is logic error which occurs when the
program does not function accurately. Logic errors are much harder to locate and correct.
INTERPRETER
Interpreter: Like the compiler, the interpreter also executes instructions written in a high -level
language.
While the compiler translates instructions written in high level programming language directly
into the machine language; the interpreter on the other hand, translates the instructions into an
intermediate form, which it then executes.

5|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Usually, a compiled program executes faster than an interpreted program. However, the big
advantage of an interpreter is that it does not need to go through the compilation stage during
which machine instructions are generated. This process can be time-consuming if the program is
long. Moreover, the interpreter can immediately execute high-level programs.
LINKER
Linker: Also called link editor and binder, a linker is a program that combines object modules to
form an executable program.
Generally, in case of a large program, the programmers prefer to break a code into smaller modules
as this simplifies the programming task. Eventually, when the source code of all the modules has
been converted into object code, you need to put all the modules together. This is the job of the
linker. Usually, the compiler automatically invokes the linker as the last step in compiling a
program.
LOADER
A loader is a special type of program that copies programs from a storage device to main memory,
where they can be executed. Most loaders are transparent to the users.
PROGRAMMING LANGUAGES
A programming language is a language specifically designed to express computations that can
be performed the computer. Programming languages are used to express algorithms or as a mode
of human communication.
While high-level programming languages are easy for the humans to read and understand, the
computer understands the machine language that consists of numbers only.
In between the machine languages and high-level languages, there is another type of language
known as assembly language. Assembly languages are similar to machine languages, but they are
much easier to program in because they allow a programmer to substitute names for numbers.
However, irrespective of what language the programmer use, the program written using any
programming languages must be converted into machine language so that the computer can
understand it. There are two ways to do this: compile the program or interpret the program
The question of which language is best depending on the following factors:
▪ The type of computer on which the program must be executed
▪ The type of program
▪ The expertise of the programmer
▪ For ex, FORTRAN is a good language for processing numerical data, but it does not lend
itself very well to organizing large programs. Pascal can be used for writing well-structured
and readable programs, but it is not as flexible as the C programming language. C++ goes
one step ahead of C by incorporating powerful object-oriented features, but it is complex
and difficult to learn.

6|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

FIRST GENERATION: MACHINE LANGUAGE


Machine language is the lowest level of programming language. It is the only language that the
computer understands. All the commands and data values are expressed using 1s and 0s.
In the 1950s each computer had its own native language. Although there were similarities between
each of the machine language, but a computer could not understand programs written in another
machine language. The main advantage of machine language is that the code can run very fast and
efficiently since it is directly executed by the CPU.
However, on the downside, the machine language is difficult to learn and is far more difficult to
edit if errors occur. Last but not the least, code written in machine language is not portable and to
transfer code to a different computer it needs to be completely rewritten. Architectural
considerations make portability a tough issue to resolve.
SECOND GENERATION: ASSEMBLY LANGUAGE
Assembly languages are symbolic programming languages that use mnemonics (symbols) to
represent machine-language instructions. Since assembly language is close to the machine, it is
also called low-level language.
Basically, an assembly language statement consists of a label, an operation code, and one or more
operands. Labels are used to identify and reference instructions in the program. The operation
code (opcode) is a mnemonic that specifies the operation that must be performed, such as move,
add, subtract, or compare. The operand specifies the register or the location in main memory from
where the data to be processed is located.
Assembly language is machine dependent. This makes the code written in assembly language less
portable as the code written to be executed on one machine will not run-on machines from a
different or sometimes even the same manufacturer.
Programs written in assembly language need a translator often known as the assembler to convert
them into machine language. This is because the computer will understand only the language of
1s and 0s. it will not understand mnemonics like ADD and SUB.
The following instructions are a part of assembly language code to illustrate addition of two
numbers
MOV AX,4 Stores the value 4 in the AX register of CPU
MOV BX,6 Stores the value 6 in the BX register of CPU
ADD AX,BX Add the contents of AX and BX register. Store the result in AX register
THIRD GENERATION PROGRAMMING LANGUAGE
The third generation was introduced to make the languages more programmer friendly. 3GLs
spurred the great increase in data processing that occurred in the 1960s and 1970s. in these
languages, the program statements are not closely related to the internal characteristics of the
computer and is therefore often ref erred to has high-level languages.

7|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

3GLs made programming easier, efficient, and less prone to errors. Programs were written in an
English-like manner, making them more convenient to use and giving the programmer more time
to address a client's problems.
Most of the programmers preferred to use general-purpose high-level languages like BASIC
(Beginners' All-purpose Symbolic Instruction Code), FORTRAN, PASCAL, COBOL, C++ or
Java to write the code for their applications.
Again, a translator is needed to translate the instructions written in high level language into
computer-executable machine language. Such translators are commonly known as interpreters and
compilers. 3GLs makes it easier to write and debug a program and gives the programmer more
time to think about its overall logic. The programs written in such languages are portable between
machines.
FOURTH GENERATION: VERY HIGH-LEVEL LANGUAGES
4GLs is a little different from its prior generation because they are basically nonprocedural, so the
programmers define only what they want the computer to do, without supplying all the details of
how it must be done. Characteristics of such language include:
▪ the code comprising of instructions are written in English-like sentences.
▪ they are nonprocedural
▪ the code is easier to maintain
▪ 4GL code enhances the productivity of the programmers as they must type fewer lines of
code to get something done. It is said that a programmer become 10 times more productive
when he writes the code using a 4GL than using a 3GL.
▪ A typical example of a 4GL is the query language that allows a user to request information
from a database with precisely worded English-like sentences.
Let us take an example in which a report has to be generated that displays the tota l number of
students enrolled in each class and in each semester.
FIFTH-GENERATION PROGRAMMING LANGUAGE
5GLs are centered on solving problems using constraints given to the program, rather than
using an algorithm written by a programmer.
Most constraint-based and logic programming languages and some declarative languages form
a part of the fifth-generation languages. 5GLs are widely used in artificial intelligence research.
Typical examples of a 5GL include Prolog, OPS5, and Mercury. Another aspect of a 5GL is
that it contains visual tools to help develop a program. A good example of a fifth -generation
language is Visual Basic.With 5GL, the programmer only needs to worry about what problems
need to be solved and what conditions need to be met, without wo rrying about how to
implement a routine or algorithm to solve them.

8|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

DESIGN OF ALGORITHMS
The first step in the program development is to devise and describe a precise plan of what
you want the computer to do. This plan, expressed as a sequence of operatio n, is called an
algorithm. An algorithm is just an outline or idea behind a program..
Definition
An Algorithm is a finite step of instructions that perform a particular task and it must satisfy
the following features.
Features of Algorithm
Following features should be present in an algorithm:
• Proper understanding of the problem
For designing an efficient algorithm, the expectations from the algorithm should be clearly
defined so that the person developing the algorithm can understand the expectations from
is. This is normally the outcome of the problem definition phase.
• Use of procedures/functions to emphasize modularity
To assist the development, implementation and readability of the program, it is usually
helpful to modularize (section) the program. Independent functions perform specific and
well defined tasks. In applying modularization, is is important to watch that the process is
not taken so far to a point at which the implementation becomes difficult to read because
of fragmentation. The program then can be implemented as calls to the various procedures
that will be needed in the final implementations.
• Choice of variable names
Proper variable names and constant names can make the program more meaningful and
easier to understand. This practice tends to make the program more self -documenting. A
clear definition of all variables and constants at the start of the procedure/algorithm can
also be helpful. For example, it is better to use variable day for the day of the weeks, instead
of the variable A or something else.
• Documentation of the program
Brief information about the segment of the code can be included in the program to facilitate
debugging and providing information. A related part of the documentation is the
information that the programmer presents to the user during the execution of the program.
Since the program is often to be used by persons who are unfamiliar with the working and
input requirements of the program, proper documentation must be provided. That is, the
program must specify what responses are required from the user. Care should also be taken
to avoid ambiguities in these specifications also the program should “catch” incorrect
responses to its requests and inform the user in an appropriate manner.
Criteria to be followed by an algorithm
The following is the criteria to be followed by an algorithm:
i) Input: There should be zero or more values which are to be supplied.
ii) Output: At least one result is to be produced.
iii) Definiteness: Each step must be clear and unambiguous.
iv) Finiteness: Algorithm must terminate after finite no. of steps.
V) Effectiveness: Every Instruction must be very basic principle to carry it out. In addition,
not only each step is definite, it must also be feasible.

9|Pag e Phaneendra Kanakamedala


Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example: An algorithm to find the area of a Circle of radius r.


Inputs to the algorithm:
▪ Radius r of the Circle.
Expected output:
▪ Area of the Circle
Algorithm:
Step1: Read\input the Radius r of the Circle
Step2: Area= PI*r*r // calculation of area
Step3: Print Area
Example: An algorithm to compute and display the sum of two numbers
Inputs to the algorithm:
▪ Two numbers
Expected output:
▪ Sum of two numbers
Algorithm:
Step1: Read two numbers a and b
Step2: Calculate the sum of a and b and store it is sum
Step3: Print sum

Example: Ravi has to attend at least 70% of Practical Classes for C programming to be eligible
to appear in the external examination. Maximum no. of practical classes allotted for the course is
50. He has attended 20 out of 30 classes held so far. Find at least how many more classes to be
attended by Ravi to be eligible for appearing in Practical Examination.
Inputs to the algorithm:
▪ Minimum Percentage of Attendance required appearing for the external exams.
▪ Maximum Number of practical classes
▪ Number of Classes held so far.
▪ Number of classes attended by Ravi so far.
Expected output:
▪ Number of classes to be attended by Ravi to get eligibility for appearing the external
examination
Algorithm:
Step1: Read Minimum percentage of attendance required.
Step2: Read Maximum no. of practical classes in the course (P)
Step3: Read Classes already attended (Ca)
Step4: Read No. of classes conducted so far.(CT)
Step5: Find the no. of Classes to be attended byRavi (Ct= C*P/100)
Step6: Print CM.

10 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example: An algorithm to convert temperature from Fahrenheit to Celsius


Inputs to the algorithm:
▪ Temperature in Fahrenheit
Expected output:
▪ Temperature in Celsius
Algorithm:
Step 1: Read Temperature in Fahrenheit F
Step 2: C= 5/9*(F=32)
Step 3: Print Temperature in Celsius: C
Step 4: Stop.
Example: An algorithm to compute and print the average of a set of data values.
Inputs to the algorithm:
▪ List of data values
Expected Output:
▪ Average of the data values
Step1: Set the sum of the data values and the count to zero
Step2: As long as the data values exist, add the next data value to the sum andadd
1 to the count.
Step3: To compute the average, divide the sum by the count.
Step4: Print average.

Example: An algorithm to calculate the factorial of a given number.


Inputs to the algorithm:
▪ An integer numbers
Expected Output:
▪ Factorial of the integer
step1: Read the number n
step2: [initialize] i 1, fact 1
step3: Repeat steps 4 through 5 until i = n
step4: fact fact*i
step5: i i +1
step6: Print fact

Example: An algorithm to check a given integer is prime or not


Inputs to the algorithm:
▪ An integer numbers
Expected Output:
▪ Prime or not
step1: Read the number n
step2: [initialize] i 2, flag 1
step3: Repeat steps 4 through 5 until i < num or flag = 0
step4: rem num mod i
step5: if rem = 0 then flag 0 else i i+1
step6: If flag = 0 then Print number is not prime else print number is prime

11 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example: Ramshewar goes to market for buying some fruits and vegetables. He is having a
currency of Rs 500 with him for marketing. From a shop he purchases 2.0 kg Apple priced Rs.
50.0 per kg, 1.5 kg Mango priced Rs.35.0 per kg, 2.5 kg Potato priced Rs.10.0 per kg, and 1.0 kg
Tomato priced Rs.15 per kg. He gives the currency of Rs. 500 to the shopkeeper. Find out the
amount shopkeeper will return to Ramshewar and also tell the total item purchased.
Before we write algorithm for solving above problem let we find out what the inputs to the
algorithm are and what expected output is.
Inputs to the algorithm are:
▪ Quantity of different items purchased.
▪ Unit Price of each item.
▪ Total amount given to the shopkeeper.
Expected output:
▪ Amount to be returned by shopkeeper after deducting total price of the purchased
vegetables and fruits.
Algorithm:
Step1: Total Cost=0;
Step2: Read Number of units of ith item purchased;
Spet3: Read unit price of ith item
Step4: cost of ith item (CI) = number of units * unit price of ith item.
Step5: total cost = total cost +CI.
Step6: i= i+1;
Step7: if i<=4 goto step 2.
Step7: RefundAmount = GivenAmount-Total Cost
Step8: Print RefundAmount

Example: Print the Multiplication Table of N.


Inputs to the algorithm are:
▪ Number N
Expected output:
▪ Table of N
Algorithm:
Step 1: I=1
Step 2: Read N
Step 3: If I <= 10 then print I*N otherwise goto Step 6
Step 4: I =I+1
Step 5: repeat step3 and 4
Step 6: stop

12 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

FLOW CHARTS
“Flow charts are pictorial representation of an algorithm”. It shows the flow of operations
in pictorial form.

The flowchart is a means of visually presenting the flow of control through an information processing
system, the operations performed within the system and the sequence in which they are performed.
It is a graphic representation of how a process works, showing, at a minimum, the sequence of steps.
Flowcharts are generally drawn in the early stages of formulating computer solutions.
Flowchart Symbols
For drawing flow chart standard symbols are used. These symbols are given in table.

Symbols Meaning/Used for

Start or end of the program

Used for writing steps of operations/action or


processing function of a program

Input or output operation

Decision making and branching operations

Connector or joining of two parts in a flowchart

Flow line used for showing flow of data

Magnetic Tape used for secondary


storage/Backup

Magnetic Disk used for secondary


storage/Backup

Flow chart Symbols

13 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Significance of flowchart
i. A flowchart is a diagrammatic representation of algorithm.
ii. A flow chart clearly illustrates the sequence of operations to be performed for getting the solution of
a problem.
iii. For simple problems flow charts may not be very useful but for complex and large problems flow
charts are very helpful in understanding the logic of the problem.
iv. Flowcharts are used as a link of communication between programmers and clients for whom the
program to be developed.
v. If you are having a flowchart for your program, then you can use it in explaining the program to
others.
vi. Once the flowchart is drawn, it becomes easy to write the computer program.
vii. Flowcharts can be used for preparing a better documentation of a complex problem.

Guidelines for drawing a flowchart


i. First of all, lists all necessary requirements in a logical order.
ii. The flowchart should be clear and easy to understand. There should not be any ambiguity
in understanding the flowchart. For doing this it is necessary to have all the steps and
operation very simple.
iii. Usually, direction of the flow of data /procedure in the system should be from left to right
or top to bottom.
iv. Only one flow line should come out from a process symbol.

v. When decision symbol is used only one flow line should enter to it (decision symbol), but there may
be two or three flow lines coming out of the decision symbol, one for each possible answer.

A<B A>B
Compare
A& B

A=B

vi. In a flowchart only one flow line should come to the end symbol.

END

14 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

vii. While writing steps inside the processing symbol, steps should be brief and if necessary, you can use
the annotation symbol to describe data or processing steps more clearly.

P=A*R

Where P = Price, A = Amount, and R = Rate

viii. In the case of complex flowchart connector symbols to be used for reducing the number of flow
lines in the flowchart.
ix. Intersection of flow lines should be avoided to make a flowchart more effective and for better way of
communication.
x. A flowchart must have a logical start and end.
xi. Once a flowchart is drawn its validity should be tested by passing through it with a
simple set of test data.

Example : Draw a flowchart to find the simple interest

START

READ P,T,R

SI=P*T*R/100

PRINT SI

STOP

15 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example: Draw a flowchart to find the largest of three numbers A, B, and C.

start

Read A B C

Yes No Yes Yes


is is is
B>C? A>B? A>C

No No

print C print A
print B print c

stop

Example: Draw a flowchart for computing factorial N (N!) Where N! = 1? 2? 3...N.

Read N

M=1
F=1

F=F*M

NO
M=M+1 Is
M=N?
YES

Print F

stop

16 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Advantages of using Flowcharts


As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial representation
of a solution/system is having many advantages. These advantages are as follows:

i) Communication: A Flowchart can be used as a better way of communication of the


logic of a system and steps involve in the Solution, to all concerned
particularly to the client of system.
ii) Effective analysis: A flowchart of a problem can be used for effective analysis of the
problem.
iii) Documentation of Program/System: Program flowcharts are a vital part of good
program documentation. Program document is used for various purposes like
knowing the components in the program, complexity of the program etc.
iv) Efficient Program Maintenance: Once a program is developed and becomes
operational it needs time to time maintenance. With help of flowchart maintenance
become easier.
v) Coding of the Program: Any design of solution of a problem is finally converted into
computer program. Writing code referring the flowchart of the solution become easy.

Limitations of using Flowcharts


• Complexity of Logic: If program logic is complex then flowchart of the program becomes
complicated.
• Alterations and Modifications in Logic: any alterations in the program logic may require
redrawing of flowchart completely.
• Reuse is Not Possible: As the flowchart symbols cannot be typed, always reproduction of
flowchart symbols is required.

Introduction
• C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.
• C was initially developed for writing system software.
• Today, C has become a popular language and various software programs are written using
this language.
• Many other commonly used programming languages such as C++ and Java are also based
on C.
Features of C
i) Middle Level Language: Among the two types of programming languages discussed
earlier(High Level and Low level), C lies in between these two categories. That’s why it is
often called a middle level language, since it was designed to have both: relatively good
programming efficiency and relatively good machine efficiency.
ii) Portability: C code is very portable, that it allows the same C program to be run on the
machines with different hardware configurations.
iii) Flexibility: The flexibility of C allows it to be used for systems programming as well as
for application programming.

17 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

iv) Structured Language: C is commonly called a structured language because of structural


similarities of ALGOL and PASCAL. Structured language is one that divides the entire
program into the modules using top-down approach where each module executes one job or
task. It is easy for debugging, testing and maintenance if a language is structured one.
Uses of C Programming
• C language is primarily used for system programming. The portability, efficiency, the ability
to access specific hardware addresses and low runtime demand on system resources makes
it a good choice for implementing operating systems and embedded system applications.
• C has been so widely accepted by professionals that compilers, libraries, and interpreters of
other programming languages are often implemented in C.
• C is widely used to implement end-user applications.

STRUCTURE OF A C PROGRAM

To solve a problem there are three main things Preprocessor directives


to be considered. firstly, what should be the Global data declarations
main() /* main function */
output? Secondly what should be the input that
{
will be required to produce this output and
Declaration part ;
thirdly the steps of instructions which use Program statements;
these inputs to produce the required output. }
Every programming language follows a set of /* user defined functions */
rules known as syntax . C is a case sensitive fun1()
language. All c programs consist of one or {
more functions. One function that must be -------
present in every C program is main(). This is -------
the first function called up when the program }
execution begins. Basically main () outlines fun2()
what a program does. {
------
The structure of a c program is illustrated in }
flowing figure1.1. Where functions fun1 (),
fun2 () represent user defined functions. Fig1.1. structure of a C program

A sample C program
From the above section you have become familiar with a programming language and structure
of a program. It is now time to write a simple C program. The program will illustrate how to
print out the message “This is a C program”.

18 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Program: write a program to print to a message on the screen

/*program to print a message*/


#include<stdio.h> /*header file*/
main () /* main function*
{
printf(“This is a program”); /*output statement*/
}

Though the program is very simple, a few points must be noted.


Every C program contains a function called main (). This is the starting point of the program.
This is the point from where the execution begins. It will usually call other fun ction to help
perform its job, some that we write and others from the standard libraries provided.
#include<stdio.h> is a reference to a special file called stdio.h which contains information that
must be included in the program when it is compiled. The inclusion of this required information
will be handled automatically by the compiler. You will find it at the beginning of almost every
C program. Basically all the statements starting with ‘# ‘ in C program are called preprocessor
directives .These will be considered in the later units just remember that this statement allows
you to use some predefined functions such as printf() and scanf().
main() declares the start of the function while the two curly{ } shows the start and finish of
the function. Curly brackets in C are used to group statements together as a function or in the
body of a loop. Such a grouping is known as a compound statement or a block every statement
within a function ends with a terminator semicolon (;).
printf(“this is a C program”); prints the words on the screen .The text to be printed is
enclosed in double quotes.
Comments may appear anywhere within a program if they are placed with in the delimiters /*
and*/. Such comments are helpful in identifying the program principal features or in explaining
the underlying logic of various program features.

19 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

C Program Execution Process

After writing the program the next step is to save the program in a file with extension .C.
This program is in high level language, but this language is not understood by the computer. So,
the next step is to convert program in high level language to machine language. This task is
performed by the software or program known as compiler. Every language has its own compiler
that converts source code to object code. The compiler will compile the program successfully if
the program is syntactically correct.

If the program contains syntax errors, they will be displayed on the screen with the corresponding
line numbers and the object file will not be produced. The errors need to be removed before
compiling the program. This process of removing the errors from the program is called as
debugging. This translation process is called compilation.

Source code Compiler Object code

Link and Run the C program


After compilation, the next step is linking the program. Compilation produces a file with an
extension .obj. Now this .obj file cannot be executed since it contains calls to function defined in
the standard library of C language. These functions have to be linked with the code you wrote, C
remembers its name. Later the linker combines the code you wrote with the object code already
found in the standard library. This process is called linking. In other words, linker is a program
that links separately compiled functions together into one program. It combines the functions in
the standard C library with the code that you wrote. The output of the linker is an executable
program. i.e., a file with an extension .exe.

Object code Linker Executable code

KEYWORDS IN C
C has a set of 32 reserved words often known as keywords. All keywords are basically a sequence
of characters that have a fixed meaning. By convention, all keywords must be written in lowercase
(small) letters.

20 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Identifiers
Identifiers are names given to program elements such as variables, arrays and functions. These are
user defined names and consist of a sequence of letters and digits, with a letter as a first character.
Both upper case and lower cases letters are permitted, although lower case letters are commonly
used. The underscore character ( _ ) is also permitted.

Rules for identifiers

• An identifier must start with an alphabet or an underscore: it may not have a space or a
hyphen.
• It cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except
the underscore"_".
• Keywords cannot be used as identifiers.
• The names are case sensitive. So, for example, “FIRST” is different from “first” and
“First”.
• It can be of any reasonable length. Though it should not contain more than 31 characters.
Example: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code

21 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

DATATYPES IN C
Data types can be broadly classified as
i) Primary data types
ii) User defined data types.
iii) Derived data types

i) Primary data types


These are also called basic data types or fundamental data types. All C compilers support five
fundamental data types.

Data type Keyword


integer int
floating point float
double precession double
Character char
void void

Primary data types are those which are already defined in programming languages also known in-
built data types. These data types are basic building blocks of any programming language and
numerous composite data types are constructed from this basic type.
Data types derived from primitive data types are called derived data types. Derived data types used
to add some functionality to the basic data types as per program requirement.
Data type that derived from an existing data type are called user-defined data type (UDT). You
can create customized data type to extend the built-in types that already available.
typedef and enum used to creates user defined data types.

22 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Integer data type


Integers are whole numbers with a range of values supported by a particular machine. If a system
allocates 16 bits, to an integer, one size of integer value is limited to one range 32,768 to 32,767
(i.e-2 15 to 2 15-1).
In order to provide some control over the range of numbers and storage space, C has four classes
of integer storage, namely short int, long int, and long long int, in both signed and the unsigned
forms.

Size and range of values of integer data types for 16 bit machine

sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)

Declaration of integer variables will be as follows :


Example : int l, m;
short a, b; same as short int a,b;
long int p; same as long p;
unsigned int x; same as unsigned x;

Floating point data type


Floating point numbers are stored in 32 bits (on all 16 bit machines),with 7 digit precision.
Floating point numbers are defined by the keyword float .When the accuracy provided by a float
number is not sufficient , the type double can be used to define the number . A double data type
number uses 64 bits giving a precision of 15 significant digits .To extend the precision we may use
long double which uses 80 bits.
Size and range values of floating data types on 16 bit machine.
sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)

Data type Size(bits) Range Precision


float 32 (4 bytes) 3.4e-38 to 3.4e38 7 digits
double 64 (8 bytes) 1.7e-308 to 1.7 e 308 15 digits
long double 80 (10 bytes) 3.4e-4931 to 3.4 e 4932 20 digits

Floating point variables declaration is as follows:


Example : float a,b;
long float l,m;
double p,q;
long double x,y;

23 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Character data type


A single character can be defined as a character type of data. Characters are stored on 8 bits of
space. The qualifier signed or unsigned may be applied to char .signed char have values between
-128 to 127 and unsigned char have values between 0 to 255.
Character type variable declaration is as follows:
char ch;

String Constants
A string constant is a sequence of characters enclosed in double quotes .The characters
may be letters, number, special characters and blank space. The format that specifies th is type of
constants is %s(where ‘s’ is called conversion character).
Example : “Hello!” “1987” “WELLDONE” “! ---? +”.

Valid examples Invalid examples(with reasons)


”hello” ”A’ (the string constant A should be enclosed in a pair of double
”143” quotation marks)
”1+43” NOTE: 7 is a decimal integer constant
”a” ’7’ is a single character constant
”7” ”7” is a string constant

Void data type


The void type has no value. This is usually used to specify the type of a function that does
not return any value to the calling function.

Example: void main()

ii) User Defined Datatypes

C allows the feature called type definition which allows programmers to define their identifier that
would represent an existing data type. There are two such types: Enum, Typedef

iii) Derived Datatypes


Data types that are derived from fundamental data types are derived types. For example: arrays,
pointers, function types, structures, etc.

24 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Backslash character constants


C supports some special backlash character constants that are used in output functions. For
example the Symbol “\n” stands for new line character. A list of such backlash character constants
is given in the below table. Note that each one of them represents one character.

Character Constant Meaning


\n New line (Line break)
\b Backspace
\t Horizontal Tab
\f Form feed
\a Alert (alerts a bell)
\r Carriage Return
\v Vertical Tab
\? Question Mark
\' Single Quote
\'' Double Quote
\\ Backslash
\0 Null

DECLARATION OF VARIABLES

After designing suitable variable names, we must declare them to the computer. Declaration does
two things
• It tells the computer what the variable name is.
• It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
The syntax for declaring a variable is as follows:
data-type v1,v2,v3….vn

where v1,v2,v3….. are names of the variables. Variables are separated by commas.A declaration
statement must end with a semicolon.

Example : int count;


char ch;
float rate,price;
double ratio;
Program : The program segment illustrates declaration of variables.
main()
{
/* declaration */
float x,y;
int code;
short count;
long amount;
double deviation;

25 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

unsigned n;
chat ch;
/* computation */
………….
…………..
}
• main() indicates beginning of the program
• Declaration of variable is done at the beginning part.

ASSIGNING VALUES TO THE VARIABLES

The values can be assigned to variables using assignment operator (=) as follows:
variable_name=constant;
Examples: count=0;
code=100;
balance=87.96;
ch=’y’;
C also permits multiple assignments in one line such as:
x= 3.5, y=78.4;are valid statements.
An assignment statement implies that the value of the variable on the left of the ‘equal’ sign is set
equal to the value of the quantity /expression on the right side.
The statement count=count+3;
means that the new value of count is equal to the old value of count plus 3. During assignment
operation C converts the type of value on right hand side to the type of value on the left. This may
involve truncation when real value is converted to an integer.

Initialization:
It is also possible to assign a value to a variable at the time of the variable is declared.
This takes the following form:

data-type variable_name=constant;

Example : int final_value=100;


char yes=’x’;
double balance=754.84;
The process of giving initial values to variables is called initialization. C permits more than one
variable initialization in one statement using multiple assignment operators. For example, the
statements
p=q=s=0;
x=y= 45; are valid.

26 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Program /* assignment examples*/


main()
{
/*declarations*/
Output:
float x,p; m=-11215
double y,q; n=1234567890
unsigned k; x=1.234567880630
int m=54321; x=1.234568
/*declarations& assignments */ y=9.876543210000
long int n=1234567890; y=9.856743
/*assignments */ k=54321 p=1.0000000 q=1.000000000000
x=1.234567890000;
y=9.87654321;
k=54321
p=q=1.0;
/*printing*/
printf(“m=%d\n”,m);
printf(“n=%ld\n”,n);
printf(“x=%.12lf\n”,x);
printf(“x=%f\n”,x);
printf(“y=%.12lf\n”,y);
printf(“y=%lf\n”,y);
printf(“k=%u p=%f q=.12lf\n”,k.p,q);
}
Here the variable m that has been declared as int is not able to store the value 54321 correctly
instead it contains some garbage value. Because maximum value that an int variable can store is
32767,if the program is executed on 16-bit machine.

The variable k declared as unsigned has stored the value correctly. Unless specified otherwise
printf() function always display float or double values to six decimal places .
INPUT FUNCTION- scanf()

We can assign values to variable through assignment statements such as x = 5 a = 0 ; and so on.
Another method is to use scanf() function which can be used to read data from a key board. It is
the general input function available in C Language. The general format of scanf() is as follows:
scanf(“control string”,&variable1,&variable2,….);
The control string contains format of the data being received. The ampersand symbol (&)before
each variable name is the operator that specifies variable name’s address. The use of & is must in
scanf() function.
Example: scanf(”%d”,&x);
When this statement is encountered, the execution of program stops and waits for the value of the
variable x to be typed in .The format %d specifies that an integer value is to be read from the

27 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

terminal, we have to type in the value in integer form. Once number typed and return key pressed,
the next statement in the program is executed.
Commonly used format specifications:
%c – read a single character.
%d – read a decimal Integer.
%e – read a floating point value in exponential form.
%f – read a floating point value.
%i – read a decimal, hexadecimal or octal Integer.
%h– read a short integer.
%x – read a hexadecimal integer (unsigned) using lower case a – f.
%X – read hexadecimal integer (unsigned) using upper case A – F.
%o – read an octal integer.
%s – read a string
%u –read unsigned decimal integer.
OUTPUT FUNCTION-printf()
printf() function in ‘C’ allows you to display information required to the user and also prints the
values of variables. Output data can be written from computer to standard output device.

Program
#include < stdio.h > Output:
main ( ) Hello!Welcome to the world of Engineering.
{
printf (“Hello!”);

printf (“Welcome to the world of Engineering!”);


}
Both the messages appear in the output as if a single line. If you wish to print the second message
to the beginning of next line, a new line character must be placed inside the quotation marks.
Program
main() Output:
Hello!
{
Welcome to the world of Engineering
printf(“Hello!\nWelcome to the world of
Engineering”);
}

28 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

General format of printf() is as follows :


printf(“control string”,exp1,exp2,exp3,……);

The control string contains format of the data to be displayed and exp1,exp 2,exp3…are output
expressions. The function accepts a series of arguments, each applying to a conversion specifier
in the given control string , printf() prints the formatted information to the standard output device,
usually the display screen
Program
#include<stdio,h>
main()
Output:
{
value of a is 100
int a;
a=100;
printf(“value of a is %d”,a);
}
Here control string contains format specifier %d indicates a decimal integer to be displayed. a is
the name of the variable. If value of a is 100 the value 100 will be displayed on screen.

OPERATORS AND EXPRESSIONS

C supports a rich set of built in operators. C Operators can be classified into the following
categories.
i) Arithmetic operators
ii) Relational operators
iii) Logical operators
iv) Assignment operators
v) Increment and Decrement operators
vi) Conditional operators (Ternary operator)
vii) Bitwise operator

Expression
Variables and constants connected by operator is called expression.

Arithmetic operators
Arithmetic operations involve negation, addition, subtraction, multiplication and division as
shown in the following table.

29 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Operator Operation Description


- -x Negation
+ +x Unary plus
+ x+y Addition
- x-y Subtraction
* x*y Multiplication
/ x/y Division
% x%y Modulus

i) The expression i % j would result in the remainder of i divided by j.

Example : int i= 10, j=3, k;


k=i%j; 1 is assigned to the variable k.
ii) The modulus operator can be used only with integer operands.

Example : float x, y, z;
z=x % y; is not valid.
iii) All other operators can be applied to operands of the arithmetic type, which consists of integer,
floating point or complex types.
iv) When both the operands in an expression are integers, the expression is called integer
expression. Integer arithmetic leads an integer value.

Example : 25/7=3, 3/4=0, 4/3=1

v) When both operands are floating point type the expression is called floating point type
expression.

Example : x=5.2, y=1.42;


z=x/y;
vi) When one of the operand is real and the other is integer the expression is called a mixed mode
expression. The result is floating point type value.

Example : 23/5.0=4.6
vii) If an expression contains more than one arithmetic operator than they are executed from left
to right in the following order
i) unary minus and unary plus
ii) *, / , %
iii) + , -

Example : 3+5/2*4-10+17%6 is evaluated as


3+((5/2)*4)-10+(17%6)
The result of the expression is 6

30 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Relational Operators

Relational Operators are used to compare the values of two expressions. An expression containing
a relational operator (Ex: a < b, n! =0, p>q) is termed as a relational expression. The value of a
relational expression is either one or zero. It is one if the specified relation is true and zero if the
relation is false.

Operator Operation Description


< x<y less than comparison
<= x<=y lesser or equal comparison
== x==y equal comparison
>= x >= y greater or equal comparison
> x>y greater comparison
!= x != y not equal comparison

Example:
int i=5,j=3,k;
k= (i<j); 0 is assigned to k
k= (i==j); 0 is assigned to k
k= (i>=j); 1 is assigned to k

Logical Operators: There are three logical operators

Operator Operation Description


! !x logical negative operation
&& x && y logical AND operation
|| x || y logical OR operation

! (NOT) If the operand of the unary logical negative operator! is nonzero, the result is true
otherwise, the result is false. The truth table for the NOT operator is

Exp ! exp
1 0
0 1
Example !0=1
!3.7=0
! (20) =0
Example: int a=5, b=6, c;
c=! (a>b); The value 1 is assigned to the variable c.

31 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

&& (AND) is used to check whether both the expressions are non-zero or not.
The truth table for AND operator is

exp1 exp2 exp1&&exp2


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

To check whether the values of three variables a, b, c form the sides of an equilateral triangle the
following code may written
if (a==b && b==c)
printf (“The values of a, b, c forms an equilateral triangle”);
else
printf (“The values of a, b, c doesn’t form an equilateral triangle”);

|| (OR) operator is used to check any one of the values of two expression is non -zero.

The truth table for OR operator is


exp1 exp2 exp1||exp2
1 1 1
1 0 1
0 1 1
0 0 0

Example: To check whether the values of three variables a, b, c form the sides of an isosceles
triangle the following code may written
if(a==b || b==c || a==c)
printf(“The values of a,b,c form an isosceles triangle”);
else
printf(“ The values of a,b,c don’t form an isosceles triangle”);

Increment and decrement operators (++ and--)


These two operators are unary operators. They exists in two forms i.e. pre and post(prefix and
postfix)
i) Increment operator (++)
Increment operator is used to increment the value of its operand by 1.General form for pre
incrimination is
++ operand

and post incrimination is


operand ++

32 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

where the operand must be a variable but cannot be constant or expression.++operand is called
pre increment or prefix increment and operand++ is called post increment or postfix increment
Example: pre incrementation
int i=20;
++i;
printf(“i=%d”,i);
output: i=21
Example: post incrementation
int i=20;
i++;
printf(i=%d”,i);
output: i=21;
In the above example prefix and postfix operation results in the same output. The prefix and postfix
operations differ in the value used for the operand when it is embedded inside expressions

Decrement operator ( - - )
This operator is used to decrement the value of the operand by 1.

General form is
--operand
or
operand--

where the operand must be a variable but cannot be constant or expression.--operand is called pre
decrement or prefix decrement and operand-- is called post decrement or postfix decrement

Example: int i=10;


--i;
printf(“i=%d”,i ) ;
output: i=9

Example: int i=10;


i--;
printf(“i=%d”,i);
output: i=9;
In the above example both the prefix and postfix operations results in the same value.

Assignment Operators
There are three forms of assignment: simple assignment, multiple assignment and compound (short
hand) assignment.

i) Simple assignment
The operator used is ‘=’.
The general form is
Variable name=expression;

33 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

The value of the expression is evaluated first and is assigned to the variable. The evaluation of the
expression is right to left.
Example:
x=10 a=10 && 5
y=12.5 a=x>y
a=”A”
area=0.5*b*h.
Note:
= is the assignment operator used to assign right side expression value to the left hand side variable.
= = is comparison operator to compare the value of left hand and right hand side expression.
a=b will assign b value to a
a==b will compare the values of a and b for equality.

ii) Multiple assignment


This is used to assign the value of an expression to two or more variables.

The general form is


v1=v2=v3=expression;

The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to
left.
Example: a=b=0.
a=b=x+y
The value of x+y is assigned to b and then the value of b is assigned to a.

iii) Compound assignment


Compound assignment is a short hand notation for a simple assignment.The compound
assignment operators are
+ =, - =, * =, / =, % =.
To evaluate a compound assignment expression, first change it to a simple expression.

Compound assignment Equivalent simple expression


x+=expression x=x+expression
x-=expression x=x-expression
x*=expression x=x*expression
x/=expression x=x/expression
x%=expression x=x%expression

Example: a*=b+3 is evaluated as a=a*(b+3)


sum+=x is evaluated as sum=sum+x
a%=10 is evaluated as a=a%10.

34 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Conditional operator
The operator symbol is ?: This is also called ternary operator. The conditional operator has three
expressions.
The general form is
expression1? expression2: expresssion3

This is called conditional expression.


First, expression1 is evaluated, if the result is non-zero, the expression2 is evaluated and its value
is the final result. Otherwise, expression3 is evaluated and its value is the final result.

Example: To find the biggest of two numbers


big= (a>b)? a: b;
This is equivalent to the if –else statement
if (a>b)
big=a;
else
big=b;

BITWISE OPERATORS
• Bitwise operators perform operations at bit level. These operators include bitwise AND,
bitwise OR, bitwise XOR and shift operators.
• The bitwise AND operator (&) is a small version of the boolean AND (&&) as it performs
operation on bits instead of bytes, chars, integers, etc.
• The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
• The bitwise NOT (~), or complement, is a unary operation that performs logical negation
on each bit of the operand. By performing negation of each bit, it p roduces the ones'
complement of the given binary value.
• The bitwise XOR operator (^) performs operation on individual bits of the operands. The
result of XOR operation is shown in the table.
Bitwise AND operator &
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an
operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 10 and 12.
10= 0 0 0 0 1 0 1 0 (In Binary)
12= 0 0 0 0 1 1 0 0 (In Binary)
--------------------------
0 0 0 0 1 0 0 0 –8

35 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example #1: Bitwise AND


#include <stdio.h>
int main()
{
int a = 10, b = 12;
printf ("Output = %d", a & b);
return 0;
}

Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
Let us suppose the bitwise OR operation of two integers 10 and 12.
10 = 0 0 0 0 1 0 1 0 (In Binary)
12 = 0 0 0 0 1 1 0 0 (In Binary)
--------------------------
0 0 0 0 1 1 1 0 –14
Example #2: Bitwise AND
#include <stdio.h>
int main()
{
int a = 10, b = 12;
printf("Output = %d", a|b);
return 0;
}
Bitwise XOR (exclusive OR) operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It
is denoted by ^.
Let us suppose the bitwise XOR operation of two integers 10 and 12.
10 = 0 0 0 0 1 0 1 0 (In Binary)
12 = 0 0 0 0 1 1 0 0 (In Binary)
--------------------------
0 0 0 0 0 1 1 0 –6

36 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example #3: Bitwise AND


#include <stdio.h>
int main()
{
int a = 10, b = 12;
printf("Output = %d", a ^ b);
return 0;
}
Bitwise complement operator ~
Bitwise compliment operator is annuary operator (works on only one operand). It changes 1 to 0
and 0 to 1. It is denoted by ~.
Let us suppose the bitwise complement operation of 10.

10= 0 0 0 0 1 0 1 0 (In Binary)


--------------------------
1 1 1 1 0 1 0 1 = -245

Twist in bitwise complement operator in C Programming


The bitwise complement of 35 (~35) is -36 instead of 220, but why?
For any integer n, bitwise complement of n will be -(n+1).
To understand this, you should have the knowledge of 2's complement.
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
Bitwise complement of any number N is -(N+1).
Here's how: bitwise complement of N = ~N (represented in 2's complement form) 2'complement
of ~N= -(~(~N) +1) = -(N+1)
BITWISE SHIFT OPERATORS
In bitwise shift operations, the digits are moved, or shifted, to the left or right. The CPU registers
have a fixed number of available bits for storing numerals, so when we perform shift operations;
some bits will be "shifted out" of the register at one end, while the same number of bits are
"shifted in" from the other end.

37 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

In a left arithmetic shift, zeros are shifted in on the right.


For example;

unsigned int x = 11000101;


Then x << 2 = 00010100

If a right arithmetic shift is performed on an unsigned integer, then zeros are shifted on
the left.

unsigned int x = 11000101;


Then x >> 2 = 00110001

OPERATOR PRECEDENCE AND ASSOCIATIVITY

Precedence is used to determine the order in which different operators in a complex expression
are evaluated.
Associativity is used to determine the order in which operators with the same precedence are
evaluated in a complex expression.
The precedence and associativity of different categories operators is presented in the following
table:
Operators Associativity
1 ( ),[ ], . , -> L to R
( ++ prefix), ( -- prefix), unary +, unary -, R to L
2
& (address), *(indirection), cast, !(negation)
3 *, /, % L to R
4 +, - L to R
5 <, <=, >, >= L to R
6 = =, != L to R
7 && L to R
8 || L to R
9 ?: R to L
10 =, +=, *=, -=, /=, %= R to L
11 , (comma operator) L to R

Example: 2+3*4 is evaluated as 2+(3*4) and the result of the expression is 14

Example: 3*8/4%5*2
Here we have four operators of the same precedence (* / % *). As the associativity of arithmetic
operators is left to right. The expression 3*8/4%5*2 is evaluated as
(((3*8)/4)%5)*2 and the result of the expression is 2.

38 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example: a+=b*=c - =5
As the associativity of assignment operators is right to left, the above expression is evaluated as
(a +=(b*=(c - =5)))
Which is expanded to (a=a+(b=b*(c=c-5))).

Example: -b++
Here postfix increment has higher precedence than unary -. Thus the above expression is evaluated
as (-(b++)).
If b is 6, then the result of the expression is -6. After the expression is complete 6 becomes 7.

TYPE CONVERSION
• Type conversion and type casting of variables refers to changing a variable of one data
type into another.
• While type conversion is done implicitly, casting must be done explicitly by the
programmer. We will discuss both of them here.
• Type conversion is done when the expression has variables of different data types. So, to
evaluate the expression, the data type is promoted from lower to higher level where the
hierarchy of data types can be given as: double, float, long, int, short and char.

For example, type conversion is automatically done when we assign an integer value to
a floating-point variable.
For example,
float x;
int y = 3;
x = y;
Now, x = 3.0, This is also called as Implicit type conversion

Converting Character to Int


#include <stdio.h>
main ()
{ int number = 1;
char character = 'k'; /*ASCII value is 107 */
int sum;
sum = number + character;
printf ("Value of sum: %d\n", sum);
}
Output: Value of sum: 108

39 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

TYPE CASTING
Type casting is also known as forced conversion or explicit type conversion. It is done when the
value of a higher data type has to be converted into the value of a lower data type. For example,
we need to explicitly type cast an integer variable into a floating-point variable.
float salary = 10000.00;
int sal;
sal = (int) salary;

Typecasting can be done by placing the destination data type in parentheses followed by the
variable name that has to be converted.

40 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

CONTROL STATEMENTS
INTRODUCTION
Control Statements determine the “flow of control” in a program and enable to specify the order
in which the various instructions in a program are to be executed by the computer. Normally high
level procedural programming languages require three basic control instructions.
• Sequential control instructions
• Decision and Selection control instructions
• Repetition or Loop or Iterative control instructions
• Jumping statements
The common thing shared by all the programs written so far is that in each of the programs, all the
statements from the first statement till the last statement get executed without fail in a serial
manner. That is, one after the other. This kind of execution of statements in a program is called
Sequential Execution.
The programming circumstances require selecting some statements for execution if some condition
is satisfied; and skipping the block of statements if the condition is not satisfied, thereby, resulting
in a change in the order of execution of statements. To be precise, selection of some statements for
execution depends on whether a condition is true or false. This kind of execution of statements is
called Conditional Execution or Selection.
Suppose, if there is a need for a group of statements to be executed repeatedly until some logical
condition is satisfied, then looping is required in the program. This can be carried out using various
Loop or Repetitive or Iterative control statements.
The Jumping statements are used to exit from loop or to go to the next repetition of the loop
after skipping the remaining statements of the loop or to transfer control from one part of the
program to another part of the program unconditionally.
Decision and Selection control instructions allows a program to take different courses of action
depending on different conditions. C provides two selection structures.
• if
• switch
Repetition or loop control instruction allows a program to execute the same section of code more
than once. A section of code may either be executed a fixed number of times, or while some
condition is true. C provides three looping statements.
• while
• for
• do-while
C provides three jumping statements
• break
• continue
• goto

41 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

DECISION-MAKING AND BRANCHING (SELECTION)


i) if-statement
ii) switch-statement
if-statements
The different forms of if- Statements are
i) The simple-if statement.
ii) The if-else Statement.
iii) The Nested if- else Statement.
iv) The else-if Ladder.
The Simple if statement
It is used to execute an instruction or block of instructions only if a condition is fulfilled.
The syntax is as follows:

False
condition

if(condition)
True
statement;
statement

Next
instruction

The above flow chart reflects the logical flow of the if statement. Where condition is the expression
that is to be evaluated. If this condition is true (non-zero), statement is executed. If it is false(zero),
statement is not executed, and the program continues to the next instruction after the conditional
statement.
Example: if((a>b)&&(a>c))
printf(“a is the largest”);
If the value of the variable a is greater than the values of both b & c, then only the printf () statement
gets executed. Otherwise, the statement is skipped.
Example: if(n%2)
printf(“n is odd”);
If the value of the variable n is not divisible by 2, i.e. if the remainder after division of n by 2 is 1,
then only printf () statement gets executed. Otherwise, the statement gets skipped.

42 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

The if-else statement


If-else structure acts as a selector of one block of statements out of two blocks.
The syntax of the if-else statement is as follows:

False True
Test-
Expression
if ( test-expression)
statement 1;
True
else
statement 2; Statement2 Statement1
statement x;
StatementsX

The above flow chart reflects the logical flow of the if -else statement.
If test-expression evaluates to true, statement 1 will be executed, otherwise, statement2 will be
executed. Then the control is transferred to statement x.
The statement1 is called if-block and the statement2 flowing else is called else-block statement.
Example: if(a>b)
printf(“a is larger than b”);
else
printf(“b is larger than a”);
Here if a is greater than b the message “a is larger than b“is displayed on the screen. Otherwise,”
b is larger than a” is displayed.

The Nested if-else Statement


We know that if execution of a block of statements is conditional, we can use one if statement.
What if the conditional execution of the block of statements is itself conditional? Here, we need to
enclose one if statement within another if statement. On the similar lines, we can even enclose an
if-else within another if-else. If one if-else is enclosed within another if -else, the resulting structure
is called nested if –else.

43 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

The syntax of nested if-else is as follows.

if (test-expression 1 )
{ False True
if(test-expression 2) Test-
expr-1
{
statement-1;
}
else False True
{ Statement-3 Test-
Expression-2
statement-2;
}
}
Statement-1 Statement-2
else
{
statement -3;
}

Here, one if-else is enclosed within another if -else. The if structure, which encloses another is
called outer-if. The if structure, which is enclosed within another is called inner-if. Statement-1,
statement-2 and statement-3 may be simple or block of statements. First, test-expression1 is
checked. If it evaluates to true, test-expression2 is checked. If test-expression2 also evaluates to
true, then else-block of the inner-if, statement-1 would get executed otherwise, statement-2 would
be evaluated. If test-expression1 itself evaluates to false, then else-block of the outer-if, statement-
3 would get executed. Thus, this variation acts as a selector of one out of three blocks of statements.
Example :The following program segment compares a and b.

if(a>=b)
{
if(a>b)
printf(“a is larger than b”);
else
printf(“a and b are equal”);
}
else
printf(“a is less than b”);

44 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

The else-if Ladder


The else-if ladder helps select one out of many alternatives blocks of statements for execution depending
on the mutually exclusive conditions. The syntax of the else-if ladder is as follows.

False
if(test-expression 1) TE-1
Statement-1;
else if (test-expression2)
Statement-2; True False
else if(test-expression3) TE-2
Statement-3; Statement-1 False
….
else if (test-expression n)
Statement - TE-3
n; Statement-2
else True
Statement-n+1;
statement x
Statement-3

Statement-x

Here test-expression1, test-expression2… test-expression-n are mutually exclusive. That is only


one test-expression of all will be true. There are n+1 of statements. Initially, test-expression1 is
checked. If it is true, then statement-1 would get executed; all the other blocks of statements would
be skipped; then the statement x gets executed. If test-expression1 is false, test-expression2 is
checked. If it is true, then statements-2 would be executed; all the other statements would be
skipped. If test-expressions 2 is false, test-expression3 is checked. If it is true, statements-3 would
get executed; all the other statements would be skipped. This is continued. In general, i th test-
expressions is checked only when the first i-1 test-expressions evaluate to false. If none of the
expressions is found to be true, the last statement would get executed. Thus, else -if ladder act as a
selector of one out of n+1 blocks of statement.

Program To find whether a number is positive, negative or 0.


void main()
{
int n;
printf (“Enter a number\n’); Input-Output
scanf (“%d”,&n);
if(n>0) Enter a number
printf (“%d is positive”,n); 78
else if (n<0)
printf (“%d is negative”,n); 78 is positive number.
else
printf (“Zero”);
getch();
}

45 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

The Switch Statement


Switch statements provide a non-iterative choice between any numbers of paths based on
specified conditions. They compare an expression to a set of constant values. Selected statements
are then executed depending on which value, if any, matches the expression. Switch statements
have the form
Here, expression is an integer or character expression. It evaluates to either integer or a
character.Value1, value 2…. Value N is the case values. The expression of the switch statement
can take any of the values. If it matches with value1, statement-1 will get executed and the break
statement following it causes the skipping of the switch structure. If the expression matches with
value2, then statement2 will get executed and so on. If the value of expression matches with none
of the case values then default option will get executed.

switch ( expression) Expression


{
case value1:statement-1;

break; Case Value 1 Statement-1


case value2:statement -2;

Case Value 2 Statement-2


break;
.
. Case Value 3 Statement-3
case value n:statement -n;
…… ……
break;
default :default statement; Case Value n Statement-n
break;
}
Default Default statement

Points to Remember:
i) The case values should not be float values or Boolean expression.
ii) The case values value1,value2,… value n should be distinct.
iii) The order of their presence is immaterial.
iv) default case is optional.
Example:
scanf (“%d”,&n);
switch (n)
{
case 1:printf (“one”);
break;
case 2:printf (“two”);
break;
default : printf (“Other than one or two \n”);
}

46 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

If the value of n is 1, then the string “one” is displayed. If the value of n is 2,then the string “two”
is displayed.
Looping or Iterative or Repetitive Statements in C
The repetition of execution of a block of statements as long as some condition is true is called
Looping. Looping is also called as Iteration.
There are three kinds of iterative statements.
i) while-loop
ii) for-loop
iii) do-while loop
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to
be executed multiple times depending upon a given Boolean condition. It can be viewed as a
repeating if statement. The while loop is mostly used in the case where the number of iterations is
not known in advance.
Properties of while loop
• A conditional expression is used to check the condition. The statements defined inside
the while loop will repeatedly execute until the given condition fails.
• The condition will be true if it returns 0. The condition will be false if it returns any
non-zero number.
• In while loop, the condition expression is compulsory.
• Running a while loop without a body is possible.
• We can have more than one conditional expression in while loop.
• If the loop body contains only one statement, then the braces are optional.
Explanation of While loop syntax and flow chart
Syntax of while loop in C language:
The syntax of while loop in c language is given below:
while(condition){
//code to be executed
}

47 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Flowchart:

Example : i=1;
sum =0;
while (i<=10)
{
sum+=i;
i++;
}
The purpose of the code is to find the sum of the first 10 natural numbers

Example :
while ((ch=getchar())!=’\n’)
{
printf (“%c\n”,toupper(ch));
}
The segment code enables us to accept characters of a line, one at a time till the new line character
is entered. Each character entered is converted to upper case and displayed.
do-while Loop
• do-while loops are exactly like while loops, except that the test is
performed at the end of the loop rather than the beginning.
• This guarantees that the loop will be performed at least once, which is
useful for checking user input among other things ( see example below. )
Syntax:
do {
body;
} while (condition);
In theory the body can be either a single statement or a block of statements within
{curly braces}, but in practice the curly braces are used with control structures like
do-whiles.
48 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Example : i=1;
sum=0;
do
{
sum+=i;
i++;
}while ( i<= 10);
The statements in the body of the loop get repeatedly executed as long as i< =10 and it finds the
sum of the first 10 natural numbers.
Example: do
{
scanf(“%d”, &n);
printf(“Do you want to continue? Enter Y or N”);
ch = getchar();
} while ( ch ==’Y’);

The above segment of code enables us to keep accepting integer value into the variable n as long
as we enter ‘Y’ to the variable ch. Once we input ‘n’ response to the statement ch = getchar (); the
loop is exited.
For loop
For loop is an entry controlled looping statement. It is used to repeat set of statements
until some condition is met. Looping statements whose condition is checked prior to
the execution of its body is called as Entry controlled loop.

49 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Syntax of for loop


for (variable-initialization; condition; variable-update)
{
// Body of for loop
}

Parts of for loop


Any repetition contains two important part- What to repeat and number of repetitions?
Variable- initialization, condition, and variable-update –defines number of repetitions
and
body of loop defines what to repeat.
o Variable-Initialization: Contains loop counter variable initialization
statements. It defines starting point of the repetition (where to start loop).
o Condition: Contains Boolean expressions and works like if …else. If
Boolean expression is true, and then execute body of loop otherwise
terminate the loop.
o Body of loop: specify what to repeat. It contains set of statements to repeat.
o Variable-update: contains loop counter update (increment/decrement)
statements.

Important note: All four parts of a for loop is optional. Hence you can write a for
loop without initialization, condition, update or body. However, you must follow
the syntax and specify semicolons.
Working of for loop
1. Initially variable-initialization block receives program control. It is non-
repeatable part and executed only once throughout the execution of for loop.
After initialization program control is transferred to loop condition.
2. The loop condition block evaluates all Boolean expression and determines
loop should continue or not. If loop conditions are met, then it transfers
program control to body of loop otherwise terminate the loop. In C we specify
a Boolean expression using relational and logical operator.
3. Body of loop executes a set of statements. After executing all statements, it
transfer program control to variable-update block.
4. Variable-update block updates loop counter variable and transfer program control
again back to condition block of loop.
5. Step 2 to 4 is repeated until condition is met.

50 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

Flowchart of for loop

Example: for (j=1;j<=10;j++)


printf(“%d\n”,j);
here the for loop prints the first 10 natural numbers.
Program to find largest of n numbers
#include<stdio.h>
void main()
{
int n,i;
float x,large;
printf ( “Enter the number of values “); Input-output:
scanf(“%d”,&n); Enter the number of values 6
printf(“Enter the first number”); Enter the first number 10
scanf(“%f”,&x); Enter the reaming numbers
large=x; -3
printf(“Enter the reaming numbers”); 23
for ( i=1; i <n; ++i) 78
{ -220
5
scanf(“%f”,&x);
Largest of given numbers=78
if(x>large)
large=x;
}
printf(“Largest of given numbers =%f \n”,large);
getch();
}

51 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

JUMP STATEMENTS
Jump statements transfer control unconditionally from one part of the program to another part of
the program.The Jump statements are
i) goto identifier
ii) continue
iii) break
goto statement
So far we have discussed ways of controlling the flow of execution based on certain
specified conditions. Like many other languages, C supports goto statement to branch
unconditionally from one point to another in the program. Although it may not be essential to use
goto statement in a highly structured language like C, there may be occasions where the use of
goto might be desirable.
The goto require 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 immedia tely
before the statement where the control is to be transferred. The general forms of goto and label
statements are shown below.

goto label; label :

-- - - -- statement;

-- - - -- -- - - --

-- - - -- -- - - --

-- - - -- -- - - --

label : goto label ;


Forward jump Backward jump
statement;

The label can be anywhere in the program either before or after the goto label; statement. During
running of a program when a statement like
goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:. This
happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the label: is before the
statement go to label; a loop will be formed and some statements will be executed repeatedly.
Such a jump is known as a backward jump. On the other hand, if the label: is placed after the go
to label; some statements will be skipped and the jump is known as forward jump.

52 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

A goto is often used at the end of a program to direct the control to go to the input statement, to
read further data.
Example: double x, y;
read :
scanf(“%d”, &x);
if (x<0)
goto read;
y=sqrt(x);
printf(“%f %f”, x,y);
goto read;
The above example evaluates the square root of a series of numbers read from the terminal. The
program uses two goto statements, one at the end, after printing the results to transfer the control
back to the input statement and other to skip any further computation when the number is negative.
Due to the unconditional goto statement at the end, the control is always transferred b ack to the
input statement. In fact, this program puts the computer in a permanent loop known as an infinite
loop. The computer goes round and round until we take some special steps to terminate the loop-
such infinite loops should be avoided.
Break Statement
Sometimes, it is required to jump out of a loop irrespective of the conditional test value.
Break statement is used inside any loop to allow the control jump to the immediate statement
following the loop. The syntax is as follows:
When nested loops are used, thenbreak;
break jumps the control from the loop where it has been used.
Break statement can be used inside any loop i.e., while, do-while, for and also in switch statement.
Let us consider a program to illustrate break statement.
Program to calculate the first smallest non-trivial divisor of a number.
#include<stdio.h>
void main ( ) Input-output:
{ Enter any number:
int div, nun, i; 9
printf (“Enter any number”); Smallest divisor for the
scanf (“%d”, &nun); number 9 is 3
for (i=2; i<=nun; ++i)
{
if (nun%i) = = 0)
{
printf (“smallest divisor for the number %d is %d”, nun, i);
break;
}
}
}
In the above program, we divide the input number with the integer starting from 2 on wards and
print the smallest divisor as soon as remainder comes out to be zero. Since we are only interested

53 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming

in first smallest divisor and not all divisors of a given number, control is exected from the loop as
soon as num%i is 0 using break statement without going further for the next iteration of for loop.
Continue statement
Unlike break statement, which is used to jump the control out of the loop, it is sometimes
required to skip some part of the loop and to continue the execution with next loop iteration.
Continue statement used inside the loop helps to bypass the section of a loop and passes the control
to the beginning of the loop to continue the execution with the next loop iteration. The syntax is
as follows:
continue;

Let us see the Program 3.11 given below to know the working of the continue statement.
Program to print first 20 natural numbers skipping the numbers divisible by 5.
#include<stdio.h>
void main ( )
{
int i ;
for( i=1; i<=20; i++)
{ Output:
if(i%5)= = 0) 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19
continue;
printf(“%d”,i);
}
}
Here, the printf statement is by passed each time when value stored in i is divisible by 5. Hence all
integers from 1 to 20 not divisible by 5 are displayed.

54 | P a g e Phaneendra Kanakamedala

You might also like