0% found this document useful (0 votes)
238 views56 pages

DCIT104 Lecture 1

The output of the program when the input is 3 would be: A 3 year old dog is about a 21 year old human.

Uploaded by

Muel Opoku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
238 views56 pages

DCIT104 Lecture 1

The output of the program when the input is 3 would be: A 3 year old dog is about a 21 year old human.

Uploaded by

Muel Opoku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

DCIT 104

PROGRAMMING
FUNDAMENTALS

Lecture 1 – Programming (General)

Course Writer: Dr. Moses Akazue


Contact Information: [email protected]

College of Education
School of Continuing and Distance Education
2020/2021 – 2022/2023
Lecture Overview

In the information age, many people believe


computational thinking, or creating a sequence of
instructions to solve a problem, will become
increasingly important for work and everyday life.
This first session introduces the basics of
programming from algorithm to program
Lecture Outline

The key topics to be covered in the session are as


follows:
• Computer Program and Programming Basics
• Computational Thinking
• Comments and Whitespace
• Errors and Warnings
• Tips on Debugging
Computer Program Basics

Computer programs are abundant in many people's lives today, carrying


out applications on smartphones, tablets, and laptops, powering
businesses like Amazon and Netflix, helping cars drive and planes fly,
and much more.
A computer program consists of instructions executing one at a time.
Basic instruction types are:

• Input
• Process
• Output

Google Confidential and Proprietary


zyBooks
Computer Program Basics (Contd.)

• Input: A program gets data, perhaps from a file, keyboard,


touchscreen, network, etc.
• Process: A program performs computations on that data, such as
adding two values like x + y.
• Output: A program puts that data somewhere, such as to a file,
screen, network, etc.

Programs use variables to refer to data, like x, y, and z below. The


name is due to a variable's value varying as a program assigns a variable
like x with new values.

Video on Next Slide Google Confidential and Proprietary


zyBooks
A Basic Program

Google Confidential and Proprietary


zyBooks
Participation Activity 1: Basic Computer Program

Consider the example above.

1. The program has a total number of _____ instructions.

2. Suppose a new instruction was inserted as follows:

...
z=x+y
Add 1 more to z (new instruction)
Put z to output

What would the last instruction then output to the screen?

3. Consider the instruction: z = x + y. If x is 10 and y is 20, then z is assigned with


_____.

Google Confidential and Proprietary


zyBooks
A Program is like a Recipe

Some people think of a program as being like a cooking recipe. A recipe


consists of instructions that a chef executes, like adding eggs or stirring
ingredients. Likewise, a computer program consists of instructions that a
computer executes, like multiplying numbers or outputting a number to
a screen.

Google Confidential and Proprietary


zyBooks
A First Programming Activity

Below is a simple tool that allows a user to rearrange some prewritten


instructions (in no particular programming language). The tool
illustrates how a computer executes each instruction one at a time,
assigning variable m with new values throughout and outputting
("printing") values to the screen.

Google Confidential and Proprietary


zyBooks
Participation Activity 2: Instructions

Which instruction completes the program to compute a triangle's area?


base = Get next input
height = Get next input
Assign x with base * height
_____
Put x to output

a) Multiply x by 2
b) Add 2 to x
c) Multiply x by ½

Google Confidential and Proprietary


zyBooks
Participation Activity 2: Instructions

Which instruction completes the program to compute the average of three


numbers?
x = Get next input
y = Get next input
z = Get next input
_____
Put a to output

a) a = (x + y + z) / 3
b) a = (x + y + z) / 2
c) a=x+y+z

Google Confidential and Proprietary


zyBooks
Computational Thinking

• Mathematical thinking became increasingly important throughout


the industrial age to enable people to successfully live and work.
• In the information age, many people believe computational
thinking, or creating a sequence of instructions to solve a
problem, will become increasingly important for work and
everyday life.
• A sequence of instructions that solves a problem is called
an algorithm.

Google Confidential and Proprietary


zyBooks
Creating Algorithms to Draw Shapes

A common way to become familiar with algorithms is called turtle graphics:


You instruct a robotic turtle to walk a certain path, via instructions like "Turn
left", "Walk forward 10 steps", or "Pen down" (to draw a line while walking).
• The 6-instruction algorithm shown below ("Pen down", "Forward 100",
etc.) draws a triangle.
– Pen down
– Forward 100
– Left 120
– Forward 100
– Left 120
– Forward 100
• Can you modify the instructions to draw a square?
• Hint: "Pen down", "Forward 100", "Left 90", "Forward 100", "Left
90"—keep going! Google Confidential and Proprietary
zyBooks
Programming Basics

A simple C++ program appears below.

• A program starts in main(), executing the statements within


main's braces { }, one at a time.
• Each statement typically appears alone on a line and ends
with a semicolon, as English sentences end with a period.
• The int wage statement creates an integer variable named
wage. The wage = 20 statement assigns wage with 20.
• The cout statements output various values.
• The return 0 statement ends the program (the 0 tells the
operating system the program ended without error).

Google Confidential and Proprietary


zyBooks
A First Program

• Code is the textual representation of a program, as seen below.


Many code editors color words, as below, to assist humans to
understand various words' roles.
• The following code (explained later) at the top of a file enables the
program to get input and put output:

#include <iostream>
using namespace std;

Video on Next Slide


Google Confidential and Proprietary
Learn.zybooks.com
A Program Can Get an Input From the Keyboard

Google Confidential and Proprietary


Learn.zybooks.com
Participation Activity 3: A First Program

Consider the program above.

1. Program execution begins at main() and executes statements surrounded by which


symbols?
a) ( )
b) { }
c) " "

2. The statement int wage; creates a variable named wage that is used to _____ the value 20.
a) input
b) output
c) Hold

3. Would the following order of statements work the same as above?


wage = 20;
int wage;
a) No
b) Yes
Google Confidential and Proprietary
Participation Activity 3: A First Program (Contd.)

Still considering the program above.

1. Each statement ends with what symbol?


a) Semicolon ;
b) Period .
c) Colon :

2. The expression wage * 40 * 50 resulted in what value?


a) 20
b) 40000
c) 20 * 40 * 50

3. Each cout statement outputs items to _____.


a) a file named output.txt
b) the keyboard
c) the screen

Google Confidential and Proprietary


Learn.zybooks.com
A First Program

Copy and paste the code below into your IDE and click RUN

#include <iostream>
using namespace std;

int main() {
int wage;

wage = 20;

cout << "Salary is ";


cout << wage * 40 * 50;
cout << endl;

return 0;
}

Google Confidential and Proprietary


Learn.zybooks.com
Basic Input

Programs commonly get input values, perform some processing on that


input, and put output values to a screen or elsewhere. Input is commonly
gotten from a keyboard, a file, fields on a web form or app, etc.

The following statement gets an input value and puts that value into
variable x: cin >> x; cin is short for characters in.

Google Confidential and Proprietary


Learn.zybooks.com
Basic Input (Contd.)

What is the output of the program below when the input is 3?

#include <iostream>
using namespace std;

int main() {
int dogYears;
int humanYears;

cin >> dogYears;


humanYears = 7 * dogYears;

cout << "A ";


cout << dogYears;
cout << " year old dog is about a ";
cout << humanYears;
cout << " year old human.";
cout << endl;

return 0;
} Google Confidential and Proprietary
Learn.zybooks.com
Basic Input (Contd.)

What is the output if the input box value changes to 5?

#include <iostream>
using namespace std;

int main() {
int dogYears;
int humanYears;

cin >> dogYears;


humanYears = 7 * dogYears;

cout << "A ";


cout << dogYears;
cout << " year old dog is about a ";
cout << humanYears;
cout << " year old human.";
cout << endl;

return 0;
} Google Confidential and Proprietary
Learn.zybooks.com
Basic Output

• The cout construct supports output; cout is short for characters out.
Outputting text is achieved via: cout << "desired text";.
• Text in double quotes " " is known as a string literal. Multiple cout
statements continue printing on the same output line.
• The statement cout << endl starts a new output line, called
a newline.
• The notation cout << ... gives the appearance of the item on the
right being "streamed" to cout (like items flowing along a stream
into a lake), where cout represents the computer's screen.

Google Confidential and Proprietary


Learn.zybooks.com
Outputting Text and Newlines

Google Confidential and Proprietary


Learn.zybooks.com
Challenge Activity 1

Write a statement that outputs the following on a single line (without a


newline):

Hi world! How are you?

#include <iostream>
using namespace std;

int main() {

/* Your code goes here */

return 0;
} Google Confidential and Proprietary
Learn.zybooks.com
Outputting a Variable’s Value

Outputting a variable's value is achieved via: cout << x;. Note that no
quotes surround x.

Note that the programmer intentionally did not start a new output line
after outputting "Wage is: " so that the wage variable's value would
appear on that same line.

Google Confidential and Proprietary


Learn.zybooks.com
Challenge Activity 2: Output Text

• Write a statement that outputs variable userAge. End with a newline.

#include <iostream>
using namespace std;

int main() {
int userAge;

cin >> userAge; // Program will be tested with values: 15, 40.

/* Your code goes here */

return 0;
}
Google Confidential and Proprietary
Learn.zybooks.com
Outputting Multiple Items With One Statement

• Programmers commonly use a single output statement for each line of


output by combining the outputting of text, variable values, and a new line.
• The programmer simply separates the items with << symbols.
• Such combining can improve program readability because the program's
code corresponds more closely to the program's output.

Google Confidential and Proprietary


Learn.zybooks.com
Single Output Statement

• In your IDE, modify the program on the next slide to use only two
output statements, one for each output sentence.
In 2014, the driving age is 18.

10 states have exceptions.

• Do not type numbers directly in the output statements; use the


variables.
ADVICE: Make incremental changes—Change one code line, run
and check, change another code line, run and check, repeat. Don't try
to change everything at once.

Google Confidential and Proprietary


Learn.zybooks.com
Single Output Statement

#include <iostream>
using namespace std;

int main() {
int drivingYear;
int drivingAge;
int numStates;

drivingYear = 2014;
drivingAge = 18;
numStates = 10;

cout << "In ";


cout << drivingYear;
cout << ", the driving age is ";
cout << drivingAge;
cout << ".";
cout << endl;
cout << numStates;
cout << " states have exceptions.";
cout << endl;

return 0;
Google Confidential and Proprietary
} Learn.zybooks.com
Challenge Activity 3: Read Multiple User Inputs

• In the program below, write two cin statements to get input values
into birthMonth and birthYear. Then write a statement to output the
month, a dash, and the year. End with newline.

The program will be tested with inputs 1 2000 and then with inputs
5 1950.

– Ex: If the input is 1 2000, the output is: 1-2000

Note: The input values come from user input, so be sure to use cin
statements, as in cin >> birthMonth, to get those input values
(and don't assign values directly, as in birthMonth = 1).
Learn.zybooks.com Google Confidential and Proprietary
Challenge Activity 3

#include <iostream>
using namespace std;

int main() {
int birthMonth;
int birthYear;

/* Your solution goes here */

return 0;
}

Learn.zybooks.com Google Confidential and Proprietary


Newline Character

• A new output line can also be produced by inserting \n, known as


a newline character, within a string literal.
• Ex: Outputting "1\n2\n3" outputs each number on its own output
line. \n use is rare but appears in some existing code, so it is
mentioned here. \n consists of two characters, \ and n, but together
are considered as one newline character.
• Good practice is to use endl to output a newline, as endl has some
technical advantages not mentioned here.

Learn.zybooks.com Google Confidential and Proprietary


Comments

A comment is text a programmer adds to code, to be read by humans


to better understand the code but ignored by the compiler. Two
common kinds of comments exist:
• A single-line comment starts with // and includes all the following
text on that line. Single-line comments commonly appear after a
statement on the same line.
• A multi-line comment starts with /* and ends with */, where all
text between /* and */ is part of the comment. A multi-line
comment is also known as a block comment.

Google Confidential and Proprietary


Learn.zybooks.com
Comments Example

Learn.zybooks.com www.id-book.com
Whitespace

Whitespace refers to blank spaces (space and tab characters) between


items within a statement and blank lines between statements (called
newlines). A compiler ignores most whitespace.
Good practice is to deliberately and consistently use whitespace to
make a program more readable. Programmers usually follow
conventions defined by their company, team, instructor, etc., such as:

• Use blank lines to separate conceptually distinct statements.


• Indent lines the same amount.
• Align items to reduce visual clutter.
• Use a single space before and after any operators like =, +, *, or <<
to make statements more readable.
Learn.zybooks.com 36
Good Use of Whitespace

Learn.zybooks.com 37
Bad Use of Whitespace

38
Learn.zybooks.com
Compiling code with comments and whitespace

• The diagram below provides a (simplified) demonstration of how a


compiler processes code from left-to-right and line by line, finding each
statement (and generating machine code using 0s and 1s) and ignoring
whitespace and comments.
• The compiler recognizes end of statement by semicolon ";".

Learn.zybooks.com
Syntax Errors

• People make mistakes. Programmers thus make mistakes—lots of


them.
• One kind of mistake, known as a syntax error, is to violate a
programming language's rules on how symbols can be combined to
create a program.
• An example is forgetting to end a statement with a semicolon.
• A compiler generates a message when encountering a syntax error.
The following program is missing a semicolon after the first output
statement.

Learn.zybooks.com
Compiler Reporting a Syntax Error

Above, the 6 refers to the 6th line in the code, and the 27 refers to the 27th
column in that line

Learn.zybooks.com
In-Class Activity

• In your IDE, complete the program below by typing the following


statement as your solution.
• Note: the statement is intentionally missing weather.yahoo.com
an ending semicolon
-- don't add the semicolon yet.

cout << "Hello”

#include <iostream>
using namespace std;
int main() {

/* type statement here */


return 0;
}
Learn.zybooks.com
Unclear Error Messages

• Compiler error messages are often unclear or even misleading. The message is
like the compiler's "best guess" of what is really wrong. Below is an example
of a misleading compiler error.
• The compiler indicates a missing semicolon ';'. But the real error is the missing
<< symbols.
• Sometimes the compiler error message refers to a line that is actually many
lines past where the error actually occurred. Not finding an error at the
specified line, the programmer should look to previous lines.

Learn.zybooks.com
Unclear Error Messages (Contd.)

• In the example below, the actual error is on line 3, but the compiler
continues processing until line 5
• On line 5, the compiler is confused, so it generates a message. But
the reported line number is past the actual syntax error.
• Upon not finding an error at line 5, the programmer should look at
earlier lines.

Learn.zybooks.com
Good Practice on Fixing Error Reported by the Compiler

1. Focus on FIRST error message, ignoring the rest.


2. Look at reported line of first error message. If error
found, fix. Else, look at previous few lines.
3. Compile, repeat.

45
Learn.zybooks.com
Fixing Syntax Errors

• Click run to compile, and note the long error list.


• Fix only the first error, then recompile.
• Repeat that process (fix first error, recompile) until the
program compiles and runs.
• Expect to see misleading error messages as well as errors that
occur before the reported line number.

46
Learn.zybooks.com
Challenge Activity 5: Basic Syntax Error

#include <iostream>
using namespace std;

int main() {
int userNum;

userNum = 5;

/* Your solution goes here */

return 0;
}

Using the code stub above, insert the following statements, correcting the one
syntax error in each statement.
Google Confidential and Proprietary
Learn.zybooks.com
Challenge Activity 5

cout << "Foretelling is hard." << end;


cout << "Particularly ‘;
cout << "of the future." << endl.
cout << "User num is: " << userNum >> endl;

• Hints: Statements end in semicolons, and string literals use double


quotes.

• Note: These activities may test code with different test values. This
activity will perform two tests: the first with userNum = 5, the
second with userNum = 11.

48
Learn.zybooks.com
Challenge Activity 6: More Syntax Errors

• Each of the following cout statements has a syntax error.


• In your IDE, using the code stub to the right, type the first cout
statement, and press Run to observe the error message.
• Fix the error, and run again. Repeat for the second, then third, cout
statement.

cout << "Num: " << songnum << endl;


cout << int songNum << endl;
cout << songNum " songs" << endl;

Google Confidential and Proprietary


Learn.zybooks.com
Challenge Activity 6: More Syntax Errors

#include <iostream>
using namespace std;

int main() {
int songNum;

songNum = 5;

/* Your solution goes here */

return 0;
}

Note: These activities may test code with different test values. This activity will
perform two tests: the first with songNum = 5, the second with songNum = 9.
Google Confidential and Proprietary
Learn.zybooks.com
More Syntax Errors

Compile-time error
• Because a syntax error is detected by the compiler, a syntax error is known as
a type of compile-time error.
Logic Error
• A logic error, also called a bug, is an error that occurs while a program runs.

Google Confidential and Proprietary


Learn.zybooks.com
More Syntax Errors: Bugs

• The term bug to describe a runtime error was popularized when


in 1947 engineers discovered their program on a Harvard
University Mark II computer was not working because a moth
was stuck in one of the relays (a type of mechanical switch).
• They taped the bug into their engineering log book, still
preserved today.

Google Confidential and Proprietary


Learn.zybooks.com
Fix the Bug

The program below has a bug that causes a logic error. The incorrect output is:
“500 beans in 3 jars yields totalBeans total”.
Can you fix the bug?

#include <iostream>
using namespace std;

// This program has a bug that causes a logic error.


// Can you find the bug?
int main() {
int numBeans;
int numJars;
int totalBeans;

numBeans = 500;
numJars = 3;

cout << numBeans << " beans in ";


cout << numJars << " jars yields ";
totalBeans = numBeans * numJars;
cout << "totalBeans" << " total" << endl;

Learn.zybooks.com Google Confidential and Proprietary


return 0;
}
Tips on Debugging: Compiling Frequently

• Good practice, especially for new programmers, is to compile after


writing only a few lines of code, rather than writing tens of lines and
then compiling.
• New programmers commonly write tens of lines before compiling,
which may result in an overwhelming number of compilation errors
and warnings and logic errors that are hard to detect and correct.

Google Confidential and Proprietary


zyBooks
Compiler Warnings

• A compiler will sometimes report a warning, which doesn't stop the


compiler from creating an executable program but indicates a possible
logic error.
• Ex: Some compilers will report a warning like "Warning, dividing by
0 is not defined" if encountering code like: totalItems = numItems /
0 (running that program does result in a runtime error).
• Even though the compiler may create an executable program, good
practice is to write programs that compile without warnings.
• In fact, many programmers recommend the good practice of configuring
compilers to print even more warnings.
• For example, the g++ compiler can be run as g++ -Wall yourfile.cpp,
where -Wall indicates that the compiler should display all warnings.
Google Confidential and Proprietary
zyBooks
References

• Felleisen, M., Findler, R. B., Flatt, M., & Krishnamurthi, S.


(2011). How to Design Programs: An Introduction to
Programming and Computing, Cambridge, MA: MIT Press
• Frank Vahid, and Roman Lysecky (2019). Programming in
C++, August 2019. zyBook ISBN: 978-1-5418-9966-7

Google Confidential and Proprietary


zyBooks

You might also like