Chapter 2- C++ Basics
Chapter 2- C++ Basics
CHAPTER TWO
C++ BASIC
Structure of C++ program
Documentation section
Linking section
Definition section
Global declaration section
Class declaration
Function
main() functions
{
Initializations;
Executable parts;
}
Function1()
{
Initializations;
Executable parts;
}…n
Documentation Section: include comment parts, which are ignored by compiler.
The comments are used to describe the functionality of each statement in the
program, its copyright, author, and date of compilation and purpose of the
program to the user. C++ supports single line (// comment) and multiline (/*
comments*/).
Syntax: //This statement is a single line comment
/*This is multiline comment*/
Link section: here we can link the necessary files and libraries to current files. Using
#include directive we can link the necessary libraries to current files.
Syntax: #include<file or library name>
Example: #include<iostream.h>
Definition Section: It is possible to define symbolic constants. Symbolic constants
are normal identifiers in which their values cannot be altered.
Syntax: #define identifier constant
Global declaration Section: variables declared under this section are available
throughout the program.
Class declaration Section: defines the class declaration.
Page 1 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
Functions: The function main, which has been written in the program, is an example
of function. A function is defined as group of instructions, which are assigned a
name and accessed by the name.
Syntax:
A source file ending with ".c" contains C source code; whereas, a file ending with
".cpp" is a C++ file. A file ending with ".h" can be both a C and C++ header file.
Sometimes the suffix ".hpp" (or ".H") is used to indicate a C++ only header file.
The compiler is a program that usually consists of many phases. The first phase of
compilation is called preprocessing. The preprocessor does many things, but two
features that must be learned immediately are file inclusion and macro (manifest
constant) definitions. After preprocessing, the compiler executes two primary steps:
lexical analysis and parsing. During lexical analysis, the source code is broken up into
tokens and the tokens are passed to the parser. The parser does syntax and semantic
analysis, which includes the generation of object code (i.e. machine language).
The linker "combines" all object code files into an executable file. Typically, the object
files created by your source files are linked with object files that are packaged into
libraries.
Most implementations allow each step of the compilation process to be executed as a
stand-alone procedure. For example, compile a source file but do not invoke the linker;
execute the preprocessor only; or, invoke the linker only.
Some older compilers translate C source code into assembly language, then execute an
assembler program to translate the assembly language into machine language.
Early C++ compilers (those prior to 1992) translated C++ code into C code and then
Page 3 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
The semantics of a programming language deal with the meanings given to syntactically
correct constructs of the language. Usually, semantics is defined in terms of the program’s
run-time behavior: What happens when the program is executed with a certain set of
inputs, what statements are executed, what values are assigned to the variables, and what
output is produced.
sum=0;
while (sum!=-1)
sum=sum+10;
To understand the basic parts of a simple program in C++, lets have a look at
the following code:
#include<iostream.h>
void main()
Any C++ program file should be saved with file name extension “ .CPP ”
Type the program directly into the editor, and save the file as hello.cpp,
compile it and then run it. It will print the words Hello World! on the
computer screen.
The first character is the #. This character is a signal to the preprocessor. Each
time you start your compiler, the preprocessor runs through the program and
looks for the hush or sharp (#) symbols and act on those lines before the
compiler runs.
The include instruction is a preprocessor instruction that directs the compiler
to include a copy of the file specified in the angle brackets in the source code.
If the path of the file is not specified, the preprocessor looks for the file under
c:\tc\include\ folder or in include folder of the location where the editor is
stored.
The effects of line 1, i.e. include<iostream.h> is to include the file iostream.h
into the program as if the programmer had actually typed it.
When the program starts, main() is called automatically.
Every C++ program has a main() function.
The return value type for main() here is void, which means main function will
not return a value to the caller (which is the operating system).
The main function can be made to return a value to the operating system.
The Left French brace “{“signals the beginning of the main function body and
the corresponding Right French Brace “}” signals the end of the main function
body. Every Left French Brace needs to have a corresponding Right French
Brace.
Page 5 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
The lines we find between the braces are statements or said to be the body of
the function.
A statement is a computation step which may produce a value or interact with
input and output streams.
The end of a single statement ends with semicolon (;).
The statement in the above example causes the string “Hello World!” to be
sent to the “cout” (VDU) stream which will display it on the computer screen.
Cin>>var1>>var2>>var3;
Here three different values will be entered for the three variables. The
input should be separated by a space, tab or newline for each variable.
0 0 0 0 →0 0 0 0 0 →0
0 0 0 1 →1 0 0 0 1 →1
0 0 1 0 →2 0 0 1 0 →2
0 0 1 1 →3 0 0 1 1 →3
0 1 0 0 →4 0 1 0 0 →4
0 1 0 1 →5 0 1 0 1 →5
0 1 1 0 →6 0 1 1 0 →6
0 1 1 1 →7 0 1 1 1 →7
1 0 0 0 →8 1 0 0 0 →0
1 0 0 1 →9 1 0 0 1 → -1
1 0 1 0 →10 1 0 1 0 → -2
1 0 1 1 →11 1 0 1 1 → -3
1 1 0 0 →12 1 1 0 0 → -4
1 1 0 1 →13 1 1 0 1 → -5
1 1 1 0 →14 1 1 1 0 → -6
1 1 1 1 →15 1 1 1 1 → -7
In the above example, in case of unsigned, since all the 4 bits can be used to represent
the magnitude of the number the maximum magnitude that can be represented will
be 15 as shown in the example.
If we use signed, we can use the first bit to represent the sign where if the value of the
first bit is 0 the number is positive if the value is 1 the number is negative. In this case
we will be left with only three bits to represent the magnitude of the number. Where
the maximum magnitude will be 7.
Declaring Variables
Variables can be created in a process known as declaration.
Syntax: Datatype Variable_Name;
The declaration will instruct the computer to reserve a memory location with the
name and size specified during the declaration.
Good variable names indicate the purpose of the variable or they should be self
descriptive.
E.g. int myAge; //variable used to store my age
Identifiers
A valid identifier is a sequence of one or more letters, digits or underscore symbols.
The length of an identifier is not limited.
Neither space nor marked letters can be part of an identifier.
Only letters, digits and underscore characters are valid.
Variable identifiers should always begin with a letter or an underscore. By any means
they should not begin with a digit.
Key words should not be used as names for identifiers.
C++ is case sensitive. Small letter and capital letters are different for C++. Eg: variable
Age is not identical with variable age
Initializing Variables
When a variable is assigned a value at the time of declaration, it is called variable
initialization.
This is identical with declaring a variable and then assigning a value to the variable
immediately after declaration.
The syntax:
DataType variable name = initial value;
e.g. int a = 0;
or: int a;
a=0;
Scope of Variables
Scope of a variable is the boundary or block in a program where a variable can be
accessed. The boundary or block is identified by the left and right French brackets.
In C++, we can declare variables anywhere in the source code. But we should declare a
variable before using it no matter where it is written.
Global variables: are variables that can be referred/accessed anywhere in the code,
within any function, as long as it is declared first. A variable declared before any
function immediately after the include statements are global variables.
Local Variables: the scope of the local variable is limited to the code level or block
within which they are declared.
In the following example, the integer data type num1 is accessible everywhere whereas
z and is only accessible in the add function and num2 is accessible in main function.
This means cout<<z; or any statement involving z is only valid in add function.
e.g:
#include<iostream.h>
int num1;
In C++ the scope of a local variable is given by the block in which it is declared.
If it is declared within a function, it will be a variable with a function scope. If it is
declared in a loop, its scope will be only in the loop, etc.
Characters
Characters variables (type char) are typically one byte in size, enough to hold 256
different values. A char can be represented as a small number (0 - 255).
Char in C++ are represented as any value inside a single quote.
E.g.: ‘x’, ‘A’, ‘5’, ‘a’, etc.
When the compiler finds such values (characters), it translates back the value to the
ASCII values. E.g. ‘a’ has a value 97 in ASCII.
\t tab
\b backspace
\” double quote
\’ single quote
\? Question mark
\\ backslash
Constants
A constant is any expression that has a fixed value.
Like variables, constants are data storage locations in the computer memory. But,
constants, unlike variables their content can not be changed after the declaration.
Constants must be initialized when they are created by the program, and the
programmer can’t assign a new value to a constant later.
C++ provides two types of constants: literal and symbolic constants.
Literal constant: is a value typed directly into the program wherever it is needed.
E.g.: int num = 43;
Example:
In C++, we have two ways to declare a symbolic constant. These are using the #define
and the const key word.
In our example, each time the preprocessor sees the word studentPerClass, it inserts 15
into the text.
Enumerated constants
Used to declare multiple integer constants using a single line with different features.
Enables programmers to define variables and restrict the value of that variable to a set
of possible values which are integer.
The enum type cannot take any other data type than integer
enum types can be used to set up collections of named integer constants. (The keyword
enum is short for ``enumerated''.)
The traditional way of doing this was something like this:
#define SPRING 0
#define SUMMER 1
#define FALL 2
You can declare COLOR to be an enumeration, and then you can define five possible
values for COLOR: RED, BLUE, GREEN, WHITE and BLACK.
E.g.: enum COLOR {RED,BLUE,GREEN,WHITE,BLACK};
Every enumerated constant has an integer value. If the programmer does not specify
otherwise, the first constant will have the value 0, and the values for the remaining
constants will count up from the initial value by 1. thus in our previous example
RED=0, BLUE=1, GREEN=3, WHITE=4 and BLACK=5
But one can also assign different numbers for each.
E.g.: enum COLOR{RED=100,BLUE,GREEN=500,WHITE,BLACK};
Where RED will have 100 and BLUE will have 101 while GREEN will have 500, WHITE 501
and BLACK 502.
White spaces: white spaces characters (spaces, tabs, new lines) can’t be seen
and generally ignored in statements. White spaces should be used to make
programs more readable and easier to maintain.
Blocks: a block begins with an opening French brace ({) and ends with a
closing French brace (}).
Expressions: an expression is a computation which yields a value. It can also
be viewed as any statement that evaluates to a value (returns a value).
E.g.: the statement 3+2; returns the value 5 and thus is an expression.
PI float constant that returns the value 3.14 if the constant is defined.
x = a + b;
y = x = a + b;
Operators
An operator is a symbol that makes the machine to take an action.
Different Operators act on one or more operands and can also have different
kinds of operators.
C++ provides several categories of operators, including the following:
Assignment operator
Arithmetic operator
Relational operator
Logical operator
Increment/decrement operator
Conditional operator
Comma operator
The size of operator
Explicit type casting operators, etc
Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=)
Compound assignment operator is the combination of the assignment operator with
other operators like arithmetic and bit wise operators.
The assignment operator has a number of variants, obtained by combining it with
other operators.
E.g.:
a -= 5; is equivalent to a = a – 5;
a /= b; is equivalent to a = a / b;
To obtain a real division when both operands are integers, you should cast one of the
operands to be real.
E.g.:
The module(%) is an operator that gives the remainder of a division of two integer
values. For instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome
of 4 and a remainder of 1; the result is therefore 1.
E.g.:
a = 11 % 3
a is 2
The operands of a relational operator must evaluate to a number. Characters are valid
operands since they are represented by numeric values. For E.g.:
‘A’ < ‘F’ would return true or 1. it is like (65 < 70)
Page 16 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false.
int k = 5;
First operand1 is a relational expression and will be evaluated. If the result of the
evaluation is non zero (which means TRUE), then operand2 will be the final result.
Otherwise, operand3 is the final result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X will be assigned to Z otherwise (if
X>=Y) the value of Y will be assigned to Z.
E.g.:
int m=1,n=2,min;
E.g.:
int m,n,min;
Here, when m is less than n, mCount++ is evaluated and the value of m is stored in
min. otherwise, nCount++ is evaluated and the value of n is stored in min.
a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55) etc
int i;
float f = 3.14;
Operator Precedence
The order in which operators are evaluated in an expression is significant and is
determined by precedence rules. Operators in higher levels take precedence over
operators in lower levels.
Precedence Table:
* / % Left to right
+ - Left to right
== != Left to right
|| Left to right
? : Left to right
= ,+=, -=, *=, /=,^= ,%=, &= ,|= ,<<= ,>>= Right to left
, Left to right
E.g.
a==b+c*d
Operators with the same precedence level are evaluated in the order specified by the
column on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated
followed by a = b.
Worksheet 2
For each of the problems, write a C++ code to perform the required task. Your program
should be based on the flow chart you’ve drawn in the first worksheet.
Spotting errors
For each of the following programs, spot the flaws:
Program 1:
// this program will calculate the area of a square
#include <iostream.h>
void main()
{
int area; / store calculated area of square
int side; / input length of side of square
cout << "How wide is the square?" << endl;
cin >> side;
area = side * side;
cout << "The square has area area" << endl;
}
Page 22 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
Program 2:
// this program prints information about the author
void main()
{
cout << 'This program was written by Wubet N';
cout << 'He didn't do a great job of it, ' << endl;
cout << 'It won't even compile';
}
Program 3:
// this program calculates user age
#include <iostream.h>
int main()
int currentyear;
int birthyear;
cout << "Enter the year you were born" << endl;
cin >> birthyear;
cout << "Enter the current year" << endl;
cin >> currentyear;
age = currentyear - birthyear;
cout << "This year you will be" << age << endl;
}
Program 4:
// this program gets the user to enter three
// integers and prints them out lined up on
// three separate lines, e.g.
// 17
// 1024
// 206
#include <iostream.h>
void main()
{
// variables for the three integers
int firstint; int secondint; int thirdint;
cout << "Please enter three integers" << endl;
cin << firstint
cin << secondint
cin << thirdint
cout << "The three integers are:;
cout << setw(5) << firstint;
cout << setw(4) << secondint;
cout << setw(3) << thirdint;
return 0;
}
Page 23 of 24 Compiled by: Wubet N. ([email protected])
Fundamentals of Programming I (Comp231) Chapter Two: C++ Basics
Program 5:
#include <iostream.h>
#include <iomanip.h>
const int Pi = 3.1415
void mian()
(
int radius; // input circle radius
int circumference; // calculated circumference
float area; // calculated area
cout << "Enter the integer radius of the circle";
cout << endl;
cin >> radius;
circumference = 2 * radius * Pi;
area = Pi * raduis * radius;