0% found this document useful (0 votes)
42 views13 pages

Kdu Sen

The document covers fundamental programming concepts, including basic definitions, types of programming languages, and key components such as variables, data types, expressions, control flow, functions, arrays, and object-oriented programming. It explains the role of algorithms, flowcharts, and the importance of data types in programming, along with examples in Python and C++. The document serves as a comprehensive introduction to programming, detailing how to write and manipulate code effectively.

Uploaded by

kinda0391
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)
42 views13 pages

Kdu Sen

The document covers fundamental programming concepts, including basic definitions, types of programming languages, and key components such as variables, data types, expressions, control flow, functions, arrays, and object-oriented programming. It explains the role of algorithms, flowcharts, and the importance of data types in programming, along with examples in Python and C++. The document serves as a comprehensive introduction to programming, detailing how to write and manipulate code effectively.

Uploaded by

kinda0391
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/ 13

Fundamentals of Programming

Basic Programming Concepts


What is programming?
Programs, algorithms, programming languages and translators,
Input, processing, and output

Variables and Data Types


Declaring and assigning variables
Primitive data types (integers, floats, Booleans, etc.)
Strings and string manipulation

Expressions and Operators


Arithmetic, relational, and logical operators
Operator precedence and associativity

Control Flow
Conditional statements (if-else, switch)
Loops (for, while, do-while)

Functions
Defining and calling functions
Parameters and return values

Arrays and Lists


Declaring and manipulating arrays
Common array operations (searching, sorting, etc.)

Object-Oriented Programming
Classes and objects
Encapsulation, inheritance, and polymorphism

1
Basic Programming Concepts

What is Programming?
Programming is the process of creating a set of instructions (a program) that tells a computer how
to perform a specific task.
Programs are written in programming languages, which are formal languages that have their own
syntax and semantics.
Programs are executed by a computer's processor, which interprets and carries out the instructions.

Types of Programming Languages


There are three types of programming languages
1) Machine Language
2) Low-Level Language
3) High-Level Languages

Machine Language

Machine language, also known as machine code, is the lowest-level programming language
directly understood by a computer's central processing unit (CPU). It consists of binary instructions
that represent the fundamental operations the CPU can perform, such as moving data, performing
arithmetic and logical operations, and controlling the flow of program execution.

In machine language, each instruction is represented as a sequence of 1s and 0s, which correspond
to the specific electrical signals that the CPU can interpret and execute. This binary representation
is the native language of the computer hardware, as the CPU can directly execute these instructions
without the need for any additional translation or interpretation.

Machine language is specific to the architecture and instruction set of the CPU. Different CPU
designs, such as x86 (used in most personal computers) or ARM (used in many mobile devices),
have their own unique machine language instructions. This means that a program written in
machine language for one CPU cannot be directly executed on a computer with a different CPU
architecture.

Low-Level Language e.g. Assembly Language

Assembly Language:
Assembly language is a low-level language that provides a more human-readable representation
of machine language. Each assembly language instruction corresponds to a specific machine
language instruction, but uses mnemonics (short abbreviations) instead of raw binary. Assembly
language programs are typically translated into machine language by an assembler program.
Assembly language provides a level of abstraction above machine language, making it easier for
programmers to write and understand.

2
High- Level Language
High-level programming languages are programming languages that are more abstracted from the
underlying computer hardware and provide a more human-readable and expressive syntax.
Examples of high-level programming languages include:

Java
Python
C#
JavaScript
PHP
Ruby
Swift

These languages are widely used in a variety of applications, including web development, mobile
app development, data science, machine learning, and more.

Translator
A translator is a software program that converts a program written in one programming language
(the source language) into an equivalent program in another programming language (the target
language). The role of translators is to bridge the gap between the human-readable programming
languages and the machine-readable instructions that the computer's hardware can execute.

The main types of translators used in computer programming are:

Compiler:
A compiler takes a program written in a high-level language (such as C, Java, or Python) and
translates it into an equivalent program in machine language or assembly language.
The compiled program can then be directly executed by the computer's hardware.
Compilers perform various optimizations to produce efficient machine code.

Interpreter:
An interpreter directly executes a program written in a high-level language without first generating
a complete machine-readable version. The interpreter reads and executes the program line by line,
performing the necessary translations and computations as it goes.
Interpreted languages, such as Python and JavaScript, are often more flexible and easier to use
interactively, but can be less efficient than compiled languages.

Assembler:
An assembler translates a program written in assembly language (a low-level language) into the
corresponding machine language instructions.
Assembly language provides a more human-readable representation of machine language, making
it easier for programmers to work with.

Transpiler (or source-to-source compiler):


A transpiler is a type of translator that converts a program written in one high-level language into
an equivalent program in another high-level language.

3
This is often used to convert code between similar languages, such as from TypeScript to
JavaScript or from Coffee Script to JavaScript.

Algorithm
An algorithm is a step-by-step procedure or a set of instructions designed to solve a specific
problem or perform a specific computation. It is a fundamental concept in computer science and
is used in various fields, including mathematics, engineering, and software development.
Algorithms are a fundamental building block of computer programming and are used to solve a
wide range of problems.

Properties/Features of an algorithm are:

Definiteness:
An algorithm must have a clear and unambiguous set of instructions that can be followed to
solve the problem.

Finiteness:
An algorithm must terminate after a finite number of steps, providing a solution or indicating
that a solution is not possible.

Input:
An algorithm typically takes one or more inputs, which are the initial data or values required
to start the computation.

Output:
An algorithm must produce one or more outputs, which are the results or solutions obtained
after the computation is complete.

Effectiveness:
An algorithm must be able to solve the problem correctly and efficiently, without wasting
resources such as time or memory.

Algorithms can be represented in various forms, including:

Pseudocode: A high-level, human-readable description of the algorithm, using a combination of


natural language and programming language constructs.
Flowcharts: A visual representation of the algorithm using shapes and arrows to depict the flow
of execution.
Programming languages: Algorithms can be implemented using programming languages, such
as Python, Java, or C++, providing a more formal and executable specification.

An algorithm is a step-by-step procedure for solving a problem.


Algorithms can be represented using pseudocode, flowcharts, or other visual representations. Good
algorithm design is essential for creating efficient and effective programs.

4
Definition of flowchart

A flowchart is a visual representation of a process or algorithm, using a set of standardized


symbols to depict the various steps and their logical flow. Flowcharts are widely used in various
fields, such as business, programming, and project management, to help understand, analyze, and
communicate complex processes.

The main symbols used in a flowchart are:

1. Terminal/Start/End Symbol: Typically represented by a rectangle with rounded


corners, it indicates the beginning or end of the process.
2. Process Symbol: Represented by a rectangle, it denotes a step or an action within the
process.
3. Decision Symbol: Represented by a diamond shape, it indicates a decision point where
the flow of the process branches based on a certain condition.
4. Connector Symbol: Represented by a circle, it is used to connect different parts of the
flowchart when the process flow cannot be shown continuously on a single page.
5. Input/Output Symbol: Represented by a parallelogram, it is used to indicate data input
or output.
6. Predefined Process Symbol: Represented by a rectangle with double-vertical lines on
the sides, it is used to indicate a predefined process or a subprocess.
7. Data Storage Symbol: Represented by a cylinder, it is used to indicate the storage of
data.

Variable and data types

Variables and data types are fundamental concepts in programming.

Variables:
A variable is a named storage location in a computer's memory that can hold a value. Variables are
used to store and manipulate data within a program. The value stored in a variable can be changed
during the execution of the program.

The process of creating a variable is called variable declaration. The general syntax for declaring
a variable is:

Data-type variable-name;

Data-type specifies the type of data that can be stored in the variable, and variable-name is the
unique identifier for the variable.

5
Data Types:
Data types are classifications that define the type of data that a variable can hold. Different
programming languages have different sets of data types, but the most common ones are:

Numeric Data Types:


Integers (int): Whole numbers, such as 0, 1, -10, 123.
Floating-point (float): Numbers with decimal points, such as 3.14, -2.5, 0.0001.
Double: A larger floating-point type that can store more precise decimal values.

Character Data Types:


Characters (char): A single character, such as 'A', 'x', '9', or '!'.
Strings (string): A sequence of characters, such as "Hello, world!" or "John Doe".

Boolean Data Types:


Boolean (bool): A logical data type that can have only two values: true or false.

Other Data Types:


Void: A special data type that indicates the absence of a value.
Enumerations (enum): User-defined data types that consist of a set of named constants.
Pointers: Variables that store memory addresses.

The choice of data type depends on the specific requirements of the program and the amount of
memory needed to store the data.

Here's an example of declaring and using variables in a programming language (in this case, C++):

#include <iostream>
using namespace std;

int main() {
// Declaring variables
int age = 25;
float pi = 3.14159;
char grade = 'A';
string name = "John Doe";
bool isStudent = true;

// Printing the values of the variables


cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
cout << "PI: " << pi << endl;
cout << "Is Student: " << isStudent << endl;

return 0;
}

6
In this example, we have declared variables of different data types (int, float, char, string,
and bool) and assigned values to them. We then print the values of these variables using the
cout statement.

Understanding variables and data types is crucial for writing efficient and effective programs.
They allow you to store, manipulate, and work with data in a systematic and organized manner.

Variable and data-type declaration in Python

Variable-name = value

age = 25
pi = 3.14159
name = "John Doe"
is-student = True

In this example, we've declared four variables: age, pi, name, and is_student.

Data Types in Python:


Python is a dynamically-typed language, which means you don't need to explicitly declare the
data type of a variable. Python will automatically infer the data type based on the value assigned
to the variable.

Common data types in Python:

1. Numeric Data Types:


o Integers (int): Whole numbers, such as 0, 1, -10, 123.
o Floating-point (float): Numbers with decimal points, such as 3.14, -2.5, 0.0001.
2. Character Data Types:
o Strings (str): A sequence of characters, such as "Hello, world!" or "John Doe".
3. Boolean Data Types:
o Boolean (bool): A logical data type that can have only two values: True or
False.
4. Other Data Types:
o Lists: Ordered collections of items, such as [1, 2, 3] or ["apple", "banana",
"cherry"].
o Tuples: Immutable (unchangeable) ordered collections of items, such as (1, 2,
3) or ("apple", "banana", "cherry").
o Dictionaries (dict): Key-value pairs, such as {"name": "John Doe", "age":
25}.

7
Example of using different data types in Python

age = 25
pi = 3.14159
name = "John Doe"
is-student = True
fruits = ["apple", "banana", "cherry"]
person = {"name": "John Doe", "age": 25}

In this example, we've declared variables of different data types: int for age, float for pi,

step-by-step guide on how to start using Python:

1. Install Python:
o Visit the official Python website (https://www.python.org/) and download the
latest version of Python for your operating system (Windows, macOS, or Linux).
o Follow the installation instructions specific to your operating system.
o Make sure to check the "Add Python to PATH" option during the installation
process, which will allow you to run Python from any directory in your
terminal/command prompt.
2. Verify the Installation:
o Open your terminal/command prompt and type python --version or python3 -
-version (depending on your system) to check if Python is installed correctly.
o You should see the installed version number displayed.
3. Explore the Python Interpreter:
o The Python interpreter is a tool that allows you to write and execute Python code
interactively.
o To start the Python interpreter, simply type python or python3 in your
terminal/command prompt.
o You should see the Python prompt >>>, which indicates that you can start typing
and executing Python code.
o Try typing a simple expression, like 2 + 2, and press Enter. The interpreter will
immediately evaluate the expression and display the result.
4. Write and Run Python Scripts:
o Create a new file with a .py extension (e.g., my_script.py) using a text editor or
an Integrated Development Environment (IDE) like Visual Studio Code,
PyCharm, or Spyder.
o In this file, write some Python code, such as:

print("Hello, World!")

Save the file and return to your terminal/command prompt.

To run the script, type python my_script.py (replace my_script.py with the name of your file).

8
The output "Hello, World!" should be displayed in the terminal.

Strings and Strings and manipulations

Strings are one of the fundamental data types in Python, and they are used to represent text.
Here's an overview of strings and string manipulation in Python:

1. Declaring Strings:
o Strings can be declared using single quotes ', double quotes ", or triple quotes
''' or """.
o Example: my_string = "Hello, World!", another_string = 'Python is
awesome!'
2. String Indexing and Slicing:
o Strings are sequences of characters, and each character has an index.
o You can access individual characters using their index, starting from 0.
o Example: my_string[0] returns 'H', my_string[6] returns 'W'.
o You can also slice a string to get a subset of characters.
o Example: my_string[0:5] returns 'Hello', my_string[7:] returns 'World!'.
3. String Concatenation:
o You can combine strings using the + operator.
o Example: greeting = "Hello, " + "World!" results in "Hello, World!".
4. String Formatting:
o There are several ways to format strings in Python, such as using the .format()
method or f-strings (introduced in Python 3.6).
o Example using .format(): "My name is {} and I'm {} years
old.".format("John", 25)
o Example using f-strings: f"My name is {name} and I'm {age} years old."
5. String Methods:
o Python provides a wide range of string methods to manipulate and operate on
strings.
o Some common methods include upper(), lower(), strip(), replace(),
split(), join(), and more.
o Example: my_string.upper() returns "HELLO, WORLD!",
my_string.replace("World", "Python") returns "Hello, Python!".
6. String Immutability:
o Strings in Python are immutable, which means you cannot change individual
characters within a string.
o If you need to modify a string, you can create a new string with the desired
changes.

9
Expressions and Operators

Expressions and operators are fundamental building blocks of programming languages, allowing
you to perform various operations, make decisions, and manipulate data as part of your code.

Expressions:
An expression is a combination of values, variables, operators, and function calls that evaluates
to a single value. Expressions are used to perform calculations, make decisions, and manipulate
data. Some examples of expressions include:

• x + y
• (a * b) / c
• "Hello" + " " + "world"
• Math.sqrt(25)

Expressions can be simple, like a single variable or value, or more complex, involving multiple
operators and operands.

Operators:
Operators are symbols or keywords that perform specific operations on one or more operands
(values or variables) and produce a result. Some common types of operators include:

1. Arithmetic Operators: Used for mathematical operations, such as addition (+),


subtraction (-), multiplication (*), division (/), and modulus (%).
2. Assignment Operators: Used to assign values to variables, like the basic = operator, as
well as combined assignment operators like +=, -=, *=, /=, and %=.
3. Comparison Operators: Used to compare values and produce a boolean result (true or
false), such as ==, !=, >, <, >=, and <=.
4. Logical Operators: Used to combine or manipulate boolean values, including && (and),
|| (or), and ! (not).
5. Bitwise Operators: Used to perform operations on the individual bits of a number, such
as & (and), | (or), ^ (xor), ~ (not), << (left shift), and >> (right shift).
6. Ternary Operator: A shorthand way of writing an if-else statement, using the syntax
condition ? valueIfTrue : valueIfFalse.
7. Special Operators: Such as the new operator for creating objects, the typeof operator
for getting the type of a value, and the () operator for function calls.

Operator precedence

Operator precedence is the order in which operators are evaluated in an expression. It determines
the sequence in which operations are performed when multiple operators are present in an
expression.

10
In programming languages, there is a well-defined hierarchy of operator precedence that follows
the mathematical convention. The general order of precedence, from highest to lowest, is as
follows:

1. Parentheses: ()
2. Unary operators: ++, --, +, -, !, ~
3. Exponentiation: **
4. Multiplication, Division, Modulus: *, /, %
5. Addition, Subtraction: +, -
6. Bitwise Shift Operators: <<, >>, >>>
7. Relational Operators: <, >, <=, >=, in, instanceof
8. Equality Operators: ==, !=, ===, !==
9. Bitwise AND: &
10. Bitwise XOR: ^
11. Bitwise OR: |
12. Logical AND: &&
13. Logical OR: ||
14. Conditional (ternary) Operator: ?:
15. Assignment Operators: =, +=, -=, *=, /=, %=, **=, <<=, >>=, >>>=, &=, ^=, |=
16. Comma Operator: ,

This order of precedence ensures that operations with higher precedence are performed first,
before operations with lower precedence. You can use parentheses to override the default
precedence and explicitly control the order of operations.

Examples

3+4*2–1

Without considering precedence, this expression might be evaluated from left to right, resulting
in (3 + 4) * 2 - 1 = 7 * 2 - 1 = 13. However, due to operator precedence, the expression
is evaluated as follows:

1. Multiplication: 4 * 2 = 8
2. Addition: 3 + 8 = 11
3. Subtraction: 11 - 1 = 10

So, the final result of the expression is 10.

11
More examples of operator precedence in different programming languages.

Python:

# Example 1

print(3 + 4 * 2) # Output: 11

# Example 2

print((3 + 4) * 2) # Output: 14

# Example 3

print(2 ** 3 * 4) # Output: 32 (2^3 = 8, then 8 * 4)

# Example 4

print(not True and False) # Output: False (not has higher precedence than and)

C++

// Example 1

std::cout << 3 + 4 * 2 << std::endl; // Output: 11

// Example 2

std::cout << (3 + 4) * 2 << std::endl; // Output: 14

// Example 3

std::cout << pow(2, 3) * 4 << std::endl; // Output: 32 (2^3 = 8, then 8 * 4)

// Example 4

std::cout << !true && false << std::endl; // Output: 0 (false)

12
Java

// Example 1

System.out.println(3 + 4 * 2); // Output: 11

// Example 2

System.out.println((3 + 4) * 2); // Output: 14

// Example 3

System.out.println(Math.pow(2, 3) * 4); // Output: 32.0 (2^3 = 8, then 8 * 4)

// Example 4

System.out.println(!true && false); // Output: false (! has higher precedence than &&)

13

You might also like