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

C++ PROGRAMMING TRIANER MODULE 2012

What is C++?
o C++ is a cross-platform language that can be used to create high-performance
applications.
o C++ was developed by Bjarne Stroustrup, as an extension to the C language.
o C++ is a powerful general-purpose programming language.
o It can be used to develop operating systems, browsers, games, and so on.
o C++ supports different ways of programming like procedural, object-oriented,
functional, and so on. 
C++ Syntax
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. cout << "Hello World!";
6. return 0;
7. }
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input and output
objects, such as cout (used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the
standard library.
Don't worry if you don't understand how #include <iostream> and using namespace std works.
Just think of it as something that (almost) always appears in your program.
Line 3: A blank line. C++ ignores white space.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called a
function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World".
Note: Every C++ statement ends with a semicolon ;.
Note: The body of int main() could also been written as:

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 6: return 0 ends the main function.
Line 7: Do not forget to add the closing curly bracket } to actually end the main function
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values/print text:
C++ New Lines
o To insert a new line, you can use the \n character:
o Another way to insert a new line, is with the endl manipulator:
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.
o Single-line comments start with two forward slashes (//).
o C++ Multi-line Comments
 Multi-line comments start with /* and ends with */.
 Any text between /* and */ will be ignored by the compiler:
C++ Variables
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). For
example,
int age = 14;
Rules for naming a variable
 A variable name can only have alphabets, numbers and the underscore _.
 A variable name cannot begin with a number.
 Variable names cannot begin with an uppercase character.
 A variable name cannot be a keyword. For example, int is a keyword that is used to
denote integers.
 A variable name can start with an underscore. However, it's not considered a good
practice.

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
 Note: We should try to give meaningful names to variables. For example, first_name is a
better variable name than fn.
C++ Data Types
 int myNum = 5; // Integer (whole number)
 float myFloatNum = 5.99; // Floating point number
 double myDoubleNum = 9.98; // Floating point number
 char myLetter = 'D'; // Character
 bool myBoolean = true; // Boolean
 string myText = "Hello"; // String
Data Type Size Description
int 4 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 7
decimal digits
double 8 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 15
decimal digits
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number, or
ASCII values

C++ Operators
Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while - is an operator used for subtraction.
Operators in C++ can be classified into 5 types:

1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
5. Bitwise Operators
1. C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example, a + b;
2. C++ Assignment Operators
In C++, assignment operators are used to assign values to variables. For example,
// assign 5 to a
a = 5;
3. C++ Relational Operators
A relational operator is used to check the relationship between two operands. For example,
// checks if a is greater than b
a > b;
4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression is
true, it returns 1 whereas if the expression is false, it returns 0.
 (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
 (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
 !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).
5. C++ Bitwise Operators
In C++, bitwise operators are used to perform operations on individual bits. They can only be
used alongside char and int data types.
C++ Strings
Strings are used for storing text.
A string variable contains a collection of characters surrounded by double quotes:
C++ Flow Control
C++ if Statement
The syntax of the if statement is:
if (condition) {
// body of if statement

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
}
The if statement evaluates the condition inside the parentheses ( ).
 If the condition evaluates to true, the code inside the body of if is executed.
 If the condition evaluates to false, the code inside the body of if is skipped
C++ if...else
The if statement can have an optional else clause. Its syntax is:
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
The if..else statement evaluates the condition inside the parenthesis.
f the condition evaluates true,
 the code inside the body of if is executed
 the code inside the body of else is skipped from execution
If the condition evaluates false,
 the code inside the body of else is executed
 the code inside the body of if is skipped from execution
C++ if...else...else if statement
The if...else statement is used to execute a block of code among two alternatives. However, if we
need to make a choice between more than two alternatives, we use the if...else if...else statement.
The syntax of the if...else if...else statement is:
if (condition1) {
// code block 1
} else if (condition2){
// code block 2
} else {
// code block 3
}

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012

 If condition1 evaluates to true, the code block 1 is executed.


 If condition1 evaluates to false, then condition2 is evaluated.
 If condition2 is true, the code block 2 is executed.
 If condition2 is false, the code block 3 is executed
WHILE
The following command evaluates booleanExpression. If this evaluates to true, then control
passes to expressions. At the end of the block, control passes back to booleanExpression and
repeats the process.
while (booleanExpression)
{
expressions;
}
DO…WHILE
The following command executes expressions. It then evaluates booleanExpression. If this
evaluates to true, control returns to the top of the loop and repeats the process.
do
{
expressions;
} while(booleanExpression);
FOR
The following command executes initCommand which may be an expression or a variable
declaration. It then evaluates boolExpression. If this evaluates to true, then control passes to
expressions1. If boolExpression is false, then control passes to the first statement after the closed
brace of the for loop. Once expressions completes, control passes to the expression contained in
loopExpression before returning to boolExpression to repeat the process. If initCommand
declares a new variable, it goes out of scope as soon as control passes outside of the loop.
for (initCommand; boolExpression; loopExpression)
{
expressions;

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
}
FOR (EACH)
for (declaration: list){
Expressions;
}
SWITCH
The following command evaluates integerExpression and compares the result to each of the
cases listed. If the value is found to equal one of the constant integral values, val1, val2, etc.,
control passes to the corresponding set of expressions and continues until control encounters a
break. If expression does not equal any of the values, control passes to the expressionsN
following default.
switch(integerExpression)
{
case val1:
expressions1;
break;
case val2:
expressions2;
break;
[default:
expressionsN;
]
}
BREAK, CONTINUE, GOTO
 A continue passes control to the end of the closed brace of any of the looping controls.
This causes the loop to continue with the next iteration. For example, the following loop
processes prime numbers between 1 and 20:
 A break passes control to the first statement after the closed brace of any of the looping
commands. This causes execution to exit the loop immediately. 
 A goto label passes control to the label provided.

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012

C++ Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.


Create a Function
Syntax
void myFunction() {
  // code to be executed
}
Example Explained
 myFunction() is the name of the function
 void means that the function does not have a return value. You will learn more about
return values later in the next chapter
 inside the function (the body), add code that defines what the function should do
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
void myFunction() {
  cout << "I just got executed!\n";
}

int main() {
  myFunction();
  myFunction();
  myFunction();

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
  return 0;
}"I just got executed!"
function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function.
For example, let us consider the function below:
void printNum(int num) {
cout << num;
}
Here, the int variable num is the function parameter.
Example 5: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
C++ Array Declaration
dataType arrayName[arraySize];
For example,
int x[6];
Here,
int - type of element to be stored

Animut geremew 0948702702


C++ PROGRAMMING TRIANER MODULE 2012
x - name of the array
6 - size of the array

Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as follows −
Double balance [5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
Double balance [] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
Balance [4] = 50.0;

Animut geremew 0948702702

You might also like