Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

UNIT 2: C++ Basics

UNIT

2 C++
BASICS

This lesson covers an overview of C++ as a


programming language and the steps required to
process a program written in C++. CodeBlocks
will be introduced as an integrated development
environment that provides comprehensive
facilities to computer programmers for software
development.
This lesson discusses the basic elements of C++,
which are symbols, identifiers, reserved words,
data types, operators, and expressions. The
students will become familiar with the basic
structure of a C++ program and input/output
fundamentals which will enable them to begin
writing a simple program.

IT 103: COMPUTER PROGRAMMING 1 58


UNIT 2: C++ Basics

1. C++ fully supports object-oriented programming, including the four pillars of object-oriented
development.

LESSON 1:
An Overview of C++

OBJECTIVES:
At the end of the lesson, students will be able to:

▪ Identify the basic characteristics of C++.

▪ Enumerate the four pillars in object-oriented programming

▪ Explore how a C++ program is processed

DURATION: 2 hours

IT 103: COMPUTER PROGRAMMING 1 59


UNIT 2: C++ Basics

The C++ Language

C++ is a statically input, compiled, general-purpose, case-sensitive, free-form


computer programming language that carries object-oriented, procedural, and generic
programming.

C++ is observed as a middle-level language, as it covers a combination of both low-


level and high-level language features.

C++ was created by Bjarne Stroustrup early in1979


at Bell Labs in Murray Hill, New Jersey, as a
development to the C language and originally named
as C with Classes, but far along, and was renamed
C++ in the year 1983.

This C++ is a superset of C, and that virtually any


legal C program is a standard C++ program.
These six frames (from the left) series of images
www.studysection.com
show that a bouncing ball animation can be viewed
when displayed in a rapid sequence.

C++ fully supports object-oriented programming, which includes the four pillars of
object-oriented development: encapsulation, abstraction/data hiding, inheritance, and
polymorphism.

▪ Encapsulation is a procedure of combining data members and functions in a


single unit called class. This is to prevent access to the data directly; the access
to them is provided through the class functions. It is the popular features of
Object-Oriented Programming(OOPs) that helps in data hiding.

How Encapsulation is achieved in a class


To do this:
1) Make all the data members private.
2) Create a public setter and getter functions for each data member in
such a way that the set function sets the value of the data member, and
the get function gets the value of the data member.

▪ Abstraction is a unique feature of Object-Oriented Programming, where you


show only relevant details to the user and hide irrelevant information.

For example, once you send an email to someone, you click send, and you get
the success message. What happens when you click send, how data is
transmitted over the network to the recipient is hidden from you (because it is
irrelevant to you).

▪ Inheritance is one of the features of Object Oriented Programming


System(OOPs). It allows the child class to acquire the properties (the data
members) and functionality (the member functions) of the parent class.
What is child class?
A class that inherits additional class is known as child class. It is also
known as a derived class or subclass.

IT 103: COMPUTER PROGRAMMING 1 60


UNIT 2: C++ Basics

What is the parent class?


The class inherited by other classes is known as a parent class,
superclass, or base class.

▪ Polymorphism is a feature of OOPs that permits the object to behave


differently in different conditions. In C++, we have two types of polymorphism:
1) Compile-time Polymorphism – This is also known as static (or early)
binding.
2) Runtime Polymorphism – This is also identified as dynamic (or late)
binding.1

Standard Libraries

Standard C++ consists of three important parts:

▪ The core language is giving all the building blocks, including variables, data
types, literals, etc.
▪ The C++ Standard Library is giving a rich set of functions operating files,
strings, etc.
▪ The Standard Template Library (STL) provides a rich set of methods for
operating data structures, etc.

The ANSI Standard

ANSI is the American member of ISO, the international standards organization. Since
1998, C++ has an international standard, a sort of a treaty between compiler vendors
from all around the world on what language features they all agree to implement. C++,
as defined by that standard, is known as ISO C++. The ANSI standard is an aim to
ensure that C++ is portable -- that code you write or compose for Microsoft compiler
will be compiled without errors, using a compiler on Mac, UNIX, Windows box, or an
Alpha.

Use of C++

▪ C++ is highly used to write device drivers and other software that rely on direct
manipulation of hardware under real-time constraints.

▪ C++ is computer programmers in virtually every application domain.

▪ C++ is broadly used for teaching and research because it is clean enough to
successfully teach basic concepts.

▪ A programmer who has used either an Apple Macintosh or a PC running


Windows has indirectly used C++ because the primary user interfaces are
written in C++.

IT 103: COMPUTER PROGRAMMING 1 61


UNIT 2: C++ Basics

Processing a C++ Program

In the previous lessons, we discussed machine language and high-level languages. A


computer can only understand machine language. There are steps required to process
a program written in C++, as discussed in the subsequent section.
1. A text editor is used in creating a C++ program using the rules or syntax of the
programming language. The written program is called the source code, or
source program and must be saved in a text file format that has the extension
.cpp.

The source program is a program written in a high-level language.


2. C++ statements are processed by a program called preprocessor. After
processing preprocessor directives, the next phase is to verify that the program
follows the programming language rule - that is, the program is syntactically
correct - and translate the program into the corresponding machine language.
The compiler checks the source program for syntax errors and then
translates into the comparable machine program if there are no errors. The
corresponding machine language program is called an object program.
Preprocessor directives are program lines included in the code of
programs preceded by a hash sign (#). These lines are not program
statements but commands for the preprocessor. 2
The preprocessor observes the code before the actual compilation of
code begins and resolves all these directives before regular statements
generate any code.
The preprocessor provides the ability to include header
files, macro expansions, conditional compilation, and line control.
Object program is known as the machine language version of the high-
level language program.
3. The programs that you write/compose in a high-level language are developed
using an integrated development environment (IDE). The IDE provides
programs that are useful in developing your program. Once the program is
designed and successfully compiled, you must still bring the code for the
resources used from IDE into your program to produce a final program that the
computer can execute. This prewritten code(program) exists in a place called
the library. A program known as linker combines the object program with the
programs from libraries.
The linker is a program that gathers the object program with other
programs in the library, and it is used in the computer program to create
the executable code.
4. The executable program must be loaded into the main memory for execution.
A program called a loader accomplishes this task.
The loader is a program that loads an executable program into the main
memory.
5. The final step is to execute the program.

IT 103: COMPUTER PROGRAMMING 1 62


UNIT 2: C++ Basics

Processing a C++ Program Flowchart

IT 103: COMPUTER PROGRAMMING 1 63


UNIT 2: C++ Basics

LESSON 2:
Basic Elements of a Program

OBJECTIVES:
At the end of the lesson, students will be able to:

▪ Recognize the basic elements of a C++ program


▪ Understand the different symbols in a C++ program
▪ Familiarize in different data types and reserved words in
constructing a C++ program

DURATION: 3 hours

IT 103: COMPUTER PROGRAMMING 1 64


UNIT 2: C++ Basics

Symbols

The smallest individual unit of a program in any programming language is called a


“token”. C++ tokens are divided into special symbols, word symbols, and identifiers.

Following are some of the special symbols:

, Commas are used to dispersed items in a list.


; Semicolons are used to end statement
+ - * / Mathematical symbols
<= != == >= Relational operators

Comment symbol

The program that you write should be direct not only to you but also to the reader itself.
Part of good programming is the including of comments in the program. Generally,
comments can be used to explain the program’s purpose or explain the meaning of
key statements in the program. The compiler ignores these comments when it
translates the program into executable code.

Two types of comments symbols

1.) // single-line comment symbol


It can be put anywhere in the line. Everything runs into in that line after
// is ignored by the compiler.

For example:

// This is my first program


// C++ Language

2.) /* */ multiple-line comment symbol


The compiler ignores anything that appears between these two symbols.

For example:

/* This is my first program


C++ Language */

IT 103: COMPUTER PROGRAMMING 1 65


UNIT 2: C++ Basics

Reserved Word

The second category of tokens is a reserved word. Reserved words are also called
keywords that cannot be redefined within any program; that is, they cannot be applied
for anything other than their expected use. Some of the essential reserved words are
given below:

C++ Reserved Words

The reserved words of C++ may be strategically located in some groups. In the first
group, were also present in the C programming language and have been continued
over into C++. There are 32 such reserved words:

auto const double float int short struct unsigned


break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

There are other 30 reserved words that were not in C, are therefore new to C++:

asm dynamic_cast namespace reinterpret_cast try


bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t

The following 11 C++ reserved words are not vital when the standard ASCII character
set is being used. Still, they have been added to give more readable alternatives for
some of the C++ operators, and also to encourage programming with character sets
that lack characters needed by C++.

xor_eq bitand compl not_eq or_eq and


and_eq bitor not or xor

A specific compiler may not be completely modern, which implies that some (and possibly many) of the
reserved words in the lead up to two groups may not yet be actualized.

Reserved words, "keywords," and predefined identifiers...

There is a differentiation between reserved words and predefined identifiers, which are once in a while
collectively referred to as keywords. Nonetheless, be aware that the terminology is nonstandard. As an
illustration, some authors use keywords in the same sense that others use the reserved word.

IT 103: COMPUTER PROGRAMMING 1 66


UNIT 2: C++ Basics

Identifier

The third category of tokens is the identifier. Identifier refers to the names of variables,
constants, functions, and other objects defined in a C++ program. It allows us to name
data and other objects in the program. Each identified object in the computer is stored
at a unique address. If we did not have identifiers that we could use to represent data
locations symbolically, we would have to know and use the object's addresses.
Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located. Different programming languages use different syntactical rules
to form identifiers.

In C++, the rules for identifiers are very simple.

▪ The only valid name symbols are the capital letters A through Z, the lowercase
letters a through z ,digits 0 – 9, and underscore.
▪ The first character cannot be a digit or an underscore.
▪ An identifier cannot contain punctuation marks, math symbols, or other special
symbols.
▪ ANSI guarantees only the first 32 characters to be significant.
▪ C++ identifier is case-sensitive,
▪ The last rule is that the name we create cannot be keywords. Keywords are
also known as reserved words.

Examples of Valid and invalid identifiers

 Valid Identifiers  Invalid Identifiers


grade grade+3
area1 1area
area_of_triangle area of triangle

Example:

Identify if each identifier is valid or invalid.

Identifiers Valid or Invalid


abd
123score
rate+1
salary
item_2

IT 103: COMPUTER PROGRAMMING 1 67


UNIT 2: C++ Basics

Data Types

A data type of a variable in the operating system assigns memory and decides what
can be stored in the reserved memory.

Primitive Built-in Data Types


C++ offers both built-in and user-defined data types. The following table lists seven
basic C++ data types:

Data Type Keyword


Boolean bool
Character char
Integer int
Floating Point float
Double Floating Point double
Valueless value
Wide Character wchar_t

Some of the basic types can be modified using one or more of these type modifiers:
▪ signed
▪ unsigned
▪ short
▪ long

The following table shows the type of variable, how much memory it takes to store
the value in memory, and the maximum and minimum value stored in such variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,647 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

IT 103: COMPUTER PROGRAMMING 1 68


UNIT 2: C++ Basics

▪ Each data type associated with a different set of values


▪ The siSize of the number represented determines the data type
▪ Data type limits the amount of memory used
▪ Other compilers may have a diverse range of values for each data type.

The String Type

The data type string is a computer programmer-defined type of data. Unlike primitive
data type, a string cannot be directly available for use in a program. To use this type,
you need to access program components from the C++ library.

A string is an arrangement of zero or more characters. Strings in C++ are bounded in


double quotation marks. A string containing no characters is called an empty string or
null. The following are examples of strings:

“Hello” “Programming” “Mary”

Data Type Example


bool true, false
char ‘A’ , ‘a’ , ‘+’
int 10 , 250 , 1002
float / double 1.50 , 10.56 , 212.245
string “Hi” , “Hello” , “bye”

Variable

A variable is used to hold data. The data stored in a variable is called its value.

In programming languages, variables are implemented as memory locations.

▪ The compiler assigns a memory location to each variable name (identifier) in


the program.
▪ Each variable in a computer program must be declared.
▪ When you declare a variable, you are telling the compiler what kind of data you
will be storing in the variable.

How to declare a variable?

Variable Declaration. A syntax rule to declare a variable is:

datatype identifier;

For example, consider the following statements:

int x;
float rate;
char answer;
IT 103: COMPUTER PROGRAMMING 1 69
UNIT 2: C++ Basics

Note:

The sizes of variables might be different from those shown in the above table
depending on the compiler and the computer you are using.

Operators

An operator is used to perform specific arithmetic or logical manipulations. C++ is rich


in built-in operators and provides the following types of operators:

▪ Assignment Operator
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators

Assignment Operator

The assignment operator (=) is used in the assignment statement, which takes the
following form:

variable = expression;

To evaluate assignment statement, the expression on the right-hand side of the equal
sign is assessed first, and then the variable on the left-hand side is set to this value.

A variable needs to be initialized the first time a value is placed in the variable,

A C++ statement such as:

y = 5; means five will be stored in y.


x= y + 2; means add 2 to the value of y, and assign the new
value to the variable x. Hence, x will yield a value of
7.

Examples of Variable Initializations

int x =10;
double pi = 3.14;
char ans = ‘y’;

IT 103: COMPUTER PROGRAMMING 1 70


UNIT 2: C++ Basics

The following arithmetical operations supported by C++ are:

Arithmetic Operator
Symbol Name Example Definition
It is taking two or more numbers
and adding them together. The
+ Addition x+y
result of an addition is called
sum.
represents the operation of
removing objects from a
- Subtraction x–y
collection. The result of
subtraction is called a difference.
one of the four basic operations
of arithmetic gives the result of
* Multiplication x* y combining groups of equal sizes.
The result of a multiplication is
called a product.
It is a method of distributing a
/ Division x/y
group of things into equal parts.
It is placed between
two expressions that have the
= Equal x=y same value, or for which one
studies the conditions under
which they have the same value
Modulus or It is the remainder after dividing
% x%y
Modulo one number by another.
++ Increment x ++ or ++ x Increases the value of x by 1
-- Decrement y ++ or -- y Decreases the value of x by 1
+ (unary) Positive +x The value of x
- (unary Negative -x The arithmetic negation of x

Arithmetic operations such as addition, subtraction, multiplication, and division


correspond literally to their respective mathematical operators.

The modulo operator, represented by a percentage sign (%), gives the remainder of a
division process.

For example:
x = 10 % 3;

The resulting value of x is 1, since dividing 10 by 3 results in 3, with a remainder of 1.

IT 103: COMPUTER PROGRAMMING 1 71


UNIT 2: C++ Basics

Order of precedence

It is likely to build mathematical expressions with several operators. When more than
one arithmetic operator is used in an expression, C++ uses the operator precedence
rules to assess the expression. In line with the order of precedence rules for arithmetic
operators,

* , / ,% are at higher level of precedence than + , -

However, when operators have the same level, the operations are performed from
left to right.

Consider the following statement:


x = 12 + 6 / 3

What value will be stored in x? The answer is 14 because the order of operations
dictates that the division operator works before the addition operator does.

Expression Value
5 + 2 *4 13
10 / 2 – 3 2
8 + 12 * 2 – 4 28
6–3*2+7–1 6
(5 + 2) * 4 28
10 / (5 – 3) 5
8 + 12 * (6 – 2) 56
(6 – 3) * (2 + 7) / 3 9

Converting Algebraic Expression to Programming Expression

You probably remember from algebra class that the expression 2xy is understood to
mean 2 times x times y. in math, you do not always use an operator for multiplication.
Programming languages, however, require an operator for any mathematical
operation.

Programming
Algebraic Expression
Expression
6B 6*B
(3)(12) 3 * 12
4xy 4*x*y
𝑥
y = 32 y=x/2*3
z = 3bc + 4 z = 3 * b *c + 4
𝑥+2
a = 𝑎−1 a = (x + 2) / (a – 1)

IT 103: COMPUTER PROGRAMMING 1 72


UNIT 2: C++ Basics

Increment and Decrement Operators

Increment (++) and Decrement (--) operators are placed either in front or after the
operand. The statements

++x; or ++x;
- -y; or y- -;

This means x is incremented by 1, and y is decremented by 1, respectively.

When used in assignment statements, however, placing the operators after the
variable takes a different meaning.

Consider the following statements:


x =5;
y =x++;
z = y- -*2;

In the assignment statement for the variables y and z, the increment and decrement
operators are placed after the variable operands. As such, the operators are called
post-increment and post-decrement operators, respectively. This means that the
variable operands will be incremented/decremented after the expressions have been
thoroughly evaluated. In the statement

y=x++;

The value of the variable x is assigned first to the variable y before it is incremented.
Thus, after the statement is executed, x=6, and y=5. In the statement

z=y- -*2;

When the increment/decrement operator is placed ahead of the variable operand, it is


considered a pre-increment/pre-decrement operator, and the increment/decrement is
executed before anything else is done with the variable.

With three different ways of writing an increment/decrement operation, the concern


now would be which of the three methods is best. As a general rule, using the ++ / - -
operators would execute faster than the standard =/- and shorthand operators.

Example 1 Example 2
x=4;
y=++x; // x contains x=5;
5, y contains y=x++;// x contains
5 6, y contains 5

IT 103: COMPUTER PROGRAMMING 1 73


UNIT 2: C++ Basics

Compound Operators (Compound Assignments)

Corresponding to the five arithmetic operators *, /, %, +, and -, there is a shorthand


notation that combines the assignment operator (=) and an arithmetic operator so that
the given variable can have its value changed by adding, subtracting, multiplying by,
or dividing by a specified value.

Shorthand Notation Equivalent to:

x += 2; x = x + 2;
y - = 5; y = y - 5;
a /= 2; a = a / 2;
b * = c; b = b * c;
z %=10 z = z % 10;

Relational Operators

Two expressions can be collated using relational operators. For example, to know if
two values are equal or if one is less than the other.
The result of such an operation is either true or false (i.e., a Boolean Value)

The relational operators in C++ are:

Relational Operator
Symbol Name Example Definition
Compares if the value of the
< Less than x<y left operand is less than the
value of the right operand.
Compares if the value of the
left operand is greater than
> Greater than x>y
the value of the right
operand.
Compares if the value of the
left operand is less than or
<= Less than or equal to x <= y
equal to the value of the
right operand.
Compares if the value of the
Greater than or equal left operand is greater than
>= x>=y
to or equal to the value of the
right operand.
Compares if the values of
== Equal to x == y two operands are equal or
not.
Compares if the values of
!= Not Equal x != y two operands are equal or
not.

IT 103: COMPUTER PROGRAMMING 1 74


UNIT 2: C++ Basics

Boolean Expressions

A Boolean expression is an expression that is either true or false.

Here there are some examples:

(7 == 5) // false
(5 > 4) // true
(3 != 2) // true
(6 >= 6) // true
(5 < 5) // false

Of course, it is not only numeric constants that can be linked but only any value,
including variables.

Suppose that a=2, b=3 and c=6, then:

// false,
(a = = 4)
since a is not equal to 4
// true,
(a * b >= c)
since (2*3 >= 6) is true
// false,
( b+4 > a)
since (3+4 > 2*6) is false

Logical Operator
Symbol Name Example Definition
((a == 5) && (b> 6)) Logical AND operator. If
// evaluates to false both the operands are non-
&& And
zero, then the condition
( true && false )
becomes true.
((a == 5) || (c>8)) Logical OR Operator. If
any of the two operands is
|| Or // evaluates to true
( true || false ) non-zero, then condition
becomes true.
!(a == 5)
// evaluates to false Logical NOT Operator.
because the Use to reverses the logical
state of its operand. If a
! Not expression at its
condition is true, then
right (a == 5) is
Logical NOT operator will
true make false.

IT 103: COMPUTER PROGRAMMING 1 75


UNIT 2: C++ Basics

Suppose that a= 5; b=3 and c=6, then:

((a == 5) && (b> 6)) // evaluates to false


( true && false )

((a == 5) || (c>8)) // evaluates to true


( true || false )

!(a == 5) // evaluates to false because the


expression at its right (a == 5)
is true

IT 103: COMPUTER PROGRAMMING 1 76


UNIT 2: C++ Basics

LESSON 3:
Code Blocks Environment

OBJECTIVES:
At the end of the lesson, students will be able to:

▪ Explore Code Blocks Environment

▪ Enumerate the different parts of the Code Blocks Environment

▪ Identify the functions of Code Blocks Environment

DURATION: 2 hours

IT 103: COMPUTER PROGRAMMING 1 77


UNIT 2: C++ Basics

Code Blocks

▪ Code::Blocks (or C::B) is a cross-platform IDE that supports compiling and


running multiple programming languages. It is a free C, C++ and Fortran IDE
built to meet the most demanding needs of its users. It is created and developed
to be very extensible and fully configurable.

▪ Code::Blocks can be extended with plugins. Any functionality can be included


by installing / coding a plugin. For instance, compiling and debugging is already
provided by plugins.

An Integrated Development Environment (IDE) is a software application that


gives comprehensive facilities to a computer programmer for software
development. An IDE normally includes a source code editor, build automation
tools, and a debugger.

CodeBlocks Project Management


Management
This window suppress the interface 'Projects' which will, in the following text be
referred to as the project view. This view shows all the activities opened in
CodeBlocks at a specific time. The 'Symbols' tab of the Management window
shows symbols, variables, and so on.

Editor
In the above outline, a source named hello.c is opened with syntax highlighting
in the editor.

Open files list


shows a list of all files opened in the editor, in this example: hello.c.

CodeSnippets
can be displayed via the menu ’View’ →’CodeSnippets’ . Here you can
accomplish text modules, links to files, and links to URLs.

Logs and others


This window is used for outputting search results, log messages of a compiler
etc..

Toolbars
These messy strips, embellished with different command buttons, cling to the
top of the Code::Blocks window. There are eight toolbars, which you can
improve, show, or cover-up. Try not to play with them until you get settled with
the interface.

IT 103: COMPUTER PROGRAMMING 1 78


UNIT 2: C++ Basics

CodeSnippets

Management
Toolbars

Editor

Open files list

Logs and
Others

The status bar gives an overview of the following settings according to


document.help.CodeBlocks:

▪ Absolute path of an opened file in the editor.


▪ The editor uses the default character encoding of your host operating
system. This setting will be displayed with default.
▪ Row and column number of the current cursor position in the editor.
▪ The configured keyboard mode for inserting text (Insert or Overwrite).
▪ Current state of a file. A modified file will be marked with Modified
otherwise this entry is empty.
▪ The permission of a file. A file with read only settings will display Read
only in the status bar. In the window ‘Open files list’ these files will be
emphasized with a lock as icon overlay.

Note:

In the active editor, the user can select the context menu properties. In the appearing
dialog in the tab 'General' the option 'File is read-only' can be chosen. This alternative
will bring in a read-only access of the relating document within CodeBlocks, but the
original read and write characteristics of the file on the filesystem are not changed.

▪ If you start CodeBlocks with one of the command line options --


personality=<profile> then the status bar will show the presently used profile,
otherwise, the default will be indicated. The settings of CodeBlocks are stored
in the corresponding configuration file <personality>.conf.

CodeBlocks offers very flexible and comprehensive project management.

IT 103: COMPUTER PROGRAMMING 1 79


UNIT 2: C++ Basics

The View menu controls the visibility of every item displayed in the window.
Choose the proper command, such as Manager, from the View menu to show or hide
that item and Control toolbars by using the View→Toolbars submenu.

The most significant thing to recall about the Code::Blocks interface isn't to
let it overwhelm you. An IDE, for example, Code::Blocks can be exceptionally scary,
in any event, when you see yourself as experienced at programming. Try not to
stress: You'll before long feel right comfortable.

▪ Maximize the Code::Blocks program window so that it fills the screen. You
need all that real estate.

▪ Each of the various areas on the screen -- Management, Editor, Logs -- can
be resized: Position the mouse pointer between two areas. When the pointer
changes to a double-arrow thingy, you can drag the mouse to change an
area’s size.

▪ Each window displays multiple “sheets” of information. Switch between the


sheets by choosing a different tab. The Editor and Logs areas feature tabbed
interfaces.

Opening C::B
▪ The 1st time it is opened C::B will search for compilers it can use.
▪ A dialog box will open. Select GCC if there are multiple options. See
Figure 3.

Figure 3. Compiler auto-detection.


Source: http://www.bu.edu/tech/files/2017

IT 103: COMPUTER PROGRAMMING 1 80


UNIT 2: C++ Basics

Step 1. Create a project from the File menu or the Start Here tab.

Step 2: Choose the Console category and then the Console Application and
click Go.

IT 103: COMPUTER PROGRAMMING 1 81


UNIT 2: C++ Basics

Step 3: Click Next on the “Welcome to the new console application wizard!”
screen.

Step 4: Choose C++. Then click Next.

cccc

Step 5: Enter a project title. Let C::B fill in the other fields for you. If you like you
can change the default folder to hold the project. Click Next.

Step 6: Choose the compiler. Choose GNU GCC as the compiler. Click Next.

IT 103: COMPUTER PROGRAMMING 1 82


UNIT 2: C++ Basics

Step 7: Right click on your project name and choose Build options

▪ Check off the C++ 11 option. Click Release on the left and do the
same there as well.
▪ Do this anytime we create a project in C::B

Step 8: Your project is now created! Click on Sources in the left column, then
double-click main.cpp.

▪ Click the icon in the toolbar or press F9 to compile and run the
program.

IT 103: COMPUTER PROGRAMMING 1 83


UNIT 2: C++ Basics

Behind the scene: The Compilation Process

IT 103: COMPUTER PROGRAMMING 1 84


UNIT 2: C++ Basics

LESSON 4:
Basic Input and Output Statement

OBJECTIVES:
At the end of the lesson, students will be able to:

▪ Understand the structure of a C++ program


▪ Learn the syntax and semantics of the C++ programming
language
▪ Identify the Input and Output statements in C++ Program

DURATION: 3 hours

IT 103: COMPUTER PROGRAMMING 1 85


UNIT 2: C++ Basics

Structure of a C++ Program

The general form of a simple C++ program is shown below:

#include <preprocessor directive>

Program lines beginning with a hash sign (#) are directives read and interpreted by
what is known as the preprocessor.

These are the lines deciphered before the arrangement of the program itself starts.
For example, the directive #include <iostream>, instructs the preprocessor to include
a section of standard C++ code, known as header iostream, for standard input and
output operations, such as displaying the output of the program to the screen.

# include <iostream>

iostream is the name of the library that contains the definitions of the routines that
handle basic input/output operation.

int main()

The line int main() means that the main body of the program starts here. It is referred
to as the main() function.

The execution of all C++ programs starts with the main() function, regardless of where
the function is situated inside the code.

IT 103: COMPUTER PROGRAMMING 1 86


UNIT 2: C++ Basics

{}

The braces { and } mark the start/beginning and end/finish of the main body of the
program. Everything between the braces is the function body that defines what
happens when the main is called. All functions use braces to demonstrate the start
and end of their definitions.

The statements within the braces are the instructions that are followed by the
computer, often called executable statements. Program statements are executed in
the order that they appear within a function body.

return 0;

The next line returns 0; terminates main()function, and causes it to return the value 0
to the calling process.

using namespace std;

There are C++ codes where std::cout is being used instead of cout alone.

cout is part of the standard C++ library, and all elements in the standard C++ library
are declared within what is called a namespace: the namespace std. Accessing the
elements in the std namespace is by means of using declarations:

using namespace std;

This will allow all elements in the std namespace to be accessed without the std::
prefix).

Let us look at the two sample codes that would print the words Hello World.

Example 1

#include <iostream>
Sample Output
int main()
Hello World!
{
std::cout<<”Hello World”;

return 0;

IT 103: COMPUTER PROGRAMMING 1 87


UNIT 2: C++ Basics

Example 2

#include <iostream>
Sample Output
using namespace std;
Hello World!
int main()
{
cout<<”Hello World”;

return 0;
}

Basic Input and Output Statements

C++ uses a suitable abstraction called streams to complete input and output
operations. A stream is an entity where a computer program can either insert or extract
characters to/from. This is a source /destination of characters and that these
characters are provided/accepted sequentially (i.e., one after another).

I/O Library Header Files

Header File Function and Description


<iostream> This file defines the cin, cout, cerr, and clog objects,
which correspond to the standard input stream, the
standard output stream, the un-buffered standard error
stream and the buffered standard error stream,
respectively.
<iomanip> This file declares services useful for performing formatted
I/O with so-called parameterized stream manipulators, such
as setw and setprecision.
<fstream> This file declares services for user-controlled file
processing. We will discuss it in detail in File and Stream
related chapter.

IT 103: COMPUTER PROGRAMMING 1 88


UNIT 2: C++ Basics

The Standard Output Stream (cout)

The predefined object cout is an instance of stream class. The cout object is said to
be "connected to" the standard output device, which usually is the display screen. The
cout is used together with the stream insertion operator written as << (two less than
signs)

cout<< expression or manipulator;

This statement means that the expression is evaluated, its value is printed, and
manipulators are used to formatting the output. Examples of manipulators will be
discussed in the later section of this lesson.

Example 1
#include <iostream> Sample Output
using namespace std;
Hello World!
int main()
{
cout<<”Hello World!”;

return 0;
}

To have formatted output operations, cout is used together with the insertion operator,
which is written as << (i.e., two "less than" signs)

The << operator inserts the data that follows it into the stream that precedes it

cout<< "Hello"; // prints Hello


cout<< 120; // prints 120
cout<< “x”; // prints x
cout<< x; // prints the value of x

IT 103: COMPUTER PROGRAMMING 1 89


UNIT 2: C++ Basics

Multiple insertion operations (<<) may be written in a single statement:

cout<< "This"<<" is my "<<"firstprogram”;

//prints This is my first program

This technique is especially useful to mix literals and variables in a single statement:

age = 18;
cout<< “I am”<< age << “years old”;

//prints I am 18 years old

x=5; y=10;
cout<< “The sum of “<<x<< “and” <<y<< “ is” <<x+y;

//prints The sum of 5 and 10 is 15

Escape Sequence

The backslash (\) is known as the escape character in the ASCII character set. The
escape character is used in the C++ language to tell the computer that a special
character follows.

The escape sequence is typed in as two characters with no space between symbols.
Several escape sequences are shown in the table below:

Escape Sequence Description


Allows cursor to move at the
\n newline
beginning of the next line
Allows cursor to move to the next
\t tab
tab stop
Allows the cursor to move one
\b backspace
space to the left
Allows cursor to move one space to
\r return
the left.
\\ backslash Displays a backslash
single
\’ Displays a single quote
quotation
double
\” Displays a double quote
quotation

IT 103: COMPUTER PROGRAMMING 1 90


UNIT 2: C++ Basics

For example, take the following two cout statements:

cout<< "Hello! ";


cout<< "Have a nice day!";

The output would be in a single line without any line breaks in between.

Hello! Have a nice day!

To insert a line break in the output, a newline character (\n) is inserted in the exact
position, and the line should be broken.

cout<< "Hello!\n ";


cout<< "Have a nice day!";

This produces the following output:

Hello!
Have a nice day!

The endl manipulator can also be used to break lines.

For example:

cout<< "Hello!"<<endl;;
cout<< "Have a nice day!"<<endl;

Formatting Floating-Point Numbers

You can use the manipulator setprecision to control the output of floating-point
numbers.

The syntax of the setprecision manipulator is:

setprecision(n);

IT 103: COMPUTER PROGRAMMING 1 91


UNIT 2: C++ Basics

You can use setprecision manipulator with cout and insertion operator. For example,
the statement,

cout<<setprecision(2);

It formats the output of floating-point numbers to two decimal places. The number of
decimal places or the precision value is passed as an argument to setprecision.

To use the manipulator setprecision an iomanip header file must be included in the
program. Thus, the following include statement is required:

#include <iomanip>

Example:

double pi=3.14159265;
cout<< setprecision(2);
cout<< pi;
Or
cout<< setprecision(2)<< pi;
// prints 3.14

IT 103: COMPUTER PROGRAMMING 1 92


UNIT 2: C++ Basics

The Standard Input Stream (cin)

The cin object is an instance of an iostream class and attached to the standard input
device, usually keyboard. It is used with the stream extraction operator(>>).

int age;
cout<<"Please enter your age: ";
cin>>age;
cout<<"You are"<< age<<“years old” <<endl;

When the above code is executed, it will prompt you to enter your age. You enter a
value and then press the enter key to see the result something as follows:

Please enter your age:18


You are 18 years old

The C++ compiler also checked the data type of the entered value and selected the
appropriate stream extraction operator to extract the value and store it in the given
variables.

The stream extraction operator >> may be used more than once in a single statement.
To request more than one data, you can use the following:

int num1,num2;
cout<< “Enter two numbers: ”;
cin>> num1>>num2;

This will be equivalent to the following two statements:

cin>>num1;
cin>>num2;

IT 103: COMPUTER PROGRAMMING 1 93


UNIT 2: C++ Basics

Sample Program using Sequential

In sequential structure, Basic I/O program statements are executed one after another,
in the order by which they appear in the program.

Start

Initialization

Input

Process
/Compute

Output

End

Example 1
#include <iostream>
using namespace std; Sample Output

main() Enter the First Number:5


{ Enter the First Number:5
Product:25
int num1;
int num2;
int prod;

cout<<"Enter the First Number:";


cin>> num1;
cout<< "Enter the Second Number:";
cin>>num2;

prod=num1*num2;

cout<<"Product: " <<prod;


return 0;
}

IT 103: COMPUTER PROGRAMMING 1 94


UNIT 2: C++ Basics

Example 2
#include <iostream> Sample Output
using namespace std;

main()
{ Enter the First Number: 1
Enter the Second Number: 1
int num1; Sum:2
int num2; Product:2
int sum; Difference:0
int prod; Quotient:1
int diff;
float quo;

cout<< "Enter the First Number:";


cin>> num1;
cout<< "Enter the Second Number:";
cin>> num2;

sum=num1+num2;
prod=num1*num2;
diff=num1-num2;
quo=num1/num2;

cout<< "Sum:" << sum; cout<<endl;


cout<<"Product:" << prod; cout<<endl;
cout<<"Difference:" << diff;
cout<<endl;
cout<<"Quotient:" << quo;

IT 103: COMPUTER PROGRAMMING 1 95

You might also like