2 Chapter Two, C++ Programming Basics

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

Fundamental of Programming, C++ Notes

Chapter Two
C++ Programming Basics
Introduction
A computer program is a set of instructions that a programmer writes to tell a computer how to
carryout a certain task.
The instructions, however, must be in a language that the computer understands. Computers
understand only binary languages (0’s & 1’s). This is a low level language and very hard to
program in. So, high level languages such as C++ were discovered to make the programming task
easier.

2.1 Integrated Development Environment (IDE)

An integrated development environment (IDE) is a programming environment that has been


packaged as an application program, typically consisting of a Source code editor, a compiler, a
debugger, and a graphical user interface (GUI) builder. The IDE may be a standalone application
or may be included as part of one or more existing and compatible applications

A source code editor is a text editor program designed specifically for editing source code of
computer programs by programmers. It may be a standalone application or it may be built into an
integrated development environment (IDE).

Source code (file) is any collection of statements or declarations written in some human-readable
computer programming language. Source code is the means most often used by programmers to
specify the actions to be performed by a computer.

A compiler is a computer program (or set of programs) that transforms source code written in a
computer language (the source language) into another computer language (the target language,
often having a binary form known as object code). The most common reason for wanting to
transform source code is to create an executable program.
A debugger or debugging tool is a computer program that is used to test and debug other
programs (the "target" program). In other words it finds the errors in a given program whether it
meets the target or not.

A graphical user interface (GUI) is a human-computer interface (i.e., a way for humans to
interact with computers) that uses windows, icons and menus and which can be manipulated by a
mouse (and often to a limited extent by a keyboard as well).
___________________________________________________________________________
Course Instructors chapter Two Page 1
Fundamental of Programming, C++ Notes
Compiler Linker
Source File Object File Executable file
Editor
Header Files Standard library, object files

NB: Both object and executable files are machine codes (languages). The steps will be: Writing,
Compiling and Running.

2.2 Basic Program construction


// my first program in C++ ==Comment line
#include<iostream.h> ==header File
//using namespace std
int main() ===Type and Name of function
{ ==Beginning of function
cout<<” Starting Programming with C++”<<endl; Body of function
return 0;
}==End of function
Notes:
// my first program in C++: - Comments are an important part of any program. They help the person
writing a program, and anyone else who must read the source file, understand what’s going on.
The compiler ignores comments, so they do not add to the file size or execution time of the
executable program. Comment can be done in two ways: Using // (two slash sign) for a single line
of code and /* */ for multiple line of codes.
#include<iostream.h>:- might look like a program statement, but it’s not. It isn’t part of a
function body and doesn’t end with a semicolon, as program statements must. Starts with # which
indicates that the line is intended for the preprocessor (part of a compiler)
int main():- It is the function or line of code where program execution starts. Functions are one of
the fundamental building blocks of C++ and a program consists at least one main function.
Cout: - (console output) is predefined in C++ and the object responsible for output.
<<: - Shows the characters are being “pushed” to the output stream.
return 0:- Terminates the function main () and also the program, returning a value zero as an exit
code to the calling program.

___________________________________________________________________________
Course Instructors chapter Two Page 2
Fundamental of Programming, C++ Notes
File Names:- The filename is metadata about a file; a special kind of string used to uniquely
identify a file stored on the file system of a computer. So, in c++ when we save programs the file
names should be with extension .cpp.
Example: - frist.cpp
123.cpp
_seciond.cpp
2.3 Built-in data types, Constants, Variables
A built-in data type is a data type for which the programming language provides built-in support.
Data used by our program are stored in the computer memory. But the computer must know what
we want to store in the memory since storing a simple number, a letter or a large number is not
going to occupy the same space in the memory. Some of them are:
1. bool:- takes values of true or false (1 byte =8 bits)
- is the result of comparison or a logical association using AND or OR.
- true is represented as one (1), false as zero (0).
2. char:- used to save character codes-an integer associated with each character.
- character or integer 8 bits length.
- Like all integral type values, character values are stored as integers.
- eg. Letter A is represented by code 65.
3. Integer types: - There are 6 integer types in Standard C++: short, int long, unsigned short,
unsigned int, unsigned long.
Short: - 2 bytes  -32768 to +32767
int :- 2 bytes -32768 to +32767
int :- 4 bytes -2,147,483,648 to +2147483647
long :- 4 byte–2,147,483,648 to +2,147,483,647
unsigned short:- 0 to 65535
unsigned int:- 0 to 65535 or 0 to 4,294,967,295
unsigned long:- 0 to 0 to 4,294,967,295
4. Floating-Point types: - C++ supports three real number types: float, double, and long double
On most systems, double uses twice as many bytes as float. Typically, float uses 4 bytes, double
uses 8 bytes, and long double uses 8, 10, 12, or 16 bytes.
float :- 4 byte  3.4E+/-38 (7 digits)
double :- 8 byte  1.7E+/-308 (15 digits)
long double :- 10 byte  1.2E+/-4932 (19 digits)
___________________________________________________________________________
Course Instructors chapter Two Page 3
Fundamental of Programming, C++ Notes
A program which describes the above data types with their corresponding bytes
int main()
{ // prints the storage sizes of the fundamental types:
cout << "Number of bytes used:\n";
cout << "\t char: " << sizeof(char) << endl;
cout << "\t short: " << sizeof(short) << endl;
cout << "\t int: " << sizeof(int) << endl;
cout << "\t long: " << sizeof(long) << endl;
cout << "\t unsigned char: " << sizeof(unsigned char) << endl;
cout << "\t unsigned short: " << sizeof(unsigned short) << endl;
cout << "\t unsigned int: " << sizeof(unsigned int) << endl;
cout << "\t unsigned long: " << sizeof(unsigned long) << endl;
cout << "\t signed char: " << sizeof(signed char) << endl;
cout << "\t float: " << sizeof(float) << endl;
cout << "\t double: " << sizeof(double) << endl;
cout << "\t long double: " << sizeof(long double) << endl;
}
Constants: - A constant is any expression that has fixed value. Constants can be integers, floating
points, characters and strings.
Example: - 125, -96  Integer constants
3.14159, 6.02E23, 3.0,  Floating point numbers
‘Z’, ‘K’, x refers to variable x, whereas 'x' refers to the character constant 'x'. 
Character constants
“Hello World” string constants
Variables: - A variable is a named memory location that can be assigned a value. The value of a
variable can be changed during the program execution. i.e., the content of a variable is changeable,
not fixed.

___________________________________________________________________________
Course Instructors chapter Two Page 4
Fundamental of Programming, C++ Notes
Declaration of variables
In order to use a variable in C++, we must first declare it specifying which of the data types above
we want it to be. The syntax to declare a new variable is to write the data type specifier that we
want (like int, short, float...) followed by a valid variable identifier.
Example:
int a;
float mynumber;
Initialization of variables
When declaring a local variable, its value is undetermined by default. But you may want that a
variable stores a concrete value since the moment in which it is declared. In order to do that, you
have to append an equal sign followed by the value wanted to the variable declaration:
type identifier = initial_value ;
For example, if we want to declare an int variable called a that contains the value 0 since the
moment in which it is declared, we could write:
int a = 0;
Scope of variables
Global variables can be referred anywhere in the code, within any function, whenever it is after
its declaration
The scope of the local variables is limited to the code level in which they are declared. If they are
declared at the beginning of a function (like in main) its scope is the whole main function. This
means that if in the example above, moreover than the function main () another function existed,
the local variables declared in main could not be used in the other function and vice versa.
In C++, the scope of a local variable is given by the block in which it is declared (a block is a
group of instructions grouped together within curly brackets {} signs). If it is declared within a
function it will be a variable with function scope, if it is declared in a loop its scope will be only
the loop, etc...

___________________________________________________________________________
Course Instructors chapter Two Page 5
Fundamental of Programming, C++ Notes
Example:-
#include<iostream.h>
Int main()
{
int length; // declares the variable
length=5; // assigns a value to a variable
cout<<”The length is “;
cout<<length; // output the value in the variable
return 0;
}
Valid names—Identifiers
Within a program names are used to represent variables, constants and functions. When choosing
valid identifiers for your variables, constants and functions, the following rules will be applied.
1) an identifier contains a series of letters, numbers, or underscore ( _ )
2) the first character must be a letter or underscore
3) no restriction on the length of an identifier
4) C++ keywords are reserved and can not be used as names: asm, auto, bool, break, case, catch,
char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum,
explicit, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new,
operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t
Example
Valid names Invalid names
a goto
_var us$
B12 586_CPU
top_of_window ture
SetTextColor object-oriented
a_very_long_name12345

___________________________________________________________________________
Course Instructors chapter Two Page 6
Fundamental of Programming, C++ Notes
Example:-
#include<iostream.h>
int main ( )
{
int a, b; //declaring a and b to be type of int
int result;
a=5; //assigning values
b=12;
result = a + b; // performing addition operation
cout<<result; // printing to the screen
return 0; // terminating the program
}
3.4 Operators and Statements

Once we know of the existence of variables and constants we can begin to operate with them. For
that purpose, C++ provides the operators, which in this language are a set of keywords and signs
that are not part of the alphabet but are available in all keyboards. It is important to know them
since they are the basis of the C++ language.
In computer programming a statement can be thought of as the smallest standalone element of an
imperative programming language. A program is formed by a sequence of one or more statements.
A statement will have internal components (e.g., expressions). Generally, C++ statements are the
program elements that control how and in what order objects are manipulated.
In C++ different operators are used.
Assignation (=).
The assignation operator serves to assign a value to a variable.
a = 5; assigns the integer value 5 to variable a. The part at the left of the =operator is known as
lvalue(left value) and the right one as rvalue(right value). lvaluemust always be a variable whereas
the right side can be either a constant, a variable, the result of an operation or any combination of
them.

___________________________________________________________________________
Course Instructors chapter Two Page 7
Fundamental of Programming, C++ Notes
Arithmetic operators (+, -, *, /, %)
The five arithmetical operations supported by the language are:
Addition (+)
Subtraction (-)
Multiplication (*/ x)
Division (/)
Module (%)
Operations of addition, subtraction, multiplication and division would not suppose an
understanding challenge for you since they literally correspond with their respective mathematical
operators.
The only one that may not be known by you is the module, specified with the percentage sign (%).
Module is the operation that gives the rest of a division of two integer values. For example, if we
write a = 11 % 3; the variable a will contain 2 as result since 2 is the rest from dividing 11
between 3.
Compound assignation operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
A feature of assignation in C++ that contributes to its fame of sparing language when writing are
the compound assignation operators (+=, -=, *= and /= among others), which allow to modify the
value of a variable with one of the basic operators:
Example:
value += increase; is equivalent to value = value + increase; a -= 5; is equivalent to
a = a - 5; a /= b; is equivalent to a = a / b; price *= units + 1; is equivalent to
price = price * (units + 1);
Increment and decrement Operators
Another example of saving when writing code are the increase operator (++) and the decrease
operator (--). They increase or reduce by 1 the value stored in a variable. They are equivalent to
+=1 and to -=1, respectively.
Thus:
a++;
a+=1;
a=a+1;
are all equivalent in its functionality: the three increase by 1 the value of a.

___________________________________________________________________________
Course Instructors chapter Two Page 8
Fundamental of Programming, C++ Notes
Example1 Example 2
B=3 B=3
A= ++B A=B++
// A= 4, B= 4 // A= 3, B=4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is
copied to A and B is later increased.
Relational operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the Relational operators.
We may want to compare two expressions, for example, to know if they are equal or if one is
greater than the other. Here is a list of the relational operators that can be performed in C++:
= = Equal
! = Different
> Greater than
< Less than
> = Greater than or Equal to
< = Less than or Equal to
Logic operators ( !, &&, || ).
Operator! is equivalent to boolean operation NOT, it has only one operand, located at its right, and
the only thing that it does is to invert the value of it, producing false if its operand is true and true
if its operand is false. It is like to say that it returns the opposite result of evaluating its operand.
Logic operators && and ||are used when evaluating two expressions to obtain a single result. They
correspond with boolean logic operations AND and OR respectively.
Conditional operator ( ? ).
The conditional operator evaluates an expression and returns a different value according to the
evaluated expression, depending on whether it is true or false.
Its format is:
condition ? result1 : result2
if condition is true the expression will return result1, if not it will return result2.
Example:-
7= =5? 4 : 3 returns 3 since 7 is not equal to 5
7= =5+2 ? 4:3 returns 4 since 7 is not equal to 5 +2
5> 3 ? a : b returns a, since 5 is greater than 3
___________________________________________________________________________
Course Instructors chapter Two Page 9
Fundamental of Programming, C++ Notes
Sizeof ()
This operator accepts one parameter, which can be either a variable type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char); this will return 1to a, because char is a one byte long type. The value returned by
sizeof is a constant, so it is always determined before program execution.
Priority of operators
When making complex expressions with several operands on it we may have some doubts about
which operand is evaluated first and which later. So knowing operator precedence is an ideal for
such problem.
2.5 Type Conversion
Type casting operators allows you to convert a datum of a given type to another.
Example:
int i;
float f = 3.14;
i = (int) f;
2.6 Library Function
C++ programs are typically written by combining functions the programmer wrtes with
“prepackaged” functions available in C++ standard library.
The C++ standard library provides a rich collection of functions for
 Performing common mathematical calculations
 String manipulation
 Character manipulation
 Input/output
 Error checking and so on
This makes the programmer’s task easier, because these functions provide many of the capabilities
programmers need. Some of the library functions commonly used are:
iostream.h
math.h
iomanip.h
string.h
conio.h……………..etc
End of Chapter Two

___________________________________________________________________________
Course Instructors chapter Two Page 10

You might also like