Computer Programs and Programming Languages
A computer program is a set of instructions that, when executed, makes the
computer perform specific actions.
Without programs, computers are unable to function.
Computers do not understand natural human languages, such as English or Nepali
directly.
To communicate tasks to a computer, we use languages it can interpret, known as
programming languages.
What is a programming language?
A programming language is a formal language comprising a set of instructions that
can be used to produce various kinds of output, primarily to instruct a computer on
how to perform specific tasks.
It provides a structured way to communicate with computers, allowing developers
to write commands that can be understood and executed by the computer’s
hardware or by other programs.
Programming languages are designed with syntax (rules for structure) and
semantics (meaning of statements) that help in expressing logical sequences,
calculations, data processing, and more.
They vary in abstraction, with some languages closely mirroring machine code
(low-level languages) and others that are more human-readable (high-level
languages). Examples include Python, Java, C++, and JavaScript, each suited to
different types of tasks, such as web development, data analysis, system
programming, and artificial intelligence.
Types or Levels of Programming Languages
Programming languages are commonly classified into two main categories:
1. Low-Level Languages
These languages are closer to machine code and are more challenging for
humans to read but are faster for the computer to execute.
Low-level languages include:
- Machine Language: The most basic language, consisting of binary code (0s
and 1s) that the computer's hardware can directly interpret.
- Assembly Language: A step above machine language, using symbolic
representations of machine code instructions. It is specific to each type of
processor.
2. High-Level Languages
High-level languages are easier for humans to read and write as they are closer to
natural language.
These languages need to be compiled or interpreted into machine code for the
computer to execute.
Examples include:
- Procedural Languages: Languages such as C and Pascal, where programs are
structured into procedures or functions.
- Object-Oriented Languages: Languages like Java and Python, which use
objects and classes to model real-world entities.
- Scripting Languages: Languages like JavaScript and PHP, often used for
automating tasks in applications or on web pages.
- Functional Languages: Languages such as Haskell and Lisp, emphasizing
functions and avoiding changing state and mutable data.
Each programming language type serves different purposes and is chosen based on
factors such as ease of use, efficiency, and the nature of the tasks to be performed.
Problem Solving with Computers
Problem solving with computers involves breaking down complex tasks into
smaller, manageable steps that a computer can execute.
The process generally includes the following stages:
1. Problem Definition
Clearly define the problem and understand what needs to be solved. This
includes identifying the inputs, expected outputs, and any constraints.
2. Planning the Solution
Develop a strategy or algorithm to solve the problem. This may involve breaking
the problem into smaller sub-problems, deciding on the steps required, and
choosing the most efficient approach.
3. Designing the Algorithm
Write a step-by-step plan, or algorithm, that outlines how to reach the solution.
Algorithms are often represented through pseudocode or flowcharts to help
visualize the logical flow.
4. Coding the Solution
Translate the algorithm into a programming language that the computer can
understand. This step requires knowledge of syntax and features of the chosen
language, such as Python, Java, or C++.
5. Testing and Debugging
Run the program with various inputs to verify it works as expected. During this
step, errors or "bugs" are identified and corrected to ensure accuracy and
efficiency.
6. Evaluation and Optimization
Assess the solution’s effectiveness and optimize it if necessary. This can include
refining the code to improve performance, reduce resource usage, or make the code
more readable and maintainable.
7. Documentation and Maintenance
Document the code to make it understandable for future users or developers.
Maintenance involves updating the code as new requirements or issues arise.
This systematic approach helps in efficiently solving problems, allowing
computers to handle tasks ranging from simple calculations to complex data
processing and artificial intelligence.
Example of Problem Solving
Problem: Find the Largest of Three Numbers
Steps:
1. Problem Definition
Input: Three integers.
Output: The largest integer among the three.
Constraints: The numbers could be positive, negative, or zero.
2. Planning the Solution
Compare the three numbers using conditional statements (if-else) to
determine the largest.
3. Designing the Algorithm
o Input three numbers.
o Compare the first number with the second and third.
o If it’s greater than or equal to both, it’s the largest.
o Repeat similar comparisons for the second and third numbers.
o Output the largest number.
4. Coding the Solution
#include <stdio.h> // Include the standard I/O library
int main() {
int num1, num2, num3, largest; // Declare variables
// Input: Read three numbers from the user
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter the third number: ");
scanf("%d", &num3);
// Processing: Determine the largest number
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
// Output: Display the largest number
printf("The largest number is: %d\n", largest);
return 0; // Indicate successful program execution
}
5. Testing and Debugging
o Test cases:
Inputs: 10, 20, 30 → Output: 30
Inputs: -5, -2, -10 → Output: -2
Inputs: 7, 7, 7 → Output: 7
Check behavior with edge cases like zeros and negatives.
6. Evaluation and Optimization
The program is efficient, as it uses simple comparisons.
7. Documentation and Maintenance
Add comments for clarity and ensure the code handles any future changes,
such as modifying it to find the largest among more numbers.
Example Run
Input:
Enter the first number: 15
Enter the second number: 42
Enter the third number: 8
Output:
The largest number is: 42
This program demonstrates breaking down the problem-solving process into
manageable steps, highlighting a practical approach to computational thinking.
Problem Analysis
Problem analysis is the process of breaking down and thoroughly understanding a
problem before attempting to solve it.
It’s a crucial step in problem solving, especially when working with computers, as
it ensures that the solution is well-planned, accurate, and efficient.
The key aspects of problem analysis include:
It helps in clarifying the goals, identifying the constraints, and recognizing the
requirements for an effective solution. Key steps in problem analysis include:
1. Understand the Problem
Begin by comprehensively understanding what the problem is. This involves
asking questions to uncover the nature of the problem, the root cause, and what
specifically needs to be achieved.
Begin by clearly defining what the problem is. Ask questions like:
What exactly needs to be solved?
What are the goals and desired outcomes?
Are there any specific requirements or constraints?
2. Identify Requirements and Constraints
Determine any specific requirements or constraints associated with the problem.
These could be resource limitations, time constraints, budget considerations, or
technical specifications that the solution must meet.
3. Define Inputs and Outputs
Clearly define what inputs are available and what outputs are expected. Inputs
could include data, parameters, or conditions that affect the solution. The output is
the desired result or outcome of solving the problem.
What data is provided and what is expected as the result?
4. Break Down the Problem
Divide the main problem into smaller, more manageable parts. This
decomposition helps in focusing on each component individually, making complex
problems easier to understand and solve.
5. Analyze Feasibility
Assess whether the problem is solvable within the given constraints, and whether
the available resources and tools are adequate for achieving a solution.
6. Determine the Scope
Define the boundaries of the problem to avoid addressing issues that fall outside
the scope of the intended solution. This helps in focusing only on the relevant parts
and prevents unnecessary complexity.
7. Identify Potential Challenges
Recognize any obstacles or difficulties that might arise in the problem-solving
process, such as data limitations, technical difficulties, or unforeseen variables.
Problem analysis is essential because it lays a strong foundation for developing an
effective solution. By thoroughly analyzing the problem, you gain a clear roadmap,
minimize errors, and improve the efficiency of the overall solution process.
Plan a solution: Think about how you can process the data to achieve the result.
Example of Problem Analysis
Problem: Write a program to calculate the area of a rectangle given its length and
width.
Steps for Problem Solving:
1. Understand the Problem:
o The task is to compute the area of a rectangle.
o Inputs: Length and width of the rectangle.
o Output: Area of the rectangle.
2. Identify Requirements and Constraints:
o The program should accept positive numbers for length and width.
o The formula for the area is: Area=Length×Width
3. Define Inputs and Outputs:
o Input: Length and width (floating-point values).
o Output: Area (floating-point value).
4. Break Down the Problem:
o Take inputs from the user.
o Calculate the area using the formula.
o Display the result.
Code Implementation
#include <stdio.h>
int main() {
// Step 1: Define variables
float length, width, area;
// Step 2: Get inputs
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
// Step 3: Validate inputs (Optional for basic example)
if (length <= 0 || width <= 0) {
printf("Length and width must be positive numbers.\n");
return 1; // Exit the program with an error code
}
// Step 4: Calculate the area
area = length * width;
// Step 5: Display the result
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
Explanation of the Code
1. Input Handling:
The program uses scanf to take the length and width as input from the user.
2. Validation:
Ensures the inputs are positive. If not, an error message is displayed, and the
program exits.
3. Computation:
Uses the formula area = length * width to calculate the area.
4. Output:
Displays the computed area with two decimal places for readability.
Sample Output
Case 1: Valid Input
Enter the length of the rectangle: 5.5
Enter the width of the rectangle: 3.2
The area of the rectangle is: 17.60
Case 2: Invalid Input
Enter the length of the rectangle: -5
Enter the width of the rectangle: 4
Length and width must be positive numbers.
This basic program demonstrates how the problem-solving process is applied in C
programming.
Summary
Problem Analysis prepares you to solve the problem efficiently by
clarifying its requirements and scope.
Problem Solving is the action of designing and implementing the solution
based on the analysis.
Difference Between Problem Solving and Problem Analysis
Aspect Problem Analysis Problem Solving
The process of understanding the problem, The process of devising and
Defini on breaking it down, and iden fying its key implemen ng a solu on to resolve the
components. problem.
Focuses on comprehending the nature of the Focuses on designing and applying a
Focus
problem, its causes, and constraints. strategy to achieve a desired outcome.
To gain clarity about the problem, its To find an effec ve, efficient, and
Goal
requirements, and possible challenges. feasible solu on to the problem.
- Understanding the problem - Planning a solu on
Steps
- Iden fying inputs, outputs, and constraints - Implemen ng the solu on
Involved
- Breaking the problem into smaller parts - Tes ng and refining the solu on
Techniques like brainstorming, root cause Algorithms, coding, mathema cal
Tools Used
analysis, or requirement gathering. modeling, or specific so ware tools.
Happens a er the problem is analyzed
Timing Happens before a emp ng to solve the problem.
and understood.
A well-defined problem statement, clear
Outcome A working solu on to the problem.
requirements, and scope.
Algorithm and Flowchart
Once the problem is understood, the next step is to devise a solution. This is
typically done using an algorithm and/or flowchart.
- Algorithm:
A step-by-step procedure or set of rules designed to solve a specific problem or
perform a task.
It breaks down complex problems into individual, manageable steps that can be
executed in sequence to achieve a desired outcome.
Algorithms are central to computer science, enabling efficient problem-solving,
data processing, and the execution of complex operations in software.
It must be:
- Unambiguous
- Finite (should terminate after a finite number of steps)
- Effective (the steps must be executable)
Key Properties and Characteristics of an Algorithm
1. Clear and Unambiguous
Each step in the algorithm must be precise, with no ambiguity, so that the
instructions are easily understood and followed.
2. Definite Inputs and Outputs
An algorithm specifies the data (inputs) it needs to process and what it will
produce (outputs). This clarity helps in understanding the purpose of the algorithm
and the results it will generate.
3. Finiteness
An algorithm must have a limited number of steps, ensuring it eventually
terminates and produces a result rather than running indefinitely.
4. Effectiveness
Each step should be simple, achievable, and capable of being carried out within a
finite amount of time.
5. Generality
The algorithm should apply to a broad range of inputs within the scope of the
problem, not just a single case, making it reusable and versatile.
An algorithm that finds the sum of two numbers:
1. Start
2. Input the numbers A and B
3. Compute the sum S = A + B
4. Output the result S
5. End
An algorithm to find the average of three numbers:
1. Start
2. Read the three numbers: a, b, and c.
3. Compute the sum of a, b, and c.
4. Divide the sum by 3 to find the average.
5. Store the result in a variable d.
6. Print the value of d (the average).
7. End
This simple algorithm calculates the average by taking three steps after inputting
the numbers: summing, dividing by the total count (3), and outputting the result.
An algorithm to find the largest number in a list:
1. Start with a list of numbers.
2. Initialize the first number as the maximum.
3. Compare this maximum with each subsequent number in the list.
4. Update the maximum if a larger number is found.
5. Repeat until all numbers have been checked.
6. Output the maximum number found.
An algorithm to find the greatest among three numbers A, B, and C:
1. Start
2. Read three numbers: A, B, and C.
3. If A > B, then go to Step 6.
4. If B > C, then print "B is greatest" and go to Step 8.
5. Print "C is greatest" and go to Step 8.
6. If A > C, then print "A is greatest" and go to Step 8.
7. Print "C is greatest."
8. End
An algorithm to Check if a Number is Prime
1. Start
2. Read integer A from the user.
3. If 𝐴≤ 1, print "Not a prime number" and go to Step 6.
4. For i = 2 to A-1:
- If A mod i = 0, then print "Not a prime number" and go to Step 6.
5. If no divisors are found, print "Prime number."
6. End
Notes:
Optimization Opportunity: Instead of iterating to A−1, you can check up
to √A, as no divisors greater than √A (square root of A) need to be checked.
Steps for A=2
1. Input: A=2
2. Loop Range: The loop in Step 4 runs from i = 2 to A−1 i.e., i=2 to 1.
o Since the starting point (i=2) is greater than the end point (A−1=1),
the loop does not execute.
3. Conclusion: Since no divisors are found (as the loop is skipped), the
algorithm proceeds to Step 5 and prints "Prime number."
Explanation of algorithm:
- Step 4 iterates through numbers starting from 2 up to A-1 and checks if A is
divisible by any of them.
- If A is divisible by any number in that range, it's not prime, and the algorithm
stops at this Step.
- If no divisors are found, A is prime, and the algorithm prints "Prime number."
Flowchart
A diagrammatic representation of the steps in an algorithm using shapes like ovals
(for Start/End), rectangles (for processes), diamonds (for decisions), and arrows
(for flow).
A flowchart is a graphical representation of a process, system, or algorithm,
showing the steps in sequential order.
It uses symbols to represent different types of actions or steps and arrows to
indicate the flow of control or data.
Flowcharts are commonly used in various fields, including computer science,
engineering, and business, to visually depict how a process works or to break down
complex procedures.
A flowchart is a visual or graphical representation of an algorithm.
Common Flowchart Symbols:
1. Oval (Terminator): Represents the start and end points of the process.
- Example: "Start" or "End"
2. Rectangle (Process): Represents a step or action in the process.
- Example: "Read input," "Perform calculation"
3. Parallelogram (Input/Output): Represents an input or output operation.
- Example: "Read data," "Display result"
4. Diamond (Decision): Represents a decision point, usually with a yes/no or
true/false outcome.
- Example: "Is the number greater than 10?"
5. Arrow (Flowline): Represents the flow or direction of the process.
- Example: Connecting steps to show the order of execution.
Benefits of Using Flowcharts
Here are the advantages of flowcharts:
1. Visual Representation of Logic:
The flowchart displays the logic of a problem in a pictorial format, making it
easier to check and understand the algorithm step by step. This visual approach
enhances clarity and simplifies the process of debugging or improving the
algorithm.
2. Effective Communication:
Flowcharts serve as an excellent communication tool. They are easy to share with
others, allowing different users (developers, stakeholders, or team members) to
quickly understand the solution to a problem. This makes flowcharts a great
medium for collaborative problem-solving.
3. Breaking Down Complex Problems:
A flowchart helps the problem solver break a complex problem into smaller,
more manageable parts. These parts can then be connected logically, forming a
clear structure or "master chart" that represents the entire solution process.
4. Permanent Record of Solutions:
Flowcharts provide a permanent record of how a problem was solved. This
documentation can be consulted later, serving as a reference for future
modifications, improvements, or understanding the logic of the solution. This is
especially useful for maintaining code and processes over time.
Overall, flowcharts are a useful tool for organizing, communicating, and
documenting problem-solving processes in a clear and systematic way.
Flowcharts are an effective tool for planning, analyzing, and communicating
processes in a visual way.
Example: Check whether a number is even or odd
Example: Flowchart to find the greatest among three numbers
Coding, Compilation, and Execution
- Coding: Once the algorithm is ready, the next step is to write the code in a
programming language (e.g., C).
For example, in C:
#include <stdio.h>
int main() {
int A, B, S;
printf("Enter two integers: ");
scanf("%d %d", &A, &B);
S = A + B;
printf("The sum is: %d\n", S);
return 0;
}
- Compilation: The source code needs to be translated into machine code that
the computer can understand. This is done using a **compiler**. For example, in
the terminal, you might use the following command to compile a C program:
gcc -o sum_program sum_program.c
This will create an executable named sum_program.
- Execution: Once compiled, the program can be executed. In the terminal, you
would run the program:
./sum_program
The program will prompt the user to enter two integers, calculate their sum, and
output the result.
We will be using Dev C as our IDE.
Compiler vs Interpreter
A high level source program must be translated first into a form that machines can
understand. This is done by software called a compiler or interpreter.
The compiler takes the source code as input and produces the machine language
code (Object code) for the machine on which it is to be executed as output. An
interpreter, like a compiler is also a translator which translates a high level
language into machine level language line by line.
The basic difference between compiler and interpreter are as follows:
History of C Programming Language
The C programming language was developed in the early 1970s by Dennis Ritchie
at Bell Labs.
It was designed to be a flexible and efficient language for system programming,
especially for writing operating systems.
C was used to develop the UNIX operating system, which contributed
significantly to its popularity.
- Key milestones:
- 1972: Dennis Ritchie creates the first version of C.
- 1978: The publication of "The C Programming Language" by Brian Kernighan
and Dennis Ritchie, which became the definitive reference.
- 1989: The ANSI C standard (C89) was established.
- 1999: The C99 standard was introduced, adding new features like inline
functions and variable-length arrays.
- 2011: The C11 standard was released, adding further improvements.
Structure of a C Program and Executing a C Program
A C program follows a specific structure, typically including the following
components:
1. Preprocessor Directives:
- Preprocessor directives are used to include libraries or files needed by the
program before the actual code is compiled.
These lines begin with #, such as `#include <stdio.h>`, which tells the compiler to
include the standard input-output library. This allows the program to use functions
like printf() and scanf() for input and output.
2. Header Files:
- Header files are files containing declarations of built-in (predefined) functions
and macros that can be used directly in a C program.
For instance, to use printf(), which displays text on the screen, you include the
header file <stdio.h> via the #include directive because stdio.h declares the printf()
function.
3. Main Function:
- Every C program has a main() function, which is the entry point of the
program.
The program’s execution starts from the `main()` function.
The `main()` function is typically prefixed with the keyword `int`, indicating it
returns an integer value when it finishes, often `0` to signal successful completion.
4. Other Functions:
Functions are the main building blocks of any C Program. Every C Program will
have one or more functions and there is one mandatory function which is called
main() function.
5. Variables:
- Variables are used to store data such as numbers, strings, and other types of
information that can be manipulated within the program. C supports various data
types, including `int` for integers, `float` for floating-point numbers, `char` for
characters, and more.
6. Statements and Expressions:
- Statements and expressions make up the logic and calculations in the program.
Statements are lines of code that perform actions, while expressions compute
values that can be assigned to variables or used within other expressions.
7. Comments:
- Comments are used to explain the code and are ignored by the compiler. Single-
line comments begin with `//`, and multi-line comments are enclosed between `/*
... */`. Comments help make the code more readable for humans.
8. Return Statement:
- The `return 0;` statement at the end of `main()` indicates that the program has
finished successfully. This is standard practice to signal the end of execution,
where `0` usually means success and non-zero values indicate errors.
Basic Structure of a C Program:
Here is an example of a simple C program that adds two integers:
#include <stdio.h> // Preprocessor directive
// Main function: entry point of the program
int main() {
// Variable declarations
int A, B, S;
// Input data
printf("Enter two integers: ");
scanf("%d %d", &A, &B);
// Process data
S = A + B;
// Output the result
printf("The sum is: %d\n", S);
return 0; // Return statement
}
- Explanation:
- `#include <stdio.h>`: Includes the Standard Input Output library, enabling the
program to use `printf()` and `scanf()`.
- `int main()`: Declares the main function where the execution begins.
- `printf()` and `scanf()`: Built-in functions for outputting to the screen and taking
input, respectively.
- `return 0;`: Signals successful completion of the program.
Compiling and Running a C Program
To execute a C program, follow these steps:
1. Compilation: Use a C compiler like `gcc` to compile the code into machine-
readable format. For example:
gcc program.c -o program
This command compiles `program.c` and creates an executable named
`program`.
2. Execution: Run the compiled program by typing:
./program
This will execute the code, and you can see the output based on the program’s
logic.
The compilation process translates your C source code into executable machine
code, making it ready for the computer to run.