KEMBAR78
Faiz | PDF | Algorithms | Computer Programming
0% found this document useful (0 votes)
26 views68 pages

Faiz

Uploaded by

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

Faiz

Uploaded by

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

UNIT ONE

FUNDAMENTALS OF PROGRAMMING
CONTENT

Concepts of algorithm, Flow chart Basics of Computer Languages, Compilers, Interpreter,

Structured, modular, Bottom-up,


top-down, procedural, OOP
•Programming features:
Programming Environments and Types of errors and debugging •Data types, Expressions and Operators-
Program design techniques:
Debugging: techniques. Arithmetic, unary, logical, bitwise,
relational, assignment, comma operators.
•Data conversions. Input/Output
statements.
Concepts of algorithm

• An algorithm is a systematic approach to problem-solving, involving


logical steps to arrive at a solution. Whether addressing mathematical
or computer-related issues, developing an algorithm is the initial
phase of problem-solving. It encompasses calculations, reasoning,
and data processing, and can be expressed through various means
such as natural languages, pseudocode, or flowcharts.
Use of Algorithm
• Computer Science: They underpin computer programming, addressing
tasks from basic sorting to complex endeavors like artificial intelligence.
• Mathematics: Algorithms solve mathematical problems, optimizing
solutions for linear equations or determining the shortest path in a graph.
• Operations Research: Algorithms optimize decisions in areas like
transportation, logistics, and resource allocation.
• Artificial Intelligence: Serving as the foundation, algorithms power
artificial intelligence and machine learning for tasks like image recognition
and decision-making.
• Data Science: In fields like marketing and healthcare, algorithms analyze
vast datasets, extracting valuable insights.
Flowchart

• Is the graphical or pictorial representation of an algorithm with the

help of different symbols, shapes, and arrows to demonstrate a process

or a program. With algorithms, we can easily understand a program.


Symbols in a
flowchart
Algorithm
and
Flowchart
• If you compare a
flowchart to a movie, then
an algorithm is the story
of that movie. In other
words, an algorithm is
the core of a flowchart.
• Computer languages:
Computer languages are formal systems
designed to communicate instructions to a
computer. They enable humans to write code
Basics of that computers can understand and execute.
Computer • Importance in programming:
Languages Essential for software development, computer
languages serve as the foundation for creating
applications, websites, and various software
solutions.
Like Python, Java, C and C++
Types of Computer Languages
• High-level languages: These languages are more abstract, making
them easier for humans to understand and write. Examples include
Python, Java, C++ and C#.
• Low-level languages: Closer to machine language, low-level
languages like Assembly , C and Machine Code provide more direct
control over hardware.
• Scripting languages: Interpreted languages like JavaScript and PHP
are often used for automating tasks and enhancing web development.
High-Level Languages
• Characteristics: High-level languages are designed for readability
and ease of use. They abstract complex operations, making it simpler
for programmers to express ideas.
• Examples: Python for its readability, Java for its portability, and C#
for its integration with Microsoft technologies.
• Use cases: High-level languages are commonly used in a wide range
of applications, from web development to artificial intelligence.
Low-Level Languages
Characteristics: Low-level languages offer more direct control over hardware, making them
suitable for system-level programming.

Examples: C language as a bridge between high-level languages and machine code, and
Machine Code as the binary representation understood by the computer's central processing
unit (CPU).
Role in system-level programming:

Low-level languages are crucial for tasks that require precise control over hardware resources.
Scripting Languages
Characteristics:

Scripting languages are often interpreted, allowing for quick development and testing. They are
commonly used for automating repetitive tasks.
Examples:

JavaScript for its role in web development, Ruby for its simplicity, and PHP for server-side scripting.

Applications:

Scripting languages are integral to web development, automation, and the creation of dynamic
content.
Choosing the Right Language

Factors to consider: The importance of considering project requirements, performance


needs, and ease of development when selecting a programming language.

Overview of popular languages:

Languages like Python for its versatility, Java for its platform independence, and C++ for
performance-critical applications.
• Explore and learn:

Explore different languages based on their project needs and interests.


• Compilers and interpreters share the task of
translating High-Level Language (HLL) source

Compilers and code into machine code understandable by

Interpreter computers. Typically, computer programs are


written in HLL for human comprehension, but to
make them readable for computers, they must
be converted into machine language.
Con’t…

• A Compiler serves as a translator, converting High-Level Language


input into low-level language, such as machine or assembly language.
Its primary function is to transform programming language codes into
machine code (represented in 0s and 1s) for computer
comprehension.
Interpreter
• An interpreter is a program that translates a programming
language into a comprehensible language. The interpreter
converts high-level language to an intermediate language. An
Interpreter works line by line on a code.
Get Started With C

To start using C, you need two things:

• A text editor, like Notepad or Integrated Development


Environment(IDE) like Code::Block, VS Code to write C
code

• A compiler, like GCC, to translate the C code into a


language that the computer will understand.
Start first Program in C
• Let's create our first C file.
• Open VS Code and go to File > New > Empty File.
• Write the following C code and save the file as:
Example explained

Line 1: #include <stdio.h> is a header file library that lets us


work with input and output functions, such as printf()
(used in line 4). Header files add functionality to C
programs.
Con’t…
• Line 2: A blank line. C ignores white space. But we use it to
make the code more readable.
• Line 3: Another thing that always appear in a C program,
is main() This is called a function. Any code inside its curly
brackets {} will be executed.
• Line 4: the printf() is a function used to output/print text to the
screen. In our example it will output “I will be the best
programmer”.
Every C statement ends with
a semicolon ;
Con’t…

• Line 5: return 0 ends the main() function.

• Line 6: Do not forget to add the closing curly bracket }


to end the main function.
Variables
• Are containers for storing data values, like numbers and
characters.
• In C, there are different types of variables (defined
with different keywords), for example:
• int: stores integers (whole numbers), without decimals,
such as 123 -123
• float: - stores floating point numbers, with decimals,
such as 19.99 or -19.99
• char: - stores single characters, such as ‘a’ or ‘b’ single
quote.
Declaring Variable
• type variableName = value;

• int num = 10;

• int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
• The data type specifies the size and type of
C Data Types information the variable will store.
Basic Format Specifiers
Exercise
C Decimal Precision
• float myFloatNum = 3.5;
double myDoubleNum = 19.99;
printf("%f\n", myFloatNum); // Outputs 3.500000
printf("%lf", myDoubleNum); // Outputs 19.990000

• float myFloatNum = 3.5;


printf("%f\n", myFloatNum); // Default will show 6 digits
• printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
Exercise: • Make the output of the following example to
only show one digit after the decimal point:
Real time example
• // Create variables of different data types
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';
// Print the outputs
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
Type Conversion
• if you try to divide two integers, 5 by 2 you would
expect the result to be 2.5 But since we are working
with integers (and not floating-point values), the
following example will just output 2:
• int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2


There are two types of conversion
• Implicit Conversion (automatically)

• Explicit Conversion (manually)


Implicit Conversion
• Implicit conversion is done automatically by the
compiler when you assign a value of one type to
another.
• For example, if you assign an int value to a float.
• // Automatic conversion:
float myFloat = 9;

printf("%f", myFloat); // 9.000000


Explicit Conversion
• Explicit conversion is done manually by placing the type
in parentheses () in front of the value.

• // Manual conversion: int to float


float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000


You can also place the type in front of a variable

int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000


Constants
• If you don't want anyone to change existing variable values,
you can use the const keyword.

• const int myNum = 15; // myNum will always be 15

myNum = 10; // error

const int minutesPerHour = 60;

const float PI = 3.14;


Operators
• Operators are used to perform operations on variables
and values.

int sum1 = 100 + 50;


int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
Operators Groups

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators
Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.
Assignment Operators
• Assignment operators are used to assign values to
variables.
• int x = 10;

• int x = 10;
x += 5;
A list of all assignment operators
Comparison Operators

• Comparison operators are used to compare two values.

• This is important in programming, it helps us to find


answers and make decisions.

• The return value of a comparison is either 1 or 0 or true


and false.
A list of all comparison operators
Logical • Logical operators are used to determine the
logic between variables or values:
Operators
Programming Environments
and Debugging Overview

• Introduction:
• Programming environments and debugging are integral
aspects of software development.
• A conducive programming environment and effective
debugging practices are crucial for writing high-quality,
error-free code.
• Importance:
• A well-configured programming environment enhances
developer productivity.
• Debugging ensures the identification and resolution of
issues, leading to reliable software.
In programming, errors can be broadly
categorized into three main types:
1. Syntax errors,

Error 2. Runtime errors


3. Logical errors.
Debugging is the process of identifying and
fixing these errors to ensure that the program
behaves as intended.
Types of error and techniques
• 1. Syntax Errors:
Syntax errors occur when the code violates the rules of the
programming language.
• Indicators:
• Typically detected by the compiler or interpreter during the compilation or
execution phase.
• Often accompanied by error messages pointing to the line and location of the
syntax issue.
Debugging Techniques

Carefully review the Check for missing or


error messages misplaced
provided by the punctuation, incorrect
compiler or keywords, or other
interpreter. syntax violations.
2. Runtime Errors
• Runtime errors occur during the
execution of the program and are often
related to issues like division by zero,
incorrect data types, or undefined
variables.
• Indicators:
• The program crashes or terminates
unexpectedly.
• Runtime error messages may provide
information about the nature of the issue.
Debugging Techniques

1 2 3
Use print statements to Employ exception Utilize debugging tools to
trace the flow of the handling (try, except step through the code
program and identify the blocks) to catch and and inspect variable
point of failure. handle specific types of values during runtime.
errors.
• Logical errors do not result in syntax or
runtime errors, but they cause the program
to produce incorrect or unexpected outputs.
Logical • Indicators:
Errors • The program runs without error messages, but
the output is not as expected.
• Review the program's logic and algorithms to
identify discrepancies.
• Use print statements strategically to output
Debugging intermediate values and verify calculations.
• Employ systematic testing and code review to
Techniques catch logical errors early in the development
process.
Print Debugger Code
Logging
Statements Tools Review

Common • Insert print • Use integrated • Implement


statements at development logging to
• Conduct
thorough code
key points in environment record reviews with
Debugging the code to
display
(IDE)
debuggers to
information
about the
peers
identify
to

Techniques variable values


and trace the
program's
step through
the code, set
breakpoints,
program's
execution,
making it
potential
errors,
especially
execution. and inspect easier to logical ones.
variables. analyze issues.
5. Unit Testing:
Write and run unit tests to ensure that individual
components of the code behave as expected.
6. Pair Programming:
Collaborate with a colleague in pair programming
Con’t… to catch errors and share insights.

Debugging is an essential skill for


programmers, and the ability to troubleshoot
effectively is crucial for building robust and
reliable software.
• Effective program design is crucial for
Program creating maintainable and scalable software.
Design • Well-designed programs are easier to
understand, modify, and extend.
Techniques
• Structured Programming:
A programming paradigm aimed at improving the
clarity, quality, and development time of a
computer program.
Example: Using control structures like sequences,
Structured selections, and iterations.
if condition:
Programming # code block
else:
# code block
Modular Design Definition: Breaking down a
program into smaller, manageable, and
Modular independent modules.
Design Example: Creating separate modules for input
processing, data manipulation, and output
generation.
Example
# Module 1: Input processing
def process_input(data):
# code block
# Module 2: Data manipulation
def manipulate_data(data):
# code block
# Module 3: Output generation
def generate_output(data):
# code block
Bottom-Up Approach
• Building the system from simple
components to more complex ones.

• Example: Developing individual


functions or modules before
integrating them into the main
program.
Example
# Function 1
def simple_function():
# code block

# Function 2
def complex_function():
simple_function()
# additional code block
Top-Down Approach
• Starting with the main program and breaking it into
smaller modules.

• Example: Defining the main program structure and


then implementing each module.
Example
# Main Program
def main_program():
module_1()
module_2()

# Module 1
def module_1():
# code block
# Module 2
def module_2():
# code block
• Procedural Programming:
Organizing code as procedures or functions.
• Example: Defining procedures for specific tasks.

# Procedure 1
Procedural def procedure_1():
# code block
Programming # Procedure 2
• def procedure_2():
• # code block
Object-Oriented
Programming (OOP)
OOP Definition: Organizing code around objects

that encapsulate data and behavior.

• Example : Defining classes and objects.


// Class definition
class Animal {
public:
Animal(std::string name) : name(name) {}
void make_sound() {
// code block
Example }
private:
std::string name;
};
// Object instantiation
Animal cat("Cat");
END UNIT ONE

You might also like