CSC103
CSC103
Introduction to
Programming
CSC 103
All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, electronic, mechanical, photocopying,
recording or otherwise, without the prior permission of the copyright owner.
ISBN: 978-021-592-1
Best wishes.
Course Overview 3
Welcome to Introduction to Programming CIS104........................................................................................... 3
Course outcomes .............................................................................................................................................................. 3
Study Session 1 7
Overview of Programming ........................................................................................................................................... 7
Introduction .......................................................................................................................................................... 7
Terminology .......................................................................................................................................................... 7
1.1 Definition of Programming ..................................................................................................................... 7
1.1.1 Application Versus System Programming ....................................................................... 8
1.2 The Computer Program ............................................................................................................................ 9
1.2.1 Writing a Computer Program............................................................................................. 10
1.3 Characteristics of Computer Program ............................................................................................. 11
1.3.1 Portability ................................................................................................................................... 11
1.3.2 Readability.................................................................................................................................. 11
1.3.3 Efficiency ..................................................................................................................................... 12
1.3.4 Structural .................................................................................................................................... 12
1.3.5 Flexibility .................................................................................................................................... 12
1.3.6 Generality.................................................................................................................................... 12
1.3.7 Documentation ......................................................................................................................... 12
1.4 The Computer Programmer................................................................................................................. 14
1.4.1 The Work of a Computer Programmer .......................................................................... 14
Study Session Summary ............................................................................................................................................. 15
Assessment ...................................................................................................................................................................... 15
Bibliography .................................................................................................................................................................... 16
Study Session 2 17
History of Programming Languages ..................................................................................................................... 17
Introduction ....................................................................................................................................................... 17
Terminology ....................................................................................................................................................... 17
2.1 The Evolution of Programming Languages ................................................................................... 17
2.1.1 The First Computer Language............................................................................................ 19
2.1.2 The Birth of Assembly Language ...................................................................................... 19
2.1.3 The First Modern Computer Languages ........................................................................ 20
2.1.4 More Recent Modern Languages ...................................................................................... 21
2.2 Categorizing Computer Languages by Epochs............................................................................. 24
2.2.1 Summary of Important Programming Languages by Year .................................... 26
Study Session Summary ............................................................................................................................................. 28
Assessment ...................................................................................................................................................................... 28
Bibliography .................................................................................................................................................................... 28
Study Session 3 29
The Programming Process ........................................................................................................................................ 29
Introduction ....................................................................................................................................................... 29
Terminology ....................................................................................................................................................... 29
3.1 Problem Definition and Analysis ....................................................................................................... 30
3.1.1 Planning and Outlining the Solution ............................................................................... 30
3.2 Coding the Program................................................................................................................................. 31
3.3 Compilation................................................................................................................................................. 32
3.4 Debugging .................................................................................................................................................... 33
3.4.1 Syntax ........................................................................................................................................... 33
3.4.2 Semantics .................................................................................................................................... 34
3.4.3 Programming Errors .............................................................................................................. 35
3.5 Testing and Validation ........................................................................................................................... 37
3.5.1 Types of Programming Tests.............................................................................................. 38
3.6 Program Documentation ....................................................................................................................... 42
Study Session Summary ............................................................................................................................................. 43
Assessment ...................................................................................................................................................................... 43
Bibliography .................................................................................................................................................................... 44
Study Session 4 44
Types of Programming Languages ........................................................................................................................ 45
Introduction ....................................................................................................................................................... 45
4.1 Characteristics of Programming Languages ................................................................................. 45
4.2 Comparing Low-level and High-level Programming Languages.......................................... 46
4.3 Compiled code and interpreted code ......................................................................................... 47
4.4 Classification of Programming Languages .................................................................................... 47
4.4.1 Modular Programming Languages................................................................................... 48
4.4.2 Structured Programming Language ................................................................................ 48
4.4.3 Business Oriented Language .............................................................................................. 49
4.4.4 Object oriented programming (OOP) language .......................................................... 50
4.4.5 Visual Programming Languages........................................................................................ 51
Study Session Summary ............................................................................................................................................. 52
Assessment ...................................................................................................................................................................... 52
Credits................................................................................................................................................................................ 52
Study Session 5 54
Algorithms and Problem-Solving ........................................................................................................................... 54
Introduction ....................................................................................................................................................... 54
Terminology .......................................................................................... Error! Bookmark not defined.
5.1 The Problem Solving Process .............................................................................................................. 54
5.2 The Concept of Algorithm ..................................................................................................................... 55
5.2.1 Properties of Algorithm ........................................................................................................ 56
5.2.2 Algorithmic Problem Solving ............................................................................................. 56
5.3 Pseudo-Codes ............................................................................................................................................. 58
5.3.1 Rules for Writing Pseudocode ........................................................................................... 58
5.3.2 Advantages of Pseudocode .................................................................................................. 60
5.3.3 Disadvantages of Pseudocode ............................................................................................ 60
5.4 Flowchart ..................................................................................................................................................... 61
5.4.1 Advantages of Flowcharts.................................................................................................... 61
5.4.2 Disadvantages of Flowcharts.............................................................................................. 62
5.4.3 Flowchart Symbols ................................................................................................................. 62
5.4.4 General Guidelines in Flowcharting ................................................................................ 63
Study Session Summary ............................................................................................................................................. 66
Assessment ...................................................................................................................................................................... 66
Credits................................................................................................................................................................................ 66
Study Session 6 67
Basics of Computer Program ................................................................................................................................... 67
Introduction ....................................................................................................................................................... 67
Terminology ....................................................................................................................................................... 67
6.1 Programming Environment ................................................................................................................. 67
6.1.1 Text Editor .................................................................................................................................. 68
6.1.2 Compiler ...................................................................................................................................... 69
6.1.3 Interpreter .................................................................................................................................. 70
6.2 Basic Syntax of Programming ............................................................................................................. 71
6.2.1 Program Entry Point .............................................................................................................. 71
6.2.2 Functions..................................................................................................................................... 71
6.2.3 Comments ................................................................................................................................... 72
6.2.4 Whitespaces ............................................................................................................................... 72
6.2.5 Semicolons.................................................................................................................................. 74
6.2.6 Syntax Error ............................................................................................................................... 75
6.2.7Hello World Program in Java ............................................................................................... 76
6.2.8 Hello World Program in Python ........................................................................................ 76
6.3 Variables....................................................................................................................................................... 76
6.3.1 Creating Variables ................................................................................................................... 77
6.3.2 Storing Values in Variables.................................................................................................. 78
6.3.3 Accessing Stored Values in Variables ............................................................................. 79
6.3.4 Variables in Java ....................................................................................................................... 80
6.3.5 Variables in Python................................................................................................................. 80
6.4 Reserved Words ........................................................................................................................................ 81
6.4.1 C Programming Reserved Keywords .............................................................................. 82
6.4.2 Java Programming Reserved Keywords ........................................................................ 82
6.4.3 Python Programming Reserved Keywords .................................................................. 83
6.5 Operators ..................................................................................................................................................... 84
6.5.1 Arithmetic Operators ............................................................................................................. 84
6.5.2 Relational Operators .............................................................................................................. 86
6.5.3 Logical Operators .................................................................................................................... 88
6.5.4 Operators in Java ..................................................................................................................... 89
6.5.5 Operators in Python ............................................................................................................... 90
6.6 Functions ..................................................................................................................................................... 91
6.6.1 Defining a Function................................................................................................................. 93
6.6.2 Calling a Function .................................................................................................................... 93
Study Session Summary ............................................................................................................................................. 94
Assessment ...................................................................................................................................................................... 95
Credits................................................................................................................................................................................ 95
Study Session 7 96
Data Types ....................................................................................................................................................................... 96
Introduction ....................................................................................................................................................... 96
Terminology ....................................................................................................................................................... 96
7.1 Understanding Data Types ................................................................................................................... 96
7.1.1 C and Java Data Types............................................................................................................ 98
7.1.2 Python Data Types .................................................................................................................. 98
7.2 Data Type and Numbers Manipulation ........................................................................................... 99
7.2.1 Math Operations on Numbers ......................................................................................... 100
7.2.2 Numbers in Java .................................................................................................................... 102
7.2.3 Numbers in Python .............................................................................................................. 103
7.3 Data Type and character manipulation ....................................................................................... 104
7.3.1 Escape Sequences ................................................................................................................. 105
7.3.2 Characters in Java ................................................................................................................. 107
7.3.3 Characters in Python........................................................................................................... 108
7.4 Data Types and String Manipulation............................................................................................. 109
7.4.1 Basic String Concepts.......................................................................................................... 111
7.4.2 Strings in Java......................................................................................................................... 112
7.4.3 Strings in Python................................................................................................................... 112
Study Session Summary .......................................................................................................................................... 113
Assessment ................................................................................................................................................................... 113
Credits............................................................................................................................................................................. 114
1
About this course manual
Your comments
After completing Introduction to Programming we would appreciate it if
you would take a few moments to give us your feedback on any aspect of
this course. Your feedback might include comments on:
Course content and structure.
Course reading materials and resources.
Course assignments.
Course assessments.
Course duration.
Course support (assigned tutors, technical help, etc.)
Your constructive feedback will help us to improve and enhance this
course.
2
Course Overview
Course Overview
Welcome to Introduction to
Programming CSC103
Welcome to the Introduction to programming course! This course
introduces the fundamental concepts, principles and techniques involved
in modern computer programming. In addition, the course offers an
introduction to the historical context of programming. A systematic
approach is used to teach students various methods of algorithm
development, program development, and program design in order to write
programs that solve well-specified problems. Emphasis is placed on the
mastery of basic programming skills, with a considerable attention to the
fundamental building blocks of computer programs, and the associated
concepts and principles. The course also provides the core knowledge to
begin programming in any language. What we are exploring here are the
core ideas and skills you will always need when programming on any
platform with any language. Now there are dozens of programming
languages you could choose from and we will see many of them in this
course, languages like JavaScript, C, Ruby and Python. We will see what
these different languages are good at and why you might pick one over
another, but I won't be trying to make you an expert on any one of them.
Instead in this course we will go through what's common across all of
these languages. We will work with things like loops, conditionals,
variables, and memory; see how to control the structure and the flow of a
program; and what you need to know about what that program is doing
under the hood.
Finally, the course compares how code is written in several different
languages, the libraries and frameworks that have grown around them,
and the reasons to choose each one. Topics include Algorithms and
problem-solving, Fundamental programming constructs: Fundamental
data structures: Primitive types; arrays; records; strings and string
processing, Software development methodology: Fundamental design
concepts and principles, data types, control structures, functions, arrays,
files, and the mechanics of running, testing, and debugging.
Course outcomes
Upon completion of Introduction to Programming CIS104, you will be
able to:
3
Course Overview
4
Getting around this course manual
Margin icons
While working through this course manual you will notice the frequent
use of margin icons. These icons serve to “signpost” a particular piece of
text, a new task or change in activity; they have been included to help you
to find your way around this course manual.
A complete icon set is shown below. We suggest that you familiarize
yourself with the icons and their meaning before starting your study.
6
Study Session 1 Overview of Programming
Study Session 1
Overview of Programming
Introduction
In this study session, you will be discussing programming. You will
begin by defining programming. You will also differentiate between
application and system programming. Thereafter, you will examine
computer programming and how to write a computer program. Lastly,
you will describe who a computer programmer is.
Learning Outcomes
When we have studied this session, we should be able to:
1.1 define programming
1.2 describe a computer program
Outcomes 1.3 highlight the characteristics of a computer program
1.4 identify a computer programmer.
Terminology
Algorithm A precise step by step plan for a computational procedure
that possibly begins with an input value and yields an
output value I a finite number of steps
7
Study Session 1 Overview of Programming
ITQ
Question
What is the first step and important step in programming?
Feedback
The important first step is the need to have the solution in a format that
is acceptable and understandable by the computer.
ITQ
Question
What makes program work?
Feedback
Algorithm
8
Study Session 1 Overview of Programming
ITQ
Question
What are the two groups of computer programming?
Feedback
As described above, the two groups of computer programming could be
Application programming or Systems programming.
9
Study Session 1 Overview of Programming
ITQ
Question
Explain the term “statements” with respect to programming?
Feedback
Statements in programming languages have a similar role to what
sentences do in English language. Statements uses words, numbers, and
punctuation to express one thought, one individual piece in
programming. Your understanding of the how statement relate to
programming is key in grasping how a program functions.
10
Study Session 1 Overview of Programming
ITQ
Question
Using a flow chart, outline the basic steps in writing a computer program
Feedback
Compiler 1
•Simple Text File (source file) Link Editor
•Source Code
(linker/binder)
•Object Code
•Object file (machine code)
Executable file
1.3.1 Portability
Portability refers to the ability of an application to run on different
platforms (operating systems) with or without minimal changes. Due to
rapid development in the hardware and the software, nowadays platform
change is a common phenomenon. Hence, if a program is developed for a
particular platform, then the life span of the program is severely affected.
1.3.2 Readability
The program should be written in such a way that it makes other
programmers or users to follow the logic of the program without much
effort. If a program is written structurally, it helps the programmers to
understand their own program in a better way. Even if some
computational efficiency needs to be sacrificed for better readability, it is
11
Study Session 1 Overview of Programming
1.3.3 Efficiency
Every program requires certain processing time and memory to process
the instructions and data. As the processing power and memory are the
most precious resources of a computer, a program should be laid out in
such a manner that it utilizes the least amount of memory and processing
time. Programs written in a good programming language are efficiently
translated into machine code, are efficiently executed, and acquire as
little space in the memory as possible. That is a good programming
language is supported with a good language translator which gives due
consideration to space and time efficiency.
1.3.4 Structural
To develop a program, the task must be broken down into a number of
subtasks. These subtasks are developed independently, and each subtask
is able to perform the assigned job without the help of any other subtask.
If a program is developed structurally, it becomes more readable, and the
testing and documentation process also gets easier. A Structured program
implies that the language should have necessary features to allow its users
to write their programs based on the concepts of structured programming.
This property of a moreover, it forces a programmer to look at a problem
in a logical way, so that fewer errors are created while writing a program
for the problem.
1.3.5 Flexibility
A program should be flexible enough to handle most of the changes
without having to rewrite the entire program. Most of the programs are
developed for a certain period and they require modifications from time
to time. For example, in case of payroll management, as the time
progresses, some employees may leave the company while some others
may join. Hence, the payroll application should be flexible enough to
incorporate all the changes without having to reconstruct the entire
application.
1.3.6 Generality
Apart from flexibility, the program should also be general. Generality
means that if a program is developed for a particular task, then it should
also be used for all similar tasks of the same domain. For example, if a
program is developed for a particular organization, then it should suit all
the other similar organizations.
1.3.7 Documentation
Documentation is one of the most important components of an
application development. Even if a program is developed following the
best programming practices, it will be rendered useless if the end user is
not able to fully utilize the functionality of the application. A well-
12
Study Session 1 Overview of Programming
ITQ
Question
What does the term ‘flexibility’ refer to?
Feedback
Flexibility refers to the ability of a program to handle most of the
changes without having to rewrite the entire program. This is necessary
as most programs are developed for a certain period and they require
modifications from time to time. Therefore, the payroll application
should be flexible enough to incorporate all the changes without having
to reconstruct the entire application.
13
Study Session 1 Overview of Programming
ITQ
Question
What other names can we call a computer programmer?
Feedback
A computer programmer can also be called a developer, coder, or
software engineer.
14
Study Session 1 Overview of Programming
ITQ
Question
What is the sole purpose of a computer programmer?
Feedback
The purpose of programming is to create a program that produces a
certain desired behaviour (customization). The process of writing source
code often requires expertise in many different subjects, including
knowledge of the application domain, specialized algorithms and formal
logic.
Assessment
SAQ 1.1 (tests Learning Outcome 1.1)
1. What is the essence of programming?
2. What is the essence of programming?
Assessment SAQ 1.2 (tests learning outcome 1.2)
What is a computer program?
SAQ 1.3 (tests learning outcome 1.3)
15
Study Session 1 Overview of Programming
Bibliography
http://www.cs.bham.ac.uk/~rxb/java/intro/2programming.html)
http://interactivepython.org/runestone/static/pythonds/Introduction/Wha
tIsProgramming.html
Reading http://www.79xperts.com/blog/good-computer-program/
https://en.wikipedia.org/wiki/Semantics_(computer_science)
https://en.wikipedia.org/wiki/Logic_errorhttps://en.wikipedia.org/wiki/L
ogic_error
https://en.wikipedia.org/wiki/Integration_testinghttps://en.wikipedia.org
/wiki/Integration_testing
https://en.wikipedia.org/wiki/unit_testinghttps://en.wikipedia.org/wiki/u
nit_testing
https://en.wikipedia.org/wiki/smoke_testing
Cem Kaner, James Bach, Bret Pettichord, Lessons learned in software
testing: a context-driven approach. Wiley, 2001
16
Study Session 2 History of Programming Languages
Study Session 2
Learning Outcomes
When you have studied this session, you should be able to:
2.1 trace the evolution of programming languages
2.2 categorize computer languages by epochs
Outcomes
Terminology
Formulaic Closely following a formula or predictable pattern
17
Study Session 2 History of Programming Languages
Analytical Engine
ITQ
Question
Why was Ada Lovelace’s set of notes recognized as the world’s first
computer program?
Feedback
Some historians have recognized Ada Lovelace’s set of notes, as the
world’s first computer program because it contained a groundbreaking
description of the possibilities of programming the machine to go
beyond number crunching to “computing”.
18
Study Session 2 History of Programming Languages
Question
Who created the first computer language?
Feedback
Herman Hollerith
19
Study Session 2 History of Programming Languages
ITQ
Question
Where was Autocode developed?
Feedback
Autocode was developed in the early 1950s at the University of
Manchester.
20
Study Session 2 History of Programming Languages
ITQ
Question
Who was responsible for the development of FORTRAN?
Feedback
John Warner Backus, an American computer scientist.
21
Study Session 2 History of Programming Languages
22
Study Session 2 History of Programming Languages
Hejlsberg. The most recent version is C# 6.0, which was released on July
20, 2015.
In January 1999, Anders Hejlsberg formed a team to build a new
language at the time called Cool, which stood for “C-like Object Oriented
Language”. Microsoft had considered keeping the name “Cool” as the
final name of the language, but chose not to do so for trademark reasons.
By the time the .NET project was publicly announced at the July 2000
Professional Developers Conference, the language had been renamed C#.
ITQ
Question
Who created C++?
Feedback
Bjarne Stroustrup created C++.
Born in 2003, Scala is a programming language for general software
applications. The name Scala is a portmanteau of “scalable” and
“language”, signifying that it is designed to grow with the demands of its
users. Scala has full support for functional programming and a very
strong static type system. This allows programs written in Scala to be
very concise and thus smaller in size than other general-purpose
programming languages. The design of Scala started in 2001 at the École
Polytechnique Fédérale de Lausanne (EPFL) by Martin Odersky,
following on from work on Funnel, a programming language combining
ideas from functional programming and Petri nets. Odersky had
previously worked on Generic Java and javac, Sun’s Java compiler.
In 2009, the Go language was born. It is also commonly referred to as
golang, is a programming language developed at Google. Go is
recognizably in the tradition of C, but makes many changes to improve
conciseness, simplicity, and safety. Go was developed at Google in 2007
by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically
typed language with syntax loosely derived from that of C, adding
garbage collection, type safety, some dynamic-typing capabilities,
additional built-in types such as variable-length arrays & key-value maps,
and a large standard library. Swift was introduced at Apple’s 2014
Worldwide Developers Conference (WWDC), It underwent an upgrade to
version 1.2 during 2014, and a more major upgrade to Swift 2 at WWDC
2015. Swift is a multi-paradigm, compiled programming language
created by Apple Inc. for iOS, OS X, and watch OS development. Swift
is designed to work with Apple’s Cocoa and Cocoa Touch frameworks
and the large body of existing Objective-C code written for Apple
products. Swift is intended to be more resilient to erroneous code
(“safer”) than Objective-C, and more concise. Development on Swift
began in 2010 by Chris Lattner, with the eventual collaboration of many
other programmers at Apple. Swift took language ideas “from Objective-
C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to
list”. On June 2, 2014, the Worldwide Developers Conference (WWDC)
application became the first publicly released app written in Swift.
23
Study Session 2 History of Programming Languages
ITQ
Question
When was Python created?
Feedback
1991
24
Study Session 2 History of Programming Languages
ITQ
Question
Which primary epoch had more impact on programming and language
design than any other language?
Feedback
The C Era.
According to Raik-Allen, the historical perspective above is one way to
look at it, but there are a few others. Which he sliced across some other
dimensions:
1. The Web Dimension: For rapidly building web sites Perl (1987)
and PHP (1995) have been two popular choices for a number of
years. Among other things they make it easy to merge business
data and page layout for delivery to web browsers. There are also
many Web Application Frameworks, which are pre-built
components, which provide many of the features required to
build and manage web sites. Different versions of these have
been built in most of the popular programming languages.
2. The Corporate Dimension : The big technology companies have
each largely aligned themselves with different languages stacks.
Oracle and IBM are aligned with Java (Oracle actually owns
Java). Google are known for their use of Python (1997), a very
versatile, dynamic and extensible language, although in reality
they are also heavy users of C++ and Java. They have also
created their own language called Go (2009). Developers who
use Microsoft technology tend to use their systems, tools, and
languages exclusively, and for over a decade now Microsoft have
focused their efforts on their own language C# (pronounced 'see
sharp'). Although its namesake is C it began life (debatably)
closer to Java and was reportedly developed as a response to
Java's growing popularity in 2000. That said, C# has since
evolved rapidly into a rich and eloquent language and if there
was any similarity to Java, it's gone. C# has been enjoying solid
growth in popularity since day one. Another language worth
mentioning is BASIC. Originally from 1964 BASIC took off
when it found its way onto almost every Personal Computer from
the 70s and 80s and two variants are still extremely popular
today. Both are made by Microsoft.
ITQ
Question
Which language is regarded as the most popular programming language
in existence today?
Feedback
The Java Language
3. The Mobile Dimension: This is the language of Apple's mobile
phones and tablets. Although officially published in 1986 it
25
Study Session 2 History of Programming Languages
remained almost dormant until the rise of the App Store in 2009.
Since then it has been one of the fastest growing languages each
year. On the other hand, Google's Android mobile platform uses
Java to write applications which is surely contributing to that
language's current popularity in a significant way.
ITQ
Question
What programming language has Oracle and IBM aligned themselves?
Feedback
Oracle and IBM are aligned with Java (Oracle actually owns Java).
4. The New Age Dimension: There is of late an emerging backlash
to the highly verbose and structured C-derived languages. Many
developers are wanting to do more with less and hence we are
seeing a rise in a number of more succinct, streamlined, and
potentially more productive languages. Three worth mentioning
are Clojure (2007), Scala (2003), and Ruby (1993). Clojure is a
modern interpretation of an older language called LISP (from the
Fortran days). Scala was designed to be a 'better Java' and has
added many new features to the language over the last few years,
making it also more C#-like. Ruby is definitely the most popular
of the bunch and has been sitting just inside the top 10 for a few
years.
ITQ
Question
What is Google known with and what other languages do they make use
of?
Feedback
Google is known for their use of Python (1997), a very versatile,
dynamic and extensible language.
They are also heavy users of C++ and Java.
26
Study Session 2 History of Programming Languages
27
Study Session 2 History of Programming Languages
Assessment
SAQ 2.1 (tests Learning Outcome 2.1)
What are the key points in the evolution of programming languages?
Assessment SAQ 2.2 (tests Learning Outcome 2.2)
1. How do you categorize computer languages by epochs?
2. Give a summary of the important languages by year.
Bibliography
https://en.wikipedia.org/wiki/Programming_languagehttps://en.wikipedi
a.org/wiki/Programming_language
http://www.ricardodsanchez.com/2015/08/31/programming-a-short-
history-of-computer-languages/
Reading
28
Study Session 3 The Programming Process
Study Session 3
Learning Outcomes
When you have studied this session, you should be able to:
3.1 explain problem definition and analysis
3.2 discuss the process of coding the program
Outcomes 3.3 define compilation
3.4 define debugging
3.5 explain testing and validation
3.6 describe programming documentation
Terminology
Flowchart A schematic representation of how the different stages in
a process are interconnected
Syntax A set of rules that govern how words are combined to form
phrases and sentences
29
Study Session 3 The Programming Process
Question
How do you identify a problem in programming?
Feedback
To identify a problem, there must be a need. The need from the end-
user/clients determines what the problem is and how to solve it
30
Study Session 3 The Programming Process
ITQ
Question
What is the uniqueness of the Pseudocode?
Feedback
Pseudocode allows you state your solution with precision and permits
you to focus on the program logic
31
Study Session 3 The Programming Process
ITQ
Question
What is the idea behind coding a program?
Feedback
It allows you not just to state your solution in plain English but to
express your solution in a programming language.
3.3 Compilation
Every programming language has to take a set of programming
specifications and translate them, i.e. create a means to execute those
specifications, by using a compiler. Technically, the term, compiler
generally means a program that produces a separate executable from the
compiler (that may require a run time library or subsystem to operate), a
compiler that merely executes the original specifications is usually
referred to as an "interpreter", although because of differing methods of
analyzing what represents compilation and what represents interpretation,
there is some overlap between the two terms. Compilation turns the
program into the instructions made up of 0's and 1's that the computer can
actually follow. This is necessary because the chip that makes your
computer work only understands binary machine code - something that
most humans would have a great deal of trouble using since it looks
something like:
01010101 11111101 10111100 10000001 10010001
Early programmers actually used to write their programs in that sort of a
style - but luckily they soon learnt how to create programs that could take
something written in a more understandable language and translate it into
this gobbled gook. These programs are called compilers, and you can
think of them simply as translators that can read a programming
language, translate it and write out the corresponding machine code.
Compilers are notoriously pedantic though - if you don't write very
correct programs, they will complain. Think of them as the strictest sort
of English teacher, who picks you up on every single missing comma,
misplaced apostrophe and grammatical error. This is where debugging
makes it first appearance, since once the compiler has looked at your
program it is likely to come back to you with a list of mistakes, the next
thing is to correct these mistakes through a process known as debugging,,
otherwise the program will not execute.
32
Study Session 3 The Programming Process
ITQ
Question
What can a compiler be compared with?
Feedback
I don’t know what you have compared a compilier with, but a compiler
can be compared with a translator. This is because they can read a
program language, translate it, and write out the corresponding machine
code.
3.4 Debugging
Debugging is the process of detecting, locating and fixing or bypassing
errors, typically known as bugs in the process of compiling a computer
program. When we compile program, we debug the program by looking
at the error messages that are displayed due to syntax error, and removing
the bug or error so that no erroneous messages are displayed. It is a
common daily life event in software industries. When a program is coded
carefully, bugs can still creep stealthily into the program. Some compilers
are equipped with debugger to remove programming errors. These
compilers diagnose errors and debug them carefully.
It should be noted that it is not actually necessary to write the entire
program before you start to compile and debug. In most cases it is better
to write a small section of the code first, get that to work, and then move
on to the next stage. This reduces the amount of code that needs to be
debugged each time and generally creates a good feeling of "getting
there" as each section is completed. Finally, the compiler presents you
with a program that the computer can run, hopefully, your solution!
To clearly understand the concept of debugging in computer programs, it
is important to first understand the concepts of Syntax, Semantics, and
program errors.
ITQ
Question
How do you improve outcome and save time while programing?
Feedback
You could save time and improve the speed of programming by
debugging in bits. Do not wait until you finish writing your program
before you start debugging. That could be overwhelming! To avoid that,
once you have written up to a particular level, you should commence the
process of debugging.
3.4.1 Syntax
The syntax of a computer language is the set of rules that defines the
combinations of symbols that are considered to be a correctly structured
document or fragment in that language. Simply put, syntax is the basic
33
Study Session 3 The Programming Process
ITQ
Question
What is syntax?
Feedback
Syntax is the basic spelling and grammar of a particular programming
language in order to indicates the program’s validity.
3.4.2 Semantics
Semantics of a programming language refer to the rules that give
meaning to programs. We can say syntax has specific output oriented
meaning, which is called semantics. It's refers to the meaning of the
language elements in terms of what they formally mean as regards
computation (operational semantics). This means that it expresses what a
term of your language effectively does assuming an underlying kind of
model that depends on which semantic we are talking about.
Wikipedia describes 3 kinds of semantics as follows:
1. operational semantics express the meaning of the language by
specifying how an abstract virtual machine behaves whenever it
executes a term. (eg: +: pops two elements from the stack and
push the sum. This is NOT formal and it is NOT how you should
really consider it, it's just to give you an idea). This is the most
used one to describe semantics of "normal" programming
languages. For example for Java you could have, for every
possible term, a sequence of JVM instruction meant to be
executed to model that term. Probably when you asked for the
meaning of semantics this is the one you were looking for.
2. Denotational semantics is a different approach: you give for
every term of the language a meaning that is represented by a
mathematical function. So for previous example you would have
a function f associated with + that contains what is the semantic
(effective meaning) of the term
3. axiomatic semantics is a way to annotate the terms of your
language expressing how they alter the validity of some logical
formulas you want to verify over your program. You should
consider reading this just because the inference rules and axioms
used are similar in how you develop this kind of semantics but
it's explained in a practical way
From this description above, you understand that a semantic is something
well defined inside a context, and you need a specified context otherwise
you couldn't give you language a formal definition of what its terms do..
34
Study Session 3 The Programming Process
Example 3.1
The semantics of the following equation tells that sum of x and y is
assigned to variable sum:
Sum = x + y
Example 3.2
Consider another equation below:
p =q*r+1/2*s*r*r
It is a syntax which has two set of variables. In right set has ‘q’, ‘r’ and
‘s’ variables and left set has only one variable ‘p’. The semantics tells
that right side has operators +, / and * working over variables. In first
step, variables are multiplied (one set ‘q’ and ‘r’ and other set s, r and r),
then 1 is divided by2*s*r*r and added to q * r, and sum is assigned to p.
Syntax is the rule used by programming grammar. So programming
statement may be correct on the basis of syntax, but it may be
semantically wrong.
ITQ
Question
What is the most important rule in programming with respect to
Semantics?
Feedback
Syntax is the rule used by programming grammar. So
programming statement may be correct because of syntax, but it
may be semantically wrong. Therefore, it is essential that you
understand the rules of semantics, how it applies to programming,
and syntax.
35
Study Session 3 The Programming Process
3. Misspelled keywords.
4. Extra blanks or missing blanks also cause syntax errors.
5. All type of operators is very sensitive to produce syntax errors,
when not used properly.
6. The use of colon (:) instead of semi-colon (;) causes syntax
errors.
The syntax errors are displayed at the time of program compilation
because compilers and interpreters are equipped with error-diagnostic
features. These errors are easily debugged from programs and some
compilers check erroneous input and recover errors also. The 50 to 75%
overall programming times are to be spent on debugging. 8023588240
8167518347 7034993743
Run-time Errors are the errors appeared at the time of program execution
Compilers do not detect these types of errors because these types of
errors are not caused by syntax errors. Rather, they are noticed at the
time of execution.
A logic error is a bug in a program that causes it to operate incorrectly
and the compiler or interpreter is unable to detect these type of errors. A
logic error produces an incorrect or unintended or undesired output or
other behaviour, although it may not immediately be recognised as such.
As an example, telling a computer to repeat an operation but not telling it
how to stop repeating may result in a situation where the program runs in
an endless cycle. Logic errors occur in both compiled and interpreted
languages. The only clue to the existence of logic errors is the production
of wrong solutions. One of the ways to find these type of errors is to
output the program's variables to a file or on the screen in order to define
the error's location in code. Although this will not work in all cases, for
example when calling the wrong subroutine, it is the easiest way to find
the problem if the program uses the incorrect results of a bad
mathematical calculation.
Example 3.3
This example function in C to calculate the average of two numbers
contains a logic error. It is missing brackets in the calculation, so it
compiles and runs but does not give the right answer due to operator
precedence (division is evaluated before addition).
int average(int a, int b)
{
return a + b / 2; /* should be (a + b) / 2 */
}
Example 3.4
The following statements are intended to be used to find the roots of a
quadratic equation. They are syntactically acceptable and would not
cause any error message but produce wrong outputs.
X1 = -b+sqrt(b^2-4*a*c/2*a);
X2 = -b-sqrt(b^2-4*a*c)/2*a;
36
Study Session 3 The Programming Process
ITQ
Question
Describe briefly the types of error in a program?
Feedback
The errors in a program are described as follows:
Syntax errors, which occur because rules guiding program
coding have not been followed.
Run-time Errors often appear at the time of program execution
Compilers do not detect these types of errors because these types
of errors are not caused by syntax errors.
A logic error is a bug in a program that causes it to operate
incorrectly and the compiler or interpreter is unable to detect
these type of errors.
37
Study Session 3 The Programming Process
4. is sufficiently usable,
5. can be installed and run in its intended environments, and
6. achieves the general result its stakeholders desire.
ITQ
Question
Mention two properties needed before a software can be tested.
Feedback
1. The software must meet the requirements that guided its design
and development, and
2. The software should respond correctly to all kinds of inputs.
38
Study Session 3 The Programming Process
39
Study Session 3 The Programming Process
ITQ
Question
What is the central theme of program testing?
Feedback
Program testing is an important tool used by either program developers
or end users to check whether a program would function properly amidst
several constraints that should make the program not function properly.
The weak and faulty areas are identified, corrected, and improved for an
enjoyable experience by the end users.
40
Study Session 3 The Programming Process
41
Study Session 3 The Programming Process
ITQ
Question
What is Regression testing?
Feedback
Regression testing is a type of software testing that verifies that software
previously developed and tested still performs correctly after it was
changed or interfaced with other software. Changes may include
software enhancements, patches, configuration changes, etc. During
regression testing, new software bugs or regressions may be uncovered.
Sometimes a Software Change Impact Analysis is performed to
determine what areas could be affected by the proposed changes.
42
Study Session 3 The Programming Process
Question
What is program documentation?
Feedback
Program documentation is a written text or illustration that accompanies
computer software.
ITQ
Question
What is the smart thing to do while undergoing the process of program
documentation?
Feedback
The wise programmer continues to document the program throughout its
design, development, and testing. This is necessary, as documentation is
needed to supplement human memory and to help organize program
planning.
Assessment
SAQ 3.1 (tests learning outcome 3.1)
1. What does Problem definition and Analysis entails?
2. How would you plan and outline solutions to the problems you
Assessment have identified?
SAQ 3.2 (tests learning outcome 3.2)
What are the processes of coding a program?
SAQ 3.3 (tests learning outcome 3.3)
What is compilation?
43
Study Session 3 The Programming Process
Bibliography
https://en.wikipedia.org/wiki/Software_documentation
Reading
44
Study Session 4 Types of Programming Languages
Study Session 4
Learning Outcomes
When you have studied this session, you should be able to:
4.1 highlight the characteristics of programming languages
4.2 compare low-level and high-level programming languages
Outcomes 4.3 describe the compiled code and interpreted code
4.4 identify the classifications of programming languages
45
Study Session 4 Types of Programming Languages
Question
List two characteristics of programming language
Feedback
Syntax and structure; Natural lifespan
46
Study Session 4 Types of Programming Languages
Question
What is the peculiarity of program languages?
Feedback
Some program languages (JavaScript, Python) are interpreted while
others (C++, COBOL) are compiled.
47
Study Session 4 Types of Programming Languages
Question
What are the unique advantages of methodology programming
language?
Feedback
It is easier to understand, easier to code, document, and modify.
48
Study Session 4 Types of Programming Languages
Question
How is ‘sequence’ different from ‘selection’?
Feedback
Sequence means going from step one to step two and so on. It does not
involve looping or branching, while Selection is used whenever choices
are to be executed between two options.
49
Study Session 4 Types of Programming Languages
Question
Mention one example of Logic Programming Language?
Feedback
A known and commercially available logic programming language is
PROLOG, which stands for PROgramming in LOGic. Its unique
property is its level of abstraction.
50
Study Session 4 Types of Programming Languages
ITQ
Question
What is the aim of using Object-Oriented Programming Language?
Feedback
The aim of using an object oriented programming language is to handle
complex software design projects in a very easy, simple and efficient
manner.
ITQ
Question
Mention examples of visual programming languages and their
application domains?
Feedback
Examples of visual programming languages include Visual Basic, Visual
51
Study Session 4 Types of Programming Languages
Assessment
SAQ 4.1 (tests Learning Outcome 4.1)
What are the characteristics of programming languages?
Assessment SAQ 4.2 (tests learning outcome 4.2)
How will you compare low-level and high level programming
languages?
SAQ 4.3 (tests learning outcome 4.3)
Identify the classifications of programming languages?
52
Study Session 4 Types of Programming Languages
Credits
This lesson has been adapted from:
http://www.uew.edu.gh/sites/default/files/teaching%20materials/A_BRI
EF_HISTORY_OF_PROGRAMMING_LANGUAGES_Sem2_2012.pd
fhttp://www.uew.edu.gh/sites/default/files/teaching
Reading materials/A_BRIEF_HISTORY_OF_PROGRAMMING_LANGUAGE
S_Sem2_2012.pdf
http://www.uew.edu.gh/sites/default/files/teaching
materials/A_BRIEF_HISTORY_OF_PROGRAMMING_LANGUAGE
S_Sem2_2012.pdf
http://www.dummies.com/how-to/content/the-types-of-programming-
languages.htmlhttp://www.dummies.com/how-to/content/the-types-of-
programming-languages.html
http://www.uew.edu.gh/sites/default/files/teaching%20materials/A_BRI
EF_HISTORY_OF_PROGRAMMING_LANGUAGES_Sem2_2012.pd
fhttp://www.uew.edu.gh/sites/default/files/teaching
materials/A_BRIEF_HISTORY_OF_PROGRAMMING_LANGUAGE
S_Sem2_2012.pdf
http://www.dummies.com/how-to/content/the-types-of-programming-
languages.html
53
Study Session 5 Algorithms and Problem-Solving
Study Session 5
Learning Outcomes
When you have studied this session, you should be able to:
5.1 explain the problem solving process
5.2 describe algorithm
Outcomes 5.3 discuss pseudo-codes
5.4 illustrate flowchart
54
Study Session 5 Algorithms and Problem-Solving
Question
How many phases are involved in the problem-solving process?
Feedback
Four (4)
55
Study Session 5 Algorithms and Problem-Solving
ITQ
Question
How can do programmers view Algorithms?
Feedback
Programmers often see algorithm as a systematic procedure to resolve
any problem. They also agree that it is an effective method expressed as
a finite set of well-defined instructions.
ITQ
Question
List the essential properties of Algorithms?
Feedback
Finiteness, definiteness, input, output, and effectiveness.
56
Study Session 5 Algorithms and Problem-Solving
57
Study Session 5 Algorithms and Problem-Solving
ITQ
Question
What is the most important rule for a computer programmer?
Feedback
A computer programmer lists down all the steps required to resolve a
problem before writing the actual code.
5.3 Pseudo-Codes
Pseudocode is an informal high-level description of the operating
principle of a computer program or other algorithm. It uses the structural
conventions of a normal programming language, but is intended for
human reading rather than machine reading. Pseudocode typically omits
details that are essential for machine understanding of the algorithm, such
as variable declarations, system-specific code and some subroutines. The
programming language is augmented with natural language description
details, where convenient, or with compact mathematical notation. The
purpose of using pseudocode is that it is easier for people to understand
than conventional programming language code, and that it is an efficient
and environment-independent description of the key principles of an
algorithm. It is commonly used in textbooks and scientific publications
that are documenting various algorithms, and also in planning of
computer program development, for sketching out the structure of the
program before the actual coding takes place.
No standard for pseudocode syntax exists, as a program in pseudocode is
not an executable program. Pseudocode resembles, but should not be
confused with skeleton programs which can be compiled without errors.
Flowcharts, drakon-charts and Unified Modeling Language (UML) charts
can be thought of as a graphical alternative to pseudocode, but are more
spacious on paper.
ITQ
Question
What augments Pseudo-Code?
Feedback
The programming language (Pseudo-Code) is augmented with natural
language description details, where convenient, or with compact
mathematical notation.
58
Study Session 5 Algorithms and Problem-Solving
59
Study Session 5 Algorithms and Problem-Solving
you are SURE it will be written in that language, then you can
use the features. If not, then avoid using the special features.
ITQ
Question
Highlight the rules for writing Pseudo-codes?
Feedback
1. Write only one statement per line
2. Capitalize the keywords
3. Indent to show hierarchy
4. End multiline structures
5. Keep stats language independent
Example 5.5
The pseudocode below prints “failed” or “passed” depending on
whether or not the student’s grade is less than 60.
1. If student's grade is greater than or equal to 60
Print "passed"
Else
Print "failed"
Example 5.6
The pseudocode below finds the class average by using the
grades of all students in the class as input:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
60
Study Session 5 Algorithms and Problem-Solving
Question
What are the disadvantages of using Pseudo-Codes?
Feedback
1. Pseudo-Code is not visual.
2. Pseudo-Code does not reveal a picture of the design.
5.4 Flowchart
Algorithms are nothing but sequence of steps for solving problems. So a
flow chart can be used for representing an algorithm. A flowchart is a
graphical representation of an algorithm, which will describe the
operations (and in what sequence) are required to solve a given problem.
These flowcharts play a vital role in the programming of a problem and
are quite helpful in understanding the logic of complicated and lengthy
problems. You can see a flow chart as a blueprint of a design you have
made for solving a problem. For example suppose you are going for a
picnic with your friends then you plan for the activities you will do there.
If you have a plan of activities then you know clearly when you will do
what activity. Similarly when you have a problem to solve using
computer or in other word you need to write a computer program for a
problem then it will be good to draw a flowchart prior to writing a
computer program. Once the flowchart is drawn, it becomes easy to write
the program in any high level language. Often we see how flowcharts are
helpful in explaining the program to others. Hence, it is correct to say that
a flowchart is a must for the better documentation of a complex program.
ITQ
Question
Explain the importance of flow charts in the documentation of a
program?
Feedback
A flowchart, once prepared, makes it easy to write programs in any high
level language. This important feature of flow charts makes it an
indispensable tool and helps in explaining the program to others.
61
Study Session 5 Algorithms and Problem-Solving
Question
What are the advantages of Flow Charts?
Feedback
Documentation of program/system; and effective analysis.
62
Study Session 5 Algorithms and Problem-Solving
or
5. Only one flow line should enter a decision symbol, but
two or three flow lines, one for each possible answer,
should leave the decision symbol.
63
Study Session 5 Algorithms and Problem-Solving
Example 5.7
The following flowchart finds the area of a circle of radius r.
Example 5.8
The flowchart below finds the greater of two numbers
64
Study Session 5 Algorithms and Problem-Solving
Example 5.9
Write an algorithm and draw the flowchart for finding the average of two
numbers
Algorithm:
Input: two numbers n1 and n2
Output: the average of n1 and n2
Steps:
1. input n1
2. input n2
3. sum = n1 + n2
4. average = sum /2
5. output average
ITQ
Question
Mention two (2) guidelines in flowcharting
Feedback
The flowchart should be clear, neat and easy to follow. There
should not be any room for ambiguity in understanding the
flowchart, and
The usual direction of the flow of a procedure or system is from
left to right or top to bottom.
65
Study Session 5 Algorithms and Problem-Solving
Assessment
SAQ 5.1 (tests Learning Outcome 5.1)
Describe the problem solving process?
Assessment SAQ 5.2 (tests learning outcome 5.2)
Explain the concept of Algorithm?
SAQ 5.3 (tests learning outcome 5.3)
Describe Pseudo-codes?
SAQ 5.4 (test learning outcome 5.4)
What is a Flowchart?
Credits
This lesson has been adapted from:
http://www.comp.nus.edu.sg/~cs1101x/4_misc/jumpstart/chap2.pdf
http://faradars.org/wp-content/uploads/2015/07/Algorithm-and-Flow-
Reading Chart.pdf
http://www.tutorialspoint.com/computer_programming/computer_progr
amming_overview.htm
http://www.comp.nus.edu.sg/~cs1101x/4_misc/jumpstart/chap3.pdfhttp:
//faradars.org/wp-content/uploads/2015/07/Algorithm-and-Flow-
Chart.pdf
http://faculty.ccri.edu/mkelly/COMI1150/PseudocodeBasics.pdfhttp://fa
culty.ccri.edu/mkelly/COMI1150/PseudocodeBasics.pdf
http://www.comp.nus.edu.sg/~cs1101x/4_misc/jumpstart/chap2.pdf
http://www.comp.nus.edu.sg/~cs1101x/4_misc/jumpstart/chap2.pdf
66
Study Session 6 Basics of Computer Program
Study Session 6
Learning Outcomes
When you have studied this session, you should be able to:
6.1 describe a programming environment
6.2 explain basic syntax of programming
Outcomes 6.3 define variables
6.4 discuss reserved words
6.5 define operators
6.6 explain functions
Terminology
Interpreter A program that executes another program written in a
programming language other than machine code.
67
Study Session 6 Basics of Computer Program
computer programs, compile, and execute them. For example, if you need
to browse Internet, then you need the following setup on your machine −
1. A working Internet connection to connect to the Internet
2. A Web browser such as Internet Explorer, Chrome, Safari, etc.
Similarly, you will need the following setup to start with programming
using any programming language.
1. A text editor to create computer programs.
2. A compiler to compile the programs into binary format.
3. An interpreter to execute the programs directly.
In case you do not have sufficient exposure to computers, you will not be
able to set up either of this software. Therefore, we suggest you take the
help from any technical person around you to set up the programming
environment on your machine from where you can start. However, for
you, it is important to understand what these items are.
ITQ
Question
What is the first step to take before writing a program?
Feedback
Environment Set-up
68
Study Session 6 Basics of Computer Program
You can use this software to type your computer program and save it in a
file at any location. You can download and install other good editors like
Notepad++, which is freely available. If you are a Mac user, then you will
have TextEdit or you can install some other commercial editor like
BBEdit to start with.
6.1.2 Compiler
You write your computer program using your favorite programming
language and save it in a text file called the program file. Now let us try
to get a little more detail on how the computer understands a program
written by you using a programming language. Actually, the computer
cannot understand your program directly given in the text format, so we
need to convert this program in a binary format, which can be understood
by the computer. The conversion from text program to binary file is done
by another software called Compiler and this process of conversion from
text formatted program to binary format file is called program
compilation. Finally, you can execute binary file to perform the
programmed task.
The following flow diagram gives an illustration of the compilation
process −
So, if you are going to write your program in any such language, which
needs compilation like C, C++, Java and Pascal, etc., then you will need
to install their compilers before you start programming.
69
Study Session 6 Basics of Computer Program
ITQ
Question
What does Program Compilation entail?
Feedback
Ordinarily, the computer cannot understand your program directly given
in the text format, so there is a need to convert the program in a binary
format, which the computer understands. This conversion from text
program to binary file is done using a software called Compiler and this
process of conversion from text formatted program to binary format file
is called program compilation.
6.1.3 Interpreter
We just discussed about compilers and the compilation process.
Compilers are required in case you are going to write your program in a
programming language that needs to be compiled into binary format
before its execution. There are other programming languages such as
Python, PHP, and Perl, which do not need any compilation into binary
format, rather an interpreter can be used to read such programs line by
line and execute them directly without any further conversion.
So, if you are going to write your programs in PHP, Python, Perl, Ruby,
etc., then you will need to install their interpreters before you start
programming.
70
Study Session 6 Basics of Computer Program
ITQ
Question
Mention two programming languages that does not require compilation
into a binary format.
Feedback
Python and PHP? Yes, you are correct.
Question
What follows the main function { main() }?
Feedback
A left curly brace
6.2.2 Functions
Functions are small units of programs and they are used to carry out a
specific task. For example, the above program makes use of two
71
Study Session 6 Basics of Computer Program
functions: main()and printf(). Here, the function main() provides the entry
point for the program execution and the other function printf() is being
used to print an information on the computer screen You can write your
own functions which we will see in a separate chapter, but C
programming itself provides various built-in functions like main(),
printf(), etc., which we can use in our programs based on our
requirement. Some of the programming languages use the word sub-
routine instead of function, but their functionality is more or less the
same.
ITQ
Question
What do we utilize functions?
Feedback
Functions are used to carry out a specific task.
6.2.3 Comments
A C program can have statements enclosed inside /*.....*/. Such
statements are called comments and these comments are used to make the
programs user friendly and easy to understand. The good thing about
comments is that they are completely ignored by compilers and
interpreters. So you can use whatever language you want to write your
comments.
ITQ
Question
How do we utilize comments?
Feedback
Comments is used to make the program more user friendly, and easy to
understand.
6.2.4 Whitespaces
When we write a program using any programming language, we use
various printable characters to prepare programming statements. These
printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #,
$, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '. Hope
I'm not missing any printable characters from your keyboard.
Apart from these characters, there are some characters which we use very
frequently but they are invisible in your program and these characters are
spaces, tabs (\t), new lines(\n). These characters are called whitespaces.
These three important whitespace characters are common in all the
programming languages and they remain invisible in your text document
–
72
Study Session 6 Basics of Computer Program
73
Study Session 6 Basics of Computer Program
ITQ
Question
What do we refer to as “Whitespaces”?
Feedback
These often refer to characters, which we use very frequently but are not
visible in your program. These characters could be spaces, tabs (\t), new
lines(\n).
6.2.5 Semicolons
Every individual statement in a C Program must be ended with a
semicolon (;), for example, if you want to write "Hello, World!" twice,
then it will be written as follows −
#include <stdio.h>
main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!\n" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World!
Hello, World!
Here, we are using a new line character \n in the first printf() function to
create a new line. Let us see what happens if we do not use this new line
character −
#include <stdio.h>
main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World! Hello, World!
We will learn identifiers and keywords in next few chapters.
Program Explanation
Let us understand how the above C program works. First of all, the above
program is converted into a binary format using C compiler. So let’s put
this code in test.c file and compile it as follows −
$gcc test.c -o demo
74
Study Session 6 Basics of Computer Program
printf("Hello, World!")
}
This program will produce the following result −
main.c: In function 'main':
main.c:7:1: error: expected ';' before '}' token
}
^
So the bottom-line is that if you are not following proper syntax defined
by the programming language in your program, then you will get syntax
errors. Before attempting another compilation, you will need to fix them
and then proceed.
ITQ
Question
How does Syntax Error occur?
Feedback
Syntax Error often occur when the rules defined by the programing
75
Study Session 6 Basics of Computer Program
language are not followed to letter. The result is that at the time of
compilation, you will get syntax errors and the program would not be
compiled leading to a failed execution
Question
Mention one important point to note when using a Python program
Feedback
Python program uses an interpreted language; therefore, it does not
require the compilation process/stage unlike the C and Java programs
that need the intermediate stage of compiling before execution.
6.3 Variables
Variables are the names you give to computer memory locations which
are used to store values in a computer program. For example, assume you
want to store two values 10 and 20 in your program and at a later stage,
you want to use these two values. Let us see how you will do it. Here are
the following three simple steps:
1. Create variables with appropriate names.
2. Store your values in those two variables.
3. Retrieve and use the stored values from the variables.
76
Study Session 6 Basics of Computer Program
77
Study Session 6 Basics of Computer Program
5. You can give any name to a variable like age, sex, salary,
year1990or anything else you like to give, but most of the
programming languages allow to use only limited characters in
their variables names. For now, we will suggest to use only a....z,
A....Z, 0....9 in your variable names and start their names using
alphabets only instead of digits.
6. Almost none of the programming languages allow to start their
variable names with a digit, so 1990year will not be a valid
variable name whereas year1990 or ye1990ar are valid variable
names.
Every programming language provides more rules related to variables
and you will learn them when you will go in further detail of that
programming language.
ITQ
Question
In C programming language, what other term can used to replace
‘Creating variables’?
Feedback
Creating variables is also called declaring variables in C programming.
78
Study Session 6 Basics of Computer Program
79
Study Session 6 Basics of Computer Program
ITQ
Question
What is necessary after creating variable?
Feedback
It is important to store variables after creating them else, the purpose of
creation would be defeated.
80
Study Session 6 Basics of Computer Program
int a = 10;
int b = 20;
printf( "Value of a = %d and value of b = %d\n", a, b );
}
81
Study Session 6 Basics of Computer Program
giving a name to your variable, you should not use any reserved keyword
for that programming language.
ITQ
Question
What is the common rule in all programming languages?
Feedback
The important and common rule in all the programming languages is
that a reserved keyword cannot be used to name variables.
Double
82
Study Session 6 Basics of Computer Program
Volatile While
Assert Finally or
83
Study Session 6 Basics of Computer Program
Def If return
Elif In while
Else Is with
6.5 Operators
An operator in a programming language is a symbol that tells the
compiler or interpreter to perform specific mathematical, relational or
logical operation and produce final result. This lesson will explain the
concept of operators and it will take you through the important arithmetic
and relational operators available in C, Java, and Python.
84
Study Session 6 Basics of Computer Program
85
Study Session 6 Basics of Computer Program
Value of c = 0
86
Study Session 6 Basics of Computer Program
87
Study Session 6 Basics of Computer Program
a is equal to 10
a is less than b
a is not equal to b
ITQ
Question
What does a programming language provide?
Feedback
A programming language provides various relational operators.
88
Study Session 6 Basics of Computer Program
Question
How do logical operators help programmers?
Feedback
Logical Operators serves as a reliable guide when taking decisions based
on certain conditions.
89
Study Session 6 Basics of Computer Program
c = a * b;
System.out.println("Value of c = " + c );
c = b / a;
System.out.println("Value of c = " + c );
c = b % a;
System.out.println("Value of c = " + c );
if( a == 10 ) {
System.out.println("a is equal to 10" );
}
}
}
ITQ
Question
What does Java provide?
Feedback
Java provide almost identical set of operators and conditional statements.
c=a/b
print "Value of c = ", c
90
Study Session 6 Basics of Computer Program
c=a%b
print "Value of c = ", c
if( a == 10 ):
print "a is equal to 10"
6.6 Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your
application and a high degree of code reusing. You have already seen
various functions like printf() and main(). These are called built-in
functions provided by the language itself, but we can write our own
functions as well and this tutorial will teach you how to write and use
those functions in C programming language.
Good thing about functions is that they are famous with several names.
Different programming languages name them differently, for example,
functions, methods, sub-routines, procedures, etc. If you come across any
such terminology, then just imagine about the same concept, which we
are going to discuss in this tutorial.
Let us start with a program where we will define two arrays of numbers
and then from each array, we will find the biggest number. Given below
are the steps to find out the maximum number from a given set of
numbers −
1) Get a list of numbers L1, L2, L3....LN
2) Assume L1 is the largest, Set max = L1
3) Take next number Li from the list and do the following
4) If max is less than Li
5) Set max = Li
6) If Li is last number from the list then
7) Print value stored in max and come out
8) Else prepeat same process starting from step 3
Let us translate the above program in C programming language −
#include <stdio.h>
main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, max;
/* Process first set of numbers available in set1[] */
max = set1[0];
i = 1;
while( i < 5 ) {
if( max < set1[i] ) {
max = set1[i];
91
Study Session 6 Basics of Computer Program
}
i = i + 1;
}
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = set2[0];
i = 1;
while( i < 5 ) {
if( max < set2[i] ) {
max = set2[i];
}
i = i + 1;
}
printf("Max in second set = %d\n", max );
}
When the above code is compiled and executed, it produces the following
result −
Max in first set = 50 Max in second set = 501
If you are clear about the above example, then it will become easy to
understand why we need a function. In the above example, there are only
two sets of numbers, set1 and set2, but consider a situation where we
have 10 or more similar sets of numbers to find out the maximum
numbers from each set. In such a situation, we will have to repeat,
processing 10 or more times and ultimately, the program will become too
large with repeated code. To handle such situation, we write our functions
where we try to keep the source code which will be used again and again
in our programming.
Now, let's see how to define a function in C programming language and
then in the subsequent sections, we will explain how to use them.
ITQ
Question
Define Functions?
Feedback
Functions are small units of programs that are used to carry out a
specific task. Kindly note that C programming provides various built-in
functions like main(), printf(), etc., which are used in programs based on
the requirement.
92
Study Session 6 Basics of Computer Program
Question
List two parts of a function
Feedback
The two parts of a function are Return Type, and Function Name.
93
Study Session 6 Basics of Computer Program
}
i = i + 1;
}
return max;
}
main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int max;
/* Process first set of numbers available in set1[] */
max = getMax(set1);
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = getMax(set2);
printf("Max in second set = %d\n", max );
}
When the above code is compiled and executed, it produces the following
result −
Max in first set = 50 Max in second set = 501
ITQ
Question
What must you bear in mind while creating a C function?
Feedback
You must always remember that while creating a C function, you should
give a definition of what the function has to do.
94
Study Session 6 Basics of Computer Program
Assessment
SAQ 6.1 (tests Learning Outcome 6.1)
Identify a program environment?
Assessment SAQ 6.2 (tests learning outcome 6.2)
Explain the basic syntax of programming?
SAQ 6.3 (tests learning outcome 6.3)
Explain Reserved Words?
SAQ 6.4 (tests learning outcome 6.4)
Define Operators?
SAQ 6.5 (tests learning outcome 6.5)
Define Functions?
SAQ 6.6 (tests learning outcome 6.6)
Mention the parts of a function?
Credits
This lesson has been adapted from:
Program Structure- http://ccm.net/contents/317-program-structure
https://en.wikipedia.org/wiki/Statement_(computer_science)
Reading http://www.webopedia.com/TERM/S/statement.htmlhttp://www.webope
dia.com/TERM/S/statement.html
https://en.wikipedia.org/wiki/Control_flowhttps://en.wikipedia.org/wiki/
Control_flow
Introduction to Problem Solving and Control Statements in Visual Basic
2010 By Paul Deitel and Harvey Deitel Apr 27, 2011
http://www.teach-
ict.com/gcse_computing/ocr/216_programming/control_flow/miniweb/p
g7.htm
http://www.tutorialspoint.com/computer_programming/
95
Study Session 7 Data Types
Study Session 7
Data Types
Introduction
In this study session, you will discuss the different data types. You will
describe the C and java data types and python data types. You will then
proceed to explaining data types and numbers manipulations. Under
which you will examine math operations on numbers, numbers in java
and numbers in python. Subsequently, you will discuss data types and
character manipulation. You will end the session by describing data types
and string manipulations.
Learning Outcomes
When we have studied this session, we should be able to:
7.1 identify data types
7.2 describe data types and numbers manipulation
Outcomes 7.3 examine data types and character manipulation
7.4 explain data types and string manipulation
Terminology
Data A representation of facts or ideas in a formalized manner
capable of being communicated or manipulated by some
processes
96
Study Session 7 Data Types
Class:
Section:
Age:
Sex:
Now, let's put one student record as per the given requirement −
Name: Zara Ali
Class: 6th
Section: J
Age: 13
Sex: F
The first example dealt with whole numbers, the second example added
two decimal numbers, whereas the third example is dealing with a mix of
different data. Let's put it as follows:
1. Student name "Zara Ali" is a sequence of characters which is also
called a string.
2. Student class "6th" has been represented by a mix of whole
number and a string of two characters. Such a mix is called
alphanumeric.
3. Student section has been represented by a single character which
is 'J'.
4. Student age has been represented by a whole number which is 13.
5. Student sex has been represented by a single character which is
'F'.
This way, we realized that in our day-to-day life, we deal with different
types of data such as strings, characters, whole numbers (integers), and
decimal numbers (floating point numbers). Similarly, when we write a
computer program to process different types of data, we need to specify
its type clearly; otherwise the computer does not understand how
different operations can be performed on that given data. Different
programming languages use different keywords to specify different data
types. For example, C and Java programming languages use int to specify
integer data, whereas char specifies a character data type.
Subsequent sections will show you how to use different data types in
different situations. For now, let's check the important data types
available in C, Java, and Python and the keywords we will use to specify
those data types.
ITQ
Question
What must we specify when writing a computer program?
Feedback
Whenever you are to write a computer program to process different
types of data, you need to specify its type clearly; otherwise the
computer does not understand how different operations should be
97
Study Session 7 Data Types
These data types are called primitive data types and you can use these
data types to build more complex data types, which are called user-
defined data type, for example a string will be a sequence of characters.
ITQ
Question
What are called primitive data types?
Feedback
The following are referred to as primitive data types: Character,
Number, Small Number, Long Number, and Decimal Number.
98
Study Session 7 Data Types
4. Tuple
5. Dictionary
Here, Number specifies all types of numbers including decimal numbers
and string represents a sequence of characters with a length of 1 or more
characters. For now, let's proceed with these two data types and skip List,
Tuple, and Dictionary, which are advanced data types in Python.
These data types are called primitive data types and you can use these
data types to build more data types, which are called user-defined data
types.
We have seen various mathematical and logical operations on numbers
during a discussion on operators. So we know how to add numbers,
subtract numbers, divide numbers, etc.
99
Study Session 7 Data Types
ITQ
Question
What must every programming language provide?
Feedback
Every programming language should provide support for manipulating
different types of numbers such as simple whole integers, and floating
point numbers.
1 double cos(double);
This function takes an angle (as a double) and returns the cosine.
2 double sin(double);
This function takes an angle (as a double) and returns the sine.
3 double tan(double);
This function takes an angle (as a double) and returns the tangent.
4 double log(double);
This function takes a number and returns the natural log of that
number.
10
0
Study Session 7 Data Types
7 double sqrt(double);
You pass this function a number and it returns its square root.
8 int abs(int);
This function returns the absolute value of an integer that is passed
to it.
9 double fabs(double);
This function returns the absolute value of any decimal number
passed to it.
10 double floor(double);
Finds the integer which is less than or equal to the argument
passed to it.
101
Study Session 7 Data Types
10
2
Study Session 7 Data Types
f: 230.470001
d: 30949.374000
Java also provides a full range of built-in functions for mathematical
calculation and you can use them in the same way as you did in C
programming.
ITQ
Question
What additional feature does Java provide?
Feedback
Java also provides a full range of built-in functions for mathematical
calculation.
103
Study Session 7 Data Types
d = 30949.374
print "s: ", s
print "i: ", i
print "l: ", l
print "f: ", f
print "d: ", d
When the above program is executed, it produces the following result −
s: 10
i: 1000
l: 1000000
f: 230.47
d: 30949.374
Python also provides a full range of built-in functions for mathematical
calculations and you can use them in the same way you have used them
in C programming.
10
4
Study Session 7 Data Types
Question
How many bits of memory does a character Data type consumes?
Feedback
A character data type consumes 8 bits of memory, which means you can
store anything in a character whose ASCII value lies in between -127 to
127, so it can hold any of the 256 different values.
10
5
Study Session 7 Data Types
10
6
Study Session 7 Data Types
char ch4;
ch1 = '\t';
ch2 = '\n';
printf( "Test for tabspace %c and a newline %c will start here", ch1,
ch2);
}
When the above program is executed, it produces the following result −
Test for tabspace and a newline
will start here
ITQ
Question
What concept does many programming support?
Feedback
Many programming languages support a concept called Escape
Sequence
107
Study Session 7 Data Types
}
}
When the above program is executed, it produces the following result −
ch1: a
ch2: 1
ch3: $
ch4: +
Java also supports escape sequence in the same way you have used them
in C programming.
ITQ
Question
How does Java handle character data types?
Feedback
Java handles character data types much in the same way as we have seen
in C programming. However, Java provides additional support for
character manipulation.
10
8
Study Session 7 Data Types
ITQ
Question
How does Python handle character data types?
Feedback
Python does not support any character data type but all the characters are
treated as string, which is a sequence of characters.
10
9
Study Session 7 Data Types
Now, let's define an array of five characters in the same way as we did for
numbers and try to print them −
#include <stdio.h>
main() {
char ch[5] = {'H', 'e', 'l', 'l', 'o'};
int i = 0;
while( i < 5 ) {
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}
Here, we used %c to print character value. When the above code is
compiled and executed, it produces the following result −
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
If you are done with the above example, then I think you understood how
strings work in C programming, because strings in C are represented as
arrays of characters. C programming simplified the assignment and
printing of strings. Let's check the same example once again with a
simplified syntax −
#include <stdio.h>
main() {
char ch[5] = "Hello";
int i = 0
/* Print as a complete string */
printf("String = %s\n", ch);
/* Print character by character */
while( i < 5 ) {
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}
Here, we used %s to print the full string value using array name ch,
which is actually the beginning of the memory address holding ch
variable as shown below −
110
Study Session 7 Data Types
Although it's not visible from the above examples, a C program internally
assigns null character '\0' as the last character of every string. It indicates
the end of the string and it means if you want to store a 5 character string
in an array, then you must define an array size of 6 as a good practice,
though C does not complain about it.
If the above code is compiled and executed, it produces the following
result −
String = Hello
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
ITQ
Question
What must you remember with reference to data types and strings
manipulation?
Feedback
You need to remember that character data type deals with a single
character and you can assign any character from your keyboard to a
character type variable.
111
Study Session 7 Data Types
112
Study Session 7 Data Types
Question
Mention two conclusions that we can deduce from the Basic String
Concept
Feedback
From the aforementioned, we can deduce that
1. Strings in C are represented as arrays of characters.
2. We can constitute a string in C programming by assigning
character by character into an array of characters.
Assessment
SAQ 7.1 (tests Learning Outcome 7.1)
1. Discuss Data types?
2. Discuss C and Java Data types?
Assessment 3. Discuss about Python Data types?
SAQ 7.2 (tests learning outcomes 7.2)
Discuss data types, numbers, character, and string manipulation?
SAQ 7.3 (tests learning outcome 7.3)
List the Basic Strings Concept that you know?
SAQ 7.4 (tests learning outcome 7.4)
1. What is important about Strings in Java?
113
Study Session 7 Data Types
Credits
This content of this lesson is adapted from
http://www.tutorialspoint.com/
Reading
114
Study Session 8 Decision-Making and Loops
Study Session 8
Learning Outcomes
When you have studied this session, you should be able to:
8.1 identify Conditional statements and their usefulness in
programming
Outcomes 8.2 explain and implement loops in programming
Terminology
Loop A programmed sequence of instructions that is repeated
until or while a particular condition is satisfied
115
Study Session 8 Decision-Making and Loops
116
Study Session 8 Decision-Making and Loops
than 95 or not and if it finds the condition is true, then the conditional
body is entered to execute the given statements. Here we have only one
printf()statement to print a remark about the student.
Similarly, the second if statement works. Finally, the third if statement is
executed, here we have the following two conditions −
1. First condition is x > 95
2. Second condition is x < 30
The computer evaluates both the given conditions and then, the overall
result is combined with the help of the binary operator &&. If the final
result is true, then the conditional statement will be executed, otherwise
no statement will be executed.
117
Study Session 8 Decision-Making and Loops
Question
What follows an ‘if..else statement’?
Feedback
An Optional Else Statement
118
Study Session 8 Decision-Making and Loops
Question
What follows an ‘If’ statement?
Feedback
An if statement can be followed by an optional else if...else statement.
119
Study Session 8 Decision-Making and Loops
case TWO:
statement(s);
break;
......
default :
statement(s);
}
The expression used in a switch statement must give an integer value,
which will be compared for equality with different cases given. Wherever
an expression value matches with a case value, the body of that case will
be executed and finally, the switch will be terminated using a break
statement. If no break statements are provided, then the computer
continues executing other statements available below to the matched
case. If none of the cases matches, then the default case body is executed.
The above syntax can be represented in the form of a flow diagram as
shown below −
12
0
Study Session 8 Decision-Making and Loops
switch( x ){
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
break;
default :
printf( "None of the above...\n");
}
}
When the above program is executed, it produces the following result −
Two
ITQ
Question
What are Switch Statement?
Feedback
A switch statement is an alternative of if statements which allows a
variable to be tested for equality against a list of values.
121
Study Session 8 Decision-Making and Loops
Question
What does Python provide?
Feedback
Python provides if,if...else, if...elif...else, and switch statements
8.2 Loops
Let us consider a situation when you want to print Hello, World! five
times. Here is a simple C program to do the same −
#include <stdio.h>
main() {
12
2
Study Session 8 Decision-Making and Loops
123
Study Session 8 Decision-Making and Loops
less than 5 or not and if it finds the condition is true, then the loop body is
entered to execute the given statements. Here, we have the following two
statements in the loop body −
1. First statement is printf() function, which prints Hello World!
2. Second statement is i = i + 1, which is used to increase the value
of variable i
After executing all the statements given in the loop body, the computer
goes back to while( i < 5) and the given condition, (i < 5), is checked
again, and the loop is executed again if the condition holds true. This
process repeats till the given condition remains true which means variable
"a" has a value less than 5.
To conclude, a loop statement allows us to execute a statement or group
of statements multiple times. Given below is the general form of a loop
statement in most of the programming languages −
Question
How does a loop help a programmer save time?
Feedback
A loop statement allows the programmer to execute a statement or group
of statements multiple times.
12
4
Study Session 8 Decision-Making and Loops
12
5
Study Session 8 Decision-Making and Loops
ITQ
Question
Mention one important to note with respect to While Loops
Feedback
A while loop starts with a keyword while followed by a condition
enclosed in ( ).
If you will write the above example using do...while loop, then Hello,
Worldwill produce the same result −
#include <stdio.h>
main() {
int i = 0;
do {
printf( "Hello, World!\n");
12
6
Study Session 8 Decision-Making and Loops
i = i + 1;
}while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
ITQ
Question
How does a ‘do…while loop’ function?
Feedback
A do…while loop allows to execute a loop body before checking a given
condition.
127
Study Session 8 Decision-Making and Loops
Following is a variant of the above program, but it will come out after
printing Hello World! only three times −
#include <stdio.h>
main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
if( i == 3 ) {
break;
}
}while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
ITQ
Question
What do we encounter in a loop?
Feedback
The Break Statement
12
8
Study Session 8 Decision-Making and Loops
main() {
int i = 0;
do {
if( i == 3 ) {
i = i + 1;
continue;
}
12
9
Study Session 8 Decision-Making and Loops
Question
What is peculiar about the break and continue statements in Java
programming?
Feedback
The break and continue statements in Java programming work quite the
same way as they work in C programming.
130
Study Session 8 Decision-Making and Loops
Question
What important point should you bear in mind about loops in python?
Feedback
Python does not make use of curly braces for the loop body; instead, it
simply identifies the body of the loop using indentation of the
statements.
131
Study Session 8 Decision-Making and Loops
Assessment
SAQ 8.1 (tests Learning Outcome8.1)
1. What are Conditional Statements?
Assessment SAQ 8.2 (tests learning outcome 8.2)
1. Explain and implement loops in programming?
2. What is peculiar about the ‘break’ and ‘continue’ statement in
Java Programming?
Credit
This content of this lesson is adapted from
http://www.tutorialspoint.com/
Reading
132
Study Session 9 Arrays
Study Session 9
Arrays
Introduction
In this study session, your focus will be on Arrays. You will begin by
explaining what an array is. You will then create, initialize and access
arrays. Thereafter, you will examine arrays in java and python.
Learning Outcomes
When you have studied this session, you should be able to:
9.1 explain the term arrays
9.2 discuss arrays in java
Outcomes 9.3 describe arrays (lists) in python.
Terminology
Array A data structure that contains a group of elements.
133
Study Session 9 Arrays
134
Study Session 9 Arrays
ITQ
Question
1. What do most programming languages provide?
2. What do all arrays consist of?
Feedback
1. Arrays
2. All arrays consist of contiguous memory locations.
135
Study Session 9 Arrays
int main () {
int number[10]; /* number is an array of 10 integers */
int i = 0;
/* Initialize elements of array n to 0 */
while( i < 10 ) {
/* Set element at location i to i + 100 */
number[ i ] = i + 100;
i = i + 1;
}
/* Output each array element's value */
i = 0;
while( i < 10 ) {
printf("number[%d] = %d\n", i, number[i] );
i = i + 1;
}
return 0;
}
When the above code is compiled and executed, it produces the following
result −
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109
ITQ
Question
How do we access an element?
Feedback
Elements are generally accessed by indexing the names of the array.
136
Study Session 9 Arrays
137
Study Session 9 Arrays
ITQ
Question
Does Java support arrays?
Feedback
Java support arrays though there is a little difference in the way they are
created.
138
Study Session 9 Arrays
ITQ
Question
Can arrays be created using the Python programming?
Feedback
Python does not have a concept of Array; instead, Python provides
another data structure called LIST, which provides similar functionality
as arrays in any other language.
Assessment
SAQ 9.1 (tests learning outcome 9.1)
1. Explain the term array?
2. How do you initialize and access array elements?
Assessment
SAQ 9.2 (tests learning outcome 9.2 and 9.3)
Discuss arrays in Java and Python?
Credit
This content of this lesson is adapted from
http://www.tutorialspoint.com/
Reading
139
Study Session 10 Computer Files
Study Session 10
Computer Files
Introduction
In this study session, you will discuss computer files in relation to
programming language. You will also examine the opening, closing,
writing and reading of computer files. You will end the session by
exploring file I/O in java and file I/O in python.
Learning Outcomes
When you have studied this session, you should be able to
10.1 discuss file input/output
10.2 explain operation modes
Outcomes 10.3 examine file I/O in Java
10.4 describe file I/O python
Terminology
File An aggregation of data on a storage device, identified by a
name
14
0
Study Session 10 Computer Files
ITQ
Question
How else can we create files if we decide not to use computer programs?
Feedback
Files cannot only be created using computer programs. We could also
create files using MS Word, MS PowerPoint, and MS Excel.
Question
Which file mode would you select if you were ONLY interested in
writing into either an existing file, or a newly created file?
Feedback
In such a case as described above, you would open the file in a Write-
Only Mode.
141
Study Session 10 Computer Files
Mode Description
W Opens a text file for writing. If it does not exist, then a new file
is created. Here, your program will start writing content from the
beginning of the file.
w+ Opens a text file for both reading and writing. It first truncates
the file to zero length, if it exists; otherwise creates the file if it
does not exist.
a+ Opens a text file for both reading and writing. It creates a file, if
it does not exist. The reading will start from the beginning, but
writing can only be appended.
ITQ
Question
How would you open a file?
Feedback
Files are often opened using the fopen() function.
14
2
Study Session 10 Computer Files
Question
What is the function for closing a file?
Feedback
int fclose( FILE *fp );
143
Study Session 10 Computer Files
}
When the above code is compiled and executed, it creates a new file
test.txtin /tmp directory and writes two lines using two different
functions. Let us read this file in the next section.
ITQ
Question
What is the key function in writing a file?
Feedback
int fputc( int c, FILE *fp );
14
4
Study Session 10 Computer Files
}When the above code is compiled and executed, it reads the file created
in the previous section and produces the following result −
1 : This 2: is testing for fprintf... 3: This is testing for fputs...
Let's analyze what happened here. First, the fscanf() method reads
Thisbecause after that, it encountered a space. The second call is for
fgets(), which reads the remaining line till it encountered end of line.
Finally, the last call fgets() reads the second line completely.
ITQ
Question
What is the key function in reading a file?
Feedback
int fgetc( FILE * fp );
14
5
Study Session 10 Computer Files
14
6
Study Session 10 Computer Files
ITQ
Question
What more can we say about file input/output in Java?
Feedback
Java provides even richer set of functions to handle File Input/Output.
Assessment
SAQ 10.1 (tests learning outcome 10.1)
Discuss file Input/Output?
Assessment SAQ 10.2 (tests learning outcome 10.2)
1. Explain Operation Modes?
2. How would you open/close a file?
3. How would you write/read a file?
Credit
This content of this lesson is adapted from
http://www.tutorialspoint.com/
Reading
147
Notes on Self Assessment Questions Computer Files
SAQ 1.4
1. A computer programmer, also known as developer, coder, or
software engineer is a person who writes computer software. The
term computer programmer can refer to a specialist in one area of
computer programming or to a generalist who writes code for
many kinds of software. A programmer's primary computer
language is often prefixed to these titles, and those who work in a
Web environment often prefix their titles with Web. As such,
based on computer programming language expertise, we can
name a computer programmers as follows −
i. C Programmer
ii. C++ Programmer
iii. Java Programmer
iv. Python Programmer
v. PHP Programmer
vi. Perl Programmer
vii. Ruby Programmer
2. The function of a computer programmer are:
i. A computer programmer figures out the process of
designing, writing, testing, debugging/troubleshooting and
maintaining the source code of computer programs.
14
8
Notes on Self Assessment Questions Computer Files
SAQ 2.1
1. The history of programming languages dates back to the 19th
century, when Ada Lovelace (1815 – 1852) wrote a set of notes
after translating the memoir of Italian mathematician Luigi
Menabrea (1809 – 1896) about the Analytical Engine shown
below during a period of nine months between 1842 and 1843. .
The Analytical Engine was an invention of English
mathematician and computer pioneer Charles Babbage (1791-
1871). Some historians have recognized Ada Lovelace’s set of
notes, as the world’s first computer program as it contained a
ground-breaking description of the possibilities of programming
the machine to go beyond number-crunching to “computing”.
2. Her notes on the engine include what is recognized as the first
algorithm intended to be carried out by a machine. Because of
this, she is often regarded as the first computer programmer.
3. 47 years after Ada Lovelace, Herman Hollerith (1860 – 1929)
created what is considered the first computer language when he
realized he could encode information on punch cards.
4. In the 1940s, machine-specific assembly language was probably
the first (vaguely) human-readable programming language.
5. John Mauchly’s Short Code, proposed in 1949, was one of the
first high-level languages ever developed for an electronic
computer.
6. By the 1950s computer engineers realized that assembly
language was too complex and a fallible process to build entire
systems, and so the first modern programming language was
born.
7. In 1957, Backus and his team had created FORTRAN. Fortran
was the first high-level programming language to be put to broad
use.
8. John McCarthy invented lisp in 1958.
9. COBOL was later designed in 1959 by the Conference on Data
Systems Languages (CODASYL).
10. In 1970, Niklaus Wirth developed Pascal.
14
9
Notes on Self Assessment Questions Computer Files
11. The language C was developed in 1972. The name was based on
an earlier language called B, which is now almost extinct.
12. Bjarne Stroustrup, a Danish computer scientist, created C++. The
motivation for creating a new language originated from
Stroustrup experience in programming for his Ph.D.
13. Primarily Brad Cox and Tom Love in the early 1980s at their
company Stepstone created objective-C in 1983.
14. Larry Wall originally developed Perl in 1987; it was developed
as a general-purpose Unix scripting language to make report
processing easier.
15. Python, a widely used general-purpose, high-level programming
language whose design philosophy emphasizes code readability,
and its syntax allows programmers to express concepts in fewer
lines of code was born in 1991.
16. Ruby, a dynamic, reflective, object-oriented, general-purpose
programming language came about in 1993. Ruby was designed
for programmer productivity and fun, following the principles of
good user interface design.
17. The year 1995 witnessed the evolution of three major modern
languages; Java, PHP and JavaScript.
18. Java is intended to let application developers “write once, run
anywhere” (WORA), meaning that compiled Java code can run
on all platforms that support Java without the need for
recompilation. The language derives much of its syntax from C
and C++.
19. Hypertext PreProcessor, PHP, is a server-side scripting language
designed for web development but also used as a general-purpose
programming language.
20. JavaScript is a high level, dynamic, untyped, and interpreted
programming language. It has been standardized in the
ECMAScript language specification. Alongside HTML and CSS,
it is one of the three essential technologies of World Wide Web
content production; the majority of websites employ it and all
modern web browsers without plug-ins support it.
21. C-sharp, C#, is intended to be a simple, modern, general-purpose,
object-oriented programming language.
22. Born in 2003, Scala is a programming language for general
software applications. Scala has full support for functional
programming and a very strong static type system. This allows
programs written in Scala to be very concise and thus smaller
than other general-purpose programming languages.
23. The Go language, commonly referred to as golang, was born in
2009. It is a programming language developed at Google, and is
recognizably in the tradition of C, but makes many changes to
improve conciseness, simplicity, and safety.
24. Swift was introduced at Apple’s 2014 Worldwide Developers
Conference (WWDC). It is a multi-paradigm, compiled
programming language created by Apple Inc. for iOS, OS X, and
watch OS development. Swift was designed to work with
Apple’s Cocoa and Cocoa Touch frameworks and the large body
of existing Objective-C code written for Apple products. It is also
15
0
Notes on Self Assessment Questions Computer Files
SAQ 2.2
1. According to Simon Raik-Allen, computer languages are
categorized thus:
i. The High-Level Dawning
ii. The C Era
iii. The Age of Java
or
According to Raik-Allen, we have:
i. The Web Dimension
ii. The Corporate Dimension
iii. The Mobile Dimension
iv. The New Age Dimension
2. In approaching this question, your attention is being pointed to
the fact that a thorough mastery of the important languages by
year is highly essential. As a way of helping you, the table has
been brought below to help with a quick check of the important
dates.
Below is a Summary of important programming languages by
year:
1951 – Regional Assembly Language
1970 – Pascal
1993 – Ruby
1952 – Autocode
1972 – C
1994 – CLOS (part of ANSI Common Lisp)
1954 – IPL (forerunner to LISP)
1972 – Prolog
1995 – Ada 95
1955 – FLOW-MATIC (led to COBOL)
1972 – Smalltalk
1995 – Delphi (Object Pascal)
1957 – COMTRAN (precursor to COBOL)
1973 – ML
1995 – Java
1957 – FORTRAN (First compiler)
1975 – Scheme
1995 – JavaScript
151
Notes on Self Assessment Questions Computer Files
1958 – ALGOL 58
1978 – SQL (a query language, later extended)
1995 – PHP
1958 – LISP
1980 – C++ (as C with classes, renamed in 1983)
1996 – WebDNA
1959 – COBOL
1983 – Ada
1997 – Rebol
1959 – FACT (forerunner to COBOL)
1984 – Common Lisp
1999 – D
1959 – RPG
1984 – MATLAB
2000 – ActionScript
1962 – APL
1985 – Eiffel
2000 – C#
1962 – Simula
1986 – Erlang
2001 – Visual Basic .NET
1962 – SNOBOL
1986 – Objective-C
2003 – Groovy
1963 – CPL (forerunner to C)
1987 – Perl
2003 – Scala
1964 – BASIC
1988 – Mathematica
2005 – F#
1964 – PL/I
1988 – Tcl
2007 – Clojure
1966 – JOSS
1989 – FL (Backus)
2009 – Go
15
2
Notes on Self Assessment Questions Computer Files
SAQ 3.1
1. Specifically, the task of defining the problem consists of
identifying what it is that you know (input-given data), and what
it is you want to obtain (output-the result). This vital information
guides you in problem identity and providing a solution to the
identified problem.
2. In carrying out a thorough task, it is expected of you to be able to
plan and outline solutions to the problems you have identified.
First, the problem is divided into several modules or tasks and
assigned to each programmer. Two common ways of planning
the solution to a problem is either to draw a flowchart or write a
pseudocode, or possibly both. Flow chart is a map of what your
program is going to do and how it is going to do it while
Pseudocode permits you to focus on the program logic without
having to be concerned just yet about the precise syntax of a
particular programming language.
SAQ 3.2
The step by step process of coding a program involves:
i. Translation of the logic from the flowchart or pseudocode-or
some other tool-to a programming language.
ii. This is the step where you actually have to sit down at the
computer and type! Coding is a little bit like writing an essay.
iii. To achieve this, you would require a programming language. A
programming language is a set of rules that provides a way of
instructing the computer what operations to perform. Examples
of programming languages include BASIC, COBOL, Pascal, etc.
iv. The correct use of the language is the required first step. Then,
your coded program must be keyed, probably using a terminal or
personal computer, in a form the computer can understand. This
is done using a text editor or a paper for beginners.
153
Notes on Self Assessment Questions Computer Files
SAQ 3.3
Compilation turns the program into the instructions made up of 0's and 1's
that the computer can actually follow. This is necessary because the chip
that makes your computer work only understands binary machine code.
SAQ 3.4
Debugging is the process of correcting the mistakes made in the course of
programming. A compiler must have identified these mistakes. This is
important as failure to do so will affect the execution of the program.
SAQ 3.5
The aim of testing is to ensure that what you have written solves the
original problem. This is important as it is possible for you to write a
program correctly without errors but the program would fail in its bid to
solve the problem it has been designed for. That is why we test to ensure
this purpose has not been defeated.
This can be achieved by subjecting the program to carefully work out set
of tests that put it through its paces, and check that it meets the
requirements and specification. Where mistakes are identified, there is a
need to figure out where in the code the mistake is. Once identified, the
problem should be fixed by changing the code and recompiling.
SAQ 3.6
Documentation is a written detailed description of the programming cycle
and facts about the program. Typical program documentation materials
include the origin and nature of the problem, a brief narrative description
of the program, logic tools such as flowcharts and pseudocode, data-
record descriptions, program listings, and testing results. Essentially,
program documentation instructs you on how to interact with a software
or a program.
2. The following are some types of documentation that exist:
Requirement documentation
Architecture/Design documentation
Technical documentation
End-user documentation
Marketing documentation
SAQ 4.1
The characteristics of programming languages are:
i. Functionality across languages
15
4
Notes on Self Assessment Questions Computer Files
SAQ 4.2
One way to classify programming languages is either as low-level
languages or high-level languages. Low-level languages interact directly
with the computer processor or CPU, are capable of performing very
basic commands, and are generally hard to read. By contrast, high-level
languages use natural language so it is easier for people to read and write.
High-level programming languages must be converted to low-level
programming languages using an interpreter or compiler, depending on
the language. Interpreted languages are considered more portable than
compiled languages, while compiled languages execute faster than
interpreted languages.
SAQ 4.3
The classification of programming languages are:
i. Modular Programming language: It is the first programming
language that introduced subprogram concepts and variable
declaration. Modular programming methodology advocates the
breakdown structure approach of a large project into several
smaller and manageable modules. Then each small module is
programmed comfortably and then put together in order to
generate program and hence the answer to the entire problem.
ii. Structured Programming Language: Structured programming
utilizes structures normally used for performing any tasks. These
include the Sequence, Selection, Iteration, and CASE structure.
An example of the structured programming language is Pascal.
iii. Business Oriented Language: An example for the business-
oriented language is COmmon Business Oriented Language
(COBOL). It has a peculiar feature such that COBOL programs
can be easily understood even by non-programmers due to its
self-∙ documenting nature and verbose of the grammar. It is also
an ideal language for processing voluminous data files making it
an excellent language for commercial data processing. Another
example is PROLOG, which stands for PROgramming in LOGic.
It has a core feature making it exclusively for Artificial
Intelligence (AI) and knowledge representation∙ techniques.
iv. Object Oriented Programming (OOP) Language: The aim of
using an object oriented programming language is to handle
complex software design projects in a very easy, simple and
efficient manner. Some of the famous objects oriented
programming languages are: Object Pascal, C++, Smalltalk,
Simula, Eiffel, Java, Ada. A major advantage of C++ is its ability
to support object oriented programming, while retaining the high
155
Notes on Self Assessment Questions Computer Files
SAQ 5.1
The problem solving process is a series of steps to be taken to arrive a
logical resolution of the identified problem. These steps have been
divided into phases and they include:
i. Phase 1: Understanding the problem.
ii. Phase 2: Devising a plan.
iii. Phase 3: Carrying out the plan.
iv. Phase 4: Looking back.
SAQ 5.2
An algorithm is a well-defined computational procedure consisting of a
set of instructions, which takes some value or set of values, as input, and
produces some value or set of values, as output. In other words, an
algorithm is a procedure that accepts data; manipulate them following the
prescribed steps, to eventually fill the required unknown with the desired
value(s).
SAQ 5.3
Pseudo-codes uses the structural conventions of a normal programming
language, but is intended for human reading rather than machine reading.
Pseudocode typically omits details that are essential for machine
understanding of the algorithm, such as variable declarations, system-
specific code and some subroutines.
The purpose of using pseudocode is that it is easier for people to
understand than conventional programming language code, and that it is
an efficient and environment-independent description of the key
principles of an algorithm.
SAQ 5.4
Flowcharts are often used as illustrations for algorithms. A flowchart is a
graphical representation of an algorithm, which will describe the
operations (and in what sequence) are required to solve a given problem.
These flowcharts play a vital role in the programming of a problem and
15
6
Notes on Self Assessment Questions Computer Files
SAQ 6.1
A program environment refers to a set-up such as a base on top of which
programs are created. Thus, it is essential to have to have the required
software setup in order to facilitate the proper execution of this function.
The following are necessary set-ups to start with in programming using
any language.
A text editor to create computer programs.
A compiler to compile the programs into binary format.
An interpreter to execute the programs directly.
SAQ 6.2
The basic syntax of programming refers to codes that written on a
program to generate a specified output. These codes comes in forms of
commands that are then interpreted to carry out the specified outcome. It
is also important to note that if there are any grammatical error (Syntax
errors in computer terminologies), then they must be fixed before
conversion into a binary format.
SAQ 6.3
Reserved word (also known as a keyword) is a word in programming that
cannot be used as an identifier, such as the name of a variable, function,
or label – it is "reserved from use"
SAQ 6.4
An operator in a programming language is a symbol that tells the
compiler or interpreter to perform specific mathematical, relational or
logical operation and produce result.
Logical operators are very important in any programming language as
they help us in taking decisions based on certain conditions. C
programming and Java provide almost identical set of operators and
conditional statements.
SAQ 6.5
Functions are small units of programs used to carry out a specific task.
Kindly note that C programming provides various built-in functions like
main(), printf(), etc., which are used in programs based on the
requirement. A function is a block of organized, reusable code used to
perform a single, related action. Functions provide better modularity for
your application and a high degree of code reusing.
SAQ 6.6
The parts of a function have been described as follows:
1) Return Type
2) Function Name
3) Parameter List
4) Function Body
157
Notes on Self Assessment Questions Computer Files
SAQ 7.1
1. The types of data we deal with on a daily basis include strings,
characters, whole numbers (integers), and decimal numbers
(floating point numbers). Different programming languages use
different keywords to specify different data types. For example,
C and Java programming languages use int to specify integer
data, whereas char specifies a character data type.
2. C and Java support almost the same set of data types. The
common types include Character, Number, Small Number, Long
Number, and Decimal Number.
3. Python has five standard data types. These include Numbers,
String, List, Tuple, and Dictionary. Please note that Number
specifies all types of numbers including decimal numbers and
string represents a sequence of characters with a length of 1 or
more characters.
SAQ 7.2
i. Every programming language provides support for manipulating
different types of numbers such as simple whole integers and
floating point numbers. The major types of data include
Character, Number, Small Number, Long Number, and Decimal
Number. These data types are called primitive data types and you
can use these data types to build more data types, which are
called user-defined data types.
ii. Note that Java provides almost all the numeric data types
available in C programming. Java also provides a full range of
built-in functions for mathematical calculation and you can use
them in the same way as you did in C programming.
iii. Python is a little different from C and Java; it categorizes
numbers in int, long, float and complex. Python also provides a
full range of built-in functions for mathematical calculations and
you can use them in the same way you have used them in C
programming.
iv. Characters are simple alphabets like a, b, c, d...., A, B, C, D... but
with an exception. In computer programming, any single digit
number like 0, 1, 2 ...and special characters like $, %, +, -... etc.,
are also treated as characters and to assign them in a character
type variable, you simply need to put them inside single quotes.
A character data type consumes 8 bits of memory, which means
you can store anything in a character whose ASCII value lies in
between -127 to 127, so it can hold any of the 256 different
values. Note that you can keep only a single alphabet or a single
digit number inside single quotes and more than one alphabets or
digits are not allowed inside single quotes.
v. Escape Sequence refers to when a character is preceded by a
backslash (\) and many programming languages support this
concept. Java handles character data types much in the same way
as we have seen in C programming. However, Java provides
additional support for character manipulation. Java also supports
escape sequence in the same way you have used them in C
programming. Python does not support any character data type
15
8
Notes on Self Assessment Questions Computer Files
SAQ 7.4
1. Java provides strings as a built-in data type like any other data
type. It means you can define strings directly instead of defining
them as array of characters.
2. Creating strings in Python is as simple as assigning a string into a
Python variable using single or double quotes. Python does not
support character type; these are treated as strings of length one,
thus also considered a substring.
SAQ 8.1
1. A conditional statement is a mechanism that allows for
conditional execution of instructions based upon the outcome of a
conditional statement, which can be either true or false. Examples
include:
The ‘If Statement’
The ‘If…Else Statement’
The ‘If…elseif….Else Statement’
The Switch Statement
SAQ 8.2
1. A Loop is an important tool in programming. Almost all the
programming languages provide this concept (i.e. loop), which
helps in executing one or more statements up to a desired number
of times e.g. rather than repeating the statement ‘hello world’ a
thousand times by writing ‘printf()’ a thousand times, you can
bypass this challenge by simply using a loop. All high-level
programming languages provide various forms of loops, which
can be used to execute one or more statements repeatedly. The
15
9
Notes on Self Assessment Questions Computer Files
most important types of loop are ‘The While Loop’, and the ‘The
Do…While Loop’
2. The break and continue statements in Java programming work
quite the same way as they work in C programming.
SAQ 9.1
1. An array is a data structure, which can store a fixed-size
collection of elements of the same data type. An array is used to
store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type. All arrays
consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last
element.
2. To create an array variable in C, a programmer specifies the type
of the elements and the number of elements to be stored in that
array. Array in C can be initialized either one by one or using a
single statement. You should know that the number of values
between braces { } cannot be larger than the number of elements
that we declare for the array between square brackets [ ]. If you
omit the size of the array, an array just big enough to hold the
initialization is created. An element is accessed by indexing the
array name. This is done by placing the index of the element
within square brackets after the name of the array.
SAQ 9.2
Java support arrays though there is a little difference in the way they are
created
Python does not have a concept of Array, instead Python provides
another data structure called list, which provides similar functionality as
arrays in any other language.
SAQ 10.1
File input means data that is written into a file and file output means data
that is read from a file. When we provide some input to our program from
the command prompt, then it is called input.
SAQ 10.2
1. Operation modes refer to a format through which a file can be
opened. This include the Read-Only Mode, Write-Only Mode,
Read & Write Mode, and the Append Mode.
2. Usually, we use the fopen() function to create a new file or to
open an existing file. This call will initialize an object of the type
FILE, which contains all the information necessary to control the
stream. In closing files, To close a file, we adopt the fclose( )
function. The prototype of this function is − int fclose( FILE *fp
);. The fclose( ) function returns zero on success, or EOF, special
character, if there is an error in closing the file. This function
actually flushes any data still pending in the buffer to the file,
closes the file, and releases any memory used for the file.
16
0
Notes on Self Assessment Questions Computer Files
161