0% found this document useful (0 votes)
105 views30 pages

Sir JM - Computer Programming 1

This document provides an introduction to computer programming using C++. It discusses key concepts like tokens, variables, data types, operators, and functions. It also explains how to install CodeBlocks IDE and provides a simple "Hello World" example to demonstrate printing output. The example breaks down the code line-by-line to explain concepts like namespaces, strings, escape sequences, and return statements.

Uploaded by

Absar Arip
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)
105 views30 pages

Sir JM - Computer Programming 1

This document provides an introduction to computer programming using C++. It discusses key concepts like tokens, variables, data types, operators, and functions. It also explains how to install CodeBlocks IDE and provides a simple "Hello World" example to demonstrate printing output. The example breaks down the code line-by-line to explain concepts like namespaces, strings, escape sequences, and return statements.

Uploaded by

Absar Arip
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/ 30

1

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
2

TABLE OF CONTENT

LESSON 1: INTRODUCTION 2
CONCEPT NOTE 2-8

LESSON 2: FLOW OF CONTROL 8


CONVEPT NOTE 8-19

LESSON 3: FUNCTIONS 19
CONCEPT NOTE 19-21

LESSON 4: ARRAYS AND STRINGS 21


CONCEPT NOTE 21-23

LESSON 5: POINTERS 23
CONCEPT NOTE 23-26

LESSON 6: CLASSES AND OBJECTS


CONCEPT NOTE 26-28

LESSON 7: MEMORY MANAGEMENT 28


CONCEPT NOTE 29

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
3

LESSON 1: INTRODUCTION

CONCEPT NOTE

For performance-critical applications that require speed and effective memory management, C++
is a popular language. It's employed in a variety of fields such as software and game
development, virtual reality, robotics, and scientific computing. Bjarne Stroustrup invented it as
a "C with Classes" supplement to the C programming language. The language has evolved
greatly over time, and modern C++ now includes object-oriented, generic, and functional
features, as well as memory manipulation capabilities.

The benefits of C++ include:


Conciseness - programming language allow us to write typical command sequences in a more
concise manner.
Maintainability - instead of rearranging hundreds of processor instructions, updating code
requires only a few text edits.
Portability- Different processors make different instructions available, therefore portability is
important. Text-based programs can be converted into instructions for a variety of processors;
one of C++'s advantages is that it can be used to develop programs for almost any processor.

HOW TO INSTALL CODEBLOCKS IDE ON WINDOWS?

1. Go to codeblocks.org. Select Download from the menu, and then select the binary release.
2. Navigate to the section for your operating platform (e.g., Windows XP / Vista / 7 / 8.x / 10)
and download the installer with GCC Compiler, e.g., codeblocks-17.12mingwsetup.exe or Click
here to download.
3. Double-click the downloaded installer to launch it, then click Next in the pop-up window. To
accept the licence agreement, click on "I Agree."
4. On the new pop-up, do nothing but click Next and then, if desired, change the installation
directory (default directory recommended). Install should be selected.
5. Wait a minute for the installation to finish. A new pop-up prompts you to launch Codeblocks.
Select YES.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
4

We must double-check the Compiler and Debugger paths (this step is optional).

1. Select Settings >> Compiler from the menu options. It defaults to GNU GCC Compiler as the
specified compiler. Select the “Toolchain Executables” tab from the list of tabs below, and make sure
the Compiler's Installation Directory is set to “C:Program FilescodeblocksMinGW.”

2. Similarly, go to Settings >> Debugger >> GDB/CDB debugger >> Default for the debugger path. If
you installed MinGW compiler before installing Codeblocks, the path for Executable should be
C:Program FilescodeblocksMinGWbing db.exe or C:MinGWbingdb.exe.

Note: If you're having trouble running the debugger with CodeBlocks, try a fresh installation.
Uninstall Codeblocks, then install MinGW, followed by Codeblocks.

HELLO WORLD

In the tradition of programmers everywhere, we'll start with a "Hello, world!" programme to
learn the fundamentals of C++

The code

// A Hello World program

#include <iostream >

int main() {

std::cout << "Hello , world!\n";

return 0;

Tokens

Tokens are the smallest meaningful symbols in the language, and they are the smallest chunk of
programme that has meaning to the compiler. Although the customary use of operators is not
present in our code, it displays all six types of tokens.

Keywords Words that have special int, double, for, auto


significance to the compiler
Identifiers Names of things that are not cout, std, x, myFunction
built into the language
Literals Names of things that aren't "Hello, world!", 24.3, 0, ’c’

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
5

part of the language's


vocabulary
Operators Values of fundamental +, -, &&, %, <<
constants
Punction/Separators Punctuation that defines a {}(),;
program's structure

Various types of spaces; Spaces, tabs, newlines,


Whitespace compiler comments ignore comments
them

Line-By-Line Explanation

1. // indicates that everything after it until the end of the line is a comment, which the compiler
ignores. A comment can also be written between /* and */ (for example, x = 1 + /*sneaky
comment here*/ 1;). This type of comment can be multi-lined. Comments are used to explain
what is happening in the code that isn't immediately evident. Make good use of them: well-
documented code!

2. Preprocessor commands are lines that begin with # and change what code is actually
compiled. #include instructs the preprocessor to load the contents of another file, in this case the
iostream file, which defines the input/output routines.

3. int main() {...}specifies the code that should be run when the programme is started. Multiple
commands are grouped together in a block using the curly brackets.

4. • cout << : cout >>: This is the syntax for displaying a text string on the screen.

5. • Namespaces: In C++, identifiers can be declared in a context called a namespace, which is


similar to a directory of names. When we want to use an identifier specified in a namespace, we
use the scope resolution operator to inform the compiler to seek for it in that namespace (::).
We're directing the compiler to look for cout in the std namespace, which contains a lot of
standard C++ identifiers

A cleaner alternative would be to insert the following line after line 2:

using namespace std;

This line instructs the compiler to look in the std namespace for any identifiers that we haven't
defined. We can omit the std:: prefix when writing cout if we do this. This is the recommended
method.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
6

Strings: A string is a series of characters such as Hello, world. A string literal is a string that is
explicitly specified in a program.

• Escape sequences: The / n character denotes the start of a new line. It's an escape sequence,
which is a symbol that represents a special character in a text literal. The following is a list of all
the C++ escape sequences that can be used in strings:

return 0 indicates that the program has completed successfully and should notify the operating
system. This syntax will be discussed in the context of functions; for now, just add it to the end
of the main block. Basic Features Values and Statements are included in the basic language.

Basic Language Features

Values and Statements are included in the basic language.

• A statement is a piece of code that performs a certain task — it's the foundation of a program.

• An expression is a statement with a value, such as a number, a string, the sum of two numbers,
and so on. Expressions include 4 + 2, x - 1, and "Hello, world!".

A statement isn't always an expression. It's pointless to discuss the worth of a #include
declaration, for example.

Operators

We can use operators to accomplish arithmetic computations. Operators combine expressions to


create a new one. For example, we might substitute (4 + 2) / 3 for "Hello, world!\n” and the
program would produce the number 2. The + operator is applied to the expressions 4 and 2 in
this situation (its operands).

Operator types:

• Mathematical: +, -, *, /, and parentheses have the same mathematical meanings as +, -, *, /, and


parentheses, including the use of - for negation. The modulus operator (percent) calculates the
difference between two numbers: 6 % 5 is equal to 1.

 Logical: used for "and," "or," and other similar terms.

• Bitwise: a method of manipulating integers' binary representations.

Data Types

Very expression has a type, which is a formal description of the data it represents. For example,
0 is a positive integer, 3.142 is a decimal number, and "Hello, world!" is a string value (a
sequence of characters). Various types of data require different amounts of memory to be stored.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
7

Variables

A value may be given a name so that it can be referred to later. This is accomplished through the
use of variables. A variable is a memory location that has a name.

Let's imagine we wanted to use the number 4 + 2 several times. We can call it x and utilize it like
this:

# include <iostream >

using namespace std ;

int main () {

int x;

x = 4 + 2;

cout << x / 3 << ’ ’ << x * 2;

return 0;

Input

We can have the program's user input values now that we know how to assign values names.
This may be seen in line 6 below:

# include <iostream >

using namespace std ;

int main () {

int x;

cin >> x;

cout << x / 3 << ’ ’ << x * 2;

return 0;

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
8

Debugging

When building C++ programs, you'll encounter two types of problems: compilation errors and
runtime errors. Compilation errors are issues that the compiler raises as a result of violations of
syntax rules or type abuse. Typos and other errors are frequently to blame. Runtime errors are
issues that only become apparent when the program is run: you specified a legal program, but it
does not perform as expected. Because the compiler won't notify you about them, they're
frequently more difficult to spot.

LECTURE 2: FLOW OF CONTROL

CONCEPT NOTE

Motivation

A program normally executes statements in order from first to last. The first statement is
performed, followed by the second, third, and so on, until the program reaches its conclusion and
ends. If a computer program executed the same series of statements every time it was run, it
wouldn't be particularly useful. It would be wonderful to be able to modify which statements ran
when and under what conditions. For example, if a program counts the number of times a certain
word appears in a file, it should be able to do so regardless of the file or word given to it.
Alternatively, a computer game should allow the user to move their character around whenever
they wish.For example, if a program counts the number of times a certain word appears in a file,
it should be able to do so regardless of the file or word given to it. Alternatively, a computer
game should allow the user to move their character around whenever they wish. We need to be
able to change the control flow, or the order in which a program's statements are executed.

Control Structures

Control structures are sections of program code that include statements and, depending on the
situation, execute these statements in a specific manner. Conditionals and loops are the two most
common types.

Conditional

Conditionals In order for a program's behaviour to change based on the input, it must be possible
to test that input. Conditionals enable the program to check variable values and execute (or not
execute) specific statements. If and switchcase conditional constructs are available in C++.

Operators

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
9

Conditionals employ two types of special operators: relational and logical operators. These are
used to determine whether or not a given condition is true. The relational operators are used to
check if two expressions are related:

Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

To integrate relational expressions into more sophisticated Boolean expressions, logical


operators are frequently used:

Operator Meaning
&& and
|| or
! Not

According to logic rules, the operators return true or false:

a b a && b
True True True
True False False
false True False
false False False

a b a| | b
True True True
True False True
False True True
false False False

The! Operator is a unary operator that takes only one argument and negates the value of that
argument:

A !a
True False
False True

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
10

Examples using logical operators (assume x = 6 and y = 2): !(x > 2) → false

(x > y) && (y > 0) → true

(x < y) && (y > 0) → false

(x < y) || (y > 0) → true

Of course, because they carry true and false values, Boolean variables can be utilized directly in
these expressions. Because of a peculiarity in C++, any value can be used in a Boolean
expression: false is represented by a value of 0, and anything that is not 0 is true. So, “Hello,
world!”, “2,” and any int variable with a non-zero value are all true. This implies! x is false, and
x and y are both true!

if, if-else and else if

The if conditional has the form: if(condition)

statement1

statement2

The condition is a value that is being tested on an expression. The statements are run before the
program continues if the condition resolves to a value of true. Otherwise, the assertions are
dismissed. The curly brackets can be eliminated if there is only one sentence, producing the
form: if(condition)

Statement

The if-else form is used to choose between two statements sequences known as blocks:
if(condition)

statementA1

statementA2

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
11

else

statementB1

statementB2

If the condition is met, the block corresponding to the if is executed. Otherwise, the block
corresponding to the else is executed. Because the condition is either satisfied or not, one of the
blocks in an if-else must execute. If there is only one statement for any of the blocks, the curly
braces for that block may be omitted: if(condition)

statementA1

else

statementB1

The else if is used to decide between two or more blocks based on multiple conditions:
if(condition1)

statementA1

statementA2

else if(condition2)

statementB1

statementB2

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
12

The block corresponding to the if is executed if the condition is met. If else is true, the block that
corresponds to else is executed because the condition must be satisfied or not, one of the if-else
blocks must be executed. If each of the blocks has only one statement, the curly braces for that
block can be omitted: if (condition)

Here's an example of how these control structures can be used:

#include <iostream>

using namespace std;

int main() {

int x = 6;

int y = 2;

if(x > y)

cout << “x is greater than y\n”;

else if(y > x)

cout << “y is greater than x\n”;

else

cout << “x and y are equal\n”;

return 0;

The output of this program is x is greater than y. If we replace lines 5 and 6 with int x = 2;

int y = 6;

then the output is y is greater than x. If we replace the lines with int x = 2;

int y = 2;

then the output is x and y are equal. 2.1.3 switch-case

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
13

The switch-case is another conditional structure that may or may not execute certain statements.
However, the switch-case has peculiar syntax and behavior: switch(expression)

case constant1:

statementA1

statementA2

...

break;

case constant2:

statementB1

statementB2

...

break;

...

default:

statementZ1

statementZ2

...

Another conditional structure is the switch-case, which can either run or not execute certain
statements. The syntax and behaviour of the switch-case, on the other hand, are odd:
switch(expression). The switch examines expression and, if it equals constant1, executes the
statements in case constant

1: until a break occurs. When expression doesn't equal constant1, it's compared to constant2. If
these are equal, the statements below case constant

2: are run until a break occurs. If not, the same procedure is followed for each of the constants
individually. The statements below default: are executed if none of the constants match

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
14

Loops

If certain circumstances are fulfilled, conditionals run specific statements; loops execute some
statements while certain conditions are met. While, do-while, and for loops are the three types of
loops available in C++.

while and do-while

The while loop follows the same format as the if conditional: in the meantime (condition)

.{

statement1

statement2

The block of statements will be run repeatedly as long as the condition holds. The curly braces
can be eliminated if there is only one statement. Here's an illustration:

#include <iostream>

using namespace std;

int main() {

int x = 0;

while(x < 10)

x = x + 1;

9 10 11

cout << “x is “ << x << “\n”;

12 13 }

return 0;

x is 10 will be printed by this application. The do-while loop is a version that ensures that the
block of statements is run at least once: do

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
15

statement1

statement2

while(condition);

The program executes the block of statements and then returns to the top of the block if the
condition holds. Curly braces are essential at all times. The semicolon after the while condition is
also worth noting. The for loop is similar to the while loop, however it has a different syntax: for
(initialization; condition; incrimination)

statement1

statement2

Curly braces may be omitted if there is only one statement for loop is designed to allow a counter
variable that is initialized at the beginning of the loop and incremented (or decremented) on each
iteration of the loop. Here is an example:

#include <iostream>

using namespace std;

int main() {

for(int x = 0; x < 10; x = x + 1)

cout << x << “\n”;

return 0;

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
16

This program will print the numbers 0 through 9 on separate lines. There's no need to define a
new counter variable in the for loop's initialization section if one already exists. As a result, the
following is acceptable:

1 2 3 4 5 6 7 8 9 10 11 12

#include <iostream>

using namespace std;

int main() {

int x = 0;

for(; x < 10; x = x + 1)

cout << x << “\n”;

return 0;

Note: The initial semicolon inside the parentheses of the for loop is still required.

A while loop can be written as a for loop, and vice versa. It's worth remembering that a for loop
has the form for (initialization; condition; incrementation)

statement1

statement2

As initialization, we may create a similar while loop.

while(condition)

statement1

statement2

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
17

incrementation

Using our example above,

#include <iostream>

using namespace std;

int main() {

for(int x = 0; x < 10; x = x + 1)

cout << x << “\n”;

return 0;

is converted to

#include <iostream>

using namespace std;

int main() {

int x = 0;

while(x < 10) {

cout << x << “\n”;

x = x + 1;

return 0;

Although the incrementation step can potentially be placed anywhere within the statement block,
it is best practice to put it towards the end, especially if the previous statements use the counter
variable's current value.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
18

Nested Control Structures By simply placing these structures inside the statement blocks, you
can put ifs inside of ifs and loops inside of loops. This makes it possible for the software to
behave in more complex ways.

Here's an example of how to use nested if conditionals:

#include <iostream>

using namespace std;

int main() {

int x = 6;

int y = 0;

if(x > y) {

cout << “x is greater than y\n”;

if(x == 6)

cout << “x is equal to 6\n”;

else

cout << “x is not equalt to 6\n”;

} else

cout << “x is not greater than y\n”;

return 0;

This program will print x is greater than y on one line and then x is equal to 6 on the next line.

Here is an example using nested loops:

#include <iostream>

using namespace std;

int main() {

for(int x = 0; x < 4; x = x + 1) {

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
19

for(int y = 0; y < 4; y = y + 1)

cout << y;

cout << “\n”;

return 0;

This program will print four lines of 0123.

LESSON 3: FUNCTIONS

 A function is a code block that only executes when it is invoked.


 Parameters are data that can be passed into a function.
 Functions are used to accomplish certain tasks and are essential for code reuse: Once the
code is defined, it can be reused numerous times.
Create a Function
Some pre-defined functions in C++, such as main(), are used to execute code. You can, however,
design your own functions to accomplish specific tasks.
To create (also known as declare) a function, type the function's name followed by parenthesis ():

Syntax
void myFunction() {
// code to be executed
}

Example Explained
 The name of the function is myFunction().
 The absence of a return value indicates that the function is void. In the next chapter, you'll learn
more about return values.
 Add code to the body of the function that defines what the function should accomplish.

Call a Function

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
20

Declared functions are not immediately performed. They've been "preserved for later use," and
will be executed when they're needed.

Write the function's name followed by two parentheses () and a semicolon to call it;

When myFunction() is called, it prints a text (the action) in the following example:

Example

Inside main, call myFunction():

// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


Function Declaration and Definition
There are two parts to a C++ function:
Declaration: The name, return type, and parameters of the function are declared (if any)
Definition: the function's main body (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}
Note: An error will occur if a user-defined function, such as myFunction(), is declared after the
main() function:

Example
int main() {
myFunction();
return 0;
}

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
21

void myFunction() {
cout << "I just got executed!";
}

// Error

However, for code optimization, the declaration and definition of the function might be
separated.

C++ applications frequently feature function declarations above main() and function definitions
below main(). This will help structure the code and make it easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}

LECTURE 4: ARRAYS AND STRINGS

CONCEPT NOTE

Arrays So far, variables have been utilized to store values in memory for subsequent use. We'll
now look at an array, which is a way of storing several values as a single unit. A set number of
elements of the same kind are kept sequentially in memory as an array. As a result, an integer
array contains a certain number of integers, a character array contains a certain number of
characters, and so on. The dimension of the array refers to its size.

In C++, we write the following to declare an array:

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
22

type arrayName[dimension];

Another option is to initialize some or all of the values before declaring them: int arr[4] = { 6, 0,
9, 6 };

It's sometimes more convenient to leave out the array's size and let the compiler figure it out for
us based on how many elements we provide it: : int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 };

The compiler will build an 8dimensional integer array in this case.

The array can also be initialized with values that are unknown at the time of initialization:
arr[5];arr[i];arr[i+3];

#include <iostream>

using namespace std;

int main() {

int arr[4];

cout << “Please enter 4 integers:“ << endl;

for(int i = 0; i < 4; i++)

cin >> arr[i];

cout << “Values in array are now:“;

for(int i = 0; i < 4; i++) cout << “ “ << arr[i];

cout << endl;

return 0;

When accessing an array, keep in mind that the index must be a positive integer between 0 and
n-1, where n is the array's dimension. The index can be provided explicitly, obtained from a
variable, or calculated using an expression: arr[5];arr[i];arr[i+3];

Strings

Strings String literals like "Hello, world!" are really represented in memory by C++ as a
sequence of characters. To put it another way, a string is nothing more than a character array that
may be modified as such.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
23

Take the following program into consideration:

#include <iostream>

using namespace std;

int main() {

char helloworld[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ',

'w', 'o', 'r', 'l', 'd', '!', '\0' };

cout << helloworld << endl;

return 0;

This application generates printouts. Hello, world! It's worth noting that the helloworld character
array finishes with a special character known as the null character. This character is used to
signal that the string has come to an end. String literals can also be used to create character
arrays. In this scenario, there is no need for a null character because the compiler will insert one
for you: “Hello, world!”; char helloworld[] = “Hello, world!”

LESSON 5: POINTERS

In C++, a pointer is a variable that stores the location of another variable. They have the same
data types as variables, so an integer type pointer may store the address of an integer variable,
and a character type pointer can store the address of a char variable.

Syntax of pointer
data_type *pointer_name;
How to declare a pointer?

/* This pointer p can hold the address of an integer


* variable, here p is a pointer and var is just a
* simple integer variable
*/
int *p, var

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
24

Assignment

An integer type pointer can hold the location of another int variable, as I described earlier. We
have an integer variable var, and the address of var is held by pointer p. The ampersand symbol
is used to assign the address of a variable to a pointer (&).

/* This is how you assign the address of another variable


* to the pointer
*/
p = &var;

How to use it?

// This will print the address of variable var


cout<<&var;

/* This will also print the address of variable


* var because the pointer p holds the address of var
*/
cout<<p;

/* This will print the value of var, This is


* important, this is how we access the value of
* variable through pointer
*/
cout<<*p;
Example of Pointer
Let's look at a simple example to help you understand what we talked about earlier.

#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;

//Assignment
p = &var;

cout<<"Address of var: "<<&var<<endl;


cout<<"Address of var: "<<p<<endl;

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
25

cout<<"Address of p: "<<&p<<endl;
cout<<"Value of var: "<<*p;
return 0;
}

Output:

Address of var: 0x7fff5dfffc0c


Address of var: 0x7fff5dfffc0c
Address of p: 0x7fff5dfffc10
Value of var: 101
Pointer and arrays
Arrays and pointers when working with arrays of pointers, there are a few things to keep in
mind. The first and most important thing to remember about arrays is that the array name alone
represents the array's base address, so when assigning the address of an array to a pointer, do not
use the ampersand sign (&). Do it this way: Correct: Because arr represents the array's address.
p = arr;
Incorrect:

p = &arr;

Example: Traversing the array using Pointers


#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p;
//Array declaration
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment
p = arr;
for(int i=0; i<6;i++){
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
}

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
26

Output:

1
2
3
4
5
6
// Pointer moves to the next int position (as if it was an array)
p++;
// Pointer moves to the next int position (as if it was an array)
++p;

/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);

How do I increase the address and value of a pointer?

When we access the value of a variable using a pointer, we may only need to increment or
decrement the value of the variable, or we may need to move the pointer to the next int position
(just like we did above while working with arrays). This is accomplished through the use of the
++ operator. One of the examples of the ++ operator we saw above was when we traversed an
array with a pointer by incrementing the pointer value with the ++ operator\.

LESSON 6: CLASSES/OBJECTS

CONCEPT NOTE

In C++, everything is linked to classes and objects, as well as their characteristics and methods.
A automobile, for example, is an object in real life. The car has characteristics like weight and
color, as well as procedures like drive and brake.

Attributes and methods are essentially the class's variables and functions. "Class members" is a
term used to describe these people.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
27

A class is a user-defined data type that may be used in our program as an object constructor or
"blueprint" for constructing objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

 A class named is created using the class keyword.


 The Public keyword is an access specifier that indicates whether or not the class's
members (attributes and methods) are accessible from outside the class.
 There is an integer variable myNum and a string variable myString in the class. Variables
specified within a class are referred to as attributes.
 Finally, add a semicolon; to the end of the class definition.

Create an Object

Create an object A class is used to make an object in C++. Because we've already constructed the
MyClass class, we can now use it to generate objects.

To make a MyClass object, start with the class name and then the object name.

Use the dot syntax (.) on the object to access the class properties (myNumber and myString):

Example

Create an object called "myObj" and access the attributes:

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
28

string myString; // Attribute (string variable)


};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

LESSON 7: MEMORY MANAGEMENT

CONCEPT NOTE
Memory management is the process of allocating memory to programs in order to optimize
overall system performance.
What is the purpose of memory management?
Because arrays store homogeneous data, most of the time, memory is allocated to the array when
it is declared. When the precise memory is not determined until runtime, a problem can develop.
We declare an array with a maximum size to avoid this scenario, but some memory will be left
unused. To reduce memory waste, we use the new operator to dynamically allocate memory
during runtime.
Memory Management OperatorsThe malloc() or calloc() functions in C are used to
dynamically allocate memory at runtime, and the free() function is used to deallocate the
dynamically created memory. These functions are likewise supported in C++, however unary
operators such as new and delete are defined to perform the same duties, namely allocating and
freeing memory.

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
29

New operator

The object is created using the new operator, and it is deleted with the delete operator. When we
use the new operator to create an object, the object will exist until we expressly delete it with the
delete operator. As a result, we can conclude that the object's lifetime is unrelated to the
program's block structure.

REFERENCES

Websites

https://en.wikipedia.org/wiki/C%2B%2B

https://www.codecademy.com/catalog/language/c-plus-
plus?g_network=g&g_device=c&g_adid=518718870684&g_keyword=c%2B%2B%20program
ming&g_acctid=243-039-
7011&g_adtype=search&g_adgroupid=102650142713&g_keywordid=kwd-
12432420&g_campaign=ROW+Language%3A+Basic+-
+Exact&g_campaignid=10074200771&utm_id=t_kwd-
12432420:ag_102650142713:cp_10074200771:n_g:d_c&utm_term=c%2B%2B%20programmin
g&utm_campaign=ROW%20Language%3A%20Basic%20-
%20Exact&utm_source=google&utm_medium=paid-
search&utm_content=518718870684&hsa_acc=2430397011&hsa_cam=10074200771&hsa_grp
=102650142713&hsa_ad=518718870684&hsa_src=g&hsa_tgt=kwd-
12432420&hsa_kw=c%2B%2B%20programming&hsa_mt=e&hsa_net=adwords&hsa_ver=3&g
clid=CjwKCAjwqeWKBhBFEiwABo_XBnhqfganM-
etQQPXC5zAE0WXCK0GVYk2IA7FsFwFLZQiqoYGCMFL6xoC-KYQAvD_BwE

https://beginnersbook.com/2017/08/cpp-pointers/

http://ocw.mit.edu/terms

https://www.w3schools.com/

Approved by: Noted by:

Prof. Shernahar K. Tahil, MPA Prof. Nureeza J. Latorre, Ph.D (CAR)


CS Department Chairperson CSS Dean

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
30

Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies

You might also like