Sir JM - Computer Programming 1
Sir JM - Computer Programming 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 3: FUNCTIONS 19
CONCEPT NOTE 19-21
LESSON 5: POINTERS 23
CONCEPT NOTE 23-26
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.
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
int main() {
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.
Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
5
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.
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.
• 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
Operator types:
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:
int main () {
int x;
x = 4 + 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:
int main () {
int x;
cin >> x;
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.
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
Operator Meaning
&& and
|| or
! Not
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
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!
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)
#include <iostream>
int main() {
int x = 6;
int y = 2;
if(x > y)
else
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;
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++.
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>
int main() {
int x = 0;
x = x + 1;
9 10 11
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>
int main() {
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>
int main() {
int x = 0;
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
while(condition)
statement1
statement2
Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
17
incrementation
#include <iostream>
int main() {
return 0;
is converted to
#include <iostream>
int main() {
int x = 0;
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.
#include <iostream>
int main() {
int x = 6;
int y = 0;
if(x > y) {
if(x == 6)
else
} else
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.
#include <iostream>
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;
return 0;
LESSON 3: FUNCTIONS
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
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
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();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
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.
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 array can also be initialized with values that are unknown at the time of initialization:
arr[5];arr[i];arr[i+3];
#include <iostream>
int main() {
int arr[4];
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
#include <iostream>
int main() {
char helloworld[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ',
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?
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 (&).
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;
//Assignment
p = &var;
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:
p = &arr;
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);
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
Example
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
Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
28
int main() {
MyClass myObj; // Create an object of MyClass
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/
Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies
30
Computer Programming 1
Mindanao State University – Sulu | College of Computer Studies