0% found this document useful (0 votes)
22 views45 pages

CP Unit1

This document provides an introduction to programming, problem-solving techniques, and the history and organization of computers. It covers the basics of programming languages, types of data, and the components of a computer system, including input/output units and the central processing unit. Additionally, it outlines an 8-step problem-solving process and discusses the advantages and limitations of computers.

Uploaded by

v lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views45 pages

CP Unit1

This document provides an introduction to programming, problem-solving techniques, and the history and organization of computers. It covers the basics of programming languages, types of data, and the components of a computer system, including input/output units and the central processing unit. Additionally, it outlines an 8-step problem-solving process and discusses the advantages and limitations of computers.

Uploaded by

v lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

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.

What is a program?

A program is a sequence of instructions that specifies how to perform a computation


and written in a language the computer understands.

Programming: a way of thinking

 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

Step 1: Define the Problem

 What is the problem?


 When did the problem start and how long has this problem been going
on?
 Is there enough data available to contain the problem .

Step 2: Clarify the Problem

 Is it a top priority to resolve the problem at this point in time?


 Are additional resources required to clarify the problem? If yes, elevate
the problem to your leader to help locate the right resources and form a
team.

Introduction to Programming(R23) Department of Information Technology


Step 3: Define the Goals

 What is your end goal or desired future state?


 What will you accomplish if you fix this problem?
 What is the desired timeline for solving this problem?

Step 4: Identify Root Cause of the Problem

 Identify possible causes of the problem.


 Prioritize possible root causes of the problem.
 What information or data is there to validate the root cause?

Step 5: Develop Action Plan

 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.

Step 6: Execute Action Plan

 Implement action plan to address the root cause.


 Verify actions are completed.

Step 7: Evaluate the Results

 Monitor and Collect Data.


 Did you meet your goals defined in step 3? If not, repeat the 8-Step
Process.
 Were there any unforeseen consequences?
 If problem is resolved, remove activities that were added previously to
contain the problem.

Step 8: Continuously Improve

 Look for additional opportunities to implement solution.


 Ensure problem will not come back and communicate lessons learned.
 If needed, repeat the 8-Step Problem Solving Process to drive further
improvements.

Introduction to Programming(R23) Department of Information Technology


History of Computers
What is a Computer?

A computer is an electronic machine that collects information, stores it, processes


it according to user instructions, and then returns the result.

Early Computing Devices

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.

4. Stepped Reckoner or Leibniz wheel


In 1673, a German mathematician-philosopher named Gottfried Wilhelm Leibniz
improved on Pascal’s invention to create this apparatus. It was a digital
mechanical calculator known as the stepped reckoner because it used fluted drums
instead of gears.

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.

Introduction to Programming(R23) Department of Information Technology


6. Analytical Engine
Charles Babbage created another calculating machine, the Analytical Engine, in
1830. It was a mechanical computer that took input from punch cards. It was
capable of solving any mathematical problem and storing data in an indefinite
memory.

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.

History of Computers Generation

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.

Introduction to Programming(R23) Department of Information Technology


Introduction to Programming(R23) Department of Information Technology
Basic Organization of a Computer:

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.

Introduction to Programming(R23) Department of Information Technology


Automation
Automation is the use of technology to complete a task with as little human interaction
as possible.
In computing, automation is typically accomplished through the use of a program, a
script, or batch processing.
Consistency
In the context of databases, consistency means that data cannot be written because it
would violate the database’s own rules for valid data.
Remembrance Power
A computer is capable of storing an unlimited amount of information or data. Any
information can be stored and retrieved for as long as you need it, for an unlimited
number of years.
It is entirely up to you how much data you want to store on it and when you want to
lose or retrieve it.
The Limitations of the Computer

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.

Introduction to Programming(R23) Department of Information Technology


Functional components of a computer

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

Introduction to Programming(R23) Department of Information Technology


Secondary Storage Devices Hard disk Fixed Head HDD / Movable head HDD
A hard disk is a set of stacked disks. Each disk has data recorded
electromagnetically in concentric circles, or tracks, on the disk
Input Devices:
Input devices can send data or information to a computer or another device.
Keyboard: It is an input device which sends data in to the computer. The data
send depends on the key pressed by the user.
Mouse: A mouse is a small handheld input device which controls a cursor in a
graphical user interface. It can move and select text, files, folders etc. on our
computer according to the user input.
Output Devices :
A device that can receive data from computer or another device and create
output with that data is called output device. Examples of various output
devices are as:
Monitor: is an output device that is responsible for receiving data from a
computer and displaying that information as text or images for users to see.
Speakers: Receives sound signal from a computer and then plays that sound
signal and thus we hear songs or music or any other audio.
Projector: Gets data from a computer and displays or projects the same
information onto a screen or a wall. Projector cannot directly accept data from a
user and send that data to another 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.

Introduction to Programming(R23) Department of Information Technology


Why is the program counter important?
The program counter is crucial because it allows the central processing unit (CPU)
to fetch instructions from memory in a sequential manner. By keeping track of the
current instruction's address, the program counter ensures that the CPU knows
which instruction to fetch next.

How does the program counter work?


The program counter is incremented each time an instruction is fetched, so it always
points to the address of the next instruction in memory. After the fetch, the program
counter is updated to the address of the subsequent instruction, allowing the central
processing unit (CPU) to continue executing the program.

Is the program counter specific to a particular programming language?


No, the program counter is not specific to a particular programming language. It is a
low-level concept that exists at the hardware level in the central processing unit
(CPU). Regardless of the programming language used, the CPU relies on the
program counter to execute instructions.

Introduction to Programming Languages:

What is a Programming Language?

A programming language is a computer language that is used by programmers


(developers) to communicate with computers. It is a set of instructions written in
any specific language ( C, C++, Java, Python) to perform a specific task.

A programming language is mainly used to develop desktop applications,


websites, and mobile applications.

Types of programming language:

Introduction to Programming(R23) Department of Information Technology


1. Low-level programming language

Low-level language is machine-dependent (0s and 1s) programming language. The


processor runs low- level programs directly without the need of a compiler or
interpreter, so the programs written in low-level language can be run very fast.

Low-level language is further divided into two parts -

i. Machine Language

Machine language is a type of low-level programming language. It is also called


as machine code or object code. It does not require a translator to convert the
programs because computers directly understand the machine language programs.

The advantage of machine language is that it helps the programmer to execute the
programs faster than the high-level programming language.

ii. Assembly Language

Assembly language (ASM) is also a type of low-level programming language that is


designed for specific processors. It represents the set of instructions in a symbolic and
human-understandable form. It uses an assembler to convert the assembly language
to machine language.

The advantage of assembly language is that it requires less memory and less execution
time to execute a program.

2. High-level programming language

High-level programming language (HLL) is designed for developing user-friendly


software programs and websites. This programming language requires a compiler or
interpreter to translate the program into machine language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and
maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C+


+, Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming
language.

A high-level language is further divided into three parts -

i. Procedural Oriented programming language

Procedural Oriented Programming (POP) language is derived from structured


programming and based upon the procedure call concept. It divides a program into
small procedures called routines or functions.

Introduction to Programming(R23) Department of Information Technology


The advantage of POP language is that it helps programmers to easily track the
program flow and code can be reused in different parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language

Object-Oriented Programming (OOP) language is based upon the objects. In


this programming language, programs are divided into small parts called objects.

The main advantage of object-oriented programming is that OOP is faster and easier
to execute, maintain, modify, as well as debug.

Example: C++, Java, Python, C#, etc.

iii. Natural language

Natural language is a part of human languages such as English, Russian, German,


and Japanese. It is used by machines to understand, manipulate, and interpret human's
language.

3. Middle-level programming language

Middle-level programming language lies between the low-level programming


language and high-level programming language. It is also known as the
intermediate programming language and pseudo-language.

Example: C, C++, language

Basics of a Computer Program :

(Algorithm, Pseudocode, Programs, and Flowcharts)

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.

Introduction to Programming(R23) Department of Information Technology


Algorithm 1: Add two numbers entered by the user
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Algorithm 2: Find the largest number among three numbers


Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Program: A program is a step-by-step machine instruction used for solving any


problem or computational task.

What is a Flowchart?

Introduction to Programming(R23) Department of Information Technology


A flowchart is used for showing the flow of control in a program and the sequence of
steps involved in a hierarchical manner. It is basically a diagrammatic representation
of an algorithm, workflow, or process.
Flowchart Symbols Here is a chart for some of the common symbols used in drawing
flowcharts.

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.

Introduction to Programming(R23) Department of Information Technology


Example of Pseudocode
Pseudocode: Calculation of Simple Interest
Step 1: START
Step 2: READ P, T, R
Step 3: I = P*T*R/100
Step 4: PRINT I
Step 5: STOP
Advantages of Pseudocode
Preparing pseudocode while solving any problem through computer has following
advantages :
 It allows the designer to focus on main logic without being distracted by
programming languages syntax.
 Since it is language independent, it can be translated to any computer language
code.
 It allows designer to express logic in plain natural language.
 It is easier to write actual code using pseudocode.
 Unlike algorithms, pseudocodes are concise so pseudocodes are more readable
and easier to modify.
Disadvantages of Pseudocode
 There are no accepted standards for writing pseudocodes and designer use their
own style while writing pseudocodes.
 Pseudocode cannot be compiled and executed so its correctness cannot be
verified by using computers.

Introduction to Compilation and Execution

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 translation process is carried out by a compiler/interpreter (for high level


language) or an assembler (for assembly language program).

 The machine language code thus created can be saved and run immediately or
later on.

Introduction to Programming(R23) Department of Information Technology


In an interpreted program, each program statement is converted into machine code
before program is executed.

The execution occurs immediately one statement at a time sequentially.

 In contrast to interpreter, a compiler converts a given source code into object


code.

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.

General compilation process is shown in Figure below:

Introduction to Programming(R23) Department of Information Technology


Figure: General Compilation and Execution Process

Primitive Data Types


“A data type is a classification of data which tells the compiler or interpreter how
the programmer intends to use the data.”
Data types in c language can be broadly classified as:

Primitive Data Types

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.

Introduction to Programming(R23) Department of Information Technology


The following primitive data types in c are available:

Integer Data Type, (int)

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, (float)

Float data type declares a variable that can store numbers containing a decimal
number.

float variable_name;

Double Data Type, (double)

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,( char)

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 ;

Introduction to Programming(R23) Department of Information Technology


Void Data Type, (void)

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 ;

Data Type Qualifiers

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.

The data type qualifiers available in c are:

 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.

Introduction to Programming(R23) Department of Information Technology


The entire list of data types in c available for use are:

Variables

What Are Variables in C?


In C programming language, a variable is a user-defined or a user-readable custom name
assigned to a memory location. Variables hold a value that can be modified and reused
many times during the program execution.

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:

Introduction to Programming(R23) Department of Information Technology


<data type> <variable-name = value>;

You may also declare and initialize multiple variables at the same time as given below:
Syntax:
<data type> <var1 = val1>, <var2 = val2>,.....<varn = valn>;

Example: int a = 10, b=20,c;

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:

Introduction to Programming(R23) Department of Information Technology


Output:

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.

Introduction to Programming(R23) Department of Information Technology


4. External Variables
External variables share the variables among the multiple C files. The extern keyword is
used in the C programming language to declare external variables.

Example:

Declare external variables in a file with .h extension(a header file demo.h)

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).

Introduction to Programming(R23) Department of Information Technology


Output:

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:

Rules to Name a Variable

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 _.

Introduction to Programming(R23) Department of Information Technology


3. Blank or spaces are not allowed in the variable name.
4. Keywords are not allowed as a variable name.
5. Upper and lowercase names are treated as different, as C is case-sensitive, so it is
suggested to keep the variable names in lowercase.

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.

Introduction to Programming(R23) Department of Information Technology


Use of the '#define' Preprocessor Directive
The '#define' preprocessor directive is another method to create constants in C. It
allows you to define symbolic names for values, making your code more readable
and maintainable.
#define constant_name value
Here's an example demonstrating the use of the '#define' directive to define and use
a constant:
Problem 1: Circle Area Calculation
#include <stdio.h>
int main() {
const float PI = 3.1415926; // Constant for Pi (π)
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
// Calculate the area of the circle
area = PI * radius * radius;
printf("The area of the circle is: %.2f\n", area);
return 0;
}

C Input Output (I/O)


C Output
In C programming, printf() is one of the main output function. The function sends
formatted output to the screen. For example,
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;

Introduction to Programming(R23) Department of Information Technology


}
Output
C Programming
How does this program work?
 All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
 The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
 To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
 The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
Example 2: Integer Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
We use %d format specifier to print int types. Here, the %d inside the quotations
will be replaced by the value of testInteger.
C Input
In C programming, scanf() is one of the commonly used function to take input from
the user. The scanf() function reads formatted input from the standard input such as
keyboards.

Example: Integer Input/Output


#include <stdio.h>
int main()

Introduction to Programming(R23) Department of Information Technology


{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output
Enter an integer: 4
Number = 4
Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in
the testInteger variable.
Note: We have used &testInteger inside scanf(). It is because &testInteger gets the
address of testInteger, and the value entered by the user is stored in that address.
I/O Multiple Values
Here's how you can take multiple inputs from the user and display them.
#include <stdio.h>
int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
Output
Enter integer and then a float: -3

Introduction to Programming(R23) Department of Information Technology


3.4
You entered -3 and 3.400000
For
mat Specifiers for I/O
As you can see from the above examples, we use
%d for int
%f for float
%lf for double
%c for char

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

Introduction to Programming(R23) Department of Information Technology


An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
C Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the
value of an operand (constant or variable) by 1.

Introduction to Programming(R23) Department of Information Technology


Increment ++ increases the value by 1 whereas decrement -- decreases the value by
1. These two operators are unary operators, meaning they only operate on a single
operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be
used as postfixes like a++ and a--
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Example 3: Assignment Operators
// Working of assignment operators
#include <stdio.h>

Introduction to Programming(R23) Department of Information Technology


int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation
is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Example 4: Relational Operators

Introduction to Programming(R23) Department of Information Technology


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1

Introduction to Programming(R23) Department of Information Technology


5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used
in decision making in C programming.
Example 5: Logical Operators
// Working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0

Introduction to Programming(R23) Department of Information Technology


(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

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));

Introduction to Programming(R23) Department of Information Technology


return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Other operators such as ternary operator ?:


The conditional operator is a ternary operator since it requires three operands.

Expression Syntax of Conditional Operator in C

expression ? statement1 : statement2

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

Introduction to Programming(R23) Department of Information Technology


char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
// assign character value to integer variable
int number = alphabet;
printf("Integer Value: %d", number);
return 0;
}
Output
Character Value: a
Integer Value: 97
Explicit Type Conversion In C
In explicit type conversion, we manually convert values of one data type to another
type.
Example: Explicit Type Conversion
#include<stdio.h>
int main() {

// create an integer variable


int number = 97;
printf("Integer Value: %d\n", number);
// (char) converts number to character
char alphabet = (char) number;
printf("Character Value: %c", alphabet);
return 0;
}
Output
Integer Value: 97
Character Value: a
Conversion of data from larger type to smaller, there will be data loss..

Introduction to Programming(R23) Department of Information Technology


Similarly, there is a hierarchy of data types in C programming. Based on the
hierarchy, if a higher data type is converted to lower type, data is lost, and if lower
data type is converted to higher type, no data is lost.

Introduction to Programming(R23) Department of Information Technology


Difference between type casting & type conversion

Problem solving strategies:


Problem solving strategies:
What is Top-Down Approach?
In the top-down approach, a complex algorithm is broken down into smaller fragments,
better known as ‘modules.’ These modules are then further broken down into smaller
fragments until they can no longer be fragmented. This process is called
‘modularization.’
How the Top-Down Approach Works?
The working of top-down approach is as follows:
 Identify the goal or problem:
The goal or problem needs to be clearly identified and measurable.

 Break it down into sub-goals:


The sub-goals/sub-problems are what the top-up approach is all about.

Introduction to Programming(R23) Department of Information Technology


 Solve each sub-goal/sub-problem:
Using the same top-up approach, the sub-problems/sub-goals/problems are
broken down into smaller manageable parts.

 Repeat steps 2 and 3 until the overall goal/problems are resolved:


The top-up approach may involve multiple iterations.
Advantages
 Each module of code is to be tested separately.
 Breaking a problem down into smaller chunks makes it far easier to understand,
solve and manage.
 Testing and debugging are efficient and easier.
 Project implementation is smoother and shorter.
Disadvantages
 Specification tends to change over time and in a top-down approach, all decisions
made from the beginning of the project depend directly or indirectly on the high-
level specification.
 In Dynamic Programming, the top-down approach is slow as compared to the
bottom-up approach, as it involves recursion.
 It takes more memory space as it involves recursion.

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.

 Build the system or solution:


The system or solution gets its name from the fact that it is built from the
individual components/tasks.

 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.

 Repeat steps 2 and 3:


This may involve several iterations of the bottom-up approach.
Introduction to Programming(R23) Department of Information Technology
Advantages
 Test conditions are easier to create.
 Observation of test results is easier.
 Contains less redundancy due to the presence of data encapsulation and data-
hiding.
 Reusability of the code.
Disadvantages
 In the Bottom-Up approach, we solve all sub-problems (even though some of the
solutions of the subproblems aren’t needed to solve), which requires additional
calculations.
 In the Bottom-Up approach, sometimes it is difficult to identify the overall
functionality of the system in the initial stages.
 As this is an iterative approach, more code needs to be written.
 It is more difficult to implement.

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:

Introduction to Programming(R23) Department of Information Technology


Ideally, it can be applied to a range of related problems with minimal
adjustments.
9) Simplicity:
Keeping the algorithm as simple as possible while meeting its
requirements, avoiding unnecessary complexity.

Algorithm Analysis(Time and Space complexities):


Analysis of efficiency of an algorithm can be performed at two different stages,
before implementation and after implementation.
Algorithm Complexity

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.

Space Factor − The space is calculated or measured by counting the maximum


memory space required by the 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

Space complexity S(p) of any algorithm p is S(p) = A + Sp(I) Where A is treated as


the fixed part and S(I) is treated as the variable part of the algorithm which depends
on instance characteristic I. Following is a simple example that tries to explain the
concept
Algorithm
SUM(P, Q)
Step 1 - START
Step 2 - R ← P + Q + 10
Step 3 - Stop

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.

Introduction to Programming(R23) Department of Information Technology


Time Complexity

Time Complexity of an algorithm is the representation of the amount of time


required by the algorithm to execute to completion. Time requirements can be
denoted or defined as a numerical function t(N), where t(N) can be measured as the
number of steps, provided each step takes constant time.

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.

Introduction to Programming(R23) Department of Information Technology


Introduction to Programming(R23) Department of Information Technology
Introduction to Programming(R23) Department of Information Technology

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy