0% found this document useful (0 votes)
84 views

Chapter Two - Basics of C++

This document provides an outline and introduction to the basics of C++ programming. It discusses the structure of a C++ program through an example "Hello World" program. It explains each line of code in the program, including comments, preprocessor directives, functions, and statements. It also notes some additional details about program structure and formatting in C++.

Uploaded by

Yab Yab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

Chapter Two - Basics of C++

This document provides an outline and introduction to the basics of C++ programming. It discusses the structure of a C++ program through an example "Hello World" program. It explains each line of code in the program, including comments, preprocessor directives, functions, and statements. It also notes some additional details about program structure and formatting in C++.

Uploaded by

Yab Yab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

CoSc 131

Computer Programming

Instructor : Welde Janfa


Chapter 2

Basics of C++
OUTLINE
1. Structure of C++ Program
2. C++ IDE
3. Showing Sample program
4. Keywords, Identifiers, Inputs, Outputs,
Comments, Parts of a program
5. Data Types, Variables, and Constants
6. Operators
7. Precedence of Operators

3
Basics of C++ - History of C and C++
C programming language
◦ was first introduced by Denis Ritchie at the AT &T’s Bell
Laboratories USA in 1972
◦ Was implemented for the first time in DEC PDP-11 computer.
◦ Denise Ritchie used the concepts of BCPL and B to develop C and
added data typing and some other powerful features.
C++ programming language
◦ Began in 1979 when Bjarne Stroustrup was working in his Ph.D.
thesis.
◦ During that period Stroustrup used to work with Simula (regarded as
the first language to support OOP paradigm).
◦ So he began working on C with classes i.e. he started working on a
new language which would have object-oriented paradigm mixed
with the features of C programming language.
◦ He created C++, and the first commercial edition of C++
programming language was released in October 1985. 4
1.2 C++ IDE
To create C++ program we can use different IDE
such as
◦ Visual Studio Code
 It is an open-source code editor designed for Windows, macOS,
and Linux.
 It is developed by Microsoft
◦ Sublime Text
 Sublime Text is a closed source cross-platform source code editor
◦ Dev C++
 Dev C++ is another good IDE for C and C++ programming
languages.
 It is an open source IDE but supports only Windows platform and
not Linux and OS X
◦ NetBeans 8, CodeLite, Eclipse

5
Structure of C++ Program

To Learn the structure of the C++ program


let us write your first program and see each
line in the program in detail. C+
+c
pro o
gra de fo
1. // my first program in C++ m r th
is
#include <iostream>
2.
int main()
3. {
4. std::cout << "Hello World!";
}
5.
n t h e ed
Hello World!
e
wh xecut
6. s ul t
 Re ram is
e
7. prog

6
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

Note :- The blue number to the left is not a part of the program. Used for
to make discussing programs and researching errors easier.
Let's examine this program line by line:
Line 1: // my first program in C++
 Two slash signs specify that the rest of the line is a comment inserted by the
programmer but which has no effect on the output of the program.
 Programmers use them to include short explanations or observations about
the code or program.

7
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

Line 2: #include <iostream>


◦ Lines beginning with a hash sign (#) are directives read and interpreted by
preprocessor.
◦ They are special lines interpreted before the compilation of the program itself
begins.
◦ The directive #include <iostream>, instructs the preprocessor to include a
section of standard C++ code, known as header iostream, that allows to
perform standard input and output operations.
Line 3: A blank line
◦ Blank lines have no effect on a program. They simply improve readability of
the code.
8
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

Line 4: int main ()


◦ Declaration of a function. Essentially, a function is a group of code statements
which are given a name: here is "main" to the group of code statements.
◦ Function definition is introduced with a succession of a type (int), a name
(main) and a pair of parentheses (()), optionally including parameters.
◦ The function named main is a special function in all C++ programs; it is the
function called when the program is run.
◦ The execution of all C++ programs begins with the main function, regardless
of where the function is actually located within the code.

9
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

Lines 5 and 7: { and }


◦ The open brace ({) at line 5 indicates the beginning of main's function
definition, and the closing brace (}) at line 7, indicates its end.
◦ Everything between these braces is the function's body that defines what
happens when main is called.
◦ All functions use braces to indicate the beginning and end of their definitions.
Line 6: std::cout << "Hello World!";
◦ This line is a C++ statement.
◦ A statement is an expression that can actually produce some effect
during execution.
10
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

Line 6: std::cout << "Hello World!";


◦ This statement has three parts:
 First, std::cout, which identifies the standard character output device
(usually, this is the computer screen).
 Second, the insertion operator (<<), which indicates that what follows is
inserted into std::cout.
 Finally, a sentence within quotes ("Hello world!"), is the content inserted
into the standard output.
◦ Notice: The statement ends with a semicolon (;). This character marks
the end of the statement. One of the most common syntax errors in C+
+ is forgetting to end a statement with a semicolon.
11
Structure of C++ Program

1. // my first program in C++


2. #include <iostream>
3.
4. int main()
5. {
6. std::cout << "Hello World!";
}
7.

 Not all the lines of this program perform actions when the code is
executed.
◦ There is a line containing a comment (beginning with //). There is a
line with a directive for the preprocessor (beginning with #).
◦ There is a line that defines a function (in this case, the main function).
◦ And, finally, a line with a statements ending with a semicolon (the
insertion into cout), which was within the block delimited by the
braces ( { } ) of the main function.

12
Structure of C++ Program

 Additional Note about the structure of C++ Program


◦ The program has been structured in different lines and properly indented, in
order to make it easier to understand for the humans reading it.
◦ But C++ does not have strict rules on indentation or on how to split
instructions in different lines.
◦ For example, instead of
int main ()
{
cout << " Hello World!";
}
possible to write it as
int main () { cout << "Hello World!"; }
For the computer and the complier don’t have an issue.

13
Structure of C++ Program

 Additional Note about the structure of C++ Program


◦ Comment
 As noted above, comments do not affect the operation of the
program;
 They provide an important tool to document directly within the
source code what the program does and how it operates.
 C++ supports two ways of commenting code:
// line comment
/* block comment */
◦ C++ File Name extension
 C++ file is saved as .cpp file
 Ex. Hello.cpp

14
Compiled and Interpreted Programming Language

 A programming language is a formal language, which comprises a set of


instructions that produce various kinds of output in computer.
 Programming languages are used in computer programming to
implement algorithms.
 Most programs are written in a high-level language such as C,  C++, Perl
or Java etc... . The high-level languages are human readable languages.
 However, computer only understands binary numbers.
 The goal of any programming language implementation is to translate a
source program into the machine language so it can be executed by the
CPU.
 So you need a translator that translate the high-level program to computer
understandable language to properly communicate, and that's what
compilers and interpreters do
 Source programs converted into some intermediate representation before
translating the intermediate representation to machine language.

15
Compiled and Interpreted Programming Language

 Complied Program
◦ The source code must be transformed into machine
readable instructions prior to execution.

16
Compiled and Interpreted Programming Language

 Interpreted language
◦ is a type of programming language for which most of its
implementations execute instructions directly and freely, without
previously compiling a program into machine-language instructions

17
Compiled and Interpreted Programming Language

Complied Language
VS
Interpreted Language
Complied Language Interpreted Language

The code of the complied language can A program written in an interpreted


be executed directly by the computer language is not compiled, it is
CPU interpreted
The source code must be transformed It doesn’t compile the source code into
into machine readable instructions prior machine language prior to running the
to execution program

Compiled program urn faster than Interpreted program can be modified


interpreted while the program is running

Deliver better performance Delivers relatively slower performance

C ,C++, Fortran, COBOL are compled Java and C# are interpreted language
language
18
Basic Input/Output

 C++ uses a convenient abstraction called streams to


perform input and output operations in sequential media
such as the screen, the keyboard or a file.
 A stream is an entity where a program can either insert or
extract characters to/from.
 All we need to know is that streams are a
source/destination of characters, and that these characters
are provided/accepted sequentially (i.e., one after another).
stream description
cin standard input stream
cout standard output stream
cerr standard error (output) stream
clog standard logging (output) stream

19
Basic Input/Output

 Standard output (cout)


◦ On most program environments, the standard output by default is
the screen, and the C++ stream object defined to access it is cout.
◦ For formatted output operations, cout is used together with
the insertion operator, which is written as << (i.e., two "less than"
signs)
 cout << "Output sentence"; // prints Output sentence on screen
 cout << 120; // prints number 120 on screen
 cout << x; // prints the value of x on screen

cout << "Hello"; // prints Hello


 cout << Hello; // prints the content of variable Hello

20
Basic Input/Output

 Standard output (cout)


◦ Multiple insertion operations (<<) may be chained in a
single statement:
 cout << "This " << " is a " << "single C++
statement";
◦ This last statement would print the text This is a single
C++ statement. Chaining insertions is especially useful
to mix literals and variables in a single statement:
 cout << "I am " << age << " years old and my zipcode is " <<
zipcode;
◦ For example if the age =24 and zipcode=5050, the output of the
previous statement would be:

I am 24 years old and my zipcode is 500

21
Basic Input/Output

 Standard input(cin)
◦ In most program environments, the standard input by default is the
keyboard, and the C++ stream object defined to access it is cin.
◦ For formatted input operations, cin is used together with the
extraction operator, which is written as >> (i.e., two "greater than"
signs). This operator is then followed by the variable where the
extracted data is stored.
◦ For example:
 int age;
 cin >> age;
◦ Extractions on cin can also be chained to request more than one
datum in a single statement:
 cin >> a >> b;
◦ This is equivalent to:
 cin >> a;
 cin >> b;

22
C++ Keywords
 Keywords are words that are reserved for the language
 Since they are used by the language, these keywords are
not available for re-definition or overloading or used a
name for other things
 List of keywords in C++
◦ alignas, alignof, and, bool, break, case, catch, char,
const, constexpr, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern,
false, float, for, goto, if, inline, int, long, return, short,
signed, sizeof, static, static_assert, switch, template,
this, throw, true, try, union, unsigned, using, virtual,
void etc…

23
C++ Variable
Variables are the backbone of any programming
language.
A variable is simply a way to store some
information for later use.
It is a portion of memory to store a value.
We can retrieve this value or data by referring to a
"word" that will describe this information.
Once declared and defined they may be used many
times within the scope.
Each variable needs a name that identifies it and
distinguishes it from the others

24
Variable Identifier
 A valid variable identifier is a sequence of one or more
letters, digits, or underscore characters (_).
 Spaces, punctuation marks, and symbols cannot be part of an
identifier.
 In addition, identifiers shall always begin with a letter. They
can also begin with an underline character (_), but such
identifiers are -on most cases- considered reserved for
compiler-specific keywords or external identifiers,
 In no case can they begin with a digit.
 Very important: The C++ language is a "case sensitive"
language.
◦ For example: Name and name are two different identifiers

25
Data type in C++
 Variables are stored somewhere in an unspecified location in
the computer memory.
 Our program does not need to know the exact location
where a variable is stored.
 What the program needs to be aware of is the kind of data
stored in the variable.
 It's not the same to store a simple integer as it is to store a
letter or a large floating-point number;
 Specifying the types of information stored in the variable is
done by declaring variable with data type
 Ex
◦ int minNum;
◦ char name;

26
Data type in C++
 Fundamental data types are basic types implemented directly by the
language that represent the basic storage units.
 They can mainly be classified into:
◦ Character types:
 represent a single character, such as 'A' or '$'.
 The most basic type is char, which is a one-byte character. Other types are also
provided for wider characters.
◦ Numerical integer types: 
 store a whole number value, such as 7 or 1024.
 They exist in a variety of sizes, and can either be signed or unsigned, depending on
whether they support negative values or not.
◦ Floating-point types: 
 They can represent real values, such as 3.14 or 0.01, with different levels of
precision, depending on which of the three floating-point types is used.
◦ Boolean type: 
 The boolean type, known in C++ as bool, can only represent one of two
states, true or false.

27
Data type in C++
Group Type names* Notes on size / precision

char Exactly one byte in size. At least 8 bits.

char16_t Not smaller than char. At least 16 bits.


Character types
char32_t Not smaller than char16_t. At least 32 bits.

Can represent the largest supported


wchar_t
character set.

signed char Same size as char. At least 8 bits.

signed short int Not smaller than char. At least 16 bits.

Integer types (signed) signed int Not smaller than short. At least 16 bits.

signed long int Not smaller than int. At least 32 bits.

signed long long int Not smaller than long. At least 64 bits.

unsigned char
unsigned short int
Integer types (unsigned) unsigned int (same size as their signed counterparts)
unsigned long int
unsigned long long int
float

Floating-point types double Precision not less than float

long double Precision not less than double

Boolean type bool


Void type void no storage
28
Variable Declaration and Initialization

 C++ is a strongly-typed language, and requires every


variable to be declared with its type before its first use.
 Declaration informs the compiler the size to reserve in
memory for the variable and how to interpret its value.
 The syntax to declare a new variable in C++ is
straightforward: we simply write the type followed by the
variable name (i.e., its identifier).
 For example:

◦ int a;
◦ float mynumber;
◦ int a, b, c;

29
Variable Declaration and Initialization

 Once the variables are declared, they have an undetermined


value until they are assigned a value for the first time.
 But it is possible for a variable to have a specific value from
the moment it is declared. This is called the initialization of
the variable.
 In c++ we can initialized variables in three ways
◦ c-like initialization
type identifier = initial_value;
int num=0;
◦ constructor initialization
type identifier (initial_value);
int num (0);
◦ uniform initialization
type identifier {initial_value};
int num {0};
30
Compound Data type - strings

 Fundamental types represent the most basic types handled


by the machines where the code may run.
 But one of the major strengths of the C++ language is its
rich set of compound types, of which the fundamental types
are mere building blocks.
 String class a compound type variable that store sequences
of characters, such as words or sentences. A very useful
feature!
 A first difference with fundamental data types is that in
order to declare and use objects (variables) of this type, the
program needs to include the header where the type is
defined within the standard library (header <string>):

31
Constants

 Constants are expressions with a fixed value that the


program may not alter and they are called literals.
 Constants can be of any of the basic data types and can be
divided into Integer Numerals, Floating-Point Numerals,
Characters, Strings and Boolean Values.
 Again, constants are treated just like regular variables except
that their values cannot be modified after their definition.
 Integer Literals
◦ 85 // decimal
◦ 0213 // octal
◦ 0x4b // hexadecimal
◦ 30 // int
◦ 30u // unsigned int
◦ 30l // long
◦ 30ul // unsigned long

32
Constants

 Floating-point Literals
◦ 3.14159 // 3.14159
◦ 6.02e23 // 6.02 x 10^23
◦ 1.6e-19 // 1.6 x 10^-19
◦ 3.0 // 3.0 .
◦ 3.14159L // long double
◦ 6.02e23f // float
 Character and string literals
◦ Character and string literals are enclosed in quotes:
◦ 'z‘
◦ 'p‘
◦ "Hello world"
◦ "How do you do?"

33
Constants

 Character and string literals can also represent special


 These special characters are all of them preceded by a
backslash character (\).
 Here you have a list of the single character escape codes:
Escape code Description
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
34
Constants

Other literals
◦ Three keyword literals exist in C++: true, false and nullptr:
◦ true and false are the two possible values for variables of type bool.
◦ nullptr is the null pointer value.
 bool foo = true;
 bool bar = false;
 int* p = nullptr;
 Typed constant expressions
◦ Sometimes, it is just convenient to give a name to a
constant value:
 const double pi = 3.1415926;
 const char tab = '\t';
◦ We can then use these names instead of the literals they
were defined to:
35
Operator in C++

Arithmetic Operators
 Assume variable X has =20 and Y=10

Operator Description Example


+ Adds two operands X + Y will give 30
- Subtracts second operand from the first X-Y will give 10

* Multiplies both operands X*Y will give 200


/ Divides numerator by de-numerator X/ Y will give 2

% Modulus Operator and remainder of after X%Y will give 0


an integer division
++ Increment operator, increases integer value Y++ will give 11
by one
-- Decrement operator, decreases integer Y-- will give 9
value by one

36
Operator in C++

Relational Operators
 Assume variable A holds 10 and variable B holds 20, then
Operator Description Example
== Checks if the values of two operands are equal or not, if yes (A == B) is not
then condition becomes true. true.
!= Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not
the value of right operand, if yes then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

37
Operator in C++

Logical Operators
 Assume variable A holds 1 and variable B holds 0, then
Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition becomes
true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then condition becomes
true.

! Called Logical NOT Operator. Use to reverses


the logical state of its operand. If a condition is
true, then Logical NOT operator will make
false.

38
Operator in C++

 Bitwise Operators
 Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ are as follows

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
 Assume if A = 60; and B = 13; now in binary format they will be as follows −
 A = 0011 1100
 B = 0000 1101
◦ A&B = 0000 1100
◦ A|B = 0011 1101
◦ A^B = 0011 0001
◦ ~A  = 1100 0011
39
Operator in C++

Assignment Operators
There are following assignment operators supported by C++
language
Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left C = A + B will assign value of A + B
side operand. into C

+= Add AND assignment operator, It adds right operand to the left operand and
assign the result to left operand. C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left
operand and assign the result to left operand. C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left
operand and assign the result to left operand. C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right
operand and assign the result to left operand. C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands


and assign the result to left operand. C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2


40
Operator in C++

Conditional ternary operator ( ? )


◦ condition ? result1 : result2
If condition is true, the entire expression evaluates to result1,
and otherwise to result2.
◦ 7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.
◦ 7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2.
◦ 5>3 ? a : b // evaluates to the value of a, since 5 is
greater than 3.
◦ a>b ? a : b

41
Operator in C++

Explicit type casting operator


◦ Type casting operators allow to convert a value of a given type to
another type.
◦ There are several ways to do this in C++. The simplest one, which has
been inherited from the C language, is to precede the expression to be
converted by the new type enclosed between parentheses (()):
 int i;
 float f = 3.14;
 i = (int) f;
i will be 3
• Sizeof Operator
 This operator accepts one parameter, which can be either a type or a
variable, and returns the size in bytes of that type or object:
 x = sizeof (char);
42
Operator in C++- Precedence of operators

Level Precedence group Operator Description Grouping


1 Scope :: scope qualifier Left-to-right
++ -- postfix increment / decrement

2 Postfix (unary) () functional forms Left-to-right


[] subscript
. -> member access

++ -- prefix increment / decrement

~! bitwise NOT / logical NOT


+- unary prefix
3 Prefix (unary) &* reference / dereference Right-to-left
new delete allocation / deallocation
sizeof parameter pack
(type) C-style type-casting
4 Pointer-to-member .* ->* access pointer Left-to-right
5 Arithmetic: scaling */% multiply, divide, modulo Left-to-right
6 Arithmetic: addition +- addition, subtraction Left-to-right
7 Bitwise shift << >> shift left, shift right Left-to-right
8 Relational < > <= >= comparison operators Left-to-right
9 Equality == != equality / inequality Left-to-right
10 And & bitwise AND Left-to-right
11 Exclusive or ^ bitwise XOR Left-to-right
12 Inclusive or | bitwise OR Left-to-right
13 Conjunction && logical AND Left-to-right
14 Disjunction || logical OR Left-to-right
= *= /= %= += -=
assignment / compound assignment
15 Assignment-level expressions >>= <<= &= ^= |= Right-to-left
?: conditional operator
43
End of Chapter Two
Thank You

44

You might also like