PPSC Notes Unit I
PPSC Notes Unit I
PPSC Notes Unit I
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.
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.
COMPUTER
SYSTEM
COMPUTER HARDWARE COMPUTER 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.
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.
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
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.
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.
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.
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.
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
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
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.
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.
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
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.
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
start
Read A B C
No No
print C print A
print B print c
stop
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
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
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
19 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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.
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.
• 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
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
Size and range of values of integer data types for 16 bit machine
23 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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” “! ---? +”.
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
24 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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.
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.
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;
26 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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!”);
28 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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.
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
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.
v) When both operands are floating point type the expression is called floating point type
expression.
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) + , -
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.
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
! (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
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.
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”);
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
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.
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.
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
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
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
37 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
If a right arithmetic shift is performed on an unsigned integer, then zeros are shifted on
the left.
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: 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
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
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
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.
43 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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
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
45 | P a g e Phaneendra Kanakamedala
Programming for Problem Solving using C - 20CS01
UNIT-I: - Introduction to Problem solving through C-Programming
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
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
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.
-- - - -- 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