π Lecture 1 β Why Programming is Important
π Overview: This introductory lecture establishes why learning to program is valuable for everyone, not just computer scientists. It outlines the essential skills needed for effective programming and introduces the concept of a program design recipe as a structured approach to problem-solving.
ποΈ Topics Covered
The lecture begins by explaining why programming is important, citing that it develops analytical and problem-solving abilities. It then discusses the specific skills a programmer needs, including paying attention to detail, thinking about reusability, designing good user interfaces, understanding computers are stupid, and commenting code liberally. Finally, it introduces the program design recipe as a structured methodology for developing programs effectively.
π Lecture Summary
Why Programming is important
Learning to program is valuable because it develops analytical and problem-solving abilities. It is a creative activity and provides a means to express abstract ideas. By designing programs, we learn skills that are important for all professions, including critical reading, analytical thinking, and creative synthesis. Programming is much more than a vocational skill; it is fun and useful for everyone, from administrative secretaries to high-tech programmers.
What skills are needed
A good programmer should cultivate several key skills. These include paying attention to detail, thinking about reusability, designing a good user interface, understanding that computers are stupid, and commenting the code liberally.
Paying attention to detail
In programming, details matter. A good programmer carefully analyzes the problem statement and pays attention to all aspects of the problem, including calculations, flow, and logic. It is possible for a program to be grammatically correct (compile and run) but still produce incorrect or absurd results if the logic is flawed. For example, the sentence "Mr. ABC sleeps thirty hours every day" is grammatically correct but illogical.
Think about the reusability
When writing a program, always keep in mind that it could be reused at some other time or to solve a related problem. A classic example is a program that calculates the area of a circle (Pi * rΒ²). This program can later be reused to calculate the area of a ring by subtracting the area of the inner circle from the area of the outer circle.
π Formula: Area of a circle = Ο * rΒ² β The area is calculated by multiplying pi by the square of the radius.
Think about Good user interface
Never assume that the user of your program is computer literate. Always provide an easy to understand and easy to use interface that is self-explanatory.
Understand the fact that computers are stupid
Computers are incredibly stupid; they do exactly what you tell them to do, no more and no less. Unlike humans, they cannot think for themselves. Instructions to the computer must be explicitly stated. For example, a human understands "What is the time?", "Time please?", or "Time?" as the same request, but a computer will only respond if asked in the exact way it was programmed. When programming, you must be able to "think" as stupidly as the computer to specify everything in minute detail.
π‘ Why this matters: This concept is fundamental to debugging. Most programming errors occur because the programmer assumed the computer would do something that was not explicitly instructed.
Comment the code liberally
Always comment your code liberally. Comment statements are ignored by the compiler and do not take any memory. They explain the functioning of the program and help other programmers, as well as the original creator, understand the code.
π Definition β Comments: Non-executable text in a program used to explain the code's logic and functionality.
Program design recipe
To design a program effectively, you must follow a design recipe. This involves:
- Analyze a problem statement, typically expressed as a word problem.
- Express its essence, abstractly and with examples.
- Formulate statements and comments in a precise language.
- Evaluate and revise the activities in light of checks and tests.
- Pay attention to detail.
π Example: Consider a payroll system for a company with permanent, contractual, hourly, and per-unit employees. First, analyze the problem to identify these four categories and their rules (e.g., benefits for permanent staff, bonuses for per-unit employees making more than 10 pieces, overtime for contractual employees). Next, divide the problem into small segments with examples, such as calculating the salary of Mr. Ahmad, a permanent Finance Manager earning Rs.20,000 with Rs.4,000 in benefits and Rs.1,200 in deductions. Then, formulate these statements using pseudo code and flowcharts. Finally, test and check the program, revising the process as needed to achieve a refined solution.
Points to remember
The major points to keep in mind are: don't assume anything on the part of the users, make the user interface friendly, don't forget to comment the code, pay attention to detail, and programβnot just writing code, but the whole process of design and development.
β Key Takeaways
Programming is a creative and analytical skill that is valuable for everyone. The most critical skills for a programmer are paying extreme attention to detail, understanding that computers execute instructions literally and need explicit commands, and writing reusable code. The program design recipe provides a structured process of analysis, formulation, and testing that is essential for developing correct and robust programs. Finally, programs must be well-commented for future understanding, and user interfaces must be designed for non-technical users.
π§ Quick Revision Questions
- Why is learning to program important for people who are not planning to become professional programmers?
- What does it mean to say a program is "grammatically correct" but still incorrect?
- Provide an example of how code reusability can save development time.
- What is the key assumption a programmer should never make about computer users?
- List the five steps in the program design recipe.
π Lecture 2 β Software Categories, History of C, and Development Environment
π Overview: This lecture introduces the fundamental categories of softwareβsystem and application softwareβand explains their roles in computing. It then traces the historical development of the C programming language from its predecessors BCPL and B, and describes the essential tools (editor, compiler, linker, loader, debugger) used in the C programming development environment.
ποΈ Topics Covered
The lecture covers the two main categories of software: system software (including operating systems, device drivers, and utility programs) and application software designed for end users. It then discusses the history of the C language, tracing its development from BCPL and B languages at Bell Laboratories to its standardization by ANSI and ISO. Finally, the lecture describes the complete development environment for C programs, including editors, compilers vs. interpreters, debuggers, linkers, and loaders, illustrated with a step-by-step execution diagram.
π Lecture Summary
Software Categories
Software is categorized into two main categories: system software and application software. System software controls the computer and communicates with its hardware, while application software is designed for end users to perform specific tasks.
System Software
The system software controls the computer by communicating with computerβs hardware (keyboard, mouse, modem, sound card etc) and controlling different aspects of operations. Sub categories of system software are: operating system, device drivers, and utilities.
π Definition β Operating System: An operating system (sometimes abbreviated as "OS") is the program that manages all the other programs in a computer. It is an integrated collection of routines that service the sequencing and processing of programs by a computer. An operating system may provide many services, such as resource allocation, scheduling, input/output control, and data management. According to Microsoft, "Operating system is the software responsible for controlling the allocation and usage of hardware resources such as memory, central processing unit (CPU) time, disk space, and peripheral devices. The operating system is the foundation on which applications, such as word processing and spreadsheet programs, are built."
Device drivers are special software used to communicate between devices and the computer. For example, when we attach a new device like a scanner, we install its device driver software. For scanners, TWAIN drivers are commonly used. TWAIN stands for Technology Without An Interesting Name. Normally the manufacturer of the device provides the device driver software with the device.
Utility software is a program that performs a very specific task, usually related to managing system resources. Examples include Disk Compression utility, which compresses files to reduce their size when saving to disk and uncompresses them when reading, and Disk Defragmentation utility, which removes fragmentation by reorganizing file chunks stored in different locations on the disk so they are stored close to each other, making data reading faster. The compilers and interpreters also belong to the System Software category.
Application Software
Application software is a program or group of programs designed for end users. Examples include programs for Accounting, Payroll, Inventory Control System, guided systems for planes, and GPS (global positioning system) which is used in vehicles to determine geographical position through satellites.
History of C Language
The C language was developed in late 60βs and early 70βs at Bell Laboratories. In those days, BCPL and B languages were developed there. The BCPL language was developed in 1967 by Martin Richards as a language for writing operating systems software and compilers. In 1970, Ken Thompson used B language to create early versions of the UNIX operating system at Bell Laboratories. Both BCPL and B were 'type less' languages β every data item occupied one 'word' in memory and the burden of treating a data item as a whole number or real number was the responsibility of the programmer.
Dennis Ritchie developed a general purpose language called C by using different features of BCPL and B languages. C uses many important concepts of BCPL and B while adding data typing and other features. C became widely known as the development language of the UNIX operating system, and the UNIX operating system was written using C. The C language is so powerful that the compiler of C and other various operating systems are written in C. C has almost unlimited powers β you can program to turn on or off any device of computer, you can do a lot to hard disk and other peripherals, and it is very easy to write a program in C that stops the running of computer.
The C language and UNIX operating system widely spread in educational and research institutions. Due to its wide spread, different researchers started to add their features, creating different variations of C. These variations led to the need of a standard version. In 1983, a technical committee was created under the American National Standards Committee on Computer and Information Processing to provide an unambiguous and machine-independent definition of the language. In 1989, the standard was approved. ANSI cooperated with the International Standard Organization (ISO) to standardize C worldwide.
π‘ Why this matters: Understanding C's history explains why C is so powerful at the hardware level and why it became the foundation for modern operating systems and programming languages.
Tools of the Trade
As programmers, we need different tools for the life cycle of programs: Editors, Compiler and Interpreter, Debugger, Linker, and Loader.
Editors are tools for writing the code of a program. While we could use word processors, they save additional formatting information (bold, italic, coloring) along with text. For programming purposes, we only need simple text. Text editors save only the text we type, so we will be using a text editor for programming.
Compiler and Interpreter are translators that convert our program written in C-Language into Machine language (0s and 1s that computers understand). Interpreters translate the program line by line β they read one line, translate it, then read the next line. The benefit is that we get errors as we go along, making it easy to correct them. The drawback is that programs execute slowly because the interpreter translates line by line, and interpreters cannot get the overall picture to optimize the program.
Compilers also translate C code into machine language, but they read the whole program and translate it completely. The difference is that a compiler will stop translating if it finds an error and no executable code will be generated, whereas an Interpreter will execute all lines before the error and stop at the line containing the error. So a Compiler needs a syntactically correct program to produce an executable code. This course will use a compiler.
Debugger is used to debug the program β to correct logical errors. Using a debugger, we can control our program while it is running. We can stop execution at some point and check values in different variables, change these values, etc. This way we can trace logical errors and see whether our program is producing correct results.
Linker is a tool that checks our program and includes all those routines or functions which we are using in our program to make a standalone executable code. Most of the time our program uses different routines and functions located in different files, so the Linker includes the executable code of those routines/functions. This process is called Linking.
Loader is the process that loads the program into memory and then instructs the processor to start execution from the first instruction (the starting point of every C program is from the main function). Linkers and loaders are part of the development environment and are categorized as system software.
The complete program execution flow is: Editor (write code) β Preprocessor (processes the code) β Compiler (creates object code stored on disk) β Linker (links object code with libraries) β Loader (puts program in memory) β CPU (takes each instruction and executes it, possibly storing new data values as the program executes).
β Key Takeaways
You must understand the distinction between system software (operating systems, device drivers, utilities) and application software, and recognize that compilers and interpreters are system software. The historical development of C from BCPL and B, with Dennis Ritchie adding data typing and other features, explains why C is both powerful and machine-oriented. The key difference between interpreters (line-by-line translation, slower, easier debugging) and compilers (full program translation, faster execution, stops on errors) is critical for understanding program development. The complete toolchain β editor β preprocessor β compiler β linker β loader β CPU execution β must be memorized as the standard program lifecycle, with the linker creating standalone executables by resolving external function references.
π§ Quick Revision Questions
- What are the two main categories of software, and what is the fundamental difference between them?
- Explain the difference between an interpreter and a compiler, including their respective advantages and disadvantages.
- Who developed the C language, from which two predecessor languages was it derived, and what key feature did C add that its predecessors lacked?
- List in order the five main tools involved in the program development process, from writing code to execution.
- What is the specific role of the linker in program development, and what does it do with functions located in different files?
π Lecture 3 β First C program & Variables, Data Types, Arithmetic Operators, Precedence of Operators, Tips
π Overview: This lecture introduces the structure of a first C program, explains how data is stored using variables and different data types, and covers how to perform calculations using arithmetic operators. It also clarifies the precedence of operators and provides essential programming tips. Mastering these fundamentals is critical for writing any C program.
ποΈ Topics Covered
The lecture begins by dissecting a simple "Hello World" program, explaining each part like #include, main(), and cout. It then defines variables as named memory locations and the assignment operator (=). The core data typesβint, short, long for whole numbers, float and double for real numbers, and char for charactersβare each explained with sample code. Finally, the arithmetic operators (+, -, *, /, %) and their precedence rules are detailed with examples.
π Lecture Summary
First C program
The best way to learn C is to start coding. The lecture presents the very first C program:
#include <iostream.h>
main()
{
cout << "Welcome to Virtual University of Pakistan";
}
The line # include <iostream.h> is a pre-processor directive. It is not part of the program but an instruction to the compiler to include the contents of the system file iostream.h, which contains code for input/output streams (sending stuff to the screen and reading from the keyboard). The sign # is known as HASH or SHARP.
The function name main() is special. A C program is made up of many functions, but C regards the name main as a special case and will run this function first. Forgetting or mistyping main will cause a compiler error.
The curly braces { } are used to group together pieces of a program; the body of main is enclosed in them. For every open brace, there must be a matching close brace.
cout is the output stream in C and C++. Think of a stream as a door through which data is transferred. cout takes data from the computer and sends it to the output device (usually the screen).
The << sign indicates the direction of data. Here, it points towards cout.
" Welcome to Virtual University of Pakistan" is a character string. In C, character strings are written in double quotes.
The semicolon (;) is very important. All C statements end with a semicolon. Missing a semicolon is a syntax error that the compiler will report.
Variables
During programming, we need to store data. Variables are locations in memory for storing data. Memory is divided into blocks, each with a numerical address. Since it's difficult to handle these numerical addresses, we give names to these locations, which are called variables. They are called "variables" because they can contain different values at different times.
Variable names in C may be started with a character or an underscore (_). However, one should avoid starting a name with an underscore because C libraries contain variable and function names starting with underscore, which could cause a conflict.
In a program, every variable has a Name, Type, Size, and Value.
π Definition β Assignment Operator (=): In C, the equal-to sign (=) is used as the assignment operator. Do not confuse it with the algebraic equal sign. In C, X = 2 means "take the value 2 and put it in the memory location labeled X." Afterwards, you can assign some other value to X, like X = 10, which means the memory location now contains 10 and the previous value 2 is no longer there.
The assignment operator is a binary operator (it has two operands). It must have a variable on its left-hand side and an expression (that evaluates to a single value) on its right-hand side. For example, X = 5, X = 10 + 5, and X = X + 1 are all valid. The statement X = X + 1 adds 1 to the current value of X and then stores the result back in X. This is a common practice for incrementing a variable.
π‘ Why this matters: This concept is fundamentally different from algebra. In algebra, X = X + 1 is invalid (except for infinity). In C, it's a core operation for counting and looping.
Data Types
A variable must have a data type associated with it, for example, int (integer), float (decimal number), or char (character). The primary difference between various data types is their size in memory. These data types are reserved words of C and cannot be used as variable names.
Whole Numbers
The C language provides three data types to handle whole numbers: int, short, and long.
-
intData Type: Used to store whole numbers (integers). It typically occupies 4 bytes (32 bits) in memory on a Windows operating system. To use an integer variable namedi, you declare it asint i;. This reserves 4 bytes of memory and labels iti. -
shortData Type: Used for storing small whole numbers. Its size is 2 bytes, and it can store numbers in the range of -32768 to 32767. It's suitable for data like a person's age. -
longData Type: Used for storing very large whole numbers that cannot fit in anint. For example,long x = 300500200;.
Sample Program 1 (using int):
#include <iostream.h>
main()
{
int x;
int y;
int z;
x = 5;
y = 10;
z = x + y;
cout << "x = ";
cout << x;
cout << " y=";
cout << y;
cout << " z = x + y = ";
cout << z;
}
In this program, three variables x, y, and z are declared as integers. They can also be declared on a single line as int x, y, z;. After assigning 5 to x and 10 to y, the statement z = x + y; evaluates the expression, adds the values of x and y, and stores the result (15) in z. Crucially, the values of x and y remain unchanged after this operation. The cout statement with a variable name (e.g., cout << x;) displays the value of the variable, not its name.
Real Numbers
The C language provides float and double to deal with real numbers (numbers with decimal points, also known as floating point numbers).
-
floatData Type: Used to store real numbers and uses 4 bytes of memory. Example:float x = 12.35; -
doubleData Type: Used to store large real numbers that cannot fit in afloat. Its size is normally twice the size offloat. Example:double x = 345624.769123;
char Data Type
Used to store single characters like 'a', 'b', or 'c'. When assigning a character value to a char variable, single quotes are used around the character, e.g., char x = 'a';.
Arithmetic Operators
C has the usual arithmetic operators for addition, subtraction, multiplication, and division. It also provides a special operator called modulus. All these are binary operators (they operate on two operands).
| OPERATION | OPERATOR | C EXPRESSION |
|---|---|---|
| Addition | + | x + y |
| Subtraction | - | x - y |
| Multiplication | * | x * y |
| Division | / | x / y |
| Modulus | % | x % y |
π Definition β Integer Division: When using the division operator / with integer operands, the result is an integer. The fractional part (after the decimal point) is truncated (ignored). For example, 5 / 2 yields 2, not 2.5. To get the correct fractional result, use float data types.
π Definition β Modulus Operator (%): This operator returns the remainder after division. It can only be used with integer operands. The expression x % y returns the remainder after x is divided by y.
π Example: 5 % 2 = 1, 23 % 5 = 3, 107 % 10 = 7.
Precedence of Operators
The arithmetic operators in an expression are evaluated according to their precedence, which determines the order of evaluation.
- Parentheses
( )are used to force the evaluation order. Operators within parentheses are evaluated first. For nested parentheses, the innermost is evaluated first. - Expressions are always evaluated from left to right.
- The operators
*,/, and%have the highest precedence after parentheses and are evaluated before+and-. - The operators
+and-have the lowest precedence. - If operators have the same precedence (e.g.,
*and/), the operator that appears first from the left is evaluated first.
π Example 1: 10 + 10 * 5 yields 60, not 100. Because * has higher precedence, 10 * 5 is evaluated first (yielding 50), and then 10 + 50 gives 60. If we force addition first using (10 + 10) * 5, the result is 100.
π Example 2: 5 * 3 + 6 / 3 yields 17, not 7. The evaluation is (5 * 3) + (6 / 3) = 15 + 2 = 17.
β Key Takeaways
A student must remember that in C, the = sign is an assignment operator, not an algebraic equals, and it requires a single variable on its left-hand side. The main() function is the mandatory starting point of every C program. Different data types (int, short, long, float, double, char) exist to store different kinds of data, and choosing the right one is important for memory efficiency and precision. When performing integer division, the fractional part is truncated, and the modulus operator (%) is used to get a remainder. Finally, the precedence of operators dictates that *, /, and % are evaluated before + and -, and parentheses can be used to override this order.
π§ Quick Revision Questions
- What is the difference between the statement
cout << βx =β;andcout << x;in the sample program? - What are the three data types in C used for storing whole numbers, and how do they differ in their memory size?
- If you have two integer variables,
a = 7andb = 3, what are the results of the expressionsa / banda % b? - Explain, step by step, why the expression
5 + 3 * 4evaluates to 17 and not 32. - What is a pre-processor directive, and what is the purpose of writing
#include <iostream.h>at the top of a program?
π Lecture 4 β Sample Program, Examples of Expressions, Use of Operators, Tips
π Overview: This lecture demonstrates how to write complete C++ programs to solve real-world problems, including calculating average age, extracting digits from a number, and computing circle measurements. It reinforces the use of arithmetic operators, the
cinandcoutstatements, and the importance of data types and operator precedence in programming.
ποΈ Topics Covered
The lecture covers a complete sample program for calculating the average age of ten students, detailing variable declaration, input/output operations, and integer division truncation. It then provides examples of writing algebraic expressions as C++ statements, emphasizing operator precedence and the use of parentheses. The use of operators is further explored through programs that separate digits of an integer using the modulus operator and calculate circle properties. Finally, it offers programming tips for clarity, memory reuse, and problem analysis.
π Lecture Summary
Sample Program
The lecture presents a sample program to calculate the average age of ten students. The problem requires declaring ten integer variables (age1 through age10) to store each student's age, using a comma separator for concise declaration. The program prompts the user for each age using cout and reads input using cin. The total age is computed by adding all ten variables and storing the result in TotalAge. The average is calculated as AverageAge = TotalAge / 10. However, because both TotalAge and 10 are integers, the division performs integer division, which truncates the decimal portion. For example, if the total age is 123, the average is 12, not 12.3. The lecture notes that to preserve decimal values, variables of type float or double should be used instead of int. The complete program code is provided, demonstrating the sequence of declarations, input prompts, cin statements, calculations, and final output.
π Definition β cin: The input stream that gets data from the user and assigns it to the variable on its right side. The >> operator indicates the direction of data flow from the user to the variable.
π Formula: TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 + age9 + age10 ; β Adds all ten ages.
π Example: If user enters ages 12, 13, 11, 14, 13, 15, 12, 13, 14, 11, then TotalAge = 123, AverageAge = 123 / 10 = 12 (decimal truncated). Output: "Average age of class is: 12".
Examples of Expressions
This section shows how to translate algebraic expressions into C++ assignment statements. Since C++ has no power operator, multiplication is used directly. The precedence of arithmetic operators (*, /, % higher than +, -) determines evaluation order. Parentheses () can be used to force a specific order of evaluation and to improve readability. Examples given include: the quadratic equation y = axΒ² + bx + c becomes y = a * x * x + b * x + c, and x = a(x + b(y + czΒ²)) becomes x = a * (x + b * (y + c * z * z)). The lecture stresses that only parentheses () are available in C++ (not curly or square brackets), and that incorrect placement of parentheses can produce wrong results, as demonstrated by x = 2 + 4 * 3 = 14 versus x = (2 + 4) * 3 = 18.
π Definition β Operator Precedence: The order in which operators are evaluated in an expression. In C++, multiplication (*), division (/), and modulus (%) have higher precedence than addition (+) and subtraction (-). Expressions are evaluated left to right for operators of the same precedence.
π Formula: Algebraic y = axΒ² + bx + c β C++ y = a * x * x + b * x + c
π Example: x = ( b * b β 4 * a * c) / ( 2 * a ) correctly computes (bΒ² β 4ac) / 2a; without parentheses, b * b β 4 * a * c / 2 * a incorrectly computes bΒ² β (4ac/2) * a.
Use of Operators
This section presents two sample programs. The first program takes a four-digit integer from the user and displays its digits separately in reverse order. The logic uses the modulus operator % to extract the last digit (remainder when divided by 10). Then, the number is divided by 10 using integer division to remove the last digit. This process is repeated four times. The variable number is reused by reassigning its value (e.g., number = number / 10), which saves memory by avoiding additional variables. The second program calculates the diameter, circumference, and area of a circle given its radius. Variables are declared as float to handle decimal results. The formulas used are: diameter = radius * 2, circumference = 2 * 3.14 * radius, and area = 3.14 * radius * radius. The value 3.14 is used as an approximation of Pi.
π Definition β Modulus Operator (%): Returns the remainder of an integer division. For example, 1234 % 10 returns 4.
π Formula: digit = number % 10; number = number / 10; β Extracts the last digit of number and then removes it.
π Example: For number = 5678:
digit = 5678 % 10 = 8, display "8, ",number = 5678 / 10 = 567digit = 567 % 10 = 7, display "7, ",number = 567 / 10 = 56digit = 56 % 10 = 6, display "6, ",number = 56 / 10 = 5digit = 5 % 10 = 5, display "5". Output: "8, 7, 6, 5"
π Example (Circle): Radius = 5 β diameter = 10, circumference = 31.4, area = 78.5.
Tips
The lecture concludes with several programming tips for writing better code:
- Use descriptive names for variables (e.g.,
TotalAgeinstead ofx). - Indent the code for better readability and understanding.
- Use parentheses for clarity and to force the order of evaluation in an expression.
- Reuse variables for better usage of memory (e.g., reassigning
number = number / 10). - Take care of division by zero to avoid runtime errors.
- Analyze the problem properly, and then start coding (i.e., first think and then write).
β Key Takeaways
You must remember that integer division truncates the decimal part, so use float or double for precise averages. The modulus operator % is essential for extracting digits from an integer, while integer division / removes the last digit. Operator precedence determines evaluation order, and parentheses can override it, but incorrect placement leads to wrong results. Reusing variables by reassigning values saves memory and is a common practice. Always analyze the problem thoroughly before coding, and use clear prompts and descriptive variable names for readability.
π§ Quick Revision Questions
- What is the output of
cout << 17 / 5;and why? - How does the
cinstatement work, and what happens when the program reaches acinline? - Write the C++ expression for the algebraic formula:
x = (a + b) / (c - d). - Explain the process to extract all digits from a 4-digit number in reverse order.
- Why is it important to use
floatfor variables when calculating the area of a circle, and what would happen if you usedint?