LECTURE NOTE
on
PROGRAMMING IN “C”
 COURSE CODE: CS-SE 303
       By Revised Version
 Asst. Professor. Dr. Ghulam Ali
                          Programming fundamentals
                                          Lecture #1
Introduction, History and overview of Computer Programming
   •   VERY EXCITING CS APPLICATIONS
   •   MOBILE PHONES
   •   AMAZING INVENTIONS…it is software on the device that makes it all possible
   •   SOME FACTS…
   •   Pakistan's IT industry's global share is estimated at US$2.8 billion
   •   Indian Software, Technology Enabled Services (ITES) and Business Process Outsourcing
       (BPO) exports during 2011-12 were estimated at $68.02
   •   IT IS TIME TO ACT…ARE YOU UP FOR THE CHALLENGE???
   •   Introduction
   •   Without software, the computer is useless
   •   Software is developed with programming languages
   •   A Brief Overview of the History of Computers
          •   HISTORY 1
          •   HISTORY 2
History of The Computer Documentary
https://www.youtube.com/watch?v=VPDy2y4AjSo
   •   A Brief Overview of the History of Computers (cont’d.)
   •   Categories of computers
          •   Mainframe computers
          •   Midsize computers
         •   Micro computers (personal computers)
  •   Elements of a Computer System
  •   Hardware
  •   CPU
  •   Main memory
  •   Secondary storage
  •   Input/Output devices
  •   Software
  •   Hardware
  •   CPU
  •   Main memory: RAM
  •   Input/output devices
  •   Secondary storage
Inside The Computer
  •   Central Processing Unit and Main Memory
  •   Central processing unit
         •   Brain of the computer
         •   Most expensive piece of hardware
         •   Carries out arithmetic and logical operations
  •   Central Processing Unit and Main Memory (cont’d.)
  •   Central Processing Unit and Main Memory (cont'd.)
  •   Random access memory
         •   Directly connected to the CPU
  •   All programs must be loaded into main memory before they can be executed
  •   All data must be brought into main memory before it can be manipulated
•   When computer power is turned off, everything in main memory is lost
•   Central Processing Unit and Main Memory (cont’d.)
•   Main memory is where programs and data are kept during execution that the processor is
    actively working with.
•   Main memory is also called Random Access Memory (RAM) or primary memory.
•   "Random" means that the memory cells can be accessed in any order randomly.
•   Main memory is an ordered sequence of memory cells
       •   Each cell has a unique location in main memory, called the address of the cell
•   Each cell can contain either a programming instruction or data
•   Main memory is:
       •   very closely connected to the processor.
       •   the contents are quickly and easily changed.
       •   interacts with the processor millions of times per second.
•   Main Memory
•   It has two types of memory.
•   Random Access Memory (RAM)
       •   Volatile
       •   Random access to any memory location
       •   Read & write access
       •   Program + data reside in this memory
•   Read only Memory (ROM)
       •   Non volatile
       •   Only read access
       •   Permanent programs reside
•   Secondary Storage
  •   Secondary storage: device that stores information permanently
  •   Connected to main memory through the bus and a controller.
  •   The contents are easily changed, but this is very slow compared to main memory.
  •   Examples of secondary storage:
         •   Hard disks
         •   Flash drives
         •   Floppy disks
         •   Zip disks
         •   CD-ROMs
         •   Tapes
  •   Quick comparison of two types of storages:
Primary memory
  1. Fast
  2. Expensive
  3. Low capacity
  4. Connects directly to the processor
Secondary memory
  1. Slow
  2. Cheap
  3. Large capacity
  4. Not connected directly to the processor
  •   Input/Output Devices
  •   Input devices feed data and programs into computers
         •   Keyboard
         •   Mouse
         •   Secondary storage
 •   Output devices
display results
         •   Monitor
         •   Printer
         •   Secondary storage
 •   Software
 •   Software is a program and data that a computer uses.
         •   Programs that do specific tasks
 •   Software is kept on some hardware device such as a hard disk or floppy disk for further
     use.
 •   Programs are lists of instructions for the processor.
 •   Data can be any information that a program needs. It could be:
         •   character data, numerical data, image data, audio data, and countless other types.
 •   Types of Software
 •   System programs control the computer
         •   Operating system monitors the overall activity of the computer and provides
             services such as:
                  •    Memory management, Input/output activities, Storage management
 •   Application programs perform a specific task
         •   Word processors, Spreadsheets, Games
                                         Lecture #2
The Language of a Computer System
  •   The Language of a Computer
  •   When you press A on your keyboard, the computer displays A on the screen. But what is
      actually stored inside the computer’s main memory?
          •   What is the language of the computer?
          •   How does it store whatever you type on the keyboard?
  •   Analog signals: continuous wave forms
  •   Digital signals: sequences of 0s and 1s
                  •   Because digital signals are processed inside a computer, the language of a
                      computer, called machine language, is a sequence of 0s and 1s.
  •   The Language of a Computer (cont’d.)
  •   Machine language: language of a computer; a sequence of 0s and 1s.
  •   Binary digit (bit): The digit 0 or 1 is called a binary digit, or bit.
  •   The Language of a Computer (cont’d.)
  •   Binary code (binary number): a sequence of 0s and 1s.
  •   Bit: A binary digit (0 or 1)
  •   Byte:
          •   A sequence of eight bits
  •   Kilobyte (KB): 210 bytes = 1024 bytes
  •   The Language of a Computer (cont’d.)
  •   The Language of a Computer (cont’d.)
  •   Every letter, number, or special symbol (such as * or {) on your keyboard is encoded as a
      sequence of bits, each having a unique representation.
  •   ASCII (American Standard Code for Information Interchange)
          •   The most commonly used encoding scheme.
       •   128 characters (0-127)
       •   A is encoded as 1000001 (65 Ascii)
       •   3 is encoded as 0110011 (51)
•   The Language of a Computer (cont’d.)
•   Inside the computer, every character is represented as a sequence of eight bits, that is, as a
    byte.
•   ASCII is a seven-bit code. Therefore, to represent each ASCII character inside the
    computer, you must convert the seven-bit binary representation of an ASCII character to
    an eight-bit binary representation.
•   The Language of a Computer (cont’d.)
•   This is accomplished by adding 0 to the left of the seven-bit ASCII encoding of a
    character.
       •   A is represented as 01000001
       •   3 is represented as 00110011
                                      Lecture #3
Evolution of Programming languages
   •   The Evolution of Programming Languages
   •   The most basic language of a computer, the machine language, provides program
       instructions in bits.
   •   The machine language of one machine is not necessarily the same as the machine
       language of another machine.
   •   The Evolution of Programming Languages (cont’d.)
   •   The only uniformity among computers is that in any modern computer, all data is stored
       and manipulated as binary codes.
   •   Early computers were programmed in machine language.
          •   To represent the data, the programmer had to remember the machine language
              codes
   •   The Evolution of Programming Languages (cont’d.)
          •   Tough to remember the instructions/code in ‘0010101’ form.
          •   Chance of errors.
   •   Assembly languages were developed to make the programmer’s job easier.
   •   Assembly language uses letters and numbers to represent machine language instructions.
   •   Machine Language and Assembly Language are both called low-level languages.
   •   The Evolution of Programming Languages (cont’d.)
   •   Assembly language instructions are mnemonic (easy to remember form)
   •   Comparing Machine Language & Assembly Language
   •   For example, the machine code for adding two integers might be:
010000110011101000111101010000010010101101000010
   •   While the assembly language code might be:
       LOAD A
    ADD B
    STORE C
       •   This causes the number in A to be added to the number in B, and the result is
           stored for later use in C.
•   The Evolution of Programming Languages (cont’d.)
•   it is much easier to write instructions in assembly language
•   Using assembly language instructions, wages = rate * hours can be written as:
    LOAD rate
    MULT hour
    STOR wages
•   The Evolution of Programming Languages (cont’d.)
•   Assembler: translates a program written in assembly language into machine language.
•   Moving from machine language to assembly language made programming easier, but:
       •   a programmer was still forced to think in terms of individual machine
           instructions.
•   The Evolution of Programming Languages (cont’d.)
•   The next step toward making programming easier was to plan high-level languages that
    were closer to natural languages, such as English, French, German, and Spanish.
•   High-level languages include Basic, FORTRAN, COBOL, Pascal, C, C++, C#, and Java.
•   The Evolution of Programming Languages (cont’d.)
•   A program written in a high-level language is called source code.
•   The programs are translated into machine language by interpreters or compilers.
•   The resulting machine language code is known as object code
•   Interpreter: Translate each instruction from the programming language as needed (line
    by line of code).
•   Compiler: translates a program written in a high-level language into machine language. A
    compiler makes the translation once so that the source code don’t have to be translated
    each time the program is run.
•   Advantages Of
    High Level Languages
•   High Level Languages:
       •   Reduce the number of instructions that must be written.
       •   Allow programs to be written in a shorter amount of time than a low-level
           language would take.
       •   Reduce the number of errors that are made, because…
               •   The instructions are easier to read.
       •   Are more portable (the programs are easier to move among computers with
           different microprocessors).
•   High Level Language Examples
•   Consider the following programs that add two numbers together:
•   Some Online Games for Learn Coding
                                            Lecture #4
Introduction to Algorithms
  •   Algorithms.
  •   Sequence.
  •   Selection: if-then.
  •   Iteration: infinite loops.
  •   Incremental development of programs.
  •   Simple software testing.
  •   Scratch: interface, motion palette, looks palette, coordinates.
  •   Introduction
  •   Have you ever given someone directions to go from one location to another?
  •   Or have you ever taught a friend how to carry out a task?
          •   E.g.
                  •   how to tie their shoelaces.
                  •   Have you ever followed a recipe? Such as to bake a cake.
  •    If your answer to any of these questions, or to similar questions, yes, then you're already
      familiar with programming.
  •   Pseudocode
  •   It is a simple way of writing programming code in English.
  •   Pseudocode is not actual programming language.
  •   It uses short phrases to write code for programs before you actually create it in a specific
      language
  •   pseudocode
  •   1. stand up and assign yourself the number 1
  •   2. pair off with someone standing, add your numbers together,
    and adopt the sum as your new number
•   3. one of you should sit down; the other should go back to step 2
•   Everyday Life Example
•   How to make a sandwich
       •   Step -1 Two slices of bread,
       •   Step-2 Place a slice of ham over one slice of bread,
       •   Step-3 Place a slice of cheese over the ham,
       •   Step- 4 place a second slice of bread on top of the cheese
       •   This process is described as a sequence of steps, which are followed in order, one
           after the other.
•   Another Example
•   How to change a light bulb
•   Step-1 If you don't have a new light bulb buy a new one.
•   Step-2 Turn off the power.
•   Step-3 Repeat, twisting the light bulb counter clockwise until you remove it.
•   Step-4 Throw out the burned light bulb.
•   Step-5 Place the new lightbulb into the socket.
•   Step-6 Repeat, turning the light bulb clockwise until it is tight.
•   Step-7 Turn the power on.
    Here we have a sequence of ordered steps which also include a decision and a repetition.
•   Algorithm
•   This ordered sequence of steps is called an algorithm.
•   It is a finite set of instructions which, if followed accomplish a particular task.
•   Algorithms describe the procedure for carrying out a task or solving a problem in a step-
    by-step fashion.
•   They may include sequences, decisions, and iterations.
•   Algorithm is independent of the machine and language used for implementation.
•   Representation of Algorithm
•   Very often, there is more than one algorithm that effectively solves a problem.
•   Let's have a look at the following map and try to give directions to a person who is
    currently at the hotel and wants to get to the train station. Can you come up with two
    algorithms for this problem
•   One option would be
•   Step -1 face north,
•   Step-2 walk two blocks,
•   Step-3 Turn to the west,
•   Step-4 walk one block.
•   Another option could be
•   Step-1 face west,
•   Step-2 walk one block,
•   Step-3 face north,
•   Step-3 walk two blocks.
•   Algorithm in English
•   Informal definition
•   Assumptions
•   To solve any problem we must assume something in our mind before actually starting the
    solution.
•   Examples: Cross the street, bake a cake, pour a glass of juice, sum two numbers of three
    digits each?
•   In each case, it is important to think about the assumptions that we make.
•   For example, what assumption are we going to make for the traffic, when designing an
    algorithm for crossing the street?
•   Is it left-hand, or right-hand? We need to take into account the direction of the vehicles in
    order to check the corresponding side.
•   There might be steps which mean something different for different people.
•   For instance, if when telling someone how to bake a cake, we instruct them to put it in the
    oven for a short time, they, they wouldn't really know at what temperature the oven
    should be, or how long a short time really is.
•   Properties of Algorithm
•   Finiteness - there is an exact number of steps to be taken and has an end.
•   Absence of Ambiguity/precise - means that every instruction is precisely described and
    clearly specified.
•   Sequence of Execution - instructions are performed from top to bottom.
•   Input and Output - defined the unknowns of the problem is specified and with the
    expected outcome.
•   Effectiveness - the solution prescribed is guaranteed to give a correct answer and that the
    specified process is faithfully carried out.
•   Scope Definition - applies to a specific problem or class of problem.
•   Precise instructions
•   Draw a diagonal line.
•   Draw another diagonal line connected to the top of the first one.
•   Draw a vertical line over the point where the diagonal lines meet.
•   Draw a horizontal line over the straight line.
•   Draw a diagonal line from the bottom of the first diagonal to the straight line.
•   Draw a diagonal line from the bottom of the second diagonal to the straight line.
•   Draw a curvy line, starting at the bottom of the straight line. What did you come up with?
                                      Lecture # 5
Algorithm Representation and Examples
  •   Steps in Program Development
  1. State the problem clearly- a problem cannot be solved correctly unless it is being
     understood.
  2. Plan and Write the Logical Order of Instructions - the computer follows the direction
     exactly at the given sequence.
  3. Code the Program - write the programming statements in the desired language.
  4. Enter the program into the computer - key in or type the statement into the computer.
  5. Run and Debug the program - check if you have the desired output; if not, trace the
     possible error.
  •   Algorithm verses Program
  •   Basic differences are:
         •   Program is written in programming language whereas algorithm is in English like
             pseudo language.
         •   Program may be non terminating (OS) whereas algorithm should terminate in
             finite steps.
  •   Algorithm representation
  •   Flowchart
         •   A flowchart is a pictorial representation of an algorithm.
  •   Pseudocode
         •   Pseudocode is an English like representation of an algorithm.
  •   Flowchart symbols
  •   Flowcharts
  •   Lecture # 6
  •   1.6: Programming Constructs and Sub-Algorithm
•   Subalgorithms
•   The advantages of subalgorithms:
       •   It is more undersatandable.
       •   A subalgorithm can be called many times in different parts of the main algorithm
           without rewritten.
                          Lecture # 6
Programming Constructs and Sub-Algorithm
 Three constructs
Flowcharts for three constructs
Pseudocode for three constructs
 Example 1
Write an algorithm in pseudocode that finds
the average of two numbers.
Solution
                  Average Of Two
               Input: Two numbers
  1.    Add the two numbers
  2.    Divide the result by 2
  3.    Return the result by step 2
                     End
Example 2
 Write an algorithm to change a numeric grade to a pass/no pass grade.
Solution
                  Pass/NoPassGrade
                 Input: One number
 1. if (the number is greater
   than or equal to 60)
   then
      1.1 Set the grade to “pass”
                                    else
                   1.2 Set the grade to
                        “nopass”
                                 End if
 1.        Return the grade
                    End
 Example 4
Write an algorithm to find the largest of a set of numbers.
You do not know the number           of numbers.
       Sub algorithms
          •   The advantages of subalgorithms:
                 •   It is more undersatandable.
                 •   A subalgorithm can be called many times in different parts of the main algorithm
                     without rewritten.
                                             FindLargest
                          Input: A list of positive integers
        1.Set Largest to 0
        2.while (more integers)
           2.1 if (the integer is greater than Largest)
                  then
                   2.1.1 Set largest to the value of the
          integer
                End if
          End while
        3.Return Largest
                                 End
         SUBALGORITHMS
              Concept of a subalgorithm
Sub algorithms
   •   The advantages of subalgorithms:
          •   It is more undersatandable.
          •   A subalgorithm can be called many times in different parts of the main algorithm
              without rewritten.
                                    FindLargest
                  Input: A list of positive integers
          1. Set Largest to 0
          2. while (more integers)
             2.1 FindLargerNumber
             End while
          3. Return Largest
                                            End
                                      Lecture # 07
                      Algorithms and Problem Solution
Including this main goal as our main principle there are some more principle that are used
for the structured programming listed as:
   •   Standardization.
   •   Abstraction.
   •   Expressive Power.
   •   Orthogonality.
   •   Minimality.
Some Structured Programming Principles
As we have already shown, structured programming is a fundamental component of all
programming languages. It essentially turns our program into a linear structure in which the
execution of the program's statements begins at the beginning of the program and proceeds linearly
through the rest of it, executing each statement in turn in a set order. An efficient involvement in
all programming languages is made possible by such a feature. If every language has such a feature,
execution would be quite simple.
The basic idea behind structured programming is to linearize control flow in computer programs
so that execution sequences follow the order in which code is written. The following qualities are
made obvious by this significant principle:
There should only be one entrance and one exit.
None of the repetition and sequence selection constructions have more than three boxes. A third
characteristic becomes clear when we see any one of the three structures (described before) in use.
Beginning with the entrance and ending with the exit.
Therefore, this approach makes code more readable, which makes it simpler to comprehend, test,
debug, document, and modify programs.
In addition to this primary objective, which serves as our guiding principle, the following
additional principles are used for structured programming:
   •   Standardization
   •   Abstraction
   •   Expressive Strength
   •   Orthogonality
   •   Minimality
(a) Standardization: It is always preferable to construct software from parts that share a common
external interface. The basic colored face has one entering point at the beginning and one departure
point at the conclusion. This possesses the power of something that is consistent with the
fundamentals of sequential programming. Additionally, it complies with the crucial notion of
calling a procedure. We view the concept of calling a procedure as a sequential step that is followed
by a return to the following instruction.
If then else, while do, and similar structures also have the property of having a single entry at the
beginning and a single exit at the conclusion.
(b) Reaction: The most crucial concept in structured programming is definitely abstraction. The
human mind is incapable of creating or comprehending a complicated system in its entirety. It is
limited in its understanding of the system. However, it is necessary and crucial to comprehend the
entire system. As a result, abstraction is utilized to tackle this difficulty. The system must be
abstracted so that subsystems may be represented by a notation that makes it possible to view them
as opaque boxes with well known functions. The procedure has long been a mechanism in
programming that serves this purpose.
(c)Expressive Power: As we saw in section 6.5, 2.2, the go-to statement has relatively little
expressive power because it can have three to four different interpretations. Because of this, we
need a mechanism for recurrence, and both recursion and a while statement are adequate to offer
this facility. Both a while statement and a do while statement are available in many programming
languages. Recursion is a feature that most languages have.
(d) Orthogonality: A smart design approach when creating a group of facilities is to make each
feature as distinct from the others as you can. If this is the case, we may more easily achieve the
goal of having a minimal amount of functions while also making sure that the facilities are
powerful enough to meet all of our needs.
(e) Minimalism: When the minimality principle prevents us from incorporating too many
facilities. Therefore, in order to adhere to the idea of minimalism, the three constructs listed by
Boehm Jacopini are all that are necessary to create a structured program. Other control structures
exist that only use three boxes or less, but of all of them, this collection of three constructs is the
bare minimum.
                         Lecture #8
 Analysis–Coding–Execution Cycle and Processing a C
                   Programming
Programming with the Problem Analysis–Coding–Execution
Cycle
  • Programming is a process of problem
    solving/accomplishing a task.
           • Different people use different techniques to solve
             problems.
           • To be a good problem solver and a good
             programmer, you must follow good problem
             solving techniques.
  • One common problem-solving technique includes
    analyzing a problem, outlining the problem
    requirements, and designing steps, called an algorithm, to
    solve the problem.
The Problem Analysis–Coding–Execution Cycle (cont’d.)
   •   Step 1: Analyze the problem
             Outline the problem and its requirements
             Design steps (algorithm) to solve the problem
   •   Step 2: Implement the algorithm
             Implement the algorithm in code
             Verify that the algorithm works
   •   Step 3: Maintenance
             Use and modify the program if the problem domain changes
The Problem Analysis–Coding–Execution Cycle (cont’d.)
   •   Analyzing the problem is the first and most important step.
             Thoroughly understand the problem and all requirements
                     Does program require user interaction (input)?
                     Does program manipulate data?
                     What is the output?
             If the problem is complex, divide it into subproblems
                     Analyze and design algorithms for each subproblem
   •   After you carefully analyze the problem, the next step is to design an algorithm to solve
       the problem.
             If you broke the problem into subproblems, you need to design an algorithm for
              each subproblem
The Problem Analysis–Coding–Execution Cycle (cont’d.)
   •   Once you designed the algorithm, check the correctness of algorithm:
             Can test using sample data
             Some mathematical analysis might be required
   •   Once the algorithm is designed and correctness verified
             Write the equivalent code in high-level language
The Problem Analysis–Coding–Execution Cycle (cont’d.)
   •   Analyzing the problem is the first and most important step.
             Thoroughly understand the problem and all requirements
                     Does program require user interaction (input)?
                     Does program manipulate data?
                     What is the output?
          If the problem is complex, divide it into subproblems
                  Analyze and design algorithms for each subproblem
•   After you carefully analyze the problem, the next step is to design an algorithm to solve
    the problem.
          If you broke the problem into subproblems, you need to design an algorithm for
           each subproblem
•   Once you designed the algorithm, check the correctness of algorithm:
          Can test using sample data
          Some mathematical analysis might be required
•   Once the algorithm is designed and correctness verified
          Write the equivalent code in high-level language
•   Enter the program using text editor
          Make sure that the program follows the language’s syntax
•   Run code through compiler.
          If compiler generates errors
                  Look at code and remove errors
                  Run code again through compiler
•   If there are no syntax errors
          Compiler generates equivalent machine code
•   Linker links machine code with system resources, and the loader places the program
    into main memory for execution.
•   The final step is to execute the program
•   Compiler guarantees that the program follows the rules of the language
          Does not guarantee that the program will run correctly
          During execution, the program might terminate abnormally due to logical errors,
           such as division by zero.
•   Under these circumstances, you may have to reexamine the code, the algorithm, or even
    the problem analysis.
                                       Lecture # 9
       1.9: Programming Methodologies, Quick Review
Programming Methodologies
   •   Two popular approaches to programming design
             Structured
             Object-oriented
Structured Programming
   •   Structured design:
          – Dividing a problem into smaller subproblems
   •   Structured programming:
          – Implementing a structured design
                  •   Analyzing each subproblem
                  •   Obtaining solution for each subproblem
                  •   Combining the solution of each subproblem to obtain overall solution
   •   The structured design approach is also called:
          – Top-down (or bottom-up) design
          – Stepwise refinement
          – Modular programming
Object-Oriented Programming
   •   Object-oriented design (OOD)
             Identify components called objects
             Determine how objects interact with each other
   •   Specify relevant data and possible operations to be performed on that data
 •   Each object consists of data and operations on that data
 •   An object combines data and operations on the data into a single unit
 •   A programming language that implements OOD is called an object-oriented
     programming (OOP) language
 •   Must learn how to represent data in computer memory, how to manipulate data, and how
     to implement operations
Summary
 •   Computer: electronic device that can perform arithmetic and logical operations
 •   Computer system has hardware/software
           Central processing unit (CPU): brain
           Primary storage (MM) is volatile; secondary storage (e.g., disk) is permanent
           Operating system monitors overall activity of the computer and provides services
           Various kinds of languages
           Compiler: translates high-level language into machine code
           Algorithm: step-by-step problem-solving process; solution in finite amount of
            time
           Problem-solving process has three steps:
           Analyze problem and design an algorithm
           Implement the algorithm in code
           Maintain the program
           Structured design:
           Problem is divided into smaller subproblems
           Each subproblem is solved
           Combine solutions to all subproblems
           Object-oriented design (OOD): a program is a collection of interacting objects
           Object: data and operations on those data
                                      Lecture # 10
10.1 A Quick Look at a C++ Program, The Basics of a C++
                        Program
WRITING YOUR FIRST PROGRAM
  •   We have to follow the rules of writing the language.
  •   The rules by which a program is written is called SYNTAX
  •   Every line ends with a semicolon ;
  •   Everything that follows a // is a comment
  •   Everything in /*…*/ is a comment
Vocabulary
  •   Variable- A variable holds data that can change while the program is running
  •   Constant- A constant is used to store data that remains the same throughout the program’s
      execution
  •   Integers- Integers include the whole numbers and the negative numbers (no decimal
      points).
  •   Floating point numbers- Floating-point numbers are real numbers (have decimal points)
  •   Data type- Data type is a type of variable that best fits the nature of the data itself