CP Unit1
CP Unit1
What is a program?
The single most important skill for a computer scientist is problem solving.
Problem solving means the ability to formulate problems, think creatively about
solutions, and express a solution clearly and accurately.
8-Step Problem Solving Process
Generate a list of actions required to address the root cause and prevent
problem from getting to others.
Assign an owner and timeline to each action.
Status actions to ensure completion.
People used sticks, stones, and bones as counting tools before computers were
invented.
1. Abacus
Abacus was invented by the Chinese around 4000 years ago. It’s a wooden rack
with metal rods with beads attached to them. The abacus operator moves the
beads according to certain guidelines to complete arithmetic computations.
2. Napier’s Bone
John Napier devised Napier’s Bones, a manually operated calculating apparatus.
For calculating, this instrument used 9 separate ivory strips (bones) marked with
numerals to multiply and divide. It was also the first machine to calculate using
the decimal point system.
3. Pascaline
Pascaline was invented in 1642 by Biaise Pascal, a French mathematician and
philosopher. It is thought to be the first mechanical and automated calculator. It
was a wooden box with gears and wheels inside.
5. Difference Engine
In the early 1820s, Charles Babbage created the Difference Engine. It was a
mechanical computer that could do basic computations. It was a steam-powered
calculating machine used to solve numerical tables such as logarithmic tables.
7. Tabulating machine
An American Statistician – Herman Hollerith invented this machine in the year
1890. Tabulating Machine was a punch card-based mechanical tabulator. It could
compute statistics and record or sort data or information. Hollerith began
manufacturing these machines in his company, which ultimately became
International Business Machines (IBM) in 1924.
The word ‘computer’ has a very interesting origin. It was first used in the 16th
century for a person who used to compute, i.e. do calculations.
A computer is an electronic device, under the control of instructions stored in its memory
that can accept data (input), process the data according to specified rules(Program) on
processor & produces information (output), and store the information for future use .
Advantages of computer
Speed
Computers excel in processing vast amounts of data at incredible speeds. They can
perform complex calculations, execute multiple tasks simultaneously, and deliver
results in a fraction of the time it would take humans to do the same.
Storage
Computers offer extensive storage capabilities, allowing users to store and manage
large volumes of data in a compact and organized manner.
Diligence
A computer is free of fatigue, lack of concentration, and so on. This is what makes a
computer work for hours without making any mistakes.
Accuracy
This is an incredible characteristic of computers, which is their high level of accuracy.
It is capable of performing 100% accurate calculations.
Reliability
A computer is a dependable machine that is capable of performing all tasks and
operations at high speeds and with near-perfect accuracy.
Just like humans, software, and hardware respond to the requests or demands made by
users.
Memory
Memory on computers is comparable to that in the human brain. It is used to store data
and directions.
Memory is the storage space on it where data is processed and processing instructions
are stored. It has both primary and secondary memories.
The task we are currently working on is saved in the main memory, and the task we
saved is saved until we delete it.
Logical
A computer system has certain characteristics, such as the capability of thinking,
reasoning, and learning.
These characteristics help them perform tasks logically and these characteristics have
been further developed into what we today know as Artificial Intelligence.
Versatility
Because computers are so versatile, they can perform almost any task that can be
reduced to a series of logical steps.
It refers to the ability or adaptation to quickly switch from one task to another.
Computers are still far from reaching a few major milestones. Humans continue to
surpass them in some tasks. They may be able to get around these restrictions in the
near future.
1. No IQ: Unfed or unprogrammed events cannot cause them to react. They are
incapable of learning anything (zero intelligent quotients). The user’s input determines
these results entirely. That is, instead of correcting the incorrect input, they produce
the incorrect result.
2. No feelings/ EQ: While they may function nonstop and relentlessly. Few activities,
though, call for advice and concepts. Only those who have positive, negative, or
mixed feelings about the task will be able to accomplish it.
In these situations, a machine fails because it lacks emotional intelligence (EQ)
(Emotional Quotient).
3. Lack of Decision-Making: They cannot decide on their own. Each operation that
they perform is fed with an algorithm to perform different processes for each situation.
However, if it faces a problem that is not fed into the system, it will not be ready for it.
It either gets corrupted or does not respond.
4. Lack of Common Sense: Despite the fact that they are automated devices, they
nevertheless need human intervention. Only when some input is given will it function.
You might have to perform calculations for your math homework, for instance. Each
sum must be fed in order to obtain the output. There are other characteristics that
make them lacking in some fields.
5. Human dependency: Once turned on, it is a mechanism that operates entirely
automatically. But it is unable to operate in order to turn on. Without such a program,
they do not know when to start and when to stop.
They have both strengths and weaknesses, much like a coin has two sides. Humans
have used them for a very long time. However, they do contain restrictions that can
only be removed with human aid.
Input/Output Units
Input Unit: A device through which data and programs from the outside world
enter the computer system.
Output unit: A device through which results stored in the computer memory are
made available outside the computer system.
Central processing unit – Comprises three parts
1. Arithmetic/Logic Unit : Performs basic arithmetic operations such as
addition and subtraction Performs logical operations such as AND, OR, and
NOT. Most modern ALUs have a small amount of special storage units called
registers that can be accessed faster than main memory.
2. Control unit It organizes the computer to work computer as single unit &
generates control signals for various devices regarding read/write or execute
operation
3. Memory A collection of cells, each with a unique physical address Most
computers are byte-addressable
Cell at address 11111110 contains 10101010
Memory Units – How much memory is required for a file/data/program etc. is
measured by memory units.
RAM and ROM- Random Access Memory (RAM) Memory in which each
location can be accessed and changed Read Only Memory (ROM) Memory in
which each location can be accessed but not changed RAM is volatile, ROM is
not Secondary Storage Devices Magnetic Tape mass auxiliary storage device
Program counter
What is a program counter (PC)?
The program counter, also known as the instruction pointer or simply PC, is a
fundamental component of a computer's central processing unit (CPU). It is a
special register that keeps track of the memory address of the next instruction to be
executed in a program.
i. Machine Language
The advantage of machine language is that it helps the programmer to execute the
programs faster than the high-level programming language.
The advantage of assembly language is that it requires less memory and less execution
time to execute a program.
The main advantage of a high-level language is that it is easy to read, write, and
maintain.
The main advantage of object-oriented programming is that OOP is faster and easier
to execute, maintain, modify, as well as debug.
What is an Algorithm?
In computer programming terms, an algorithm is a set of well-defined instructions to
solve a particular problem. It takes a set of input(s) and produces the desired output.
Qualities of a Good Algorithm
Input and output should be defined precisely.
Each step in the algorithm should be clear and unambiguous.
Algorithms should be most effective among many different ways to solve a
problem.
An algorithm shouldn't include computer code. Instead, the algorithm should be
written in such a way that it can be used in different programming languages.
What is a Flowchart?
What Is Pseudo-Code in C?
The pseudocode in C is an informal way of writing a program for better human
understanding. It is written in simple English, making the complex program easier to
understand.
Pseudocode cannot be compiled or interpreted. It doesn't follow the programming
language's syntax; it is thus written in pseudocode so that any programmers or non-
programmers can easily understand it.
Following points should be remembered while preparing pseudocode :
Pseudocode will be enclosed by START (or BEGIN) and STOP (or END).
Pseudocode should be concise so ignore unnecessary details.
To accept data from user, generally used statements are INPUT, READ, GET or
OBTAIN.
To display result or any message, generally used statements are PRINT,
DISPLAY, or WRITE.
Generally used keywords are capitalized while preparing pseudocode.
Generally coding is done in high level language or low level language (assembly
language). For the computer to understand these languages, they must be translated
into machine level language.
The machine language code thus created can be saved and run immediately or
later on.
Once an object code is obtained, the compiled programs can be faster and more
efficient than interpreted programs.
Compilation Process
A source code must go through several steps before it becomes an executable
program.
In the first step the source code is checked for any syntax errors.
After the syntax errors are traced out a source file is passed through a
compiler which first translates high level language into object code (A
machine code not ready to be executed).
A linker then links the object code with pre-compiled library functions,
thus creating an executable program.
This executable program is then loaded into the memory for execution.
The primitive data types in c language are the inbuilt data types provided by the c
language itself. Thus, all c compilers provide support for these data types.
Integer data type is used to declare a variable that can store numbers without a
decimal. The keyword used to declare a variable of integer type is “int”. Thus, to
declare integer data type following syntax should be followed:
int variable_name;
Float data type declares a variable that can store numbers containing a decimal
number.
float variable_name;
Double data type also declares variable that can store floating point numbers but
gives precision double than that provided by float data type. Thus, double data type
are also referred to as double precision data type.
double variable_name ;
Character data type declares a variable that can store a character constant. Thus, the
variables declared as char data type can only store one single character.
char variable_name ;
Unlike other primitive data types in c, void data type does not create any variable
but returns an empty set of values. Thus, we can say that it stores null.
void variable_name ;
Apart from the primitive data types mentioned above, there are certain data type
qualifiers that can be applied to them in order to alter their range and storage space
and thus, fit in various situations as per the requirement.
short
long
signed
unsigned
It should be noted that the above qualifiers cannot be applied to float and can only
be applied to integer and character data types.
Variables
Declaration of Variables in C
A few simple parameters are considered to declare a variable in the C programming
language. These parameters are collectively termed syntax.
Syntax:
<data type> <variable-list>;
Example:
int a, b, sum;
Initialization of Variables in C
There are two ways to utilize variables in C.
You either have to declare them or
Initialize them at the declaration stage.
When a variable is declared, C compilers store a random or a garbage value in the declared
variable.
Note:
If you do not wish to store a garbage value and intend to store a dedicated value in your
variable, you can consider initializing your variable with a valid value.
Syntax:
You may also declare and initialize multiple variables at the same time as given below:
Syntax:
<data type> <var1 = val1>, <var2 = val2>,.....<varn = valn>;
Types of Variables in C
C language helps you with providing a wide range of variable varieties for different
programming purposes, as described below.
Local variables
Global variables
Static variables
External variables
Automatic variables
1. Local Variables
Variables that are declared inside the functions with the keyword local are called local
variables. The local variable's scope is inside the function in which it is declared.
Example:
2. Global Variables
Variables declared outside the functions with the keyword global are called global
variables. Global variables can be accessed by multiple functions defined in the program.
3. Static Variables
Variables declared with a keyword static are static variables, whose lifetime is throughout
the program run time.
Example:
In File 1(demo. c): access external variables x and y to perform addition operations by
including the header file(demo. h).
Output:
To access the same external variables x and y in the second file (demo1.c) to perform
subtraction operation, you include the header file (demo. h).
5. Automatic Variables
Variables declared with auto keywords are known as automatic variables. The variables
declared inside the block of functions are automatic variables by default. The scope of
automatic variables is inside the block in which it is declared.
Example:
Output:
When you create a variable, you should always give a meaningful name to the variable.
And follow the below rules for naming the variable:
1. Variable names must not start with a digit.
2. The variable name can consist of alphabets, digits, and special symbols like
underscore _.
Constants
Variables having fixed values that don’t change and cannot be changed throughout
the execution of the program once initialized are called Constants.
Use of the Constants in C
In the C programming language, A variable can be used as a constant by the
following methods:
Using const keyword.
Using the #define preprocessor.
Use of the 'const' Keyword
The 'const' keyword is a fundamental way to create constants in C. It allows you to
declare a variable as constant, ensuring that its value remains unchanged throughout
the program.
const data_type constant_name = value;
Here's an example demonstrating the use of the 'const' keyword to declare and use a
constant:
#include <stdio.h>
int main() {
const float pi = 3.1415926; // Declaring a constant for Pi
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = pi * radius * radius; // Using the constant 'pi'
printf("The area of the circle is %f\n", area);
return 0;
}
In this example, we declare a constant 'pi' using the 'const' keyword, and then we
use it to calculate the area of a circle.
Operators
An operator is a symbol that operates on a value or a variable. For example: + is an
operator to perform addition.
Types of Operators in C
C has many built-in operators and can be classified into 6 types:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Other Operators
C Arithmetic Operators
C Bitwise Operators
During computation, mathematical operations like: addition, subtraction,
multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
C Type Conversion
In C programming, we can convert the value of one data type (int, float, double,
etc.) to another. This process is known as type conversion.
There are two types of type conversion:
Implicit Conversion(Type Conversion)
Explicit Conversion(Type Casting)
Implicit Type Conversion In C
In implicit type conversion, the value of one type is automatically converted to the
value of another type.
Example: Implicit Type Conversion
#include<stdio.h>
int main() {
// character variable
Bottom-Up Model
In this approach, the modules are designed individually and are then integrated together
to form a complete algorithmic design.
How the Bottom-Up Approach Works?
The working of bottom-up approach is as follows:
Identify the components or tasks:
The components or tasks need to be clearly identified and measurable.
Test:
The system/solution needs to be tested to meet the requirements. This can be
done by running a series of tests on the system/solution.
Characteristics of an algorithm
1) Efficiency:
A good algorithm should perform its task quickly and use minimal
resources.
2) Correctness:
It must produce the correct and accurate output for all valid inputs.
3) Clarity:
The algorithm should be easy to understand and comprehend, making it
maintainable and modifiable.
4) Scalability:
It should handle larger data sets and problem sizes without a significant
decrease in performance.
5) Reliability:
The algorithm should consistently deliver correct results under different
conditions and environments.
6) Optimality:
Striving for the most efficient solution within the given problem
constraints.
7) Robustness:
Capable of handling unexpected inputs or errors gracefully without
crashing.
8) Adaptability:
Suppose X is treated as an algorithm and N is treated as the size of input data, the
time and space implemented by the Algorithm X are the two main factors which
determine the efficiency of X.
Time Factor − The time is calculated or measured by counting the number of key
operations such as comparisons in sorting algorithm.
The complexity of an algorithm f(N) provides the running time and / or storage
space needed by the algorithm with respect of N as the size of input data.
Space Complexity
Space complexity of an algorithm represents the amount of memory space needed
the algorithm in its life cycle.
Space needed by an algorithm is equal to the sum of the following two components
Here we have three variables P, Q and R and one constant. Hence S(p) = 1+3. Now
space is dependent on data types of given constant types and variables and it will be
multiplied accordingly.
For example, in case of addition of two n-bit integers, N steps are taken.
Consequently,
the total computational time is t(N) = c*n, where c is the time consumed for
addition of two bits. Here, we observe that t(N) grows linearly as input size
increases.