Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Introduction To Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Introduction To Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Module 2.

Introduction to Programming
In this module, you will take the first steps on your journey to becoming an amazing
computer programmer by learning how you can instruct a computer to perform
interesting actions and solve complex problems that would take human minds years
to solve.

During the lectures, you are going to learn how to create a set of instructions that a
computer will execute, a program. You will learn how to speak the language of
computers by using programming languages. Also, you will learn how data is used to
store information that your programs can use to solve problems, and how operators
are used to transform (change) your data. Further, you will learn about user-defined
datatypes such as Structures, Unions and Enumerations.

In this module, you will explore:

● Learn what data data types are, their importance, and their application in
programming.
● Discover the functionality and structure of operators, and their importance,
and their application in programming.
● Gain insights into constants and literals, understanding how to create and
use them
● Learn user defined datatypes/structures such as: Structures, Unions and
Enumerations

To enhance your understanding, we have tailored specific learning activities:

● Write a program to store the details of a student.


● Write a program to add numbers using arithmetic operators.
● Write a program to print a greeting using literals and variables.

Subject Learning Outcomes

The material in this module relates to the following subject learning outcomes:

​ SLO 2: Gain the ability to create and modify basic data structures such as
arrays and linked lists, along with performing operations like insertion,
deletion, and traversal.
Student Expectations

During this module, you are expected to spend time working through the prescribed
material prior to attending class. This will enable a more valuable discussion to take
place in online tutorials or conferences, where you will be able to discuss concepts,
present ideas and explore information collaboratively in greater depth.

Accordingly, it is suggested that you allow:

4 hours for facilitated study. This includes guided facilitated study, watching or
attending course lectures (live or pre-recorded), responding to facilitator feedback.

8 hours for personal study. This includes reading through course material,
undertaking learning activities and exploring additional related resources.

Topic 1. Data Types and Variables

Key takeaways from this topic...

1. In C++, data types are classified into primitive types (such as integers,
characters, and floating points) and abstract types, which are user-defined.
2. Variables in C++ store data and are declared with a specific data type; their
names must follow naming conventions and are used to manage data in
memory.
3. C++ uses cout for output and cin for input, with stream operators (<< and
>>) to handle data display and retrieval.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Data Types

In the world of data you are going to learn that


not all data is the same. Data has different types. One type is an integer, a whole
number such as 0, -12, 3, 42, and 1337. Another type is a float, a real number such
as 3.14159265, and 0.76.
This module introduces you to the fundamental data types of C++, including
Integers, characters, and more. You will learn how to modify data types to be able to
have different ranges of values, by using data type modifiers. You will then learn how
to store data that your program can access, via using variables. Variables are a way
of associating a name and a data type that your program can use to make decisions.

A data type is a classification of data that tells the compiler or interpreter how the
programmer intends to use the data.

Data Types in C++

These are mainly divided into two types:

● Primitive Data Types


These are predefined or built-in data types and can be used directly by the
programmer to declare variables. The following are the basic data types
we could use:
○ Integer
○ Character
○ Boolean
○ Floating point
○ Double floating point
● Abstract or user-defined data type
These data types are defined by the user.

Primitive Data Types

● Integer (int): Used for storing whole numbers (100, 20, 4, and so on...).
● Character (char): Used for storing a single character (4, b, $, and so
on...).
● Boolean (bool): Used for storing boolean or logical values (true or false).
Represented in memory as 1 for true and 0 for false.
● Floating point (float): Used for storing values with a decimal point
(3.1415927). Can have up to 7 decimal places.
● Double floating point (double): Used for storing values with a decimal
point (3.141592653589794). Can have up to 15 decimal places.

Data type modifiers

Data type modifiers are used with primitive data types to modify the length of data
that a particular data type can hold. Data type modifiers available in C++ are:

● Signed
● Unsigned
● Short
● Long
● Signed, unsigned, long and short modifiers can be used for int.
● Signed and unsigned can be used for char.
● Long can be used for double.

Section 2: Variables

Variables are used to store information that can be referenced and manipulated by a
computer program. It is called a variable because we can change the value stored. It
is a way of labelling data with a descriptive name, so our program is easier to
understand.

Variables are like containers that hold information. The purpose of them is to label
and store data in computer memory (RAM). Different types of variables require
different amounts of memory, and have a specific set of operations that can be
applied to them. Imagine a large warehouse with lots of storage bays, tables,
shelves, rooms etc. We can store different types of items in each of these places.

Variable data type


C++ is a strongly-typed programming language, so it requires every variable to be
declared with its type before its first use. A typical variable declaration and
initialisation is of this form:

data_type name = value;

A variable has a valid C++ data type, like the primitive data types we just saw.
Examples are:

○ int: number = 3;
○ float: value = -23.45;
○ bool: finished = false;
○ char: letter = ‘a’;

Variable naming

A variable has a name that can consist of:

○ Alphabets (both upper and lower case), numbers and the


underscore ‘_’ character.
○ The name is needed to uniquely identify and reference a
variable, to assign a value to the variable (e.g. radius = 3.2).

It can also be used to retrieve the value stored (e.g., circumference = 2* PI * radius).

A name cannot begin with a number, and there are some defined naming
conventions for C++ variables, but there is no particular standard naming
convention, so you should use the naming convention designated by your company
or team.

Scope of a Variable
There are two different types of variables based on the scope.

○ Global Variable
○ Local Variable

The scope of a variable is determined by where in the program it is declared.

Section 3: Input and Output

Output (cout <<)

Output in C++ is done via cout and the stream insertion operator << chains items.

cout << "Hello " << "world!" << endl;

In the above example, the endl can be used to produce a new line. Whenever an
endl is printed, the cursor moves to the beginning of the next line without any visible
output.

A string is enclosed by a pair of double quotes (“any_text”), and will be printed as it


is, including punctuation marks within the double quotes.

We can also use \n, which denotes a newline character just like endl. Similarly, you
could use \t which denotes tab character, to move the cursor to the next tab position.

cout << "hello world, again!\n";

cout << "\thello,\none\tmore\ttime.\n";


Input (cin >>)

Input in C++ is done via cin and the stream extraction operator >> reads input from
the keyboard and stores the value into a variable.

#include <iostream>

using namespace std;

int main()

// creating a float variable with a default value

float studentMark = 100.0f;

// get input from the user to change the student's mark

cin >> studentMark; // user gives a value of 65.2

// print out the student's mark on the screen

cout << studentMark << endl; // Output: 65.2

Topic 2. Operators

Key takeaways from this topic...

1. Arithmetic Operators are for performing mathematical operations on numbers.


2. Relational Operators are for comparing values and determining their
relationships.
3. Logical operators are used to combine and evaluate boolean expressions for
decision-making.
4. C++ uses assignment operators to assign values to variables and modify their
contents.
5. Increment and Decrement Operators increase or decrease the value of a
variable by one.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Operators

An operator in a programming language tells a compiler to perform specific


mathematical and logical computations on operands.

In the following example, ‘+’ is the addition operator and the variables numOne
and numTwo are operands. The addition operator tells the compiler to add both
numOne and numTwo.

#include <iostream>

using namespace std;


int main()

int numOne = 10;

int numTwo = 20;

int result = 0;

result = numOne + numTwo;

C++ has many built-in operators and they can be classified as:

● Arithmetic operators
● Relational operators
● Logical Operators
● Assignment operators
● Increment and Decrement operators
● Bitwise operators
● Special operators

Arithmetic Operators

Symbol Usage Explanation


+ x+y Adds two operands (x and y)

- x-y Subtracts the second operand (y) from the first operand
(x)

* x*y Multiplies both the operands (x and y)

/ x/y Divides first operand (x) by the second operand (y)

% x%y The modulus operator divides the first operand (x) by the
second operand (y) and returns the remainder.

Assignment Operators

Are used to assign values to a variable.

Symbol Usage Explanation


= x=y Assigns the value from the y to x.

+= x += y Adds the value of y to the value of x and assigns the result


to x.

-= x -= y Subtracts the value of y from the value of x and assigns


the result to x.

*= x *= y Multiplies the value of y to the value of x and assigns the


result to x.

/= x /= y Divides the value of x with the value of y and assigns the


result to x.

%= x %= y Divides the value of x by the value of y and returns the


remainder, the remainder is assigned to x.

Increment / Decrement Operators

Are unary operators that require only one operand.


Symbol Usage Explanation

++ x++ Post-increment, increases the value of the operand (x) by


1 after using its value.

++x Pre-increment, increases the value of the operand (x) by 1


before using its value.

-- x-- Post-decrement, decreases the value of the operand (x)


by 1 after using its value.

--x Pre-decrement, decreases the value of the operand (x) by


1 before using its value.

Relational Operators

Are used for comparing two operands, the result of a relational operator is a boolean
value that is either true or false.
Symbol Usage Explanation

< x<y Checks if the value of x is less than the value of y.

<= x <= y Checks if the value of x is less than or equal to the value
of y.

> x>y Checks if the value of x is greater than the value of y

>= x >= y Checks if the value of x is greater than or equal to the


value of y.

== x == y Checks if the value of x is equal to the value y.

!= x != y Checks if the value of x is not equal to the value of y.

Logical Operators
These take boolean values as input and return boolean values as output. Here, the x
and y are boolean values.

Symbol Usage Explanation

&& x && y Logical AND, returns true when both conditions are
satisfied. Otherwise, it returns false.

|| x || y Logical OR, returns true when one (or both) of the


conditions is satisfied. Otherwise, it returns false if both
the conditions are not satisfied.

! !x Logical NOT, returns true if the condition is not satisfied,


and returns false if the condition is satisfied.

!y

Rule of Precedence and Associativity

The precedence of an operator decreases from top to bottom.


Operator Description Associati
s vity

() Parentheses L -> R

*, /, % Multiplication, Division & Modulus

+, - Addition and Subtraction

<, <=, >, >= Less than, Less than equal to, greater than, greater than
equal to

=, +=, -= Assignment, compound assignment by sum and difference R -> L

Further Reading: A list of all C++ operators

Links to an external site.

shows the precedence and associativity.


Topic 3. Constants, Literals, and User-Defined Data
Types/Structures

Key takeaways from this topic...

1. Constants in C++ are fixed values that do not change during program
execution and are defined using the const keyword
2. Literals are specific values directly written into the code, such as numbers or
characters, that represent fixed data of a particular type.
3. Structures and unions in C++ are user-defined types for grouping data, with
structures allowing different types of data to be combined and unions sharing
the same memory space for multiple data types, while enums define a set of
named integer constants for better code readability and management.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Understanding Literals


A literal is a fixed value that is written directly into the source code. Literals are
compiled into constants with the values in the source code.

In the following example, Hello world! and 5 are literals.

int x = 5;

cout << "Hello world!" << endl;

Both literals and variables have a value, and they both have a type. The type of a
variable is given in its declaration. The type of a literal is assumed from the value
and format of the literal itself.

Types of Literals

Literals can be of any primitive (built-in) data type:

● Integer
● Floating-point (includes float and double)
● Character
● String
● Boolean

Section 2: Understanding Constants

Defining constants

Constants are treated just like regular variables except that their values cannot be
modified after their definition. Use a constant variable to avoid accidentally changing
a variable that should not change.
There are two simple ways in C++ to define constants—by using:

● const keyword
● #define preprocessor

const

We can use the const prefix to declare constants with a specific data type. The
syntax for creating a constant variable is:

const type variableName = value;

The constant variables should be initialised with a value when the variable is
created.

const double PI = 3.141592653589793238;

If we try to change the value of the constant variable after its initialisation, we will get
an error

PI = 231.424; // this line will result in a compile error

#define preprocessor

Another mechanism to name constant values is to use the #define preprocessor


directive. The syntax of the preprocessor directive is:

#define identifier replacementValue


After this directive, any occurence of identifier in the code is interpreted as
replacementValue, where replacementValue is any sequence of characters (until the
end of the line).

#define PI 3.141592653589793238

This is a blind replacement as it is performed by the preprocessor, and happens


before the program is compiled. The validity of the types or syntax involved will not
be checked in any way.

Section 3: User-Defined Datatypes - Structures, Unions and Enumerations

Structures

Structure is a user-defined data type. It is used to combine different data types into
one unit.

It is declared using the keyword struct.

Unions

Unions are user-defined data types. Similar to structures, they can declare and
contain members of different data types. How they differ from a structure is that
member variables in a union share the same memory location.

It is declared using the keyword union.

Enumerations (Enums)
Enums are user-defined data types that contain named integral constants. Enums
help to assign constants into a set of names, which makes programs more readable.

It is declared using the keyword enum.

Further Resources
The resources in this section are for further exploration, providing additional
information for deeper insights.

Expand All
Panels
Collapse All
Panels
Reading: Converting unsigned integers to signed integers can lead to hidden
bugs
This blog post demonstrates the dangers of converting between two data types that
you learnt about in this week’s lectures, signed and unsigned integers. It is
exceptionally useful to understand how your programs might have accidental
problems, and this is a common source of problems.

Converting unsigned integers to signed integers can lead to hidden bugs

Links to an external site.

Reference: Pluralsight (2016) 'Converting unsigned integers to signed integers can lead to hidden
bugs', available at:
https://www.pluralsight.com/blog/software-development/convert-unsigned-int-to-signed-int [accessed
16/09/2024]

Reading: C++ Operator Precedence


This article details how operator precedence functions in C++. It is very easy to
introduce errors in your program by not understanding which order operators will be
executed. Understanding the order allows you to write programs faster and without
precedence errors.

C++ Operator Precedence

Links to an external site.


Reference: cppreference.com (n.d.) 'C++ Operator Precedence', cppreference.com wiki, available at:
https://en.cppreference.com/mwiki/index.php?title=cpp/language/operator_precedence&oldid=118915
[accessed 16/09/2024]

Reading: Structures, Unions and Enumerations in C++


This tutorial details how Structures, Unions and Enumerations work in C++. It is very
useful to use these user-defined data types in your programs. Understanding this
allows you to write programs that are well-organised.

Structures, Unions and Enumerations in C++

Links to an external site.

Reference: Geeksforgeeks (2024) 'Structures, Unions and Enumerations in C++', Geeksforgeeks,


available at: https://www.geeksforgeeks.org/structures-unions-and-enumerations-in-cpp/ [accessed
16/09/2024]

Reading: C++ Unions


This tutorial details how Unions works in C++. It is very useful to use this
user-defined data type in your programs to keep them well organised.

C++ Unions

Links to an external site.

Reference: Geeksforgeeks (2024) 'C++ Unions', Geeksforgeeks, available at:


https://www.geeksforgeeks.org/cpp-unions/ [accessed 16/09/2024]

You might also like