0% found this document useful (0 votes)
30 views36 pages

Prog I Chapter III Basic Concepts Student Manual

This document provides an introduction to C++ programming, covering basic concepts such as variables, data types, and arithmetic operations. It explains how to write and execute a simple C++ program, including the use of input/output streams and comments. The document also includes evaluations to test understanding of the material presented in each lesson.

Uploaded by

Japeth Matta
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)
30 views36 pages

Prog I Chapter III Basic Concepts Student Manual

This document provides an introduction to C++ programming, covering basic concepts such as variables, data types, and arithmetic operations. It explains how to write and execute a simple C++ program, including the use of input/output streams and comments. The document also includes evaluations to test understanding of the material presented in each lesson.

Uploaded by

Japeth Matta
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/ 36

Computer Programming in c++

(IT 112/CpE 112)

Chapter III: basic concepts

Minerva M. Fiesta

2020
Basic Concepts

I. What is C++
II. Hello World
III. Getting the Tools
IV. Printing Text
V. Comments
VI. Variables
VII. Working with Variables
VIII. Basic Arithmetic
IX. Assignment & Increment Operators
X. Chapter Evaluation (Worded problems)
Lesson 1: What is C++

Welcome to C++
C++ is a general-purpose programming language.
C++ is a cross-platformed language that can be used to create sophisticated
high-performance applications.
C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to
the C language.
C++ gives programmers a high level of control over system resources and
memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11,
C++14, and C++17.

C++isC++
used to derived
was create computer
from C, andprograms.
is largely based on it.

C++ Quickstart

Let's create our first C++ file.


Open Codeblocks and go to File > New > Empty File.
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save
File as):
Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code.
In Codeblocks, it should look like this:

Then, go to Build > Build and Run to run (execute) the program. The result
will look something to this:
Your First C++ Program

A C++ program is a group of commands or statements.


The example below is a code that has “I Love IFSU!” as its output.

Here is the break down of the code.

C++ offers several headers, each of which covers material needed for programs
to work correctly. This specific program calls for the header <iostream>. The
pound sign (#) at the beginning of a line aims the compiler’s pre-processor. In
this case, #include (used to include one source file into another) tells the pre-
processor to include the <iostream> header.

 The <iostream> header defines the standard stream objects that input and output data.

The C++ compiler ignores blank lines.


In general, blank lines serve to improve the code’s readability and structure.

 Whitespace, such as spaces, tabs, and newlines, is also ignored, although it is used to
enhance the programs visual appeal.
In our code, the line using namespace std; tells the compiler to use the std
(standard) namespace.

 The std namespace includes features of the C++ standard Library.

Main
Program execution begins with the main function, int main()

Curly brackets { } indicate the beginning and end of a function, which can also
be called the function’s body. The information inside the brackets indicates what
the function does when executed.

 The entry point of every C++ program is main(), irrespective of what the program does.
The next line, cout<<”Hello world!”; results in the display of “Hello world!” to the screen.

In C++, streams are used to perform input and output operations.


In most program environments, the standard default output destination is the
screen. In C++, cout is the stream object used to access it.
cout is used in combination with the insertion (<<)operator. Write the insertion
operator as << to insert the data that comes after it into the stream that comes
before.

 In C++, the semicolon is used to terminate a statement. Each statement must end with a
semicolon. It indicates the end of one logical expression.

Statements
A block is a set of logically connected statements, surrounded by opening and
closing curly braces.

 You can have multiple statements on a single line, as long as you remember to end each
statement with a semicolon. Failing to do so will result in an error.

Return
The last instruction in the program is the return statement. The line return 0;
terminates the main() function and causes it to return the value 0 to the calling
process. A non-zero value (usually of 1) signals abnormal termination.
 If the return statement is left off, the C++ compiler implicitly inserts “return 0; “ to the end of
the main() function.
Chapter III Lesson 1 Evaluation
1. C++ is a:
a. Movie making program.
b. Client-side scripting language
c. General purpose programming language.
2. Write the correct syntax to include the <iostream> header.
3. Write the correct syntax to use names from the std namespace
4. What is the starting point of a computer program?
a. From <iostream>
b. Main function
c. First line
5. Each instruction must end with a:
a. Dot (.)
b. Semicolon (;)
c. Comma (,)
d. Colon (:)
6. Write a program code that outputs “Welcome to IFSU” on the screen.
7. Rearrange the codeblocks to form a valid C++ program:
a. cout<<”Awesome!; return 0;
b. int main() {
c. }
Lesson 2: Printing Text

Your First C++ Program


several insertion operations after cout can be added.
The cout object, together with the << operator, is used to output values/print
text:

Result:

You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:

New Line
The cout operator does not insert a line break at the end of the output.
One way to print two lines is to use the endl manipulator; which will put in a
line break.
The endl manipulator moves down to the new line to print the second text.

New Lines
The new line character \n can be used as an alternative to endl.
The backslash ( \ ) is called an escape character. And indicates a “special”
character.
Example:
Result:

Two new line characters placed together result in a blank line

Result:

 Both \n and endl are used to break lines. However, \n is used more often and is the preferred
way.
Multiple New Lines
Using a single cout statement with as many instances of \n as your program
requires will print out multiple line text.

Result:

Comments
Comments are explanatory statements that can be included in the C++ code to
explain what the code is doing.
The compiler ignores everything that appears in the comment, so none of the
information shows in the result.
A comment beginning with two slashes (//) called a single-line comment. The
slashes tell the compiler to ignore everything that follows, until the end of the
line.
For example:

When the above code is compiled, it will ignore the //, prints “Hello world”
statement and will produce the following result:

 Comments make your code more readable for others

Multi-Line Comments
Comments that require multiple lines begin with /* and end with */.
You can place them on the same line or insert one or more lines between them.

 If you write a wrong code segment, don’t delete it immediately. Put it into a multi-line comment,
and then delete it when you find the right solution.
Using Comments
Comments can be written anywhere, and can be repeated any number of times
throughout the code.
Within a comment marked /* and */, // characters have no special meaning,
and vice versa. This allows you to “nest” one comment type within another.

 Adding comments to your code is good practice. It simplifies a clear understanding of the code
for you and for others who read it.

 Single or multi-line comments?


 It is up to you which you want to use. Normally, we use // for short comments, and /* */ for
longer.
Chapter III Lesson 2 Evaluation

1. Write a code that prints “I love C++” on the screen


2. What should be used to move to a new line?
a. endl
b. return
c. #include
d. Startl
3. What is the symbol for moving to a new line?
a. \b
b. \n
c. \a
4. Write the correct program code to print “hello” and “world” separated by a
blank line.
5. Create a program that prints “I love Ifugao State University!” with each
word in a new line.
6. Which of the following is true?
a. Single line comment starts with an asterisk ( * ).
b. Comments are used to confuse programmers.
c. Comments are ignored by the compiler.
7. Which choice indicates a single line comment?
a. # #single line comment
b. * *single line comment
c. / / single line comment
8. Create a block comment (multiple comment) in C++ using the statement
bellow
a. This is a block/multiple comment in C++
Chapter III Lesson 3
Variables
Creating variables reserves a memory location, or a space in memory for storing
values. The compiler requires that you provide a data type for each variable you
declare.
C++ offer a rich assortment of built-in as well as user define data types.
Integer, a built-in type, represents a whole number value.
Define integer using the keyword int.
C++ requires that you specify the type and the identifier for each variable.
An identifier is a name for a variable, function, class, module, or any other user
defined item. An identifier starts with a letter (A-Z or a-z) or an underscores and
digits (0-9).
For example, define a variable called myVariable that can hold integer values as
follows:

 Different operating systems can reserve different sizes of memory for the same data type.

Now, let us assign a value to the variable and print it.


Output:

You can also declare a variable without assigning the value, and assign the value
later:

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous
value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

However, you can add the const keyword if you don't want others (or yourself)
to override existing values (this will declare the variable as "constant", which
means unchangeable and read-only):
Other Types
A demonstration of other data types:

 The C++ programming language is case-sensitive, so myVariable and myvariable are two
different identifiers.

Define all variables with a name and a data type before using them in a
program. In cases in which you have multiple variables of the same type, it’s
possible to define them in one declaration, separating them with commas.

A variable can be assigned a value, and can be used to perform operations. For
example, we can create an additional variable called sum, and add two variables
together.

 Use the + operator to add two numbers or variables


Let’s create a program to calculate and print the sum of two integers

 Always keep in mind that all variables must be defined with a name and data type before they
can be used.

Declaring Variables

You have the option to assign a value to the variable at the time you declare the
variable or to declare it and assign a value later.
You can also change the value of a variable.

 You can assign a value to a variable only in a declared data type.


Display Variables

The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:

Add Variables Together


To add a variable to another variable, you can use the + operator:

Declare Many Variables


To declare more than one variable of the same type, you can use a comma-
separated list:
C++ Identifiers
All C++ variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code.
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits and underscores
• Names must begin with a letter or an underscore (_)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Names cannot contain whitespaces or special characters like !, #, %, etc.
• Reserved words (like C++ keywords, such as int) cannot be used as names.

User Input

You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.
To enable the user to input a value, use cin in combination with the extraction
operator ( >> ). The variable containing the extracted data follows the operator.
The following example shows how to accept user input and store it in the num
variable:
 As with cout, extractions on cin can be chained to request more than one input in a single
statement: cin>>a>>b;

Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator
(<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Accepting User Input


The following program prompt the user to input a number and stores it in the
variable a:
When the program runs, it displays the message “ Please enter a number: “ and
then waits for the user to enter a number and press the Enter key.
The entered number is stored in the variable a.

 The program will wait for as long as the user needs to type in a number.

You can accept user input multiple times trough out the program:

Let’s create a program that accepts the input of two numbers and print their
sum.
Specifying the data type is required just once, at the time when the variable is
declared.
After that, the variable maybe used without referring to the data type.

 Specifying the data type for a given variable more than once results in a syntax error.

A variable’s value may be changed as many times as necessary throughout the


program.
For example:
Chapter III Lesson 3 Evaluation

1. What is the data type name for integers?


a. Answer ____________________
2. Supposed you have variable named Var, type the correct code to print its
value.
a. Answer ____________________
3. Write a C++ code that declares variable sum equal to a + b.
a. Answer ____________________
4. Which two statements are true for variables in C++?
a. Variables must have a data type.
b. Variables do not have names.
c. Variables are pre-processor directives.
d. Variables must be declared before they are being used.
5. Write a C++ code that declares variable a of data type int and assign 7 as
its value.
a. Answer ____________________
6. What is the purpose of cin?
a. Take information (data) from the user.
b. Print variable value.
c. Includes a header file.
7. Type in the code that accepts a value to be entered for variable a.
a. Answer ____________________
8. Write a C++ code that declares variable var of type int, that accepts an
input number and store it in variable var.
a. Answer ____________________
9. Write the correct syntax of a C++ program that declares sum as a variable,
assign it the value 21 + 7 and print out its value.
a. Answer ____________________
10. How many times should a data type be mentioned for a variable?
a. Everywhere the variable is used.
b. When printing a variable value.
c. When entering variable’s value using cin.
d. Only once: when declaring the variable.
11. Type in a code to declare variable b and assign a’s value to b, and
then print sum of a and b on the screen.
a. Answer ____________________
Chapter III Lesson IV: Basic Arithmetic

Arithmetic Operators
C++ supports these arithmetic operators.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value from another x/y

% Modulus Returns the division remainder x%y

The addition operator adds its operands together.

 You can use multiple arithmetic operators in one line

Subtraction

The subtraction operator subtracts one operand from the other.


Multiplication

The multiplication operator multiplies its operands

Division

The division operator divides the first operand by the second. Any remainder is
dropped in order to return an integer value.
Example:

If one or both of the operands are floating point values, the division operator
performs floating division.

 Dividing by 0 will crash your program.

Modulus

The modulus operator (%) is informally known as remainder operator because


it returns the remainder after an integer division.
For example:
Operator Precedence

The operator precedence determines the grouping of terms in an expression,


which affects how an expression is evaluated. Certain operators take higher
precedence over others; for example, the multiplication operator has higher
precedence over the addition operator.
For example:

The program above evaluates 2*2 first, and then adds the result to 5.
As in mathematics, using parenthesis alters operator precedence.

Operator Precedence

Parenthesis force the operations to have higher precedence. If there are


parenthetical expressions nested within one another, the expression within the
innermost parentheses is evaluated first.

 If none of the expression are in parentheses, multiplicative (multiplication, division, modulus)


operators will be evaluated before additive (addition, subtraction 0 operators.
Chapter III Lesson 4 Evaluation

1. Type in a code to declare a variable x, assign to it the values 4 + 6, and


print it to the screen
a. Answer:________________________
2. Write a C++ code that declares y equals x minus 12 and print the result
on the screen. Let x = 24.
a. Answer:________________________
3. Which symbol is used to multiply variables in C++?
a. %
b. *
c. X
d. +
4. Type in a code that will declare variable x with an assigned value of 81
and divide it by 3.
a. Answer:________________________
5. Which operator is used to determine the remainder?
a. +
b. %
c. /
d. *
6. Fill in the missing mathematical symbols to have x’s value equals 14.
int x = ____ 4 + 3 ____ * 2;
cout<< x ;
a. Answer:________________________
7. Which two statements are correct for arithmetic operations?
a. Multiplication is done before addition.
b. Parentheses first, then multiplication and division.
c. Addition is done before multiplication.
d. Subtraction is done first.
Chapter III Lesson V: Assignment & Increment Operators

Assignment Operators
The simple Assignment operator (=) assign the right side to the left side.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

C++ provides shorthand operators that have the capability of performing an


operation and assignment at the same time.
The addition assignment operator (+=) adds a value to a variable:
For Example:

 Assignment operator (=) assigns the right side to the left side

The same shorthand syntax applies to the multiplication, division, and modulus
operators.
Other list of all assignment operators:

Operator Example Same As

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

C++ Comparison Operators


Comparison operators are used to compare two values.
Tip: The return value is either true (1) or false (0). You will learn more about
them and how to use them in a later chapter.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

C++ Logical Operators


Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are x < 5 && x <
true 10
|| Logical or Returns true if one of the x < 5 || x <
statements is true 4

! Logical not Reverse the result, returns false if !(x < 5 && x
the result is true < 10)

Increment Operators
The increment operator is used to increase the integer’s value by one, and is
a commonly used C++ operator.

For example:

// outputs 12

The increment operator has two forms, prefix and postfix.

Prefix increments the value, and then proceeds with the expression.
Postfix evaluates the expression and then performs the incrementing.
Prefix example:

Postfix example:

 The prefix example increments the value of x, and then assigns it to y.


 The postfix example assigns the value of x to y and then increments it.

Decrement Operators
The decrement operator (--) works in much the same way as the increment
operator, but instead of increasing the value, it decreases it by one.

 The decrement operator (--) works in much the same way as the increment operator
Chapter I Lesson 5 Evaluation
1. What is the alternative for x = x+10?
a. x = y+10;
b. x+=10;
c. x-=9;
2. Write the correct code in C++ that divides x by 5 using the shorthand
operator for division.
a. Answer: ___________________
3. x++ has the same meaning as?
a. x = x + 1;
b. x = x – 4;
c. x /= 17;
4. Create a program that declares x as the variable and increment its value
using the ++ operator and print its value on the screen. Let x=20.
a. Answer: ___________________
5. What is the difference between ++x and x++? Select all that applies.
a. ++x uses x’s value before incrementing it.
b. x++ uses x’s value then increments it.
c. x++ increment’s x’s value before using it.
d. ++x increments x’s value before using it.
6. Create a program that declares x as the variable and decrement its value
using the ++ operator and print its value on the screen. Let x=20.
7. In every C++ program:
a. There should be a function named main.
b. Variable names should be either x or y.
c. There must be at least two declared variables.
d. Each variable must have its data type.
Chapter I: Basic Concepts Worded Problems:

Evaluate the given simple worded problems and write the complete and correct
syntax using C++.
1. Create a program in C++ that will print “Welcome to IFSU!” in one line.
Using the escape sequence new line, Display “I Love C++” in three
different lines.
2. Create a program in C++ that declares two variables of type int and print
their sum on the screen. Let variable 1 be x and variable 2 be y. Assign
any numerical value for x and y.
3. Design a program in C++ that accepts two input numbers from the user
using variables a and b. Divide the value of the first variable by the
second variable and display the quotient on the screen.
4. What is the output of the given program?

5. Create a program that gives the user to display the sum of the first and
the second input numbers, difference of the sum and the third input
number, product of the difference and the fourth input number, and
the quotient of the product and the fifth input number. Display the
output of each arithmetic operation.

You might also like