0% found this document useful (0 votes)
1 views15 pages

Computer Programming

The document provides a comprehensive overview of computer programming, detailing the process of writing, testing, and maintaining programs, as well as the various programming languages and their generations. It covers fundamental programming constructs, including data types, variables, input/output, decision-making, loops, and advanced concepts such as functions, structures, arrays, strings, and pointers. Additionally, it discusses structured and modular programming approaches, the program development life cycle, and introduces object-oriented programming concepts.

Uploaded by

tom cruise
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)
1 views15 pages

Computer Programming

The document provides a comprehensive overview of computer programming, detailing the process of writing, testing, and maintaining programs, as well as the various programming languages and their generations. It covers fundamental programming constructs, including data types, variables, input/output, decision-making, loops, and advanced concepts such as functions, structures, arrays, strings, and pointers. Additionally, it discusses structured and modular programming approaches, the program development life cycle, and introduces object-oriented programming concepts.

Uploaded by

tom cruise
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

FUNDAMENTALS OF

Computer Programming
1. Overview of Computer Programming and Programming Languages
Computer programming is the process of designing, writing, testing, and maintaining a set of precise
instructions — a program — that a computer can execute to perform a specific task. A program is an
implementation of an algorithm, expressed in a notation the machine (or a translator working on its
behalf) can understand.

1.1 What Is Computer Programming?


• A computer only executes instructions; it does not “understand” a problem the way a person
does. The programmer's job is to break a problem down into small, unambiguous,
executable steps.
• Programming sits at the intersection of problem-solving (algorithm design and logic) and
language syntax (correctly expressing that logic in a specific notation).
• Good software is correct (produces the right output), efficient (uses time and memory well),
readable / maintainable, and robust (handles unexpected input gracefully).

1.2 From Source Code to Execution


Programmers write source code in a human-readable language. Before a CPU can run it, the code
must be translated into machine instructions. Three broad translation strategies are used:

• Compiler — translates the entire source file into a standalone machine-code executable
before the program runs; errors are reported at compile time. Examples: C, C++.
• Interpreter — translates and executes source code line by line at run time, without
producing a separate executable file. Examples: Python, traditional JavaScript.
• Hybrid (compiled + interpreted) — source is first compiled to an intermediate bytecode,
which is then interpreted or JIT-compiled at run time. Example: Java (bytecode run by the
JVM), C#.

1.3 Generations of Programming Languages


• 1GL — Machine Language: raw binary instructions specific to a CPU; fastest to execute,
extremely difficult for humans to write or read.
Fundamentals of Computer Programming

• 2GL — Assembly Language: uses mnemonics (MOV, ADD, JMP) instead of raw binary; an
assembler translates it to machine code. Still hardware-specific.
• 3GL — High-Level Languages: human-readable, largely hardware-independent syntax — C,
Pascal, Java, C++, Python. A compiler or interpreter converts these to machine code.
• 4GL — Very-High-Level / Declarative Languages: focus on what should be done rather than
how; e.g. SQL for querying databases, report generators.
• 5GL — Constraint / AI-Based Languages: the programmer specifies goals or constraints and
the system works out the steps; e.g. Prolog, some expert-system tools.

1.5 A Few Widely Used Languages at a Glance


Language Typical Use Paradigm
C Systems and embedded programming Procedural
C++ Systems, games, performance-critical apps Procedural + OOP
Java Enterprise applications, Android Object-Oriented
Python Data science, scripting, AI, web OOP + Scripting
JavaScript Web front-end and back-end ([Link]) Scripting + OOP

2. Fundamental Programming Constructs


Every program, no matter how large, is built from a small set of basic constructs: data types to
describe values, variables to store them, input/output to communicate with the user, and decisions
and loops to control the flow of execution.

2.1 Data Types


A data type tells the compiler or interpreter what kind of value a variable can hold and what
operations are valid on it.

• Primitive (built-in) types — integer, floating-point, character, boolean.


• Derived / user-defined types — array, structure, pointer, class (covered in Chapter 3 and
Chapter 6).

Figure 2: Hierarchy of data types: primitive vs. derived/user-defined.

Type Example Declaration Typical Size* Example Value


int int age; 4 bytes 25

Page 2 of 15
Fundamentals of Computer Programming

Type Example Declaration Typical Size* Example Value


float float price; 4 bytes 19.99
double double pi; 8 bytes 3.14159
char char grade; 1 byte 'A'
bool bool isValid; 1 byte true
*Sizes are typical for C/C++ on common 32-/64-bit systems; the exact size can vary by compiler and
platform.

2.2 Variables
A variable is a named location in memory used to store a value that can change while the program
runs.

• Declaration — stating a variable's type and name, e.g. int score;


• Initialization — assigning an initial value, e.g. int score = 0;
• Naming rules (typical) — starts with a letter or underscore, no spaces, not a reserved
keyword, case-sensitive.
• Scope: local — declared inside a function or block; visible only there. Global — declared
outside all functions; visible throughout the file or program.
• Lifetime — how long a variable's memory stays allocated; local variables are typically
destroyed when the function returns.

int totalMarks = 0; // global variable


void calculate() {
int bonus = 5; // local variable, exists only inside calculate()
totalMarks = totalMarks + bonus;
}

2.3 Basics of Input and Output


Programs read data (input) and present results (output). The exact syntax differs by language:

• C: scanf("%d", &age); for input, printf("Age: %d", age); for output.


• C++: cin >> age; for input, cout << "Age: " << age; for output.
• Python: age = int(input("Enter age: ")) for input, print("Age:", age) for
output.
Regardless of language, good practice includes prompting the user clearly, matching the input to the
expected data type or format, and validating input before it is used in calculations.

2.4 Decision Making (Selection Structures)


Decisions let a program choose between different paths based on a condition — a Boolean
expression that evaluates to true or false.

• if — executes a block only if a condition is true.

Page 3 of 15
Fundamentals of Computer Programming

• if...else — chooses between two blocks.


• else-if ladder — chooses among several alternatives, tested in order.
• switch...case — selects one of several blocks based on the value of a single variable or
expression.

if (marks >= 90) {


grade = 'A';
} else if (marks >= 75) {
grade = 'B';
} else {
grade = 'C';
}

2.5 Loops (Iteration / Repetition Structures)


Loops repeat a block of statements while, or until, a condition holds.

• for loop — best when the number of iterations is known in advance.


• while loop — repeats while a condition is true; the condition is checked before the body
runs.
• do...while loop — like while, but the body always runs at least once because the condition is
checked after.
• break exits a loop immediately; continue skips directly to the next iteration.

for (int i = 1; i <= 5; i++) {


print(i);
}

The flowchart below combines both ideas in one worked example: it loops through the numbers 1 to
N and, for each one, makes a decision about whether it is even or odd.

Page 4 of 15
Fundamentals of Computer Programming

Figure 3: Flowchart combining a loop (repeat for i = 1 to N) with a decision (even or odd).

3. Functions, Structures, Arrays, Strings, and Pointers


Beyond the basic constructs, most real programs rely on functions to organise logic, and on
structures, arrays, strings, and pointers to organise data.

3.1 Functions
A function is a named, reusable block of code that performs a specific task. Breaking a program into
functions avoids repetition and makes code easier to read, test, and maintain.

• Declaration / prototype — tells the compiler the function's name, return type, and
parameter types.
• Definition — the actual body / implementation of the function.
• Call — invoking the function, optionally passing arguments.
• Parameters vs. arguments — parameters are the placeholders in the definition; arguments
are the actual values supplied at the call site.
• Passing by value — a copy of the argument is passed; changes inside the function do not
affect the caller's original variable.
• Passing by reference (or via a pointer) — the function can access and modify the original
variable's memory directly.
• Return value — the result sent back to the caller via return.
• Recursion — a function that calls itself to solve a smaller instance of the same problem (e.g.
factorial, Fibonacci); it needs a base case so it eventually stops.

Page 5 of 15
Fundamentals of Computer Programming

int sum(int a, int b) {


return a + b;
}

int main() {
int result = sum(5, 3); // result = 8
}

Figure 4: How control and data move between main() and a called function.

3.2 Structures
A structure (struct) groups several related variables, possibly of different types, under one name
— useful for representing a real-world record such as a student or an employee.

struct Student {
char name[30];
int rollNo;
float gpa;
};

struct Student s1;


[Link] = 101;
[Link] = 3.8;

A structure differs from an array: an array holds many values of the same type accessed by position
(index); a structure holds related values that may be of different types, accessed by member name.

3.3 Arrays
An array is a fixed-size, ordered collection of elements of the same data type, stored in contiguous
memory and accessed by an index (position), typically starting at 0.

• Declaration: int marks[5];


• Access: marks[0] is the first element, marks[4] is the last of a 5-element array.
• Multi-dimensional arrays: e.g. int matrix[3][4]; — a 2D grid useful for tables and
images.

3.4 Strings
A string is a sequence of characters. In C, a string is typically stored as a character array terminated
by a special null character, '\0'. Higher-level languages provide a dedicated string type with built-in

Page 6 of 15
Fundamentals of Computer Programming

operations such as concatenation, length, substring, comparison, and search — C++'s string,
Python's str, Java's String.

char name[20] = "Alice"; // C-style string


string name2 = "Alice"; // C++ string type

3.5 Pointers
A pointer is a variable that stores the memory address of another variable, rather than a value
directly.

• & — address-of operator: gives the memory address of a variable.

• * — dereference operator: accesses the value stored at the address a pointer holds.

• Declaring a pointer: int *ptr;


• Pointer arithmetic — incrementing a pointer moves it forward by the size of the type it
points to; this is how array traversal is often implemented internally.
• Pointers and arrays — an array's name, used by itself, behaves like a pointer to its first
element.
• Pointers and functions — passing a pointer lets a function modify the caller's original
variable, which is how “pass by reference” is implemented in C.

int x = 10;
int *ptr = &x; // ptr holds the address of x
printf("%d", *ptr); // dereferencing ptr prints 10
*ptr = 20; // modifies x through the pointer; x is now 20

Figure 5: An array stored in contiguous memory, with a pointer variable referencing its first element.

Page 7 of 15
Fundamentals of Computer Programming

4. Structured and Modular Programming

4.1 Structured Programming


Structured programming is an approach where any program's logic is built from exactly three control
structures:

1. Sequence — statements executed one after another, in order.


2. Selection — a decision that chooses between alternative paths (if, switch).
3. Iteration — a loop that repeats a block (for, while, do-while).
This approach deliberately avoids uncontrolled jumps ( goto), which historically made large
programs hard to follow — sometimes called 'spaghetti code'. Structured programs are easier to
read top-to-bottom, reason about, and debug.

4.2 Modular Programming


Modular programming breaks a large program into smaller, self-contained modules — in most
languages implemented as functions, or grouped into separate files or libraries — each responsible
for one well-defined task.

• Easier to understand and maintain — each module can be studied in isolation.


• Reusability — a well-written module can be reused in other programs.
• Parallel development — different team members can build and test different modules
independently.
• Easier testing and debugging — a fault can usually be isolated to a specific module.
The typical design approach is top-down design: start with the overall problem, then progressively
break it into smaller sub-problems or modules (“divide and conquer”) until each module is simple
enough to implement directly.

Figure 6: Top-down decomposition of a program into modules and sub-modules.

5. Program Development

Page 8 of 15
Fundamentals of Computer Programming

Turning a problem into working software is itself a process with distinct, repeatable stages.

5.1 Analyzing the Problem


• Understand exactly what is being asked: what inputs are given, what output or result is
required, and what rules or formulas connect them.
• Identify edge cases early — empty input, zero, negative numbers, very large values.

5.2 Designing the Algorithm / Solution


An algorithm is a finite, ordered sequence of well-defined, unambiguous steps that solves a problem
and is guaranteed to terminate. Good algorithms are usually worked out first in a language-
independent form:

• Pseudocode — plain, structured, code-like English that describes the logic without worrying
about a specific language's syntax.
• Flowchart — a diagram using standard symbols (oval = start/end, parallelogram =
input/output, rectangle = process, diamond = decision) to show the flow of logic visually.

5.3 Translating the Algorithm into a Program (Coding)


Once the logic has been verified on paper, it is translated into the syntax of a chosen programming
language, then compiled or interpreted and run.

5.4 Worked Example: Largest of Three Numbers


Problem: given three numbers, find and display the largest.

Pseudocode:

START
INPUT a, b, c
IF a >= b AND a >= c THEN
largest = a
ELSE IF b >= a AND b >= c THEN
largest = b
ELSE
largest = c
PRINT largest
END

C code:

#include <stdio.h>
int main() {
int a, b, c, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a >= b && a >= c)

Page 9 of 15
Fundamentals of Computer Programming

largest = a;
else if (b >= a && b >= c)
largest = b;
else
largest = c;

printf("Largest number is %d\n", largest);


return 0;
}

This four-stage cycle — analyze, design, code, test — repeats (often with earlier stages revisited)
until the program is correct and complete, as shown below.

Figure 7: The program development life cycle, from problem analysis to documentation and maintenance.

6. Object-Oriented Programming and Software Development

6.1 Why Object-Oriented Programming?


Procedural programming centres on functions acting on data. As programs grow, keeping data and
the functions that operate on it separate becomes hard to manage safely. Object-oriented
programming (OOP) instead organises a program around objects — self-contained units that bundle
data (attributes) and behaviour (methods) together, modelling real-world entities more naturally.

6.2 Objects and Classes


• A class is a blueprint or template that defines what attributes (data) and methods
(behaviour) its objects will have.
• An object is a concrete instance of a class, with its own copy of the attributes.

Page 10 of 15
Fundamentals of Computer Programming

class Circle {
private:
double radius;
public:
void setRadius(double r) { radius = r; }
double getArea() { return 3.14159 * radius * radius; }
};

int main() {
Circle c1; // c1 is an object (instance) of class Circle
[Link](5.0);
cout << [Link]();
}

6.3 Encapsulation
Encapsulation bundles data and the methods that operate on it inside a class, and restricts direct
access to the internal data from outside — usually by declaring attributes private and exposing
controlled access through public methods (getters/setters, such as setRadius() above). This
protects an object's internal state from invalid or accidental changes and hides implementation
details behind a clean interface.

6.4 Inheritance
Inheritance lets one class (the derived or child class) acquire the attributes and methods of another
class (the base or parent class), promoting code reuse and modelling “is-a” relationships — a Circle is
a Shape.

class Shape {
public:
virtual double getArea() { return 0; }
};

class Circle : public Shape { // Circle inherits from Shape


private:
double radius;
public:
double getArea() override { return 3.14159 * radius * radius; }
};

6.5 Polymorphism
Polymorphism (“many forms”) allows the same function name or operation to behave differently
depending on the object or arguments involved.

• Compile-time (static) polymorphism — achieved through function overloading (same name,


different parameter lists) and operator overloading.

Page 11 of 15
Fundamentals of Computer Programming

• Run-time (dynamic) polymorphism — achieved through function overriding: a derived class


redefines a base class method (typically declared virtual in C++), and the correct version is
chosen automatically at run time based on the actual object type.
This is exactly what the class diagram below shows: Circle and Rectangle each override getArea()
with their own formula, but other code can call a shape's getArea() without needing to know
which specific shape it is.

6.6 Operator Overloading


Operator overloading lets built-in operators — +, -, ==, <<, and others — be redefined to work
sensibly with objects of a user-defined class.

class Complex {
public:
double real, imag;
Complex operator+(const Complex& other) {
Complex result;
[Link] = real + [Link];
[Link] = imag + [Link];
return result;
}
};
// Usage: Complex c3 = c1 + c2; // '+' now works on Complex objects

Figure 8: Class diagram showing encapsulation (private data with public methods) and inheritance, with Circle and
Rectangle each providing their own polymorphic getArea().

7. Exception Handling, Testing, and Debugging

Page 12 of 15
Fundamentals of Computer Programming

7.1 Exception Handling


An exception is an unexpected event that disrupts a program's normal flow — division by zero,
invalid input, a missing file. Exception handling lets a program detect and respond to such events
gracefully instead of crashing.

• try block — contains code that might raise an exception.


• catch (or except) block — contains code that handles a specific exception if one occurs.
• finally block — contains code that always runs, whether or not an exception occurred (e.g.
closing a file); standard in Java, C#, and Python.
• throw / raise — signals that an exception has occurred, optionally with a custom exception
type.

try {
if (denominator == 0)
throw "Division by zero!";
result = numerator / denominator;
} catch (const char* msg) {
cout << "Error: " << msg;
}

Page 13 of 15
Fundamentals of Computer Programming

Figure 9: Exception handling flow: try, catch, and finally.

7.2 Testing
Testing means executing a program deliberately in order to find defects before real users do.

• Unit testing — tests the smallest pieces (a single function or module) in isolation.
• Integration testing — tests whether independently-working modules function correctly
together.
• System testing — tests the complete, integrated application against overall requirements.
• Black-box testing — tests based only on expected inputs and outputs, without looking at the
internal code.
• White-box testing — tests based on the internal logic or structure of the code, e.g. making
sure every branch executes at least once.

7.3 Debugging
Debugging is the process of locating and fixing the cause of a defect found during testing, or
reported by a user. Errors are commonly grouped into three categories:

Page 14 of 15
Fundamentals of Computer Programming

• Syntax errors — violate the rules of the language; caught by the compiler or interpreter
before the program runs.
• Runtime errors — occur while the program is executing, e.g. dividing by zero or accessing an
invalid array index.
• Logical errors — the program runs and produces output, but the output is wrong because
the underlying logic is flawed.
Common debugging techniques include reading error messages carefully, inserting temporary print
or trace statements, using a debugger to step through code line by line while inspecting variable
values, and testing with small, simple inputs first to isolate exactly where behaviour diverges from
what was expected.

Page 15 of 15

You might also like