Unit-1 Intro To Prog (AK23)
Unit-1 Intro To Prog (AK23)
ON
INTRODUCTION TO PROGRAMMING
(Common to All Branches of Engineering)
2023 – 2024
B.Tech I-Year I-Semester
(Autonomous-AK23)
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
INTRODUCTION TO PROGRAMMING
(Common to All Branches of Engineering)
UNIT 1
Introduction to Programming and Problem Solving
History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter,
Introduction to Programming Languages, Basics of a Computer Program-Algorithms, flowcharts (using Dia
Tool), pseudo code. Introduction to compilation and Execution, Primitive Data Types, Variables and
Constants, Basic Input and Output, Operations, Type conversion and Casting.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies:
Top-down approach, Bottom-up approach, Time and space complexities of algorithms.
1. Abacus:
* It was a wooden rack which has metal rods with beads mounted on them. 1. Abacus
* The beads were moved by the abacus operator according to some rules to
perform arithmetic calculations.
* Abacus is still used in some countries like China, Russia and Japan.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 2
5. Babbage’s Difference Engine :
* Charles Babbage developed a machine called difference engine In early
1820s.
* These machines calculate logarithmic tables to a high degree of precision.
8. Mark-1 :
* Howard Aiken contracted an electro mechanical computer named mark-1
In the year 1944.
* It could multiply two 10-digit number in 5-seconds.
* It was also the first programmable digital computer marking a new era in
the computer world.
9. ENIAC :
* Electronic Numerical Integrator and Calculator were built by Prof. Eckerit
and Mauchly. 7. Tabulating (or) Hollerith’s Machine
* It used about 19000 vacuum tubes and can perform about 300
multiplications per second.
10. EDSAC :
* Electronic Delay Storage Automatic Computer was developed by Maurice
willies.
* It has ability to input, output, staring the data.
* It also able to perform and control arithmetic calculations. 8. Mark-1
11. EDVAC :
* Electronic Discrete Variable Automatic Computer was developed by Prof.
Eckerit and Mauchly.
* In this both the data and instruction can be stored in binary form instead
of decimal number system.
12. UNIVAC :
* Universal Automatic Computer developed by Remington.
* It was cable of performing to access both numeric and alphabetic 9. ENIAC (Electronic Numerical
Integrator And Computer)
information.
13. UNIVAC-1:
* It is the first computer which is used for commercial purpose in 1954.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
Generations of Computers: .
Evolution of Modern Computers from the olden days is known as “Generation of Computers.”
Generations of computers are broadly classified based on the following characteristics:
* Increasing in storage capacity.
* Increasing in processing speed.
* Increasing reliability.
There are totally 5 generations of computers till today. They are,
* During this period magnetic storage devices have been started their development. Because of this,
speed and storage capacity has been increased.
* They are capable to perform 20,000 to 50,000 additions per second.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
* Intel Corporation invented the microprocessor in the year 1980 with this development the cost of
a computer has reduced a lot.
* The floppy disk technology was developed during this generation.
Input Unit:
Computers need to receive data and instructions in order to solve any problem.
• The input unit consists of one or more input devices like keyboard, mouse, joystick etc.
• Regardless of the type of the input device used in a computer system, all input devices perform the
following functions.
o Accept the data
o Convert data to computer understandable form.
o Supply converted data for further processing.
CPU:
The actual processing of the data is carried out in the Central Processing Unit (CPU), which is the brain
of computer. The CPU stores the data and instructions in the primary memory of the computer, called the
Random Access Memory (RAM) and processes them from this location.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
• CPU stands for “Central Processing Unit.”
• CPU is like a computer Brain. It performs the following operations.
o It performs all calculations.
o It takes all decisions.
o It controls all units of computer.
• Control unit, Memory unit and Arithmetic logic unit of the computers are together known as central
processing unit.
The Control Unit (CU) and the Arithmetic Logic Unit (ALU) are the two subcomponents of the CPU.
The ALU carries out the arithmetic and logical operations while the CU retrieves the information from the
storage unit and interprets this information. The CPU also consists of circuitry devices called cache and
registers.
Control Unit:
• The control unit controls all other units in the computer.
• The control unit instructs the input unit where to store data after receiving it from the user.
• It also controls the flow of data and instructions from the memory unit to “ALU”.
• It controls the flow of results from ALU to output unit.
Program Counter:
A program counter is a register in a
computer processor that contains the
address (location) of the instruction being
executed at the current time.
As each instruction gets fetched,
the program counter increases its stored
value by 1.
Memory Unit:
• Memory Unit of the computer holds data and instructions that we enter through the input unit.
• It is also used to preserve intermediate and final results before they are sent to the output unit.
• It is used to preserve the data for later usage.
• The various storage devices used for storage can be classified in to a categories namely,
o Primary Memory
o Secondary Memory
• Primary memory stores and provides information very fast but it loses the contents when we switch
off the computer.
• Secondary memory stores the data permanently. The program that we want to run on the computer
is first transferred to the primary memory from secondary.
Output Unit:
• The output unit of a computer provides information and results of an operation to the outside world.
• The output unit also converts Binary data to a form that uses can understand.
• The commonly used to output devices are Monitors, Printers, and Plotters.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
Introduction to Programming Languages: .
A programming language is a set of symbols, grammars and rules with the help of which one is able
to translate algorithms to programs that will be executed by the computer. The programmer communicates
with a machine using programming languages.
Program & Programming
• A program is a set of logically related instructions that is arranged in a sequence that directs the computer
in solving a problem.
• The process of writing a program is called programming.
• Software is a collection of computer programs and related data that provides the instructions for telling a
computer what to do and how to do it.
• Computer software broadly classified into two categories: a) System software and b) Application software
a) System Software:
• System software is a collection of programs that interfaces with the hardware.
• Categories of system software:
(or)
b) Application Software:
• Application software is written to enable the computer to solve a specific data processing task.
• Categories of application software:
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 7
Programming Language:
• A programming language is composed of a set of instructions in a language understandable to the
programmer and recognizable by a computer.
• Programming languages can be classified as,
(a) High-level language - BASIC, COBOL & FORTRAN (application programs)
(b) Middle level language - C (application & system programs)
(c) Low level language - assembly language (system programs)
• System programming language:
– It is designed to make the computer easier to use.
– For ex.: OS which control many other programs that control i/o devices, multiple tasks.
• Application programming language:
– It is designed for specific computer application such as payroll, inventory etc.
– Its 2 sub categories are:
• Business program
• Scientific Program
COMPILER:
• For executing a program written in a high-level language, it must be first translated into a form the
machine can understand. This is done by a software called the compiler.
• The compiling process consists of two steps:
a) The analysis of the source program
b) Check for syntax error
• Compiler action:
INTERPRETER:
• During the process of translation There is another type of software that also does translation. This
is called an interpreter.
• Differences between compiler and interpreter:
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
Third, Forth & Fifth Generation Languages:
* The 3GLs are procedural in nature i.e., these languages specify “how to do”. Hence 3GLs require
the knowledge of complete steps to solve a problem.
* In case of 4GLs, they are non-procedural i.e., they specify “what to do”. Hence in 4GLs we need to
specify only what we required and rest gets done on its own
Advantages:
* Smaller code
* Reduced development time and maintenance cost
* Easy to programmers
* Doesn’t require a high knowledge on program GUI Based Languages
* With the invention of GUI based interfaces, many programming languages are developed
that help programmer to develop GUI applications.
* Some of the GUI based languages are,
* Visual Basic (VB)
* C#
* VB.Net
Classification of Programming Languages:
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
Basics of a Computer Program: .
Computer Programming is a set of instructions, that helps the developer to perform certain tasks that
return the desired output for the given valid inputs.
A computer is a machine that processes information and this information can be any data that is
provided by the user through devices such as keyboards, mice, scanners, digital cameras, joysticks, and
microphones. These devices are called Input Devices and the information provided is called input.
The computer requires storage to store this information and the storage is called Memory. Computer
Storage or Memory is of Two Types. (i) Primary Memory or RAM (Random Access Memory): This is the
internal storage that is used in the computers and is located on the motherboard. RAM can be accessed or
modified quickly in any order or randomly. The information that is stored in RAM is lost when the computer
is turned off called as Volatile. (ii) Secondary Memory or ROM (Read-Only Memory): Information (data)
stored in ROM is read-only, and is stored permanently called as Non-Volatile. The ROM stored instruction is
required to start a computer.
Processing: Operations done on this information (input data) is called Processing. The Processing of
input is done in the Central Processing Unit which is popularly known as CPU.
Output Devices: These are the computer hardware devices that help in converting information into
human-readable form. Some of the output devices include Visual Display Units (VDU) such as a Monitor,
Printer, Graphics Output devices, Plotters, Speakers, etc.
Developers should have essential knowledge on the following concepts to become skilled in
Computer Programming,
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
Algorithms:
Definition:
An algorithm is defined as a finite set of steps that provide a chain of actions for solving a problem.
(or) An algorithm is a sequence of instructions that are carried out in a predetermined sequence in order to
solve a problem. (or) A step-by-step procedure used to solve a problem is called Algorithm. (or) An algorithm
(pronounced AL-go-rith-um) is a procedure or formula for solving a problem, based on conducting a sequence
of specified actions.
Analyzing an Algorithm:
When one writes an algorithm, it is essential to know how to analyses the algorithm.
• Analyzing the algorithm refers to calculating the resources such as computer memory, processing
time, logic gates and so on …..
• Time is most important resource because the program developed should be faster in processing.
• The analysis can also be made by reading the algorithm for logical accuracy, tracing the algorithm and
checking with the data.
Categories of Algorithm:
The steps in an algorithm can be divided into three categories, namely
• Sequence
• Selection and
• Iteration
Sequence
• The steps described in an algorithm are performed successively one by one without skipping any step.
• The sequence of steps defined in an algorithm should be simple and easy to understand.
Selection
• We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
• The selection of statements can be shown as follows,
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
if(condition)
Statement-1;
else
Statement-2;
• The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed.
• In case the operation is unsuccessful. Then sequence of algorithm should be changed / corrected in
such a way that the system will re-execute until the operation is successful.
Iteration
• In a program, sometimes it is very necessary to perform the same action for a number of times.
• If the same statement is written repetitively, it will increase the program code.
• To avoid this problem, iteration mechanism is applied.
• The statement written in an iteration block is executed for a given number of times based on certain
condition.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
Flowcharts (using Dia Tool):
A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we use
pictorial representation for every step.
Definition:
Flowchart is a diagrammatic or pictorial representation of various steps involved in the Algorithm.
A complete flowchart enables us to organize the problem into a plan of actions i.e. it specifies what
comes first, second, third, . . . .
* Flowchart also represents the flow of data.
* It is an easy way to solve the complex problems because it makes the reader to flow the process
quickly from the flowchart incited of going through text.
* A flowchart is a set of symbols that indicates various operations in a program.
* For every process there is a corresponding symbol in the flowchart.
* Once the algorithm is written, its pictorial representation can be done using flowchart symbol.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 14
• Problem 4: Draw a flowchart to swap two numbers.
Pseudo Code:
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is intended
for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation (code) in a high-level
language.
Algorithm and Pseudocode are the two related terms in computer programming. The basic difference
between algorithm and pseudocode is that an algorithm is a step-by-step procedure developed to solve a
problem, while a pseudocode is a technique of developing an algorithm.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 15
Difference between Algorithm and Pseudocode:
Algorithm Pseudocode
An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of an
problem in form of a well-defined step-based form. algorithm in code-like structure using English text.
An algorithm only uses simple English words It uses reserved keywords like if-else, for, while, etc.
These are a sequence of steps of a solution to a These are fake codes as the word pseudo means
problem fake, using code like structure and plain English text
There are no rules to writing algorithms There are certain rules for writing pseudocode
Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm
It is difficult to understand and interpret It is easy to understand and interpret
Example 1:
To implement a simple program that calculates the average of three numbers using pseudo code in C:
Pseudo code:
1. Start
2. Input three numbers
3. Calculate the sum of the three numbers
4. Divide the sum by 3 to get the average
5. Display the average
6. End
7.
Example 2:
To find the Factorial value of the given number using pseudo code in C:
Algorithm to find Factorial of n: Pseudocode to Factorial of n: C program to find Factorial of n:
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 16
INTRODUCTION TO COMPILATION AND EXECUTION: .
Compilation process in C is also known as the process of converting Human Understandable Code (C
Program) into a Machine Understandable Code (Binary Code). Compilation process in C involves four steps:
pre-processing, compiling, assembling, and linking.
• The preprocessor tool helps in comments removal, macros expansion, file inclusion, and conditional
compilation. These commands are executed in the first step of the compilation process.
• Compiler software helps boost the program's performance and translates the intermediate file to an
assembly file.
• Assembler helps convert the assembly file into an object file containing machine-level code.
• Linker is used for linking the library file with the object file. It is the final step in compilation to
generate an executable file.
The compiling process consists of two steps: i) The analysis of the source program and ii) The synthesis
of the object program in the machine language of the specified machine.
• The analysis phase uses the precise description of the source programming language.
• A source language is described using a) lexical rules, b) syntax rules, and () semantic rules.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 17
Linker:
• Linking resolves symbolic references between object programs.
• It makes object programs known to each other.
• Linking makes the addresses of programs known to each other so that transfer of control from one
subprogram to another or a main program takes place during execution.
• In FORTRAN / COBOL, all program units are translated separately.
Relocation:
• Relocation is more than simply moving a program from one area to another in the main memory.
• Relocation means adjustment of all address-dependent locations, such as address constant,
correspond to the allocated space, which means simple modification of the object program so that
it can be loaded at an address different from the location originally specified.
Loader:
• Loading means physically placing the machine instructions and data into main memory, also known
as primary storage area.
a. Assignment of load-time storage area to the program
b. Loading of program into assigned area
c. Relocation of program to execute properly from its load time storage area
d. Linking of programs with one another
Program Execution:
• When a program is compiled and linked, each instruction and each item of data is assigned an
address.
• At execution time, the CPU finds instructions and data from these addresses.
• The program counter, is a CPU register that holds the address of the next instruction to be executed
in a program.
The CPU has random access capability to any and all words of the memory, no matter what their
addresses
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 18
PRIMITIVE DATA TYPES: .
Data Types:
Note:
• Float is a single precision value. ( After decimal 7 digits has been considered )
• Double is a double precision value. ( After decimal 14 digits has been Considered )
• In-Built data Types are supported by “C” compiler by default.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 19
1. Character (Denoted as "char" in C programming language)
Description: A character denotes any alphabet, digit or special symbol used to represent in formation and
it is used to store a single character.
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.
5. void:
Description: It is a special data type used for,
• To specify that a function doesn’t returns any value.
• To specify a function takes no arguments.
• To create generic pointers.
Eg: 1. void print (void)
1. void *ptr
VARIABLES:
Variable Names:
• A variable is an identifier that is used to store data elements.
• The data may be numerical quantity (or) a character constant.
• The data item must be assigned a value to the variable at some point in the program. Then data item
can be accessed by referring to the variable name.
• In other words, a variable is an identifier which changes its value during the execution of the program.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 20
Declaration of a Variable:
• Any variable which is used in the program should be declared first.
• A declaration of a variable specifies two things:
o It tells the compiler about the name of the variable.
o It specifies about the type of data that a variable can hold.
• The above declaration results in declaring the variables a, b, c as integer data type.
CONSTANTS:
Constants and its types:
• These are fixed values that will not change during the execution of program.
• There are 4 basic types of constants in ‘C’. They are
Integer Constant:
An integer constant is an integer valued number. Rules for Constructing Integer Constant:
• It shouldn’t have a decimal point.
• An integer constant must have at least one digit.
• Commas, Blank spaces, special characters can’t be included with in the constants.
• The constant can be preceded by a minus sign if desired.
• The range of integer constants is -32,768 to 32,767
Decimal Numbers:
o A Decimal integer constant can consist of any combinations of digits taken from the set 0-9.
o If the constant contains 2 (or) more digits, the first digit must be something other than zero.
Eg: 0, 1, 723, 32156
Octal Constants:
o An Octal integer constant can consist of any combination of digits taken from the set 0-7.
o The first digit must be zero in order to identify the constant as an octal number.
Eg: 0, 01, 0723.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 21
Hexa Decimal Numbers:
o A Hexa Decimal integer constant must begin with either 0x, (or) 0x.
o It can consist of the digits taken from the set 0-9, and a-f {upper case / lower case}.
o The letters a-f, represent the quantities 10-15 respectively.
Eg: 0x, 0x, 0x7.
Scientific Notation:
o When we want to represent very large values (or) very small values, instead of representing
the value of sequence of digits we can represent a floating-point constant value in a scientific
notation as follows,
Mantissa E (or) e exponent.
Eg: 1.2E + 3 => 1.2 * (10^3)
o Note that if no sign is represented after ‘E’ it will be treated as positive.
o Floating point constants are identified by appending the letter F {either upper case (or) lower
case} to the end of the constants.
Eg: 3E5F = 300000F.
Character Constants:
o A character constant is a single character enclosed in single quotation marks. The Max length
of character constant is “one”. The single character can be either alphabet (or) Digit (or) a
special symbol.
o Eg: ‘a’, ‘1’, ‘?’
Note: Most computers make use of the “ASCII” { American Standard Code for Information
Interchange }, character set, in which each individual character is numerically encoded.
o ASCII code is a 7-bit code. ASCII values ranges from 0-127.
String Constants:
o A string constant is an array of characters that has a fixed value enclosed within double
quotation marks ( “ “ ).
o String constant is a sequence of characters enclosed within a pair of double quotes.
o For example, “DataFlair”, “Hello world!”
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 22
BASIC INPUT AND OUTPUT: .
C language has standard libraries that allow input and output in a program. The stdio.h or standard
input output library in C that has methods for input and output.
Formated Input:
scanf()
The scanf() method, in C, reads the value from the console as per the type specified.
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of this
variable, stored at this address in the memory.
Formated Output:
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of this
variable, stored at this address in the memory.
The basic type in C includes types like int, float, char, double. Inorder to input or output the specific
type, the X in the above syntax is changed with the specific format specifier of that type.
#include <stdio.h>
int main()
{
int num; // Declare the variables
char ch;
float frac;
printf("Enter the integer: "); // Integer – i/o
scanf("%d", &num);
printf("\n Entered integer is: %d", num);
return 0;
}
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 23
Output:
Enter the integer: 10
Entered integer is: 10
OPERATORS: .
i) Arithmetic Operators:
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c;
Output:
printf(“ Enter a, b values: ”); Enter a, b values:
scanf(“%d%d”, &a, &b); sum=
sub=
c = a + b; mul=
printf(“sum= %d \n”, c); div=
mod=
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 24
ii) Relational Oprators:
• Relational Operators are used to perform comparison between two values.
• These operators‟ returns true (1) if the comparison condition is true otherwise false (0).
• The operators used for comparison in ‘C’ are listed below,
Operator Description or Action Expression Example
< less than a<b 5 < 10
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Example 1:
35 < 5 - false (0)
10 <= 10 - true (1)
45 > 5 -
11 >= 5 -
35 == 10 -
35 != 10 -
(10+5) == (5*3) - true (1)
Example 2: Write a program to use various relational operators and display their return values?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\n Condition \t : Return values \n ");
printf("\n 10 != 10 \t : %5d", 10 != 10);
getch();
}
Output:
10 != 10 : 0
10 == 10 :
10 >= 10 :
10 > 5 :
10 <= 100 :
10 < 9 : 0
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 25
iii) Logical Oprators:
• To take a decision based on 2 (or) more conditions then use logical operators.
• There are three logical operators available in ‘C’
Operator Purpose Expression Example
&& Logical AND if(a<b) && (a<c) - false(0) a=5; b=10; c=3
|| Logical OR if(a<b) || (a<c) - a=5; b=10; c=3
! Logical NOT if(a != b) - a=5; b=10; c=3
Truth Table
A B A && B A B A || B A !A
F F F F F F F T
F T F F T T T F
T F F T F T
T T T T T T
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 26
v) Bitwise Operators:
• Bitwise operators are one of the salient features of ‘C’ language.
• These are specially designed to manipulate the data at Bit level.
• The Bitwise operators are not applicable for float (or) Double data type.
• The following are the some of the Bit wise operators available in ‘C’ language.
Operator Meaning .
& Bitwise Logical AND
| Bitwise Logical OR
^ Bitwise Logical XOR
<< Left Shift
>> Right Shift
~ Bitwise Compliment [ 2's Complement = Bitwise 1’s Compliment number + 1 ]
vi) Assignment Operators:
• This operator is used to assign a constant value (or) the result of an expression to a variable.
• In this operation Right hand side expression is evaluated first and then the result is assigned to left
hand side variable.
•
Operator Meaning .
= - Assign Right Hand value to LHS value
+= - Value of LHS add to value of RHS and assign it back to the variable in LHS
Eg: a += 2; which means, a = a + 2;
-= - Value of RHS variable will be subtracted from the value of LHS and assign it back to
the variable in LHS. Eg: a -= 2; which means, a = a – 2;
*= - Value of LHS variable will be multiplied to the value of RHS and Assign it back to the
variable in LHS. Eg: a *= 2; which means, a = a * 2;
/= - Value of LHS variable will be divided by the value of RHS and Assign it back to the
variable in LHS. Eg: a /= 2; which means, a = a * 2;
%= - The Remainder will be stored back to the LHS after integer, division Is carried out
between the LHS variable and RHS variable. Eg: a %= 2 which means, a = a % 2.
Example:
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d\n", c); // c is 5
c += a;
printf("c = %d\n", c); // c is 10
c -= a;
printf("c = %d\n", c); // c is 5
c *= a;
printf("c = %d\n", c); // c is 25
c /= a;
printf("c = %d\n", c); // c is 5
c %= a;
printf("c = %d\n", c); // c = 0
return 0;
}
Output:
c=5 c = 10 c=5 c = 25 c=5 c=0
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 27
Expressions:
An expression is a combination of operators and operands which reduces to a single value. An
operator indicates an operation to be performed on data that yields a value. An operand is a data item on
which an operation is performed.
A simple expression contains only one operator for example 3+5 is a simple expression which yields
a value 8, -a is also a single expression. A complex expression contains more than one operator. An example
of complex expression is 6+2*7.
An expression can be divided into six categories based on the number of operators, positions of the
operands and operators, and the precedence of operator.
Primary Expressions:
In C, the operand in the primary expression can be a Name, a Constant, or a Parenthesized Expression.
Name is any identifier for a variable. A constant is the one whose value cannot be changed during program
execution. Any value enclosed within parenthesis must be reduced to single value. A complex Expression can
be converted into primary expression by enclosing it with parenthesis.
The following is an example,
( 3 * 5 + 8 ); ( c = a = 5 * c );
Postfix Expressions
The postfix expression consists of one operand and one operator. Example: A Function Call, The
function name is operand and parenthesis is the operator.
The other examples are post increment and post decrement. In post increment the variable is
increased by 1, a++ results in the variable increment by 1.
Similarly in post decrement, the variable is decreased by 1, a-- results in the variable decreased by 1.
Prefix Expressions
Prefix Expressions consists of one operand and one operator, the operand comes after the operator.
Examples of prefix expressions are prefix increment and prefix decrement i.e., ++a, --a.
The only difference between postfix and prefix operators is, in the prefix operator, the effect take
place before the expression that contains operators is evaluated. It is other way in case of postfix expressions.
Unary Expressions
A unary expression is like a prefix expression consists of one operand and one operator and the
operand comes after the operator.
Example: +a; -b; -c; +d;
Binary Expressions
Binary Expressions are the combinations of two operands and an operator. Any two variables added,
subtracted, multiplied or divided is a binary expression.
Example: a + b; c * d;
Ternary Expressions
Ternary Expressions is an expression which consists of a ternary operator pair “ ? : ” In the example, if exp1
is true exp2 is executed else exp3 is executed.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 28
Example 1:
#include <stdio.h>
int main()
{
int n1 = 5, n2 = 10, max;
max = (n1 > n2) ? n1 : n2;
printf("Largest number between %d and %d is: %d. ", n1, n2, max);
return 0;
}
Output: Largest number between 5 and 10 is: 10.
Example 2:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
Output: Enter your age: 12
You cannot vote
Example 3:
#include <stdio.h>
int main()
{
char operator = '+';
int num1 = 8;
int num2 = 7;
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("%d", result);
return 0;
}
Output: 15
• Every operator has a precedence value. An expression containing more than one operator is known
as a complex expression.
• Complex expressions are executed according to precedence of operators.
• Associativity specifies the order in which the operators are evaluated with the same precedence in a
complex expression.
• Associativity is of two ways i.e., left-to-right and right-to-left.
• Left-to-right associativity evaluates an expression stating from left and moving towards right.
• Right-to-left associativity proceeds from right to left.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 29
The precedence and associativity of various operators in C are as shown in the following table,
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 30
TYPE CONVERSION AND CASTING: .
Type Conversion:
• In some situations, some variables are declared as integers and while performing an operation on
these variables we require the result as floating point type. In such situations we use type
conversion.
• The type conversion is used to convert the set of declared data types to some other required types.
Conversion can be carried out in 2 ways,
o Converting by using assignment (Implicit casting).
o Using cast operator (Explicit casting).
Converting by Assignment:
• The usual way of converting a value from one data type to another is by using the assignment
operator.
int a;
float b;
a=b;
• In this method, if a larger data type value is assigned to smaller data type then the value will be
truncated {cut off}. This method is called “Narrowing”.
Cast Operator:
• The cast operator is a technique to forcefully to convert one data type to another.
• The operator used to force this conversion is known as “Cast Operator” and the process is known as
type casting.
Syntax: x= (cast) expression Example of Cast Operator:
(or) #include <stdio.h>
X= cast (expression) int main()
{
Eg: int a, b; int sum= 17, count = 5;
float f; float mean;
f= (float) a/b; mean = (float) sum / count;
(or) printf("Value of mean : %f\n", mean );
f= float (a)/b; }
O/p: Value of mean : 3.400000
Explanation: The cast operator has precedence over division, so the value of sum is first converted to float
data type and finally it gets divided by count yielding a float value.
gets only integer output: wrong gets float output: but wrong gets float output w/o CAST: Correct
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() int main() int main()
{ { {
int sum = 17, count = 5; int sum = 17, count = 5; float sum= 17; int count = 5;
int mean; float mean; float mean;
mean = sum / count; mean = sum / count; mean = sum / count;
printf("Value of mean : %d\n", mean ); printf("Value of mean : %f\n", mean ); printf("Value of mean : %f\n", mean );
} } }
O/p: O/p: O/p:
Value of mean : 3 Value of mean : 3.000000 Value of mean : 3.400000
The actual output needed is 3.400000, The actual output needed is 3.400000, The actual output needed is 3.400000,
but the result is 3. So to get the correct but the result is 3.000000. So to get the also the result is 3.400000. Getting the
output one way is to change the data correct output one way is to change the correct output by declaring the correct
type of a given variable. data type of a given variable. data type of a given variable. (without
TYPE CONVERSION or CASTING)
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 31
PROBLEM SOLVING TECHNIQUES: .
Algorithmic approach:
There may be several methods under an approach. Example, Sorting is an approach and different
sorting techniques are methods each. An algorithm is a sequence of logical steps to solve a problem.
There are many types of algorithms but the most important and fundamental algorithms that you
must are discussed in this article.
• Brute Force Algorithm
• Recursive Algorithm
o Divide and Conquer Algorithm
o Dynamic Programming Algorithms
o Greedy Algorithm
o Backtracking Algorithm
• Randomized Algorithm
• Sorting Algorithm
• Searching Algorithm
• Hashing Algorithm
Example: If there is a lock of 4-digit PIN. The digits to be chosen from 0-9 then the brute force will be
trying all possible combinations one by one like 0001, 0002, 0003, 0004, and so on until we get the right PIN.
In the worst case, it will take 10,000 tries to find the right combination.
2. Recursive Algorithm:
This type of algorithm is based on recursion. In recursion, a problem is solved by breaking it into
subproblems of the same type and calling own self again and again until the problem is solved with the help
of a base condition.
Example: Some common problem that is solved using recursive algorithms are Factorial of a Number,
Fibonacci Series, Tower of Hanoi, DFS for Graph, etc.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 32
This type of algorithm is also known as the memoization technique because in this the idea is
to store the previously calculated result to avoid calculating it again and again. In Dynamic
Programming, divide the complex problem into smaller overlapping subproblems and store the result
for future use.
Example: The following problems can be solved using the Dynamic Programming algorithm
Knapsack Problem, Weighted Job Scheduling, Floyd Warshall Algorithm, etc.
c) Greedy Algorithm:
In the Greedy Algorithm, the solution is built part by part. The decision to choose the next
part is done on the basis that it gives an immediate benefit. It never considers the choices that had
been taken previously.
Example: Some common problems that can be solved through the Greedy Algorithm are Dijkstra
Shortest Path Algorithm, Prim’s Algorithm, Kruskal’s Algorithm, Huffman Coding, etc.
d) Backtracking Algorithm:
In Backtracking Algorithm, the problem is solved in an incremental way i.e., it is an algorithmic
technique for solving problems recursively by trying to build a solution incrementally, one piece at a
time, removing those solutions that fail to satisfy the constraints of the problem at any point of time.
Example: Some problems can be solved through the Backtracking Algorithm are the Hamiltonian
Cycle, M-Coloring Problem, N Queen Problem, Rat in Maze Problem, etc.
3. Randomized Algorithm:
In the randomized algorithm, we use a random number.it helps to decide the expected outcome. The
decision to choose the random number so it gives the immediate benefit
Example: Some common problems that can be solved through the Randomized Algorithm are Quicksort:
In Quicksort we use the random number for selecting the pivot.
4. Sorting Algorithm:
The sorting algorithm is used to sort data in maybe ascending or descending order. It’s also used for
arranging data in an efficient and useful manner.
Example: Some common problems that can be solved through the sorting Algorithm are Bubble sort,
insertion sort, merge sort, selection sort, and quick sort are examples of the Sorting algorithm.
5. Searching Algorithm:
The searching algorithm is the algorithm that is used for searching the specific key in particular sorted
or unsorted data.
Example: Some common problems that can be solved through the Searching Algorithm are Binary
search or linear search is one example of a Searching algorithm.
6. Hashing Algorithm:
Hashing algorithms work the same as the Searching algorithm but they contain an index with a key
ID i.e. a key-value pair. In hashing, we assign a key to specific data.
Example: Some common problems can be solved through the Hashing Algorithm in password
verification.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 33
Characteristics of an Algorithm:
There are some important characteristics which every algorithm should follow. They are as follows:
Structured programming is a programming paradigm aimed on improving the clarity, quality, and
development time of a computer program by making extensive use of subroutines. It is possible to do
structured programming in any programming language, though it is preferable to use something like a
procedural programming language. Example: ALGOL, Pascal, PL/I and Ada.
Top-down approach:
• Program design concentrates on planning the solution as a collection of sub solutions. During top-
down design the divide and conquer policy is followed.
• The problem is divided into smaller sub problems and these sub problems are further divided into
even smaller sub problems.
• In the top-down approach, the calling components is always designed before its sub component.
• Thus top-down design represents a successive refinement of functionality of the program.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 34
• It allows us to build solutions to a problem in a stepwise fashion.
(or)
Bottom-up approach:
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 35
Deference between top-down and bottom-up approaches are,
• Fixed Part: This refers to the space that is required by the algorithm. For example, input
variables, output variables, program size, etc.
• Variable Part: This refers to the space that can be different based on the implementation of
the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack
space, etc.
Therefore, Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is
the variable part of the algorithm, which depends on instance characteristic I.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 36
2. Time Complexity: The time complexity of an algorithm refers to the amount of time required
by the algorithm to execute and get the result. This can be for normal operations, conditional if-else
statements, loop statements, etc.
Therefore, Time complexity of any algorithm P is T(P) = C + TP(I), where C is the constant time part and
TP(I) is the variable part of the algorithm, which depends on the instance characteristic I.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 37
Some Important sort outs:
Problem: Draw a flowchart to find the roots of a Problem: Write the PSEUDO CODE for checking
quadratic equation whether a given number is a prime number or not.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 38