Unit 1
Unit 1
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.
The history of computer begins with the birth of abacus which is believed to be the first computer. It is said that
Chinese invented Abacus around 4,000 years ago. let us consider the development of a computer through various stages.
1.Abacus:
✓ It was a wooden rack which has metal rods with beads mounted on them.
✓ 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.
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.
✓ 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.
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 information.b
13.UNIVAC-1:
✓ It is the first computer which is used for commercial purpose in 1954.
Generations of Computers:
Gen Technology Year speed Languages Examples Dis ADV
No specific Analytical
Very slowest Very Large,
Mechanical languages instead Engine,
0th 1642-1940 computing Bulky and
gears of that patterns Difference
devices noisy
used Engine
Slowest Large, Bulky
st Vacuum Machine level
1 1940-1956 computing EDSAC ,EDVAC and difficult to
Tubes language
devices program
High cost and
Faster than first Assembly level IBM-1401, IBM- limited to
2nd Transistor 1956-1963
generation language 1620 special
purpose tasks
Integrated Limited
Faster than High level IBM-360,
3rd circuits 1964-1975 storage
second generation languages HoneyWell-6000
(ICs) capacity
Faster than third High level IBM PC series , Difficult to
4th VLSI 1975-1989
generation languages Apple Series manufacture
HLL , Integrated Laptop , PDA Lack of human
1989 – till Fastest of all
5th ULSI Development (Personal Digital like
date times
Environment (IDE assistance) Intelligence
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.
➢ Accept the data
➢ Convert data to computer understandable form.
➢ 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.
(or)
b) Application Software:
✓ Application software is written to enable the computer to solve a specific data processing task.
✓ Categories of application software:
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:
Advantages of Compiler
✓ A compiler translates a program in a single run.
✓ It consumes less time.
✓ CPU utilization is more.
✓ Both syntactic and semantic errors can be checked concurrently.
✓ It is easily supported by many high-level languages like C, C++, JAVA, etc.
INTERPRETER:
✓ During the process of translation There is another type of software that also does translation. This is called an
interpreter.
Advantages of Interpreter
✓ An interpreter translates the program line by line.
✓ The interpreter is smaller in size.
✓ It is flexible.
✓ Error localization is easier.
✓ The interpreter facilitates the implementation of computer programming language constructs.
Differences between compiler and interpreter:
Program Compilers scan the entire program in The program is interpreted/translated one line at a
scanning one go. time.
Compilers convert the source code to Interpreters do not convert the source code into
Object code
object code. object code.
Programming Programming languages that use Programming languages that uses interpreter
languages compilers include C, C++, C#, etc.. include Python, Ruby, Perl, MATLAB, etc.
Computer languages are the languages through which the user can communicate with the computer by writing
program instructions.
Every computer programming language contains a set of predefined words and a set of rules (syntax) that are used
to create instructions of a program.
Computer Languages Classification
Over the years, computer languages have been evolved from Low-Level to High-Level Languages. In the earliest days of
computers, only Binary Language was used to write programs.
From the above figure, we can observe the following key points...
• The programming languages like C, C++, Java, etc., are written in High-level language which is more comfortable
for the developers.
• A high-level language is closer to the users.
• Low-level language is closer to the computer. Computer hardware can understand only the low-level language
(Machine Language).
• The program written in the high-level language needs to be converted to low-level language to make
communication between the user and the computer.
• Middle-level language is not closer to both user and computer. We can consider it as a combination of both high-
level language and low-level language.
EXECUTION PROCESS OF A C PROGRAM
IMPORTANT POINTS
• C program file (Source file) must save with .c extension.
• The compiler converts complete program at a time from high-level language to low-level language.
• Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in this process.
• The compiler converts the file only if there are no errors in the source code.
• CPU places the result in User Screen window.
PROGRAM DEVELOPMENT LIFE CYCLE
When we want to develop a program using any programming language, we follow a sequence of steps. These steps are
called phases in program development. The program development life cycle is a set of steps or phases that are used to
develop a program in any programming language.
• Problem Definition
• Problem Analysis
• Algorithm Development
• Coding & Documentation
• Testing & Debugging
• Maintenance
1. PROBLEM DEFINITION
In this phase, we define the problem statement and we decide the boundaries of the problem. In this phase we need to
understand the problem statement, what is our requirement, what should be the output of the problem solution. These are
defined in this first phase of the program development life cycle.
2. PROBLEM ANALYSIS
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means we gather the
required resources to solve the problem defined in the problem definition phase. We also determine the bounds of the
solution.
3. ALGORITHM DEVELOPMENT
During this phase, we develop a step-by-step procedure to solve the problem using the specification given in the previous
phase. This phase is very important for program development. That means we write the solution in step-by-step statements.
4. CODING & DOCUMENTATION
This phase uses a programming language to write or implement the actual programming instructions for the steps defined in
the previous phase. In this phase, we construct the actual program. That means we write the program to solve the given
problem using programming languages like C, C++, Java, etc.,
5. TESTING & DEBUGGING
During this phase, we check whether the code written in the previous step is solving the specified problem or not. That
means we test the program whether it is solving the problem for various input data values or not. We also test whether it is
providing the desired output or not.
6. MAINTENANCE
During this phase, the program is actively used by the users. If any enhancements found in this phase, all the phases are to
be repeated to make the enhancements. That means in this phase, the solution (program) is used by the end-user. If the user
encounters any problem or wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
C Background
C is a structured programming language. It is also known as function orientated programming language. C programming
language was developed in the year of 1972 by Dennis Ritchie at Bell Laboratories in the USA (AT & T).
In the year of 1968, research was started by Dennis Ritchie on programming languages like BCPL, CPL. The main aim of
his research was to develop a new language to create an OS called UNIX. After four years of research, a new programming
language was created with solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new language
was introduced with the name “Traditional C”.
• The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because most of the features of 'c'
were derived from BCPL (B language).
• The first outcome of the c language was the UNIX operating system. The initial UNIX OS was completely
developed using 'c' programming language.
• The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and also “Father of UNIX”.
• The c programming language is very popular because it is reliable, simple and easy to use and it is the base for
almost all the other programming languages.
• The following are the language before ‘c’ & various versions of ‘c’.
Flowcharts
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.
Some of the commonly used flowchart symbols are listed below
Note: (Name of the Symbols)
Oval, Diamond, Circle, Square (or) Rectangle, Parallelogram, hexagon shaped symbol, arrows (Data Flow lines),
Subroutine Symbol (rectangle with a line at each end of the shape).
Flowchart Example:
•Problem 1: Draw a flowchart to find the sum of 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.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode is an
intermediate state between algorithm and program that plays supports the transition of the algorithm into the
program.
Algorithm Pseudocode
An Algorithm is used to provide a solution to A Pseudocode is a step-by-step description of
a problem in form of a well-defined step-based an algorithm in code-like structure using English
form. 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:
Step 1: start Start program #include<stdio.h>
Step 2: initialize fact = 1 Declare fact and n void main()
Step 3: input the user value n Enter number for n {
Step 4: for i=1 to i <= n repeat for i=1 to i <=n int n, fact=1,i;
the process Perform fact = fact printf("enter value for n: ");
Step 5: fact = fact * i * i Display fact scanf("%d", &n);
Step 6: i++ [increment i by one] End program for(i=1; i<=n; i++)
Step 7: print fact value { fact=fact*i; }
Step 8: stop printf("\n factorial is: %d", fact);
}
STRUCTURE OF C PROGRAM
• Single Line Comments: Single line comment begins with // symbol. We can write any number of
single line comments.
• Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can
write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write comments. All the
comment lines in a C program just provide the guidelines to understand the program and its code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use the #include
statement to include the header file into our program. We use a #define statement to define a constant. The
preprocessing statements are used according to the requirements. If we don't need any header file, then no
need to write #include statement. If we don't need any constant, then no need to write a #define statement.
Line 3: Global Declaration
The global declaration is used to define the global variables, which are common for all the functions after
its declaration. We also use the global declaration to declare functions. This global declaration is used
based on the requirement.
Line 4: int main()
Every C program must write this statement. This statement (main) specifies the starting point of the C
program execution. Here, main is a user-defined method which tells the compiler that this is the starting
point of the program execution. Here, int is a data type of a value that is going to return to the Operating
System after completing the main method execution. If we don't want to return any value, we can use it as
void.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C program,
every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and functions that are local to the function or block in which they
are declared. The variables which are declared in this section are valid only within the function or block in
which they are declared.
Line 7: Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the result,
calculations, etc., All the statements in this section are written according to the requirements.
Line 9: Closing Brace (})
The close brace indicates the end of the block which belongs to the main method. In C program every block
end with a '}' symbol.
Line 10, 11, 12, ...: User-defined function ()
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined function need
not be declared. Directly it can be implemented, but it must be before the main method. In a program, we
can define as many user-defined functions as we want. Every user-defined function needs a function call to
execute its statements.
Every C program contains statements. These statements are constructed using words and these words are
constructed using characters from C character set.
• Alphabets
• Digits
• Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower- and upper-case letters together
support 52 alphabets.
• lower case letters - a to z
• UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
• Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
• C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
backspace vertical tab etc.,
Commonly used characters in C with their ASCII values
C KEYWORDS
As every language has words to construct statements, C programming also has words with a specific
meaning which are used to construct c program instructions. In the C programming language, keywords are
special words with predefined meaning. Keywords are also known as reserved words in C programming
language.
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning which is
already known to the compiler.
Properties of Keywords
➢ All the keywords in C programming language are defined as lowercase letters so they must be used
only in lowercase letters
➢ Every keyword has a specific meaning, users can not change that meaning.
➢ Keywords cannot be used as user-defined names like variable, functions, arrays, pointers, etc...
C DATA TYPES
Def: -The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.
➢ Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics. All
the values in a data type have the same properties.
➢ Data types in the c programming language are used to specify what kind of value can be stored in a
variable. The memory size and type of the value of a variable are determined by the variable data
type. In a c program, each variable or constant or array must have a data type and this data type
Example Program
#include <stdio.h>
void main()
{
// Determine and Print the size of int
printf("Size of int: %u bytes\n", sizeof(int));
C VARIABLES
Def: - Variable is a name given to a memory location where we can store different values of the same data
type during the program execution.
Variables in a c programming language are the named memory locations where the user can store
different values of the same data type during the program execution. That means a variable is a name given
to a memory location in which we can store different values of the same data type. In other words, a
variable can be defined as a storage container to hold values of the same data type during the program
execution.
Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a data type that determines the range and type of values be stored and the
size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol.
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore (_).
4. A variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
DECLARATION OF VARIABLE
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified data type values into that memory location. In C
programming language, the declaration can be performed either before the function as global variables or
inside any block or function. But it must be at the beginning of block or function.
The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and
allows only integer values into that memory location.
C CONSTANTS
Def: - A constant is a named memory location which holds only one value throughout the program
execution.
In C programming language, a constant is similar to the variable but the constant hold only one
value during the program execution. That means, once a value is assigned to the constant, that value can't
be changed during the program execution. Once the value is assigned to the constant, it is fixed throughout
the program.
In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,
TYPES OF C CONSTANT:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
INTEGER CONSTANTS
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l'
whereas unsigned long integer constant value is suffixed with 'ul'.
EXAMPLE
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
CREATING CONSTANTS IN C
In a c programming language, constants can be created using two concepts...
• Using the 'const' keyword
• Using '#define' preprocessor
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
Input means to provide the program with some data to be used in it and Output means to display data on
the screen or write the data to a printer or a file.
The C programming language provides standard library functions to read any given input and display
output on the console.
➢ Standard Input (stdin)
➢ Standard Output (stdout)
Standard input or stdin is used for taking input and Standard output or stdout is used for giving output. The
functions used for standard input and output are present in the stdio.h header file. Hence, to use those
functions, we need to include the stdio.h header file in our program.
#include <stdio.h>
C language offers us several built-in functions for performing input/output operations.
1. printf() function - Show Output
2. scanf() function - Take Input
3. getchar() and putchar() function
4. gets() and puts() function
1. THE PRINTF() FUNCTION
The printf() function is the most used function in the C language. This function is defined in the
stdio.h header file and is used to show output on the console (standard output).
1. Print a sentence
#include <stdio.h>
int main()
{
// using printf()
printf("Welcome to c language");
return 0;
}
Output:
Welcome to Study c language
2. Print an Integer value
We can use the printf() function to print integer value coming from a variable using the %d format
specifier.
For example,
#include <stdio.h>
It reads data from stdin and stores it according to the parameter format into the locations pointed by the
additional arguments. On success, the function returns the number of items of the argument list successfully
filled.
The scanf() function can be used to take any data type input from user, all we have to take care is that the
variable in which we store the value should have the same data type.
Using the format specifier, we tell the compiler what type of data is in a variable and & is the address
operator which tells the compiler the address of the variable so that the compiler can assign the variable
with the value entered by the user.
scanf() Code Examples
1. Input Integer value
If we have to take an integer value input from the user, we have to define an integer variable and then use
the scanf() function.
EXAMPLE
#include <stdio.h>
int main()
{
// using scanf()
int a;
printf("Please enter a number: ");
scanf("%d", &a);
printf("You entered: %d", a);
return 0;
}
OUTPUT
Please enter a number: 7
You entered: 7
FORMAT SPECIFIERS
To print values of different data types using the printf() statement and while taking input using the
scanf() function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable. Some examples are %c, %d, %f, etc.
ESCAPE SEQUENCE
To display the output in different lines or as we wish, we use some special characters called escape
sequences. Escape sequences are special characters with special functionality used in printf() function to
format the output according to the user requirement. In the C programming language,
C STORAGE CLASSES
Storage class specifiers in C language tells to the compiler where to store a variable (Storage area of
variable), how to store the variable, Scope of variable, Default value of a variable (if it is not initialized it),
what is the initial value of the variable and life time of the variable.
Type
Storage place Scope Life Default Value
(Keyword)
Register variable
Register variables are also local variables, but stored in register memory. Whereas, auto variables
are stored in main CPU memory.
Advantages: The register variables are faster than remaining variables, because register variable are stored
in register memory not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low. (16 bits, 32
bits or 64 bits).
Explanation
In scanf() function if address is provided for the register variable then it will give error, if addition is
not provided it normally work.
Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the
memory is available or else stored in stack area of data segment.
Automatic auto Computer Garbage Local to the block in Till the control remains within
Memory Value which the variable the block in which variable is
(RAM) has defined defined
Static static Computer Zero Local to the block in The value of the persists
Memory which the variable between different function
(RAM) has defined calls (i.e., Initialization is done
only once)
Register register CPU Garbage Local to the block in Till the control remains within
Register Value which the variable the block in which variable is
has defined defined
OPERATORS
An operator is a symbol used to perform arithmetic and logical operations in a program. That means an
operator is a special symbol that tells the compiler to perform mathematical or logical operations. C
programming language supports a rich set of operators that are classified.
< Returns TRUE if the first value is smaller than second value otherwise returns FALSE 10 < 5 is FALSE
> Returns TRUE if the first value is larger than second value otherwise returns FALSE 10 > 5 is TRUE
<= Returns TRUE if the first value is smaller than or equal to second value otherwise returns 10 <= 5 is FALSE
FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise returns 10 >= 5 is TRUE
FALSE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
EXAMPLE 1: EXAMPLE 2:
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE
! Logical NOT - Returns TRUE if condition is FLASE and returns !(10 < 5 && 12 > 10) is
FALSE if it is TRUE TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE then
complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then
complete condition becomes TRUE.
The increment and decrement operators are used infront of the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is used after
the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the expression
evaluation. That means, when we use pre-increment or pre-decrement, first the value of the variable is
incremented or decremented by one, then the modified value is used in the expression evaluation.
Example Program
#include<stdio.h> OUTPUT:
#include<conio.h> i=6 j=6
void main()
{
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j =
%d",i,j);
}
+= Add both left and right-hand side values and store the result into left-hand A += 10
side variable ⇒ A = A+10
-= Subtract right-hand side value from left-hand side variable value and store A -= B
the result ⇒ A = A-B
into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and store A *= B
the result ⇒ A = A*B
into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value A /= B
and store the result ⇒ A = A/B
into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value A %= B
and store the remainder ⇒ A = A%B
into the left-hand side variable
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is A & B
0 ⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise A^B
it is 1 ⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right by A >> 2
the specified number of positions ⇒ 6 (00110)
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left
shift) and >> (right shift).
NOTE:
➢ Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT
operation.
➢ Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left
shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted by 2
places.
EXAMPLE OUTPUT:
#include <stdio.h>
AND_opr value = 0
int main()
OR_opr value = 120
{
NOT_opr value = -41
int m = 40,n =
XOR_opr value = 120
80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
left_shift value = 80
AND_opr = (m&n);
right_shift value = 20
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are...
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
EXAMPLE
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
EXAMPLE
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
EXAMPLE
EXAMPLE CODE
#include <stdio.h> OUTPUT
main() { Value of (a + b) * c / d is : 90
int a = 20; Value of ((a + b) * c) / d is : 90
int b = 10; Value of (a + b) * (c / d) is : 90
int c = 15; Value of a + (b * c) / d is : 50
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
C EXPRESSION EVALUATION
An expression is evaluated based on the precedence and associativity of the operators in that expression.
In the C programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to their
precedence and associativity. The operator with higher precedence is evaluated first and the operator with
the least precedence is evaluated last.
To understand expression evaluation in c 10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence. So,
according to the operator precedence both multiplication and division are evaluated first and then the
addition is evaluated. As multiplication and division have the same precedence they are evaluated based on
the associativity. Here, the associativity of multiplication and division is left to right. So, multiplication is
performed first, then division and finally addition. So, the above expression is evaluated in the order of * /
and +. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
TYPES OF ERRORS IN C
Run time errors can occur because of various reasons. Some of the reasons are:
• Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets to
enter a break statement. This will lead the program to run infinite times, hence resulting in a run
time error.
• Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array's data,
the program might start leaking memory, resulting in a run time error.
• Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root
of -1 will also result in a run time error.
• Undefined Variables: If a programmer forgets to define a variable in the code, the program will
generate a run time error.
3. Logical Error
Sometimes, we do not get the output we expected after the compilation and execution of a program.
Even though the code seems error free, the output generated is different from the expected one. These types
of errors are called Logical Errors. Logical errors are those errors in which we think that our code is correct,
the code compiles without any error and gives no error while it is running, but the output we get is different
from the output we expected.
4. Semantic Error
➢ Errors that occur because the compiler is unable to understand the written code are called Semantic
Errors. A semantic error will be generated if the code makes no sense to the compiler, even though
it is syntactically correct. It is like using the wrong word in the wrong place in the English language.
For example, adding a string to an integer will generate a semantic error.
➢ Semantic errors are different from syntax errors, as syntax errors signify that the structure of a
program is incorrect without considering its meaning. On the other hand, semantic errors signify the
incorrect implementation of a program by considering the meaning of the program.
➢ The most commonly occurring semantic errors are: use of un-initialized variables, type
compatibility, and array index out of bounds.
Type Conversion
The type conversion is the process of converting a data value from one data type to another data type
automatically by the compiler. Sometimes type conversion is also called implicit type conversion. The
implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the integer
value automatically gets converted to float value by adding decimal value 0. And when a float value is
assigned to an integer variable the float value automatically gets converted to an integer value by removing
the decimal value. To understand more about type conversion observe the following...
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable. Here, the
compiler automatically converts the float value (90.99) into integer value (90) by removing the decimal part
of the float value (90.99) and then it is assigned to variable i. Similarly, when we assign x = i, the integer
value (90) gets converted to float value (90.000000) by adding zero as the decimal part.
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type to
another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case,
we convert the data from one data type to another data type using explicit type conversion. To perform this
we use the unary cast operator. To convert data from one type to another type we specify the target data
type in parenthesis as a prefix to the data value that has to be converted.
(TargetDatatype) DataValue
Example
int total Marks = 450, max Marks = 600;
float average;
average = (float) total Marks / max Marks * 100;
In the above example code, both total Marks and max Marks are integer data values. When we perform
total Marks / max Marks the result is a float value, but the destination (average) data type is a float. So we
use type casting to convert total Marks and max Marks into float data type.
Example Program
Implicit Explicit
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int num1 = 10; float num1 = 15.6;
int num2 = 5; int num2=14, num3;
float result; num3 = (int) num1+num2; // Explicit cast from
result = num1 / num2; // Implicit cast from int to float to int
float printf("The result is: %d\n", num3);
printf("The result is: %.2f\n", result); return 0;
return 0; }
}
Bottom-up approach:
The bottom-up design is the reverse of the top-down approach.
➢ Here the process starts with the identification of the smallest sub component of the total program
which can be easily implemented.
➢ Such smallest components are combined to reach to a more abstract level and plan components of
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.
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.
How to Calculate, Time Complexity?
The time complexity of an algorithm is also calculated by determining the following 2 components:
1. Constant time part: Any instruction that is executed just once comes in this part.
For example, input, output, if-else, switch, arithmetic operations, etc.
2. Variable Time Part: Any instruction that is executed more than once, say n times,
comes in this part. For example, loops, recursion, 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.
The analysis of Algorithms:
Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific computational
problem. Analysis of algorithms is the determination of the amount of time and space resources required
to execute it.
Analysis of algorithm is the process of analyzing the problem-solving capability of the algorithm
in terms of the time and size required (the size of memory for storage while implementation). However,
Problem: Draw a flowchart to find the roots of Problem: Write the PSEUDO CODE for
a quadratic equation checking whether a given number is a prime
number or not.
************************************************************************************